@ship.zone/runner 0.2.4 → 1.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/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,
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,37 @@ class LeaseGuard {
199
209
  }
200
210
  }
201
211
 
202
- export const runnerCapabilities = (config: IRunnerConfig): IRunnerCapabilities => {
212
+ /**
213
+ * The first specification versions that define the optional capabilities: `resources` from
214
+ * 1.1.0, `leaseFeatures` and `maximumTimeoutMs` from 1.2.0. These are fixed facts of the
215
+ * specification history, not the version this runner implements.
216
+ */
217
+ const resourceLimitsSpecVersion = '1.1.0';
218
+ const leaseMatchingSpecVersion = '1.2.0';
219
+
220
+ /**
221
+ * The capabilities this runner advertises: the `oci` profile in `container` isolation on the
222
+ * native linux platform of its verified OCI engine, the `none` network mode, the configured
223
+ * transfer limits, the resource ceilings it enforces per attempt, no lease features (it uses no
224
+ * image grants, candidate bindings, or npm read grants), and its configured longest job timeout.
225
+ */
226
+ export const runnerCapabilities = (
227
+ config: IRunnerConfig,
228
+ runtime: Pick<IOciRuntimeFacts, 'os' | 'architecture'>,
229
+ ): IRunnerCapabilities => {
203
230
  const artifactEnabled = config.maximumArtifacts > 0 && config.maximumArtifactBytes > 0 &&
204
231
  config.maximumArtifactExtractedBytes > 0 && config.maximumArtifactEntries > 0;
205
232
  const cacheEnabled = config.maximumCaches > 0 && config.maximumCacheArchiveBytes > 0 &&
206
233
  config.maximumCacheExtractedBytes > 0 && config.maximumCacheEntries > 0;
207
234
  return createRunnerCapabilitySnapshot({
208
- executionProfiles: ['oci.v1'],
235
+ executionProfiles: ['oci'],
236
+ isolation: ['container'],
237
+ platforms: [`${runtime.os}/${runtime.architecture}`],
209
238
  labels: [...config.labels],
210
239
  features: [
211
240
  'source.tar-gz',
212
- ...(artifactEnabled ? ['artifacts.v1' as const] : []),
213
- ...(cacheEnabled ? ['caches.v1' as const] : []),
241
+ ...(artifactEnabled ? ['artifacts' as const] : []),
242
+ ...(cacheEnabled ? ['caches' as const] : []),
214
243
  ],
215
244
  networks: [...config.oci.allowedNetworks],
216
245
  sourceFormats: ['tar.gz'],
@@ -231,6 +260,35 @@ export const runnerCapabilities = (config: IRunnerConfig): IRunnerCapabilities =
231
260
  maximumWorkspaceBytes: config.oci.workspaceSizeBytes,
232
261
  maximumWorkspaceEntries: config.maximumWorkspaceEntries,
233
262
  },
263
+ resources: {
264
+ maximumMemoryBytes: config.oci.maximumMemoryBytes,
265
+ maximumCpus: config.oci.maximumCpus,
266
+ maximumPids: config.oci.maximumPids,
267
+ maximumSharedMemoryBytes: config.oci.maximumSharedMemoryBytes,
268
+ },
269
+ leaseFeatures: [],
270
+ maximumTimeoutMs: config.oci.maximumTimeoutMs,
271
+ });
272
+ };
273
+
274
+ /**
275
+ * Restricts capabilities to the constructs defined at the lower of the coordinator and runner
276
+ * specification versions, the version every non-job message may use.
277
+ */
278
+ export const capabilitiesForCoordinator = (
279
+ capabilities: IRunnerCapabilities,
280
+ discovery: Pick<IDiscoveryResponse, 'spec'>,
281
+ ): IRunnerCapabilities => {
282
+ const messageSpec = lowerSpecVersion(discovery.spec, runnerSpecVersion);
283
+ const defines = (since: string): boolean => compareSpecVersions(messageSpec, since) >= 0;
284
+ const { resources, leaseFeatures, maximumTimeoutMs, ...defined } = capabilities;
285
+ return createRunnerCapabilitySnapshot({
286
+ ...defined,
287
+ ...(resources !== undefined && defines(resourceLimitsSpecVersion) ? { resources } : {}),
288
+ ...(leaseFeatures !== undefined && defines(leaseMatchingSpecVersion) ? { leaseFeatures } : {}),
289
+ ...(maximumTimeoutMs !== undefined && defines(leaseMatchingSpecVersion)
290
+ ? { maximumTimeoutMs }
291
+ : {}),
234
292
  });
235
293
  };
236
294
 
@@ -239,8 +297,10 @@ export const reconcileProtocolLimits = (
239
297
  discovery: IDiscoveryResponse,
240
298
  capabilities: IRunnerCapabilities,
241
299
  ): void => {
242
- if (discovery.protocol !== runnerProtocolIdentifier) {
243
- throw new ProtocolError('Coordinator discovery protocol changed during startup');
300
+ if (!specMajorVersionsMatch(discovery.spec, runnerSpecVersion)) {
301
+ throw new ProtocolError(
302
+ `Coordinator specification ${discovery.spec} is incompatible with runner specification ${runnerSpecVersion}`,
303
+ );
244
304
  }
245
305
  if (config.maximumResponseBytes > discovery.limits.maximumJsonBytes) {
246
306
  throw new ProtocolError('Configured JSON response limit exceeds coordinator discovery');
@@ -270,6 +330,7 @@ export class ShipRunner {
270
330
  private drainRequested = false;
271
331
  private sessionInvalid = false;
272
332
  private readonly now: () => number;
333
+ private readonly monotonicNow: () => number;
273
334
  private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
274
335
 
275
336
  constructor(
@@ -277,6 +338,7 @@ export class ShipRunner {
277
338
  private readonly dependencies: IRunnerDependencies,
278
339
  ) {
279
340
  this.now = dependencies.now ?? Date.now;
341
+ this.monotonicNow = dependencies.monotonicNow ?? (() => performance.now());
280
342
  this.sleep = dependencies.sleep ?? defaultSleep;
281
343
  }
282
344
 
@@ -292,15 +354,18 @@ export class ShipRunner {
292
354
  this.sessionInvalid = false;
293
355
  this.dependencies.api.setRunnerToken(this.config.runnerToken);
294
356
 
295
- await this.dependencies.executor.verifyRuntime();
357
+ const runtime = await this.dependencies.executor.verifyRuntime();
296
358
  const discovery = await this.dependencies.api.discover(options.signal);
297
- const capabilities = runnerCapabilities(this.config);
359
+ const capabilities = capabilitiesForCoordinator(
360
+ runnerCapabilities(this.config, runtime),
361
+ discovery,
362
+ );
298
363
  reconcileProtocolLimits(this.config, discovery, capabilities);
299
364
  const validator = new RunnerProtocolValidator(capabilities);
300
365
  const session = await this.dependencies.api.startSession({
301
366
  sessionRequestId: crypto.randomUUID(),
302
367
  runnerId,
303
- protocol: runnerProtocolIdentifier,
368
+ spec: runnerSpecVersion,
304
369
  runnerVersion,
305
370
  capabilities,
306
371
  }, options.signal);
@@ -417,11 +482,16 @@ export class ShipRunner {
417
482
  }
418
483
 
419
484
  const unvalidatedIdentity = safeIdentityFromUnknown(runnerId, sessionId, claim.lease);
420
- let lease: IJobLease;
485
+ let lease: IOciJobLease;
421
486
  try {
422
- lease = await validator.validateJobLease(claim.lease);
487
+ lease = await validator.validateExecutableLease(claim.lease);
423
488
  } catch (error) {
424
489
  if (!unvalidatedIdentity) throw error;
490
+ this.dependencies.onMessage?.(
491
+ `Refused lease ${unvalidatedIdentity.jobId}/${unvalidatedIdentity.attemptId}: ${
492
+ error instanceof Error ? error.message : 'invalid lease'
493
+ }`,
494
+ );
425
495
  await this.abandon(unvalidatedIdentity, 'runner_error');
426
496
  return { claimed: true, status: 'system_error' };
427
497
  }
@@ -592,13 +662,17 @@ export class ShipRunner {
592
662
  private async runAcceptedAttempt(
593
663
  runnerId: string,
594
664
  sessionId: string,
595
- lease: IJobLease,
665
+ lease: IOciJobLease,
596
666
  identity: IJobIdentity,
597
667
  preparedLease: IPreparedOciLease,
598
668
  guard: LeaseGuard,
599
669
  journal: AttemptStateStore,
600
670
  ): Promise<IRunnerRunResult> {
601
671
  const executionAbort = new AbortController();
672
+ // The attempt deadline starts when the acceptance 204 has been received and covers source
673
+ // extraction, cache restoration, and every step. Reaching it terminates execution as a
674
+ // cancellation does, unless an accepted cancellation already did.
675
+ const acceptedAt = this.monotonicNow();
602
676
  const heartbeatLifecycle = new AbortController();
603
677
  const heartbeatState: IHeartbeatState = {};
604
678
  const heartbeat = this.jobHeartbeatLoop(
@@ -609,10 +683,11 @@ export class ShipRunner {
609
683
  heartbeatLifecycle.signal,
610
684
  );
611
685
  const startedAt = new Date(this.now()).toISOString();
686
+ const redactionSet = SecretRedactionSet.forLease(lease);
612
687
  const logs = new LogSender(
613
688
  this.dependencies.api,
614
689
  identity,
615
- Object.values(lease.job.secrets),
690
+ redactionSet,
616
691
  this.config.maximumLogBytes,
617
692
  this.config.maximumLogChunkBytes,
618
693
  guard.controller.signal,
@@ -661,6 +736,9 @@ export class ShipRunner {
661
736
  recordFailure(error);
662
737
  };
663
738
 
739
+ const deadlineTimer = setTimeout(() => {
740
+ if (!executionAbort.signal.aborted) executionAbort.abort('job_timeout');
741
+ }, Math.max(0, lease.job.timeoutMs - (this.monotonicNow() - acceptedAt)));
664
742
  try {
665
743
  if (lease.job.artifacts.length > 0 && !this.dependencies.artifactManager) {
666
744
  throw new RunnerError('Artifact manager is not configured');
@@ -688,6 +766,10 @@ export class ShipRunner {
688
766
  lease,
689
767
  preparedLease,
690
768
  workspacePath: stagingWorkspace.path,
769
+ timeoutMs: Math.max(
770
+ 0,
771
+ Math.ceil(lease.job.timeoutMs - (this.monotonicNow() - acceptedAt)),
772
+ ),
691
773
  signal: executionSignal,
692
774
  terminationDeadline: () => heartbeatState.cancellationDeadline,
693
775
  onLog: (stream, data) => logs.write(stream, data),
@@ -699,6 +781,11 @@ export class ShipRunner {
699
781
  } catch (error) {
700
782
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
701
783
  else if (
784
+ executionAbort.signal.reason === 'job_timeout' && !guard.controller.signal.aborted
785
+ ) {
786
+ status = 'timed_out';
787
+ exitCode = null;
788
+ } else if (
702
789
  executionAbort.signal.reason === 'job_canceled' && heartbeatState.cancellation &&
703
790
  !guard.controller.signal.aborted
704
791
  ) {
@@ -706,6 +793,11 @@ export class ShipRunner {
706
793
  exitCode = null;
707
794
  } else if (!guard.controller.signal.aborted) recordFailure(error);
708
795
  }
796
+ clearTimeout(deadlineTimer);
797
+ const timedOut = executionAbort.signal.reason === 'job_timeout';
798
+ // Artifact collection and cache publication follow execution and are bounded by the fence
799
+ // only; after the deadline they still archive the artifacts an unsuccessful attempt keeps.
800
+ const transferSignal = timedOut ? guard.controller.signal : executionSignal;
709
801
 
710
802
  if (!cleanupFailure && !guard.controller.signal.aborted) {
711
803
  try {
@@ -722,22 +814,23 @@ export class ShipRunner {
722
814
  recordFailure(heartbeatState.systemFailure);
723
815
  }
724
816
  if (
725
- heartbeatState.cancellation && status !== 'system_error' &&
817
+ heartbeatState.cancellation && !timedOut && status !== 'system_error' &&
726
818
  !guard.controller.signal.aborted
727
819
  ) {
728
820
  status = 'canceled';
729
821
  exitCode = null;
730
822
  }
731
823
 
732
- if (runtimeWorkspace && !cleanupFailure && !executionSignal.aborted) {
824
+ if (runtimeWorkspace && !cleanupFailure && !transferSignal.aborted) {
733
825
  if (lease.job.caches.length > 0) {
734
826
  try {
735
827
  await this.dependencies.cacheManager!.save({
736
828
  workspace: runtimeWorkspace,
737
829
  job: lease.job,
738
830
  status,
831
+ redactionSet,
739
832
  identity,
740
- signal: executionSignal,
833
+ signal: transferSignal,
741
834
  });
742
835
  } catch (error) {
743
836
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
@@ -746,15 +839,16 @@ export class ShipRunner {
746
839
  }
747
840
  if (
748
841
  lease.job.artifacts.length > 0 && !cleanupFailure &&
749
- !executionSignal.aborted
842
+ !transferSignal.aborted
750
843
  ) {
751
844
  try {
752
845
  await this.dependencies.artifactManager!.upload({
753
846
  workspace: runtimeWorkspace,
754
847
  job: lease.job,
755
848
  status,
849
+ redactionSet,
756
850
  identity,
757
- signal: executionSignal,
851
+ signal: transferSignal,
758
852
  });
759
853
  } catch (error) {
760
854
  if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
@@ -791,7 +885,7 @@ export class ShipRunner {
791
885
  recordFailure(heartbeatState.systemFailure);
792
886
  }
793
887
  if (
794
- heartbeatState.cancellation && status !== 'system_error' &&
888
+ heartbeatState.cancellation && !timedOut && status !== 'system_error' &&
795
889
  !guard.controller.signal.aborted
796
890
  ) {
797
891
  status = 'canceled';