@ship.zone/runner 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@ship.zone/runner",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "The Firecracker microVM OCI job runner for ship.zone CI/CD",
5
- "homepage": "https://code.foss.global/ship.zone/runner",
5
+ "homepage": "https://foss.global/ship.zone/runner",
6
6
  "bugs": {
7
- "url": "https://code.foss.global/ship.zone/runner/issues"
7
+ "url": "https://foss.global/ship.zone/runner/issues"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://code.foss.global/ship.zone/runner.git"
11
+ "url": "git+https://foss.global/ship.zone/runner.git"
12
12
  },
13
13
  "author": "Task Venture Capital GmbH",
14
14
  "license": "MIT",
@@ -27,17 +27,10 @@
27
27
  "default": "./dist_ts/index.js"
28
28
  }
29
29
  },
30
- "scripts": {
31
- "build": "tsbuild && node scripts/verify-npm-entrypoint.ts && tsrust",
32
- "build:release": "tsbuild && node scripts/verify-npm-entrypoint.ts && tsrust --configured-targets && tsrust verify",
33
- "build:binary": "pnpm run build:release && tsbundle && tssea build",
34
- "test": "pnpm run build && tstest test/ --verbose && cargo test --manifest-path rust/Cargo.toml"
35
- },
36
- "packageManager": "pnpm@12.10.1",
37
30
  "dependencies": {
38
31
  "@push.rocks/smartsea": "^1.1.0",
39
32
  "@push.rocks/smartvm": "^2.0.0",
40
- "@ship.zone/ci-spec": "3.0.0",
33
+ "@ship.zone/ci-spec": "3.1.0",
41
34
  "ajv": "^8.20.0"
42
35
  },
43
36
  "devDependencies": {
@@ -64,5 +57,11 @@
64
57
  "rust-toolchain.toml",
65
58
  "!ts/tsconfig.json",
66
59
  "!ts_web/tsconfig.json"
67
- ]
68
- }
60
+ ],
61
+ "scripts": {
62
+ "build": "tsbuild && node scripts/verify-npm-entrypoint.ts && tsrust",
63
+ "build:release": "tsbuild && node scripts/verify-npm-entrypoint.ts && tsrust --configured-targets && tsrust verify",
64
+ "build:binary": "pnpm run build:release && tsbundle && tssea build",
65
+ "test": "pnpm run build && tstest test/ --verbose && cargo test --manifest-path rust/Cargo.toml"
66
+ }
67
+ }
package/readme.md CHANGED
@@ -76,7 +76,7 @@ Requests directly.
76
76
  Install the `ship-zone-runner` executable on a Linux host:
77
77
 
78
78
  ```sh
79
- curl -fsSL https://code.foss.global/ship.zone/runner/releases/download/latest/install.sh | sudo bash
79
+ curl -fsSL https://foss.global/ship.zone/runner/releases/download/latest/install.sh | sudo bash
80
80
  ```
81
81
 
82
82
  The installer is an asset of every release from 3.0.0 on. It downloads the executable of the newest
@@ -88,7 +88,7 @@ executable with `--version` before it changes anything. It installs to
88
88
  to check the release assets without changing anything:
89
89
 
90
90
  ```sh
91
- curl -fsSL https://code.foss.global/ship.zone/runner/releases/download/latest/install.sh | sudo bash -s -- --version vX.Y.Z
91
+ curl -fsSL https://foss.global/ship.zone/runner/releases/download/latest/install.sh | sudo bash -s -- --version vX.Y.Z
92
92
  ```
93
93
 
94
94
  Running it again updates the executable. The installer never touches the runner's configuration
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@ship.zone/runner',
6
- version: '5.0.0',
6
+ version: '5.1.0',
7
7
  description: 'The Firecracker microVM OCI job runner for ship.zone CI/CD'
8
8
  }
@@ -22,7 +22,8 @@ export interface IAttemptJournal {
22
22
 
23
23
  const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
24
24
  const journalName = 'active-attempt.json';
25
- const maximumJournalBytes = 1024;
25
+ const maximumJournalBytes = 64 * 1024;
26
+ const maximumConcurrentJournalEntries = 256;
26
27
 
27
28
  const validateJournal = (value: unknown): IAttemptJournal => {
28
29
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
@@ -51,6 +52,34 @@ const validateJournal = (value: unknown): IAttemptJournal => {
51
52
  };
52
53
  };
53
54
 
55
+ const validateJournalDocument = (value: unknown): IAttemptJournal[] => {
56
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
57
+ throw new RunnerError('Attempt journal must contain a JSON object');
58
+ }
59
+ const record = value as Record<string, unknown>;
60
+ const keys = Object.keys(record);
61
+ if (keys.length === 1 && Object.hasOwn(record, 'attempts')) {
62
+ if (!Array.isArray(record.attempts)) {
63
+ throw new RunnerError('Attempt journal attempts field must be an array');
64
+ }
65
+ if (record.attempts.length > maximumConcurrentJournalEntries) {
66
+ throw new RunnerError('Attempt journal exceeds maximum concurrent entries');
67
+ }
68
+ const seen = new Set<string>();
69
+ const entries: IAttemptJournal[] = [];
70
+ for (const item of record.attempts) {
71
+ const validated = validateJournal(item);
72
+ if (seen.has(validated.attemptId)) {
73
+ throw new RunnerError('Attempt journal contains duplicate attemptId');
74
+ }
75
+ seen.add(validated.attemptId);
76
+ entries.push(validated);
77
+ }
78
+ return entries;
79
+ }
80
+ return [validateJournal(value)];
81
+ };
82
+
54
83
  export class AttemptStateStore {
55
84
  readonly path: string;
56
85
  private readonly stateDirectory: string;
@@ -61,12 +90,65 @@ export class AttemptStateStore {
61
90
  }
62
91
 
63
92
  async load(): Promise<IAttemptJournal | undefined> {
93
+ const entries = await this.loadAll();
94
+ return entries[0];
95
+ }
96
+
97
+ async loadAll(): Promise<IAttemptJournal[]> {
98
+ return await this.owner.serialize(async () => await this.loadAllUnlocked());
99
+ }
100
+
101
+ async save(journal: IAttemptJournal): Promise<void> {
102
+ const validated = validateJournal(journal);
103
+ await this.owner.serialize(async () => {
104
+ await this.writeRawUnlocked(validated);
105
+ });
106
+ }
107
+
108
+ async add(journal: IAttemptJournal): Promise<void> {
109
+ const validated = validateJournal(journal);
110
+ await this.owner.serialize(async () => {
111
+ const existing = await this.loadAllUnlocked();
112
+ const filtered = existing.filter((entry) => entry.attemptId !== validated.attemptId);
113
+ if (filtered.length >= maximumConcurrentJournalEntries) {
114
+ throw new RunnerError('Attempt journal exceeds maximum concurrent entries');
115
+ }
116
+ const next = [...filtered, validated];
117
+ if (next.length === 1) {
118
+ await this.writeRawUnlocked(next[0]);
119
+ } else {
120
+ await this.writeRawUnlocked({ attempts: next });
121
+ }
122
+ });
123
+ }
124
+
125
+ async remove(attemptId: string): Promise<void> {
126
+ await this.owner.serialize(async () => {
127
+ const existing = await this.loadAllUnlocked();
128
+ const remaining = existing.filter((entry) => entry.attemptId !== attemptId);
129
+ if (remaining.length === 0) {
130
+ await this.clearUnlocked();
131
+ } else if (remaining.length === 1) {
132
+ await this.writeRawUnlocked(remaining[0]);
133
+ } else {
134
+ await this.writeRawUnlocked({ attempts: remaining });
135
+ }
136
+ });
137
+ }
138
+
139
+ async clear(): Promise<void> {
140
+ await this.owner.serialize(async () => {
141
+ await this.clearUnlocked();
142
+ });
143
+ }
144
+
145
+ private async loadAllUnlocked(): Promise<IAttemptJournal[]> {
64
146
  await this.ensureDirectory();
65
147
  let pathStat: plugins.Stats;
66
148
  try {
67
149
  pathStat = await plugins.fs.lstat(this.path);
68
150
  } catch (error) {
69
- if (isNotFound(error)) return undefined;
151
+ if (isNotFound(error)) return [];
70
152
  throw error;
71
153
  }
72
154
  this.assertSafeJournalFile(pathStat);
@@ -98,14 +180,13 @@ export class AttemptStateStore {
98
180
  } catch (error) {
99
181
  throw new RunnerError('Attempt journal is not valid JSON', { cause: error });
100
182
  }
101
- return validateJournal(parsed);
183
+ return validateJournalDocument(parsed);
102
184
  },
103
185
  'Attempt journal read and close failed',
104
186
  );
105
187
  }
106
188
 
107
- async save(journal: IAttemptJournal): Promise<void> {
108
- const validated = validateJournal(journal);
189
+ private async writeRawUnlocked(payload: IAttemptJournal | { attempts: IAttemptJournal[] }): Promise<void> {
109
190
  await this.ensureDirectory();
110
191
  try {
111
192
  this.assertSafeJournalFile(await plugins.fs.lstat(this.path));
@@ -116,7 +197,7 @@ export class AttemptStateStore {
116
197
  this.stateDirectory,
117
198
  `.${plugins.crypto.randomUUID()}.attempt-journal.tmp`,
118
199
  );
119
- const bytes = new TextEncoder().encode(`${JSON.stringify(validated)}\n`);
200
+ const bytes = new TextEncoder().encode(`${JSON.stringify(payload)}\n`);
120
201
  if (bytes.byteLength > maximumJournalBytes) {
121
202
  throw new RunnerError('Attempt journal exceeds its size limit');
122
203
  }
@@ -147,7 +228,7 @@ export class AttemptStateStore {
147
228
  }
148
229
  }
149
230
 
150
- async clear(): Promise<void> {
231
+ private async clearUnlocked(): Promise<void> {
151
232
  await this.ensureDirectory();
152
233
  let stat: plugins.Stats;
153
234
  try {
package/ts/index.ts CHANGED
@@ -11,6 +11,7 @@ export * from './npm-grants.js';
11
11
  export * from './oci-registry.js';
12
12
  export * from './protocol-validator.js';
13
13
  export * from './redactor.js';
14
+ export * from './resource-budget.js';
14
15
  export * from './runner.js';
15
16
  export * from './source-workspace.js';
16
17
  export * from './spec-version.js';
package/ts/interfaces.ts CHANGED
@@ -120,9 +120,16 @@ export interface IStartSessionResponse {
120
120
  credential?: IRunnerCredential;
121
121
  }
122
122
 
123
+ export interface IAvailableResources {
124
+ cpus: number;
125
+ memoryBytes: number;
126
+ slots: number;
127
+ }
128
+
123
129
  export interface IRunnerHeartbeatRequest {
124
130
  runnerId: string;
125
131
  sessionId: string;
132
+ availableResources?: IAvailableResources;
126
133
  }
127
134
 
128
135
  export interface IRunnerHeartbeatResponse {
@@ -135,6 +142,7 @@ export interface IClaimJobRequest {
135
142
  claimRequestId: string;
136
143
  runnerId: string;
137
144
  sessionId: string;
145
+ availableResources?: IAvailableResources;
138
146
  }
139
147
 
140
148
  export interface IClaimJobResponse {
@@ -651,6 +659,7 @@ export interface IOciRuntimeFacts {
651
659
  readonly initrdPath: string;
652
660
  readonly kernelPath: string;
653
661
  readonly shapes: readonly IMicroVmShapeInfo[];
662
+ readonly slotCount?: number;
654
663
  }
655
664
 
656
665
  export interface IPrepareOciLeaseContext {
@@ -40,6 +40,7 @@ import { EgressAllowlistController, grantOriginsFromLease } from './egress-proxy
40
40
  import { buildNpmrcContent, GUEST_NPMRC_PATH } from './npm-grants.js';
41
41
  import {
42
42
  ensurePrivateStateDirectory,
43
+ resolvePackagedSmartVmBridgePath,
43
44
  resolvePackagedWorkspaceHelperPath,
44
45
  type RunnerStateOwner,
45
46
  workspaceHelperMaximumBytes,
@@ -487,10 +488,12 @@ export class MicroVmExecutor implements IJobExecutor {
487
488
  if (runtimeDir) {
488
489
  await plugins.fs.mkdir(runtimeDir, { recursive: true, mode: 0o700 });
489
490
  }
491
+ const bridgeBinaryPath = this.config.oci.smartvmBridgePath ??
492
+ await resolvePackagedSmartVmBridgePath();
490
493
  const options: plugins.smartvm.ISmartVMConnectOptions = {
491
494
  ...(this.config.oci.smartvmSocketPath ? { helperSocketPath: this.config.oci.smartvmSocketPath } : {}),
492
495
  ...(runtimeDir ? { runtimeDir } : {}),
493
- ...(this.config.oci.smartvmBridgePath ? { bridgeBinaryPath: this.config.oci.smartvmBridgePath } : {}),
496
+ ...(bridgeBinaryPath ? { bridgeBinaryPath } : {}),
494
497
  requestTimeoutMs: this.config.requestTimeoutMs,
495
498
  };
496
499
  this.smartvmPromise = this.connectSmartVm(options).catch((error) => {
@@ -630,6 +633,7 @@ export class MicroVmExecutor implements IJobExecutor {
630
633
  initrdPath,
631
634
  kernelPath: this.config.oci.kernelPath,
632
635
  shapes: smartvm.info.shapes,
636
+ slotCount: smartvm.info.slotCount,
633
637
  };
634
638
  return this.runtimeFacts;
635
639
  }
@@ -0,0 +1,206 @@
1
+ import * as plugins from './plugins.js';
2
+ import type {
3
+ IAvailableResources,
4
+ IMicroVmShapeInfo,
5
+ IOciJobLease,
6
+ IOciRuntimeFacts,
7
+ IRunnerConfig,
8
+ } from './interfaces.js';
9
+
10
+ const mib = 1024 * 1024;
11
+ const maxWireCpus = 1024;
12
+ const maxWireMemoryBytes = 4_398_046_511_104;
13
+ const maxWireSlots = 1024;
14
+ const defaultHostMemoryReserveRatio = 0.15;
15
+ const minimumHostMemoryReserveBytes = 512 * mib;
16
+
17
+ export interface IResourceReservation {
18
+ readonly attemptId: string;
19
+ readonly cpus: number;
20
+ readonly memoryBytes: number;
21
+ }
22
+
23
+ export interface IResourceBudgetHostProbe {
24
+ totalCpus(): number;
25
+ totalMemoryBytes(): number;
26
+ availableMemoryBytes(): number | undefined;
27
+ }
28
+
29
+ /**
30
+ * Reads Linux `MemAvailable` from `/proc/meminfo` (in bytes), which accurately accounts for
31
+ * reclaimable page cache unlike `os.freemem()`. Returns `undefined` when unavailable.
32
+ */
33
+ export const readLinuxMemAvailableBytes = (): number | undefined => {
34
+ try {
35
+ const content = plugins.fsSync.readFileSync('/proc/meminfo', 'utf8');
36
+ const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(content);
37
+ if (!match) return undefined;
38
+ const kib = Number(match[1]);
39
+ if (!Number.isSafeInteger(kib) || kib < 0) return undefined;
40
+ return kib * 1024;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ };
45
+
46
+ const defaultHostProbe = (): IResourceBudgetHostProbe => ({
47
+ totalCpus: () => {
48
+ const raw = typeof plugins.os.availableParallelism === 'function'
49
+ ? plugins.os.availableParallelism()
50
+ : plugins.os.cpus().length;
51
+ return Math.max(1, raw);
52
+ },
53
+ totalMemoryBytes: () => Math.max(0, plugins.os.totalmem()),
54
+ availableMemoryBytes: readLinuxMemAvailableBytes,
55
+ });
56
+
57
+ const clampCpus = (value: number): number =>
58
+ Math.max(0, Math.min(maxWireCpus, Math.round(value * 1000) / 1000));
59
+
60
+ const clampBytes = (value: number): number =>
61
+ Math.max(0, Math.min(maxWireMemoryBytes, Math.floor(value)));
62
+
63
+ const clampSlots = (value: number): number =>
64
+ Math.max(0, Math.min(maxWireSlots, Math.floor(value)));
65
+
66
+ /**
67
+ * Tracks live unreserved CPU, memory, and VM slot capacity for dynamic multi-job concurrency.
68
+ * Reservations are taken when a lease is claimed and released immediately when its microVM exits.
69
+ */
70
+ export class RunnerResourceBudget {
71
+ private readonly reservations = new Map<string, IResourceReservation>();
72
+ readonly totalSlots: number;
73
+ readonly totalCpus: number;
74
+ readonly totalMemoryBytes: number;
75
+ private readonly hostMemoryReserveBytes: number;
76
+ private readonly minimumClaimCpus: number;
77
+ private readonly minimumClaimMemoryBytes: number;
78
+ private readonly shapes: readonly IMicroVmShapeInfo[];
79
+ private readonly probe: IResourceBudgetHostProbe;
80
+
81
+ constructor(
82
+ private readonly config: IRunnerConfig,
83
+ runtime: IOciRuntimeFacts,
84
+ probe: IResourceBudgetHostProbe = defaultHostProbe(),
85
+ ) {
86
+ this.probe = probe;
87
+ this.shapes = runtime.shapes;
88
+
89
+ const rawCpus = Math.max(1, probe.totalCpus());
90
+ // Reserve up to 2 cores for the host OS / smartvm-helper / runner daemon on multi-core hosts.
91
+ const hostReservedCpus = rawCpus > 4 ? 2 : rawCpus > 2 ? 1 : 0;
92
+ const maxShapeCpus = runtime.shapes.reduce((acc, shape) => Math.max(acc, shape.vcpus), 0);
93
+ this.totalCpus = clampCpus(
94
+ Math.max(rawCpus - hostReservedCpus, Math.min(rawCpus, maxShapeCpus || config.oci.maximumCpus)),
95
+ );
96
+
97
+ const rawMemory = Math.max(0, probe.totalMemoryBytes());
98
+ this.hostMemoryReserveBytes = Math.max(
99
+ minimumHostMemoryReserveBytes,
100
+ Math.floor(rawMemory * defaultHostMemoryReserveRatio),
101
+ );
102
+ const usableMemory = rawMemory > this.hostMemoryReserveBytes
103
+ ? rawMemory - this.hostMemoryReserveBytes
104
+ : rawMemory;
105
+ const maxShapeMemory = runtime.shapes.reduce(
106
+ (acc, shape) => Math.max(acc, shape.memMib * mib),
107
+ 0,
108
+ );
109
+ this.totalMemoryBytes = clampBytes(
110
+ Math.max(usableMemory, Math.min(rawMemory, maxShapeMemory || config.oci.maximumMemoryBytes)),
111
+ );
112
+
113
+ const configuredSlots = runtime.slotCount !== undefined && runtime.slotCount > 0
114
+ ? runtime.slotCount
115
+ : 1;
116
+ this.totalSlots = clampSlots(Math.max(1, configuredSlots));
117
+
118
+ if (runtime.shapes.length > 0) {
119
+ this.minimumClaimCpus = runtime.shapes.reduce(
120
+ (acc, shape) => Math.min(acc, shape.vcpus),
121
+ Number.POSITIVE_INFINITY,
122
+ );
123
+ this.minimumClaimMemoryBytes = runtime.shapes.reduce(
124
+ (acc, shape) => Math.min(acc, shape.memMib * mib),
125
+ Number.POSITIVE_INFINITY,
126
+ );
127
+ } else {
128
+ this.minimumClaimCpus = 0.25;
129
+ this.minimumClaimMemoryBytes = 64 * mib;
130
+ }
131
+ }
132
+
133
+ public activeCount(): number {
134
+ return this.reservations.size;
135
+ }
136
+
137
+ public available(): IAvailableResources {
138
+ let reservedCpus = 0;
139
+ let reservedMemoryBytes = 0;
140
+ for (const reservation of this.reservations.values()) {
141
+ reservedCpus += reservation.cpus;
142
+ reservedMemoryBytes += reservation.memoryBytes;
143
+ }
144
+ const slots = clampSlots(this.totalSlots - this.reservations.size);
145
+ const cpus = clampCpus(this.totalCpus - reservedCpus);
146
+ let memoryBytes = clampBytes(this.totalMemoryBytes - reservedMemoryBytes);
147
+ const liveMemAvailable = this.probe.availableMemoryBytes();
148
+ if (liveMemAvailable !== undefined) {
149
+ const liveUsable = Math.max(0, liveMemAvailable - this.hostMemoryReserveBytes);
150
+ // Use the smaller of our reservation budget and actual unallocated host RAM so host pressure
151
+ // throttles new claims on the fly without double-counting already-running microVMs.
152
+ memoryBytes = clampBytes(Math.min(memoryBytes, liveUsable));
153
+ }
154
+ return { cpus, memoryBytes, slots };
155
+ }
156
+
157
+ public canClaimAnother(): boolean {
158
+ const current = this.available();
159
+ if (current.slots < 1) return false;
160
+ if (current.cpus < this.minimumClaimCpus) return false;
161
+ // Allow claiming whenever free memory can fit at least the smallest shape minus guest overhead
162
+ // (or the smallest shape itself when overhead is small).
163
+ const minNeededMemory = Math.max(
164
+ 64 * mib,
165
+ this.minimumClaimMemoryBytes - this.config.oci.guestMemoryOverheadBytes,
166
+ );
167
+ return current.memoryBytes >= minNeededMemory;
168
+ }
169
+
170
+ /** Computes the shape-rounded CPU and memory footprint a claimed lease will occupy. */
171
+ public estimateLeaseFootprint(lease: IOciJobLease): { cpus: number; memoryBytes: number } {
172
+ const requestedCpus = lease.job.resources?.cpus ?? this.config.oci.defaultCpus;
173
+ const requestedMemory = (lease.job.resources?.memoryBytes ?? this.config.oci.defaultMemoryBytes) +
174
+ this.config.oci.guestMemoryOverheadBytes;
175
+
176
+ // Match the smallest VM shape that fits, mirroring MicroVmExecutor.selectShapeForJob.
177
+ const fitting = this.shapes
178
+ .filter((shape) => shape.vcpus >= requestedCpus && shape.memMib * mib >= requestedMemory)
179
+ .sort((a, b) => (a.memMib - b.memMib) || (a.vcpus - b.vcpus));
180
+ if (fitting.length > 0) {
181
+ return {
182
+ cpus: fitting[0].vcpus,
183
+ memoryBytes: fitting[0].memMib * mib,
184
+ };
185
+ }
186
+ return {
187
+ cpus: requestedCpus,
188
+ memoryBytes: requestedMemory,
189
+ };
190
+ }
191
+
192
+ public reserve(attemptId: string, lease: IOciJobLease): IResourceReservation {
193
+ const footprint = this.estimateLeaseFootprint(lease);
194
+ const reservation: IResourceReservation = {
195
+ attemptId,
196
+ cpus: footprint.cpus,
197
+ memoryBytes: footprint.memoryBytes,
198
+ };
199
+ this.reservations.set(attemptId, reservation);
200
+ return reservation;
201
+ }
202
+
203
+ public release(attemptId: string): void {
204
+ this.reservations.delete(attemptId);
205
+ }
206
+ }