@ship.zone/runner 5.0.1 → 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/ts/runner.ts CHANGED
@@ -49,6 +49,7 @@ import { runnerVersion } from './interfaces.js';
49
49
  import { LogSender } from './log-sender.js';
50
50
  import { createRunnerCapabilitySnapshot, RunnerProtocolValidator } from './protocol-validator.js';
51
51
  import { SecretRedactionSet } from './redactor.js';
52
+ import { type IResourceBudgetHostProbe, RunnerResourceBudget } from './resource-budget.js';
52
53
  import { runnerSpecVersion, specMajorVersionsMatch } from './spec-version.js';
53
54
  import { scavengeRunnerStaging } from './staging-scavenger.js';
54
55
  import type { RunnerStateOwner } from './state-owner.js';
@@ -92,6 +93,8 @@ export interface IRunnerDependencies {
92
93
  /** Monotonic milliseconds that measure the attempt deadline; `performance.now` by default. */
93
94
  monotonicNow?: () => number;
94
95
  sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
96
+ /** Optional host resource probe for deterministic concurrency testing. */
97
+ hostProbe?: IResourceBudgetHostProbe;
95
98
  }
96
99
 
97
100
  interface IHeartbeatState {
@@ -346,6 +349,7 @@ export class ShipRunner {
346
349
  if (session.credential) await this.applyCredential(session.credential);
347
350
 
348
351
  const journal = new AttemptStateStore(stateOwner);
352
+ const budget = new RunnerResourceBudget(this.config, runtime, this.dependencies.hostProbe);
349
353
  const sessionLifecycle = new AbortController();
350
354
  const externalAbort = (): void => sessionLifecycle.abort('runner_shutdown');
351
355
  options.signal?.addEventListener('abort', externalAbort, { once: true });
@@ -356,6 +360,7 @@ export class ShipRunner {
356
360
  const runnerHeartbeat = this.runnerHeartbeatLoop(
357
361
  runnerId,
358
362
  session.sessionId,
363
+ budget,
359
364
  sessionLifecycle,
360
365
  ).catch((error) => {
361
366
  heartbeatError = error;
@@ -363,9 +368,39 @@ export class ShipRunner {
363
368
  });
364
369
  let operationError: unknown;
365
370
  let lastResult: IRunnerRunResult = { claimed: false };
371
+ const inFlight = new Map<string, Promise<void>>();
372
+ let wakeWaiters: Array<() => void> = [];
373
+ const notifyCapacityChange = (): void => {
374
+ const current = wakeWaiters;
375
+ wakeWaiters = [];
376
+ for (const resolveWake of current) resolveWake();
377
+ };
378
+ const waitUntilCapacityOrDelay = async (
379
+ delayMs: number,
380
+ signal: AbortSignal,
381
+ ): Promise<void> => {
382
+ if (signal.aborted) return;
383
+ const wakeController = new AbortController();
384
+ const onParentAbort = (): void => wakeController.abort(signal.reason);
385
+ signal.addEventListener('abort', onParentAbort, { once: true });
386
+ const onWake = (): void => {
387
+ if (!wakeController.signal.aborted) wakeController.abort('capacity_changed');
388
+ };
389
+ wakeWaiters.push(onWake);
390
+ try {
391
+ await this.sleep(delayMs, wakeController.signal);
392
+ } catch (error) {
393
+ if (wakeController.signal.reason === 'capacity_changed' && !signal.aborted) return;
394
+ throw error;
395
+ } finally {
396
+ signal.removeEventListener('abort', onParentAbort);
397
+ wakeWaiters = wakeWaiters.filter((fn) => fn !== onWake);
398
+ }
399
+ };
400
+
366
401
  try {
367
402
  await this.dependencies.executor.reconcileOrphans(runnerId, session.sessionId);
368
- await this.recoverInterruptedAttempt(
403
+ await this.recoverInterruptedAttempts(
369
404
  journal,
370
405
  runnerId,
371
406
  session.sessionId,
@@ -374,22 +409,107 @@ export class ShipRunner {
374
409
  while (
375
410
  !this.drainRequested && !this.sessionInvalid && !sessionLifecycle.signal.aborted
376
411
  ) {
377
- lastResult = await this.runOnce(
412
+ if (!budget.canClaimAnother()) {
413
+ if (options.once) break;
414
+ await waitUntilCapacityOrDelay(this.config.pollIntervalMs, sessionLifecycle.signal);
415
+ continue;
416
+ }
417
+ const claimStartedAt = this.now();
418
+ const claim = await this.dependencies.api.claimJob({
419
+ claimRequestId: plugins.crypto.randomUUID(),
420
+ runnerId,
421
+ sessionId: session.sessionId,
422
+ availableResources: budget.available(),
423
+ }, sessionLifecycle.signal);
424
+ const claimElapsedMs = Math.max(0, this.now() - claimStartedAt);
425
+ if (claim.lease === null) {
426
+ lastResult = { claimed: false };
427
+ if (options.once) break;
428
+ const waitMs = Math.max(this.config.pollIntervalMs, claim.retryAfterMs ?? 0);
429
+ await waitUntilCapacityOrDelay(waitMs, sessionLifecycle.signal);
430
+ continue;
431
+ }
432
+
433
+ const unvalidatedIdentity = safeIdentityFromUnknown(
378
434
  runnerId,
379
435
  session.sessionId,
380
- validator,
381
- discovery.limits,
382
- journal,
383
- sessionLifecycle.signal,
436
+ claim.lease,
384
437
  );
385
- if (options.once) break;
386
- if (!lastResult.claimed) {
387
- await this.sleep(this.config.pollIntervalMs, sessionLifecycle.signal);
438
+ let lease: IOciJobLease;
439
+ try {
440
+ lease = await validator.validateExecutableLease(claim.lease);
441
+ } catch (error) {
442
+ if (!unvalidatedIdentity) throw error;
443
+ this.dependencies.onMessage?.(
444
+ `Refused lease ${unvalidatedIdentity.jobId}/${unvalidatedIdentity.attemptId}: ${
445
+ error instanceof Error ? error.message : 'invalid lease'
446
+ }`,
447
+ );
448
+ await this.abandon(unvalidatedIdentity, 'runner_error');
449
+ lastResult = { claimed: true, status: 'system_error' };
450
+ if (options.once) break;
451
+ continue;
388
452
  }
453
+
454
+ if (options.once) {
455
+ budget.reserve(lease.attemptId, lease);
456
+ try {
457
+ lastResult = await this.executeValidatedLease(
458
+ runnerId,
459
+ session.sessionId,
460
+ claim,
461
+ claimElapsedMs,
462
+ lease,
463
+ discovery.limits,
464
+ journal,
465
+ sessionLifecycle.signal,
466
+ );
467
+ } finally {
468
+ budget.release(lease.attemptId);
469
+ }
470
+ break;
471
+ }
472
+
473
+ budget.reserve(lease.attemptId, lease);
474
+ const attemptTask = (async (): Promise<void> => {
475
+ try {
476
+ lastResult = await this.executeValidatedLease(
477
+ runnerId,
478
+ session.sessionId,
479
+ claim,
480
+ claimElapsedMs,
481
+ lease,
482
+ discovery.limits,
483
+ journal,
484
+ sessionLifecycle.signal,
485
+ );
486
+ } catch (error) {
487
+ if (error instanceof ResourceCleanupError) {
488
+ this.sessionInvalid = true;
489
+ operationError ??= error;
490
+ if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('runner_shutdown');
491
+ } else if (!sessionLifecycle.signal.aborted) {
492
+ operationError ??= error;
493
+ sessionLifecycle.abort('runner_shutdown');
494
+ }
495
+ } finally {
496
+ budget.release(lease.attemptId);
497
+ inFlight.delete(lease.attemptId);
498
+ notifyCapacityChange();
499
+ }
500
+ })();
501
+ inFlight.set(lease.attemptId, attemptTask);
502
+ }
503
+ if (inFlight.size > 0) {
504
+ await Promise.allSettled(inFlight.values());
389
505
  }
390
506
  } catch (error) {
391
507
  if (error instanceof ResourceCleanupError) this.sessionInvalid = true;
392
- operationError = error;
508
+ operationError ??= error;
509
+ if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('runner_shutdown');
510
+ if (inFlight.size > 0) {
511
+ await Promise.allSettled(inFlight.values());
512
+ }
393
513
  } finally {
394
514
  if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('runner_shutdown');
395
515
  options.signal?.removeEventListener('abort', externalAbort);
@@ -409,66 +529,41 @@ export class ShipRunner {
409
529
  return lastResult;
410
530
  }
411
531
 
412
- private async recoverInterruptedAttempt(
532
+ private async recoverInterruptedAttempts(
413
533
  journal: AttemptStateStore,
414
534
  runnerId: string,
415
535
  sessionId: string,
416
536
  signal: AbortSignal,
417
537
  ): Promise<void> {
418
- const interrupted = await journal.load();
419
- if (!interrupted) return;
420
- try {
421
- await this.dependencies.api.recoverAttempt({
422
- recoveryRequestId: plugins.crypto.randomUUID(),
423
- runnerId,
424
- currentSessionId: sessionId,
425
- previousSessionId: interrupted.previousSessionId,
426
- jobId: interrupted.jobId,
427
- attemptId: interrupted.attemptId,
428
- reason: 'runner_restarted',
429
- }, signal);
430
- } catch (error) {
431
- if (!isDefinitiveConflict(error)) throw error;
538
+ const interruptedEntries = await journal.loadAll();
539
+ for (const interrupted of interruptedEntries) {
540
+ try {
541
+ await this.dependencies.api.recoverAttempt({
542
+ recoveryRequestId: plugins.crypto.randomUUID(),
543
+ runnerId,
544
+ currentSessionId: sessionId,
545
+ previousSessionId: interrupted.previousSessionId,
546
+ jobId: interrupted.jobId,
547
+ attemptId: interrupted.attemptId,
548
+ reason: 'runner_restarted',
549
+ }, signal);
550
+ } catch (error) {
551
+ if (!isDefinitiveConflict(error)) throw error;
552
+ }
553
+ await journal.remove(interrupted.attemptId);
432
554
  }
433
- await journal.clear();
434
555
  }
435
556
 
436
- private async runOnce(
557
+ private async executeValidatedLease(
437
558
  runnerId: string,
438
559
  sessionId: string,
439
- validator: RunnerProtocolValidator,
560
+ claim: IClaimJobResponse,
561
+ claimElapsedMs: number,
562
+ lease: IOciJobLease,
440
563
  protocolLimits: IProtocolLimits,
441
564
  journal: AttemptStateStore,
442
565
  runnerSignal: AbortSignal,
443
566
  ): Promise<IRunnerRunResult> {
444
- const claimStartedAt = this.now();
445
- const claim = await this.dependencies.api.claimJob({
446
- claimRequestId: plugins.crypto.randomUUID(),
447
- runnerId,
448
- sessionId,
449
- }, runnerSignal);
450
- const claimElapsedMs = Math.max(0, this.now() - claimStartedAt);
451
- if (claim.lease === null) {
452
- if (claim.retryAfterMs && claim.retryAfterMs > this.config.pollIntervalMs) {
453
- await this.sleep(claim.retryAfterMs - this.config.pollIntervalMs, runnerSignal);
454
- }
455
- return { claimed: false };
456
- }
457
-
458
- const unvalidatedIdentity = safeIdentityFromUnknown(runnerId, sessionId, claim.lease);
459
- let lease: IOciJobLease;
460
- try {
461
- lease = await validator.validateExecutableLease(claim.lease);
462
- } catch (error) {
463
- if (!unvalidatedIdentity) throw error;
464
- this.dependencies.onMessage?.(
465
- `Refused lease ${unvalidatedIdentity.jobId}/${unvalidatedIdentity.attemptId}: ${
466
- error instanceof Error ? error.message : 'invalid lease'
467
- }`,
468
- );
469
- await this.abandon(unvalidatedIdentity, 'runner_error');
470
- return { claimed: true, status: 'system_error' };
471
- }
472
567
 
473
568
  const identity = identityFor(runnerId, sessionId, lease);
474
569
  const guard = new LeaseGuard(protocolLimits, this.config.leaseSafetyMarginMs);
@@ -549,7 +644,7 @@ export class ShipRunner {
549
644
  }
550
645
 
551
646
  try {
552
- await journal.save({
647
+ await journal.add({
553
648
  previousSessionId: sessionId,
554
649
  jobId: lease.jobId,
555
650
  attemptId: lease.attemptId,
@@ -591,7 +686,7 @@ export class ShipRunner {
591
686
  );
592
687
  }
593
688
  if (isDefinitiveConflict(error)) {
594
- await journal.clear();
689
+ await journal.remove(identity.attemptId);
595
690
  return { claimed: true, status: 'system_error' };
596
691
  }
597
692
  if (guard.controller.signal.reason === 'runner_shutdown') {
@@ -914,7 +1009,7 @@ export class ShipRunner {
914
1009
  return { claimed: true, status: 'system_error' };
915
1010
  }
916
1011
  if (fenceReason === 'lease_lost' || fenceReason === 'lease_expired') {
917
- if (guard.definitive) await journal.clear();
1012
+ if (guard.definitive) await journal.remove(identity.attemptId);
918
1013
  else this.sessionInvalid = true;
919
1014
  if (heartbeatState.terminalError !== undefined) throw heartbeatState.terminalError;
920
1015
  return { claimed: true, status };
@@ -951,10 +1046,10 @@ export class ShipRunner {
951
1046
  };
952
1047
  try {
953
1048
  await this.dependencies.api.completeJob(completion);
954
- await journal.clear();
1049
+ await journal.remove(identity.attemptId);
955
1050
  } catch (error) {
956
1051
  if (isDefinitiveConflict(error)) {
957
- await journal.clear();
1052
+ await journal.remove(identity.attemptId);
958
1053
  } else {
959
1054
  throw error;
960
1055
  }
@@ -1070,12 +1165,13 @@ export class ShipRunner {
1070
1165
  private async runnerHeartbeatLoop(
1071
1166
  runnerId: string,
1072
1167
  sessionId: string,
1168
+ budget: RunnerResourceBudget,
1073
1169
  lifecycle: AbortController,
1074
1170
  ): Promise<void> {
1075
1171
  while (!lifecycle.signal.aborted) {
1076
1172
  try {
1077
1173
  const heartbeat = await this.dependencies.api.heartbeatRunner(
1078
- { runnerId, sessionId },
1174
+ { runnerId, sessionId, availableResources: budget.available() },
1079
1175
  lifecycle.signal,
1080
1176
  );
1081
1177
  this.drainRequested ||= heartbeat.drainRequested;
@@ -1115,7 +1211,7 @@ export class ShipRunner {
1115
1211
  } catch (error) {
1116
1212
  if (!isDefinitiveConflict(error)) throw error;
1117
1213
  }
1118
- await journal?.clear();
1214
+ await journal?.remove(identity.attemptId);
1119
1215
  }
1120
1216
 
1121
1217
  private async applyCredential(credential: IRunnerCredential): Promise<void> {