@ship.zone/runner 5.0.1 → 5.2.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.
@@ -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,24 @@ export interface IStartSessionResponse {
120
120
  credential?: IRunnerCredential;
121
121
  }
122
122
 
123
+ export interface IAvailableResources {
124
+ cpus: number;
125
+ memoryBytes: number;
126
+ diskBytes?: number;
127
+ slots: number;
128
+ }
129
+
130
+ export interface IResourceUsage {
131
+ peakMemoryBytes?: number;
132
+ peakDiskBytes?: number;
133
+ peakCpus?: number;
134
+ durationMs?: number;
135
+ }
136
+
123
137
  export interface IRunnerHeartbeatRequest {
124
138
  runnerId: string;
125
139
  sessionId: string;
140
+ availableResources?: IAvailableResources;
126
141
  }
127
142
 
128
143
  export interface IRunnerHeartbeatResponse {
@@ -135,6 +150,7 @@ export interface IClaimJobRequest {
135
150
  claimRequestId: string;
136
151
  runnerId: string;
137
152
  sessionId: string;
153
+ availableResources?: IAvailableResources;
138
154
  }
139
155
 
140
156
  export interface IClaimJobResponse {
@@ -244,6 +260,7 @@ export interface ICompleteJobRequest {
244
260
  completedAt: string;
245
261
  cancellationRequestId?: string;
246
262
  error?: string;
263
+ resourceUsage?: IResourceUsage;
247
264
  }
248
265
 
249
266
  export interface ICompleteJobResponse {
@@ -651,6 +668,7 @@ export interface IOciRuntimeFacts {
651
668
  readonly initrdPath: string;
652
669
  readonly kernelPath: string;
653
670
  readonly shapes: readonly IMicroVmShapeInfo[];
671
+ readonly slotCount?: number;
654
672
  }
655
673
 
656
674
  export interface IPrepareOciLeaseContext {
@@ -701,6 +719,7 @@ export interface IExecutionResult {
701
719
  stopReason?: TExecutionStopReason;
702
720
  producedImage?: IProducedImageManifest;
703
721
  workspace?: IRuntimeWorkspaceExporter;
722
+ resourceUsage?: IResourceUsage;
704
723
  }
705
724
 
706
725
  export interface IJobExecutor {
@@ -633,6 +633,7 @@ export class MicroVmExecutor implements IJobExecutor {
633
633
  initrdPath,
634
634
  kernelPath: this.config.oci.kernelPath,
635
635
  shapes: smartvm.info.shapes,
636
+ slotCount: smartvm.info.slotCount,
636
637
  };
637
638
  return this.runtimeFacts;
638
639
  }
@@ -1000,10 +1001,13 @@ export class MicroVmExecutor implements IJobExecutor {
1000
1001
  });
1001
1002
  }
1002
1003
 
1003
- const attemptDeadline = this.now() + context.timeoutMs;
1004
+ const executionStartedAt = this.now();
1005
+ const attemptDeadline = executionStartedAt + context.timeoutMs;
1004
1006
  let lastExitCode: number | null = 0;
1005
1007
  let stopReason: TExecutionStopReason | undefined;
1006
1008
  let producedImage: IExecutionResult['producedImage'];
1009
+ let peakWorkspaceBytes = packed.tarBytes.byteLength;
1010
+ const selectedShape = runtime.shapes.find((s) => s.id === context.preparedLease.shapeId);
1007
1011
 
1008
1012
  if ('build' in job) {
1009
1013
  const pushGrant = context.lease.grants.find((g) => g.access === 'push');
@@ -1226,6 +1230,14 @@ export class MicroVmExecutor implements IJobExecutor {
1226
1230
  }
1227
1231
  }
1228
1232
 
1233
+ if (
1234
+ typeof stepResult.workspaceBytes === 'number' &&
1235
+ Number.isFinite(stepResult.workspaceBytes) &&
1236
+ stepResult.workspaceBytes > peakWorkspaceBytes
1237
+ ) {
1238
+ peakWorkspaceBytes = Math.floor(stepResult.workspaceBytes);
1239
+ }
1240
+
1229
1241
  if (logFailure) {
1230
1242
  stopReason = 'log_delivery_failed';
1231
1243
  lastExitCode = null;
@@ -1295,6 +1307,14 @@ export class MicroVmExecutor implements IJobExecutor {
1295
1307
  ...(stopReason ? { stopReason } : {}),
1296
1308
  ...(producedImage ? { producedImage } : {}),
1297
1309
  workspace: exporter,
1310
+ resourceUsage: {
1311
+ peakMemoryBytes: selectedShape
1312
+ ? selectedShape.memMib * 1024 * 1024
1313
+ : memoryBytes,
1314
+ peakDiskBytes: Math.max(0, Math.floor(peakWorkspaceBytes)),
1315
+ peakCpus: selectedShape ? selectedShape.vcpus : cpus,
1316
+ durationMs: Math.max(0, Math.floor(this.now() - executionStartedAt)),
1317
+ },
1298
1318
  };
1299
1319
  } catch (error) {
1300
1320
  try {
@@ -0,0 +1,258 @@
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 gib = 1024 * mib;
12
+ const maxWireCpus = 1024;
13
+ const maxWireMemoryBytes = 4_398_046_511_104;
14
+ const maxWireDiskBytes = 109_951_162_777_600;
15
+ const maxWireSlots = 1024;
16
+ const defaultHostMemoryReserveRatio = 0.15;
17
+ const minimumHostMemoryReserveBytes = 512 * mib;
18
+ const defaultHostDiskReserveBytes = 4 * gib;
19
+
20
+ export interface IResourceReservation {
21
+ readonly attemptId: string;
22
+ readonly cpus: number;
23
+ readonly memoryBytes: number;
24
+ readonly diskBytes: number;
25
+ }
26
+
27
+ export interface IResourceBudgetHostProbe {
28
+ totalCpus(): number;
29
+ totalMemoryBytes(): number;
30
+ availableMemoryBytes(): number | undefined;
31
+ availableDiskBytes?(): number | undefined;
32
+ }
33
+
34
+ /**
35
+ * Reads Linux `MemAvailable` from `/proc/meminfo` (in bytes), which accurately accounts for
36
+ * reclaimable page cache unlike `os.freemem()`. Returns `undefined` when unavailable.
37
+ */
38
+ export const readLinuxMemAvailableBytes = (): number | undefined => {
39
+ try {
40
+ const content = plugins.fsSync.readFileSync('/proc/meminfo', 'utf8');
41
+ const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(content);
42
+ if (!match) return undefined;
43
+ const kib = Number(match[1]);
44
+ if (!Number.isSafeInteger(kib) || kib < 0) return undefined;
45
+ return kib * 1024;
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ };
50
+
51
+ /**
52
+ * Reads live free disk bytes on the microVM storage volume (`/var/lib/smartvm` if present,
53
+ * otherwise `fallbackDir`). Returns `undefined` when `statfsSync` is unavailable.
54
+ */
55
+ export const readAvailableDiskBytes = (fallbackDir: string): number | undefined => {
56
+ const candidates = ['/var/lib/smartvm', fallbackDir];
57
+ for (const dir of candidates) {
58
+ try {
59
+ if (!dir) continue;
60
+ const stat = plugins.fsSync.statfsSync(dir);
61
+ const bavail = Number(stat.bavail);
62
+ const bsize = Number(stat.bsize);
63
+ if (Number.isFinite(bavail) && Number.isFinite(bsize) && bavail >= 0 && bsize > 0) {
64
+ return Math.floor(bavail * bsize);
65
+ }
66
+ } catch {
67
+ // Try next candidate
68
+ }
69
+ }
70
+ return undefined;
71
+ };
72
+
73
+ const defaultHostProbe = (stateDirectory: string): IResourceBudgetHostProbe => ({
74
+ totalCpus: () => {
75
+ const raw = typeof plugins.os.availableParallelism === 'function'
76
+ ? plugins.os.availableParallelism()
77
+ : plugins.os.cpus().length;
78
+ return Math.max(1, raw);
79
+ },
80
+ totalMemoryBytes: () => Math.max(0, plugins.os.totalmem()),
81
+ availableMemoryBytes: readLinuxMemAvailableBytes,
82
+ availableDiskBytes: () => readAvailableDiskBytes(stateDirectory),
83
+ });
84
+
85
+ const clampCpus = (value: number): number =>
86
+ Math.max(0, Math.min(maxWireCpus, Math.round(value * 1000) / 1000));
87
+
88
+ const clampBytes = (value: number): number =>
89
+ Math.max(0, Math.min(maxWireMemoryBytes, Math.floor(value)));
90
+
91
+ const clampDiskBytes = (value: number): number =>
92
+ Math.max(0, Math.min(maxWireDiskBytes, Math.floor(value)));
93
+
94
+ const clampSlots = (value: number): number =>
95
+ Math.max(0, Math.min(maxWireSlots, Math.floor(value)));
96
+
97
+ /**
98
+ * Tracks live unreserved CPU, memory, disk, and VM slot capacity for dynamic multi-job concurrency.
99
+ * Reservations are taken when a lease is claimed and released immediately when its microVM exits.
100
+ */
101
+ export class RunnerResourceBudget {
102
+ private readonly reservations = new Map<string, IResourceReservation>();
103
+ readonly totalSlots: number;
104
+ readonly totalCpus: number;
105
+ readonly totalMemoryBytes: number;
106
+ private readonly hostMemoryReserveBytes: number;
107
+ private readonly minimumClaimCpus: number;
108
+ private readonly minimumClaimMemoryBytes: number;
109
+ private readonly shapes: readonly IMicroVmShapeInfo[];
110
+ private readonly probe: IResourceBudgetHostProbe;
111
+
112
+ constructor(
113
+ private readonly config: IRunnerConfig,
114
+ runtime: IOciRuntimeFacts,
115
+ probe: IResourceBudgetHostProbe = defaultHostProbe(config.stateDirectory),
116
+ ) {
117
+ this.probe = probe;
118
+ this.shapes = runtime.shapes;
119
+
120
+ const rawCpus = Math.max(1, probe.totalCpus());
121
+ // Reserve up to 2 cores for the host OS / smartvm-helper / runner daemon on multi-core hosts.
122
+ const hostReservedCpus = rawCpus > 4 ? 2 : rawCpus > 2 ? 1 : 0;
123
+ const maxShapeCpus = runtime.shapes.reduce((acc, shape) => Math.max(acc, shape.vcpus), 0);
124
+ this.totalCpus = clampCpus(
125
+ Math.max(rawCpus - hostReservedCpus, Math.min(rawCpus, maxShapeCpus || config.oci.maximumCpus)),
126
+ );
127
+
128
+ const rawMemory = Math.max(0, probe.totalMemoryBytes());
129
+ this.hostMemoryReserveBytes = Math.max(
130
+ minimumHostMemoryReserveBytes,
131
+ Math.floor(rawMemory * defaultHostMemoryReserveRatio),
132
+ );
133
+ const usableMemory = rawMemory > this.hostMemoryReserveBytes
134
+ ? rawMemory - this.hostMemoryReserveBytes
135
+ : rawMemory;
136
+ const maxShapeMemory = runtime.shapes.reduce(
137
+ (acc, shape) => Math.max(acc, shape.memMib * mib),
138
+ 0,
139
+ );
140
+ this.totalMemoryBytes = clampBytes(
141
+ Math.max(usableMemory, Math.min(rawMemory, maxShapeMemory || config.oci.maximumMemoryBytes)),
142
+ );
143
+
144
+ const configuredSlots = runtime.slotCount !== undefined && runtime.slotCount > 0
145
+ ? runtime.slotCount
146
+ : 1;
147
+ this.totalSlots = clampSlots(Math.max(1, configuredSlots));
148
+
149
+ if (runtime.shapes.length > 0) {
150
+ this.minimumClaimCpus = runtime.shapes.reduce(
151
+ (acc, shape) => Math.min(acc, shape.vcpus),
152
+ Number.POSITIVE_INFINITY,
153
+ );
154
+ this.minimumClaimMemoryBytes = runtime.shapes.reduce(
155
+ (acc, shape) => Math.min(acc, shape.memMib * mib),
156
+ Number.POSITIVE_INFINITY,
157
+ );
158
+ } else {
159
+ this.minimumClaimCpus = 0.25;
160
+ this.minimumClaimMemoryBytes = 64 * mib;
161
+ }
162
+ }
163
+
164
+ public activeCount(): number {
165
+ return this.reservations.size;
166
+ }
167
+
168
+ public available(): IAvailableResources {
169
+ let reservedCpus = 0;
170
+ let reservedMemoryBytes = 0;
171
+ let reservedDiskBytes = 0;
172
+ for (const reservation of this.reservations.values()) {
173
+ reservedCpus += reservation.cpus;
174
+ reservedMemoryBytes += reservation.memoryBytes;
175
+ reservedDiskBytes += reservation.diskBytes;
176
+ }
177
+ const slots = clampSlots(this.totalSlots - this.reservations.size);
178
+ const cpus = clampCpus(this.totalCpus - reservedCpus);
179
+ let memoryBytes = clampBytes(this.totalMemoryBytes - reservedMemoryBytes);
180
+ const liveMemAvailable = this.probe.availableMemoryBytes();
181
+ if (liveMemAvailable !== undefined) {
182
+ const liveUsable = Math.max(0, liveMemAvailable - this.hostMemoryReserveBytes);
183
+ // Use the smaller of our reservation budget and actual unallocated host RAM so host pressure
184
+ // throttles new claims on the fly without double-counting already-running microVMs.
185
+ memoryBytes = clampBytes(Math.min(memoryBytes, liveUsable));
186
+ }
187
+ const liveDiskAvailable = this.probe.availableDiskBytes?.();
188
+ const diskBytes = liveDiskAvailable !== undefined
189
+ ? clampDiskBytes(
190
+ Math.max(0, liveDiskAvailable - defaultHostDiskReserveBytes - reservedDiskBytes),
191
+ )
192
+ : undefined;
193
+ return {
194
+ cpus,
195
+ memoryBytes,
196
+ ...(diskBytes !== undefined ? { diskBytes } : {}),
197
+ slots,
198
+ };
199
+ }
200
+
201
+ public canClaimAnother(): boolean {
202
+ const current = this.available();
203
+ if (current.slots < 1) return false;
204
+ if (current.cpus < this.minimumClaimCpus) return false;
205
+ // Allow claiming whenever free memory can fit at least the smallest shape minus guest overhead
206
+ // (or the smallest shape itself when overhead is small).
207
+ const minNeededMemory = Math.max(
208
+ 64 * mib,
209
+ this.minimumClaimMemoryBytes - this.config.oci.guestMemoryOverheadBytes,
210
+ );
211
+ return current.memoryBytes >= minNeededMemory;
212
+ }
213
+
214
+ /** Computes the shape-rounded CPU, memory, and disk footprint a claimed lease will occupy. */
215
+ public estimateLeaseFootprint(
216
+ lease: IOciJobLease,
217
+ ): { cpus: number; memoryBytes: number; diskBytes: number } {
218
+ const requestedCpus = lease.job.resources?.cpus ?? this.config.oci.defaultCpus;
219
+ const requestedMemory = (lease.job.resources?.memoryBytes ?? this.config.oci.defaultMemoryBytes) +
220
+ this.config.oci.guestMemoryOverheadBytes;
221
+ const diskBytes = clampDiskBytes(
222
+ lease.job.requirements.limits.maximumWorkspaceBytes || this.config.oci.workspaceSizeBytes,
223
+ );
224
+
225
+ // Match the smallest VM shape that fits, mirroring MicroVmExecutor.selectShapeForJob.
226
+ const fitting = this.shapes
227
+ .filter((shape) => shape.vcpus >= requestedCpus && shape.memMib * mib >= requestedMemory)
228
+ .sort((a, b) => (a.memMib - b.memMib) || (a.vcpus - b.vcpus));
229
+ if (fitting.length > 0) {
230
+ return {
231
+ cpus: fitting[0].vcpus,
232
+ memoryBytes: fitting[0].memMib * mib,
233
+ diskBytes,
234
+ };
235
+ }
236
+ return {
237
+ cpus: requestedCpus,
238
+ memoryBytes: requestedMemory,
239
+ diskBytes,
240
+ };
241
+ }
242
+
243
+ public reserve(attemptId: string, lease: IOciJobLease): IResourceReservation {
244
+ const footprint = this.estimateLeaseFootprint(lease);
245
+ const reservation: IResourceReservation = {
246
+ attemptId,
247
+ cpus: footprint.cpus,
248
+ memoryBytes: footprint.memoryBytes,
249
+ diskBytes: footprint.diskBytes,
250
+ };
251
+ this.reservations.set(attemptId, reservation);
252
+ return reservation;
253
+ }
254
+
255
+ public release(attemptId: string): void {
256
+ this.reservations.delete(attemptId);
257
+ }
258
+ }