@ship.zone/runner 0.2.3 → 1.0.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/ts/redactor.ts CHANGED
@@ -1,41 +1,250 @@
1
+ import type { ISecretContentMatcher, ISecretRedactionSet, TLogStream } from './interfaces.ts';
2
+ import { utf8Length } from './validation.ts';
3
+
4
+ /** Redaction set members shorter than this many UTF-8 bytes are left out by the protocol. */
5
+ export const minimumRedactionMemberBytes = 8;
6
+
7
+ const redactionReplacement = '***';
8
+ const textEncoder = new TextEncoder();
9
+
10
+ /** The secret-bearing values of one lease: job secret values and npm grant tokens. */
11
+ export interface IRedactionSource {
12
+ job: { secrets: Readonly<Record<string, string>> };
13
+ npmGrants?: readonly { secret: string }[];
14
+ }
15
+
16
+ const membersFor = (values: Iterable<string>): string[] => {
17
+ const members = new Set<string>();
18
+ for (const value of values) {
19
+ const candidates = [value];
20
+ const lines = value.split(/\r\n|\n|\r/);
21
+ if (lines.length > 1) candidates.push(...lines);
22
+ for (const candidate of candidates) {
23
+ if (utf8Length(candidate) >= minimumRedactionMemberBytes) members.add(candidate);
24
+ }
25
+ }
26
+ return [...members].sort((left, right) => right.length - left.length);
27
+ };
28
+
29
+ /**
30
+ * The redaction set of an attempt: every secret value, every npm grant token, and each line of a
31
+ * multi-line value, leaving out members shorter than eight UTF-8 bytes.
32
+ */
33
+ export class SecretRedactionSet implements ISecretRedactionSet {
34
+ readonly members: readonly string[];
35
+ private readonly membersByFirstCodeUnit: ReadonlyMap<number, readonly string[]>;
36
+ private readonly memberBytes: readonly Uint8Array[];
37
+
38
+ constructor(values: Iterable<string>) {
39
+ this.members = Object.freeze(membersFor(values));
40
+ const byFirst = new Map<number, string[]>();
41
+ for (const member of this.members) {
42
+ const first = member.charCodeAt(0);
43
+ const entries = byFirst.get(first);
44
+ if (entries) entries.push(member);
45
+ else byFirst.set(first, [member]);
46
+ }
47
+ this.membersByFirstCodeUnit = byFirst;
48
+ this.memberBytes = Object.freeze(this.members.map((member) => textEncoder.encode(member)));
49
+ }
50
+
51
+ static forLease(source: IRedactionSource): SecretRedactionSet {
52
+ return new SecretRedactionSet([
53
+ ...Object.values(source.job.secrets),
54
+ ...(source.npmGrants ?? []).map((grant) => grant.secret),
55
+ ]);
56
+ }
57
+
58
+ get empty(): boolean {
59
+ return this.members.length === 0;
60
+ }
61
+
62
+ /** The longest member in UTF-16 code units, the look-ahead a streaming redactor retains. */
63
+ get maximumMemberLength(): number {
64
+ return this.members[0]?.length ?? 0;
65
+ }
66
+
67
+ /** The longest member at `index` of `text`, when one starts there. */
68
+ memberAt(text: string, index: number): string | undefined {
69
+ const candidates = this.membersByFirstCodeUnit.get(text.charCodeAt(index));
70
+ return candidates?.find((member) => text.startsWith(member, index));
71
+ }
72
+
73
+ /** Whether any member occurs in `text`. */
74
+ occursIn(text: string): boolean {
75
+ return this.members.some((member) => text.includes(member));
76
+ }
77
+
78
+ /** A streaming matcher over bytes that reports whether any member occurs in them. */
79
+ createContentMatcher(): SecretContentMatcher {
80
+ return new SecretContentMatcher(this.memberBytes);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Aho-Corasick matcher over the UTF-8 bytes of the redaction set. It is fed a byte stream in
86
+ * arbitrary chunks and detects members that span chunk boundaries. Transitions live in one map
87
+ * keyed by `state * 256 + byte`, so memory stays proportional to the total member bytes.
88
+ */
89
+ export class SecretContentMatcher implements ISecretContentMatcher {
90
+ private readonly transitions = new Map<number, number>();
91
+ private readonly failure: number[] = [0];
92
+ private readonly terminal: boolean[] = [false];
93
+ private state = 0;
94
+ private matched = false;
95
+
96
+ constructor(members: readonly Uint8Array[]) {
97
+ const children: number[][] = [[]];
98
+ for (const member of members) {
99
+ let current = 0;
100
+ for (const byte of member) {
101
+ let next = this.transitions.get(current * 256 + byte);
102
+ if (next === undefined) {
103
+ next = this.failure.length;
104
+ this.failure.push(0);
105
+ this.terminal.push(false);
106
+ children.push([]);
107
+ this.transitions.set(current * 256 + byte, next);
108
+ children[current].push(byte);
109
+ }
110
+ current = next;
111
+ }
112
+ this.terminal[current] = true;
113
+ }
114
+ const queue = children[0].map((byte) => this.transitions.get(byte)!);
115
+ for (let head = 0; head < queue.length; head++) {
116
+ const current = queue[head];
117
+ for (const byte of children[current]) {
118
+ const child = this.transitions.get(current * 256 + byte)!;
119
+ let fallback = this.failure[current];
120
+ while (fallback !== 0 && !this.transitions.has(fallback * 256 + byte)) {
121
+ fallback = this.failure[fallback];
122
+ }
123
+ this.failure[child] = this.transitions.get(fallback * 256 + byte) ?? 0;
124
+ this.terminal[child] ||= this.terminal[this.failure[child]];
125
+ queue.push(child);
126
+ }
127
+ }
128
+ }
129
+
130
+ /** Feeds bytes and returns whether a member has occurred anywhere in the stream so far. */
131
+ push(bytes: Uint8Array): boolean {
132
+ if (this.matched || this.failure.length === 1) return this.matched;
133
+ let state = this.state;
134
+ for (const byte of bytes) {
135
+ let next = this.transitions.get(state * 256 + byte);
136
+ while (next === undefined && state !== 0) {
137
+ state = this.failure[state];
138
+ next = this.transitions.get(state * 256 + byte);
139
+ }
140
+ state = next ?? 0;
141
+ if (this.terminal[state]) {
142
+ this.matched = true;
143
+ break;
144
+ }
145
+ }
146
+ this.state = state;
147
+ return this.matched;
148
+ }
149
+
150
+ get found(): boolean {
151
+ return this.matched;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Replaces every member occurring in one text stream with `***`, retaining just enough look-ahead
157
+ * to catch members split across writes.
158
+ */
1
159
  export class StreamingSecretRedactor {
2
- private readonly secrets: string[];
3
- private readonly maximumSecretLength: number;
4
160
  private buffer = '';
5
161
 
6
- constructor(secrets: Iterable<string>) {
7
- this.secrets = [...new Set([...secrets].filter((secret) => secret.length > 0))]
8
- .sort((left, right) => right.length - left.length);
9
- this.maximumSecretLength = this.secrets.reduce(
10
- (maximum, secret) => Math.max(maximum, secret.length),
11
- 0,
12
- );
13
- }
162
+ constructor(private readonly redactionSet: SecretRedactionSet) {}
14
163
 
15
164
  push(chunk: string): string {
16
- if (this.secrets.length === 0) return chunk;
165
+ if (this.redactionSet.empty) return chunk;
17
166
  this.buffer += chunk;
18
167
  return this.consume(false);
19
168
  }
20
169
 
21
170
  flush(): string {
22
- if (this.secrets.length === 0) return '';
171
+ if (this.redactionSet.empty) return '';
23
172
  return this.consume(true);
24
173
  }
25
174
 
26
175
  private consume(flush: boolean): string {
176
+ const buffer = this.buffer;
177
+ const lookAhead = this.redactionSet.maximumMemberLength;
27
178
  let output = '';
28
- while (this.buffer.length > 0 && (flush || this.buffer.length >= this.maximumSecretLength)) {
29
- const matchingSecret = this.secrets.find((secret) => this.buffer.startsWith(secret));
30
- if (matchingSecret) {
31
- output += '***';
32
- this.buffer = this.buffer.slice(matchingSecret.length);
179
+ let index = 0;
180
+ while (index < buffer.length && (flush || buffer.length - index >= lookAhead)) {
181
+ const member = this.redactionSet.memberAt(buffer, index);
182
+ if (member) {
183
+ output += redactionReplacement;
184
+ index += member.length;
33
185
  } else {
34
- const [firstCodePoint] = this.buffer;
35
- output += firstCodePoint;
36
- this.buffer = this.buffer.slice(firstCodePoint.length);
186
+ const width = (buffer.codePointAt(index) ?? 0) > 0xffff ? 2 : 1;
187
+ output += buffer.slice(index, index + width);
188
+ index += width;
37
189
  }
38
190
  }
191
+ this.buffer = buffer.slice(index);
39
192
  return output;
40
193
  }
41
194
  }
195
+
196
+ export interface IRedactedLogSegment {
197
+ stream: TLogStream;
198
+ data: string;
199
+ }
200
+
201
+ /**
202
+ * Redacts the attempt's log output in emission order across all streams, so that no log chunk and
203
+ * no concatenation of consecutive chunks contains a member. A replacement spanning streams is
204
+ * attributed to the stream in which the member started.
205
+ */
206
+ export class LogSequenceRedactor {
207
+ private text = '';
208
+ private streams: TLogStream[] = [];
209
+
210
+ constructor(private readonly redactionSet: SecretRedactionSet) {}
211
+
212
+ push(stream: TLogStream, data: string): IRedactedLogSegment[] {
213
+ if (data.length === 0) return [];
214
+ if (this.redactionSet.empty) return [{ stream, data }];
215
+ this.text += data;
216
+ for (let index = 0; index < data.length; index++) this.streams.push(stream);
217
+ return this.consume(false);
218
+ }
219
+
220
+ flush(): IRedactedLogSegment[] {
221
+ if (this.redactionSet.empty) return [];
222
+ return this.consume(true);
223
+ }
224
+
225
+ private consume(flush: boolean): IRedactedLogSegment[] {
226
+ const text = this.text;
227
+ const lookAhead = this.redactionSet.maximumMemberLength;
228
+ const segments: IRedactedLogSegment[] = [];
229
+ const emit = (stream: TLogStream, data: string): void => {
230
+ const last = segments[segments.length - 1];
231
+ if (last && last.stream === stream) last.data += data;
232
+ else segments.push({ stream, data });
233
+ };
234
+ let index = 0;
235
+ while (index < text.length && (flush || text.length - index >= lookAhead)) {
236
+ const member = this.redactionSet.memberAt(text, index);
237
+ if (member) {
238
+ emit(this.streams[index], redactionReplacement);
239
+ index += member.length;
240
+ } else {
241
+ const width = (text.codePointAt(index) ?? 0) > 0xffff ? 2 : 1;
242
+ emit(this.streams[index], text.slice(index, index + width));
243
+ index += width;
244
+ }
245
+ }
246
+ this.text = text.slice(index);
247
+ this.streams = this.streams.slice(index);
248
+ return segments;
249
+ }
250
+ }
@@ -1,10 +1,9 @@
1
1
  import { join } from '@std/path';
2
2
  import { ConfigurationError, RunnerError } from './errors.ts';
3
3
  import type { IRegisterRunnerRequest } from './interfaces.ts';
4
- import { runnerProtocolIdentifier } from './interfaces.ts';
5
4
  import { canonicalizeJson, createRunnerCapabilitySnapshot } from './protocol-validator.ts';
5
+ import { validateWireMessage } from './wire-schema.ts';
6
6
 
7
- const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
8
7
  const journalName = 'pending-registration.json';
9
8
  const maximumJournalBytes = 64 * 1024;
10
9
 
@@ -14,55 +13,23 @@ export type TRegistrationRequestTemplate = Omit<
14
13
  >;
15
14
 
16
15
  const validateRegistrationRequest = (value: unknown): IRegisterRunnerRequest => {
17
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
18
- throw new RunnerError('Registration journal must contain a JSON object');
19
- }
20
- const record = value as Record<string, unknown>;
21
- const requiredKeys = [
22
- 'registrationRequestId',
23
- 'protocol',
24
- 'runnerVersion',
25
- 'name',
26
- 'capabilities',
27
- ];
28
- if (
29
- Object.keys(record).length !== requiredKeys.length ||
30
- requiredKeys.some((key) => !Object.hasOwn(record, key)) ||
31
- Object.keys(record).some((key) => !requiredKeys.includes(key))
32
- ) {
33
- throw new RunnerError('Registration journal has an invalid shape');
34
- }
35
- if (
36
- typeof record.registrationRequestId !== 'string' ||
37
- !identifierPattern.test(record.registrationRequestId)
38
- ) {
39
- throw new RunnerError('Registration journal contains an invalid registrationRequestId');
40
- }
41
- if (record.protocol !== runnerProtocolIdentifier) {
42
- throw new RunnerError('Registration journal contains an invalid protocol');
43
- }
44
- if (
45
- typeof record.runnerVersion !== 'string' || record.runnerVersion.length < 1 ||
46
- record.runnerVersion.length > 64
47
- ) {
48
- throw new RunnerError('Registration journal contains an invalid runnerVersion');
49
- }
50
- if (typeof record.name !== 'string' || record.name.length < 1 || record.name.length > 128) {
51
- throw new RunnerError('Registration journal contains an invalid name');
16
+ let request: IRegisterRunnerRequest;
17
+ try {
18
+ request = validateWireMessage<IRegisterRunnerRequest>('RegisterRunnerRequest', value);
19
+ } catch (error) {
20
+ throw new RunnerError('Registration journal has an invalid shape', { cause: error });
52
21
  }
53
22
  return {
54
- registrationRequestId: record.registrationRequestId,
55
- protocol: runnerProtocolIdentifier,
56
- runnerVersion: record.runnerVersion,
57
- name: record.name,
58
- capabilities: createRunnerCapabilitySnapshot(
59
- record.capabilities as IRegisterRunnerRequest['capabilities'],
60
- ),
23
+ registrationRequestId: request.registrationRequestId,
24
+ spec: request.spec,
25
+ runnerVersion: request.runnerVersion,
26
+ name: request.name,
27
+ capabilities: createRunnerCapabilitySnapshot(request.capabilities),
61
28
  };
62
29
  };
63
30
 
64
31
  const withoutRequestId = (request: IRegisterRunnerRequest): TRegistrationRequestTemplate => ({
65
- protocol: request.protocol,
32
+ spec: request.spec,
66
33
  runnerVersion: request.runnerVersion,
67
34
  name: request.name,
68
35
  capabilities: request.capabilities,
@@ -88,7 +55,7 @@ export class RegistrationStateStore {
88
55
 
89
56
  async loadOrCreate(
90
57
  template: TRegistrationRequestTemplate,
91
- createRequestId: () => string = crypto.randomUUID,
58
+ createRequestId: () => string = () => crypto.randomUUID(),
92
59
  ): Promise<IRegisterRunnerRequest> {
93
60
  const candidate = validateRegistrationRequest({
94
61
  registrationRequestId: 'pending-validation',
package/ts/runner.ts CHANGED
@@ -21,9 +21,10 @@ import type {
21
21
  IJobHeartbeatRequest,
22
22
  IJobHeartbeatResponse,
23
23
  IJobIdentity,
24
- IJobLease,
25
24
  ILogAcknowledgement,
26
25
  ILogChunk,
26
+ IOciJobLease,
27
+ IOciRuntimeFacts,
27
28
  IPreparedOciLease,
28
29
  IPreparedWorkspace,
29
30
  IProtocolLimits,
@@ -40,9 +41,16 @@ import type {
40
41
  TExecutionStopReason,
41
42
  TJobCompletionStatus,
42
43
  } from './interfaces.ts';
43
- import { runnerProtocolIdentifier, runnerVersion } from './interfaces.ts';
44
+ import { runnerVersion } from './interfaces.ts';
44
45
  import { LogSender } from './log-sender.ts';
45
46
  import { createRunnerCapabilitySnapshot, RunnerProtocolValidator } from './protocol-validator.ts';
47
+ import { SecretRedactionSet } from './redactor.ts';
48
+ import {
49
+ compareSpecVersions,
50
+ lowerSpecVersion,
51
+ runnerSpecVersion,
52
+ specMajorVersionsMatch,
53
+ } from './spec-version.ts';
46
54
  import { scavengeRunnerStaging } from './staging-scavenger.ts';
47
55
 
48
56
  export interface IRunnerCoordinatorClient {
@@ -78,6 +86,8 @@ export interface IRunnerDependencies {
78
86
  onCredential?: (credential: IRunnerCredential) => Promise<void>;
79
87
  onMessage?: (message: string) => void;
80
88
  now?: () => number;
89
+ /** Monotonic milliseconds that measure the attempt deadline; `performance.now` by default. */
90
+ monotonicNow?: () => number;
81
91
  sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
82
92
  }
83
93
 
@@ -118,7 +128,7 @@ const defaultSleep = (milliseconds: number, signal?: AbortSignal): Promise<void>
118
128
  signal?.addEventListener('abort', onAbort, { once: true });
119
129
  });
120
130
 
121
- const identityFor = (runnerId: string, sessionId: string, lease: IJobLease): IJobIdentity => ({
131
+ const identityFor = (runnerId: string, sessionId: string, lease: IOciJobLease): IJobIdentity => ({
122
132
  runnerId,
123
133
  sessionId,
124
134
  jobId: lease.jobId,
@@ -199,18 +209,34 @@ class LeaseGuard {
199
209
  }
200
210
  }
201
211
 
202
- export const runnerCapabilities = (config: IRunnerConfig): IRunnerCapabilities => {
212
+ /**
213
+ * The first specification version that defines the optional capability `resources`. This is a
214
+ * fixed fact of the specification history, not the version this runner implements.
215
+ */
216
+ const resourceLimitsSpecVersion = '1.1.0';
217
+
218
+ /**
219
+ * The capabilities this runner advertises: the `oci` profile in `container` isolation on the
220
+ * native linux platform of its verified OCI engine, the `none` network mode, the configured
221
+ * transfer limits, and the resource ceilings it enforces per attempt.
222
+ */
223
+ export const runnerCapabilities = (
224
+ config: IRunnerConfig,
225
+ runtime: Pick<IOciRuntimeFacts, 'os' | 'architecture'>,
226
+ ): IRunnerCapabilities => {
203
227
  const artifactEnabled = config.maximumArtifacts > 0 && config.maximumArtifactBytes > 0 &&
204
228
  config.maximumArtifactExtractedBytes > 0 && config.maximumArtifactEntries > 0;
205
229
  const cacheEnabled = config.maximumCaches > 0 && config.maximumCacheArchiveBytes > 0 &&
206
230
  config.maximumCacheExtractedBytes > 0 && config.maximumCacheEntries > 0;
207
231
  return createRunnerCapabilitySnapshot({
208
- executionProfiles: ['oci.v1'],
232
+ executionProfiles: ['oci'],
233
+ isolation: ['container'],
234
+ platforms: [`${runtime.os}/${runtime.architecture}`],
209
235
  labels: [...config.labels],
210
236
  features: [
211
237
  'source.tar-gz',
212
- ...(artifactEnabled ? ['artifacts.v1' as const] : []),
213
- ...(cacheEnabled ? ['caches.v1' as const] : []),
238
+ ...(artifactEnabled ? ['artifacts' as const] : []),
239
+ ...(cacheEnabled ? ['caches' as const] : []),
214
240
  ],
215
241
  networks: [...config.oci.allowedNetworks],
216
242
  sourceFormats: ['tar.gz'],
@@ -231,16 +257,38 @@ export const runnerCapabilities = (config: IRunnerConfig): IRunnerCapabilities =
231
257
  maximumWorkspaceBytes: config.oci.workspaceSizeBytes,
232
258
  maximumWorkspaceEntries: config.maximumWorkspaceEntries,
233
259
  },
260
+ resources: {
261
+ maximumMemoryBytes: config.oci.maximumMemoryBytes,
262
+ maximumCpus: config.oci.maximumCpus,
263
+ maximumPids: config.oci.maximumPids,
264
+ maximumSharedMemoryBytes: config.oci.maximumSharedMemoryBytes,
265
+ },
234
266
  });
235
267
  };
236
268
 
269
+ /**
270
+ * Restricts capabilities to the constructs defined at the lower of the coordinator and runner
271
+ * specification versions, the version every non-job message may use.
272
+ */
273
+ export const capabilitiesForCoordinator = (
274
+ capabilities: IRunnerCapabilities,
275
+ discovery: Pick<IDiscoveryResponse, 'spec'>,
276
+ ): IRunnerCapabilities => {
277
+ const messageSpec = lowerSpecVersion(discovery.spec, runnerSpecVersion);
278
+ if (compareSpecVersions(messageSpec, resourceLimitsSpecVersion) >= 0) return capabilities;
279
+ const { resources: _resources, ...withoutResources } = capabilities;
280
+ return createRunnerCapabilitySnapshot(withoutResources);
281
+ };
282
+
237
283
  export const reconcileProtocolLimits = (
238
284
  config: IRunnerConfig,
239
285
  discovery: IDiscoveryResponse,
240
286
  capabilities: IRunnerCapabilities,
241
287
  ): void => {
242
- if (discovery.protocol !== runnerProtocolIdentifier) {
243
- throw new ProtocolError('Coordinator discovery protocol changed during startup');
288
+ if (!specMajorVersionsMatch(discovery.spec, runnerSpecVersion)) {
289
+ throw new ProtocolError(
290
+ `Coordinator specification ${discovery.spec} is incompatible with runner specification ${runnerSpecVersion}`,
291
+ );
244
292
  }
245
293
  if (config.maximumResponseBytes > discovery.limits.maximumJsonBytes) {
246
294
  throw new ProtocolError('Configured JSON response limit exceeds coordinator discovery');
@@ -270,6 +318,7 @@ export class ShipRunner {
270
318
  private drainRequested = false;
271
319
  private sessionInvalid = false;
272
320
  private readonly now: () => number;
321
+ private readonly monotonicNow: () => number;
273
322
  private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
274
323
 
275
324
  constructor(
@@ -277,6 +326,7 @@ export class ShipRunner {
277
326
  private readonly dependencies: IRunnerDependencies,
278
327
  ) {
279
328
  this.now = dependencies.now ?? Date.now;
329
+ this.monotonicNow = dependencies.monotonicNow ?? (() => performance.now());
280
330
  this.sleep = dependencies.sleep ?? defaultSleep;
281
331
  }
282
332
 
@@ -292,15 +342,18 @@ export class ShipRunner {
292
342
  this.sessionInvalid = false;
293
343
  this.dependencies.api.setRunnerToken(this.config.runnerToken);
294
344
 
295
- await this.dependencies.executor.verifyRuntime();
345
+ const runtime = await this.dependencies.executor.verifyRuntime();
296
346
  const discovery = await this.dependencies.api.discover(options.signal);
297
- const capabilities = runnerCapabilities(this.config);
347
+ const capabilities = capabilitiesForCoordinator(
348
+ runnerCapabilities(this.config, runtime),
349
+ discovery,
350
+ );
298
351
  reconcileProtocolLimits(this.config, discovery, capabilities);
299
352
  const validator = new RunnerProtocolValidator(capabilities);
300
353
  const session = await this.dependencies.api.startSession({
301
354
  sessionRequestId: crypto.randomUUID(),
302
355
  runnerId,
303
- protocol: runnerProtocolIdentifier,
356
+ spec: runnerSpecVersion,
304
357
  runnerVersion,
305
358
  capabilities,
306
359
  }, options.signal);
@@ -417,11 +470,16 @@ export class ShipRunner {
417
470
  }
418
471
 
419
472
  const unvalidatedIdentity = safeIdentityFromUnknown(runnerId, sessionId, claim.lease);
420
- let lease: IJobLease;
473
+ let lease: IOciJobLease;
421
474
  try {
422
- lease = await validator.validateJobLease(claim.lease);
475
+ lease = await validator.validateExecutableLease(claim.lease);
423
476
  } catch (error) {
424
477
  if (!unvalidatedIdentity) throw error;
478
+ this.dependencies.onMessage?.(
479
+ `Refused lease ${unvalidatedIdentity.jobId}/${unvalidatedIdentity.attemptId}: ${
480
+ error instanceof Error ? error.message : 'invalid lease'
481
+ }`,
482
+ );
425
483
  await this.abandon(unvalidatedIdentity, 'runner_error');
426
484
  return { claimed: true, status: 'system_error' };
427
485
  }
@@ -592,13 +650,17 @@ export class ShipRunner {
592
650
  private async runAcceptedAttempt(
593
651
  runnerId: string,
594
652
  sessionId: string,
595
- lease: IJobLease,
653
+ lease: IOciJobLease,
596
654
  identity: IJobIdentity,
597
655
  preparedLease: IPreparedOciLease,
598
656
  guard: LeaseGuard,
599
657
  journal: AttemptStateStore,
600
658
  ): Promise<IRunnerRunResult> {
601
659
  const executionAbort = new AbortController();
660
+ // The attempt deadline starts when the acceptance 204 has been received and covers source
661
+ // extraction, cache restoration, and every step. Reaching it terminates execution as a
662
+ // cancellation does, unless an accepted cancellation already did.
663
+ const acceptedAt = this.monotonicNow();
602
664
  const heartbeatLifecycle = new AbortController();
603
665
  const heartbeatState: IHeartbeatState = {};
604
666
  const heartbeat = this.jobHeartbeatLoop(
@@ -609,10 +671,11 @@ export class ShipRunner {
609
671
  heartbeatLifecycle.signal,
610
672
  );
611
673
  const startedAt = new Date(this.now()).toISOString();
674
+ const redactionSet = SecretRedactionSet.forLease(lease);
612
675
  const logs = new LogSender(
613
676
  this.dependencies.api,
614
677
  identity,
615
- Object.values(lease.job.secrets),
678
+ redactionSet,
616
679
  this.config.maximumLogBytes,
617
680
  this.config.maximumLogChunkBytes,
618
681
  guard.controller.signal,
@@ -661,6 +724,9 @@ export class ShipRunner {
661
724
  recordFailure(error);
662
725
  };
663
726
 
727
+ const deadlineTimer = setTimeout(() => {
728
+ if (!executionAbort.signal.aborted) executionAbort.abort('job_timeout');
729
+ }, Math.max(0, lease.job.timeoutMs - (this.monotonicNow() - acceptedAt)));
664
730
  try {
665
731
  if (lease.job.artifacts.length > 0 && !this.dependencies.artifactManager) {
666
732
  throw new RunnerError('Artifact manager is not configured');
@@ -688,6 +754,10 @@ export class ShipRunner {
688
754
  lease,
689
755
  preparedLease,
690
756
  workspacePath: stagingWorkspace.path,
757
+ timeoutMs: Math.max(
758
+ 0,
759
+ Math.ceil(lease.job.timeoutMs - (this.monotonicNow() - acceptedAt)),
760
+ ),
691
761
  signal: executionSignal,
692
762
  terminationDeadline: () => heartbeatState.cancellationDeadline,
693
763
  onLog: (stream, data) => logs.write(stream, data),
@@ -699,6 +769,11 @@ export class ShipRunner {
699
769
  } catch (error) {
700
770
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
701
771
  else if (
772
+ executionAbort.signal.reason === 'job_timeout' && !guard.controller.signal.aborted
773
+ ) {
774
+ status = 'timed_out';
775
+ exitCode = null;
776
+ } else if (
702
777
  executionAbort.signal.reason === 'job_canceled' && heartbeatState.cancellation &&
703
778
  !guard.controller.signal.aborted
704
779
  ) {
@@ -706,6 +781,11 @@ export class ShipRunner {
706
781
  exitCode = null;
707
782
  } else if (!guard.controller.signal.aborted) recordFailure(error);
708
783
  }
784
+ clearTimeout(deadlineTimer);
785
+ const timedOut = executionAbort.signal.reason === 'job_timeout';
786
+ // Artifact collection and cache publication follow execution and are bounded by the fence
787
+ // only; after the deadline they still archive the artifacts an unsuccessful attempt keeps.
788
+ const transferSignal = timedOut ? guard.controller.signal : executionSignal;
709
789
 
710
790
  if (!cleanupFailure && !guard.controller.signal.aborted) {
711
791
  try {
@@ -722,22 +802,23 @@ export class ShipRunner {
722
802
  recordFailure(heartbeatState.systemFailure);
723
803
  }
724
804
  if (
725
- heartbeatState.cancellation && status !== 'system_error' &&
805
+ heartbeatState.cancellation && !timedOut && status !== 'system_error' &&
726
806
  !guard.controller.signal.aborted
727
807
  ) {
728
808
  status = 'canceled';
729
809
  exitCode = null;
730
810
  }
731
811
 
732
- if (runtimeWorkspace && !cleanupFailure && !executionSignal.aborted) {
812
+ if (runtimeWorkspace && !cleanupFailure && !transferSignal.aborted) {
733
813
  if (lease.job.caches.length > 0) {
734
814
  try {
735
815
  await this.dependencies.cacheManager!.save({
736
816
  workspace: runtimeWorkspace,
737
817
  job: lease.job,
738
818
  status,
819
+ redactionSet,
739
820
  identity,
740
- signal: executionSignal,
821
+ signal: transferSignal,
741
822
  });
742
823
  } catch (error) {
743
824
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
@@ -746,15 +827,16 @@ export class ShipRunner {
746
827
  }
747
828
  if (
748
829
  lease.job.artifacts.length > 0 && !cleanupFailure &&
749
- !executionSignal.aborted
830
+ !transferSignal.aborted
750
831
  ) {
751
832
  try {
752
833
  await this.dependencies.artifactManager!.upload({
753
834
  workspace: runtimeWorkspace,
754
835
  job: lease.job,
755
836
  status,
837
+ redactionSet,
756
838
  identity,
757
- signal: executionSignal,
839
+ signal: transferSignal,
758
840
  });
759
841
  } catch (error) {
760
842
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
@@ -791,7 +873,7 @@ export class ShipRunner {
791
873
  recordFailure(heartbeatState.systemFailure);
792
874
  }
793
875
  if (
794
- heartbeatState.cancellation && status !== 'system_error' &&
876
+ heartbeatState.cancellation && !timedOut && status !== 'system_error' &&
795
877
  !guard.controller.signal.aborted
796
878
  ) {
797
879
  status = 'canceled';