@defrex/autobuild 1.15.0 → 1.17.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.
Files changed (80) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +110 -10
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +41 -7
  5. package/docs/configuration.md +41 -7
  6. package/docs/dispatcher-hosting.md +3 -0
  7. package/docs/operator-api.md +15 -5
  8. package/docs/plugin-authoring.md +1 -0
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +3 -1
  11. package/docs/restacking.md +41 -1
  12. package/docs/setup.md +15 -6
  13. package/docs/troubleshooting.md +51 -3
  14. package/docs/workspaces.md +4 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/accounts.ts +3 -0
  17. package/packages/core/src/cli/binary-direct.ts +14 -1
  18. package/packages/core/src/cli/binary.ts +10 -7
  19. package/packages/core/src/cli/dispatch.ts +610 -356
  20. package/packages/core/src/cli/secrets.ts +2 -0
  21. package/packages/core/src/config/schema.ts +15 -2
  22. package/packages/core/src/events/payloads.ts +8 -5
  23. package/packages/core/src/events/repository.ts +12 -6
  24. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  25. package/packages/core/src/kernel/engine.ts +118 -0
  26. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  27. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  28. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  29. package/packages/core/src/ontology.ts +1 -0
  30. package/packages/core/src/operator/index.ts +10 -0
  31. package/packages/core/src/operator/merged-builds.ts +51 -0
  32. package/packages/core/src/operator/registry.ts +190 -101
  33. package/packages/core/src/operator/repo-argument.ts +43 -0
  34. package/packages/core/src/ports/tickets/grants.ts +2 -0
  35. package/packages/core/src/ports/tickets/remote.ts +2 -0
  36. package/packages/core/src/ports/types.ts +25 -4
  37. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +811 -169
  39. package/packages/core/src/processes/build-child.ts +15 -1
  40. package/packages/core/src/processes/build-runner.ts +349 -20
  41. package/packages/core/src/processes/dispatcher.ts +509 -104
  42. package/packages/core/src/processes/harvest-child.ts +21 -1
  43. package/packages/core/src/processes/harvest-runner.ts +82 -35
  44. package/packages/core/src/processes/invocation-budget.ts +6 -0
  45. package/packages/core/src/processes/launch-cut.ts +37 -0
  46. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  47. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  48. package/packages/core/src/processes/repo-view.ts +25 -4
  49. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  50. package/packages/core/src/store/adapter.ts +34 -5
  51. package/packages/core/src/store/build-feed.ts +148 -22
  52. package/packages/core/src/store/build-scope.ts +12 -3
  53. package/packages/core/src/store/caller-attribution.ts +170 -0
  54. package/packages/core/src/store/contract.ts +1038 -165
  55. package/packages/core/src/store/local/schema.ts +12 -1
  56. package/packages/core/src/store/local/store.ts +260 -25
  57. package/packages/core/src/store/memory.ts +156 -9
  58. package/packages/core/src/store/phase-session.ts +23 -3
  59. package/packages/core/src/store/reducer-value-shapes.json +5351 -5338
  60. package/packages/core/src/store/remote/client.ts +90 -11
  61. package/packages/core/src/store/remote/credentials.ts +2 -0
  62. package/packages/core/src/store/remote/index.ts +31 -5
  63. package/packages/core/src/store/remote/protocol.ts +45 -8
  64. package/packages/core/src/store/remote/released-clients.json +22 -0
  65. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  66. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  67. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  68. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  69. package/packages/core/src/store/session-handle.ts +12 -3
  70. package/packages/core/src/store/types.ts +48 -3
  71. package/packages/core/src/testing/reduced-read-budget.ts +310 -12
  72. package/skills/guide/SKILL.md +58 -9
  73. package/skills/guide/references/operator-api.md +15 -5
  74. package/skills/guide/references/plugin-authoring.md +1 -0
  75. package/skills/guide/references/remote-store-protocol.md +13 -3
  76. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  77. package/skills/guide/references/restacking.md +41 -1
  78. package/skills/guide/references/setup.md +15 -6
  79. package/skills/operate/SKILL.md +31 -7
  80. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import { withCallerStage } from '../store/caller-attribution'
2
3
  import {
3
4
  recordRetention,
4
5
  restoreRetainedHead,
@@ -360,6 +361,7 @@ import {
360
361
  recoveryStepOf,
361
362
  type WorkspaceRecoveryStep,
362
363
  } from '../ports/workspace/recovery-step'
364
+ import { isLaunchCutByDeadline, type CutLaunch } from './launch-cut'
363
365
  import type {
364
366
  DependencyState,
365
367
  Forge,
@@ -406,6 +408,7 @@ import {
406
408
  } from '../objective'
407
409
  export { specConformance, type SpecConformance } from '../spec-standard'
408
410
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
411
+ import { describeProvisionProgress, provisioningAbandonmentMessage } from './provisioning-progress'
409
412
  import { settleOpenExecution } from './execution-settlement'
410
413
  import { isWorkDigest, RepoViewStore } from './repo-view'
411
414
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
@@ -686,14 +689,18 @@ export interface TickReport {
686
689
  provisioning: number
687
690
  /** Builds whose provisioning start was deferred because the bounded
688
691
  * invocation's remaining budget was shorter than the provider's
689
- * provisioning estimate. Nothing is written; a later invocation starts it. */
692
+ * provisioning estimate, including a first provision right after a claim.
693
+ * The build is recorded in `dispatcher.work-deferred` and the next tick
694
+ * provisions it first. */
690
695
  provisioningDeferred: number
691
696
  /** Builds whose stopped-sandbox recovery, or a launch waiting on one, the
692
- * invocation budget deferred this tick. Nothing is charged; the build is
693
- * recorded in `dispatcher.work-deferred` and the next tick runs it first. */
697
+ * invocation budget deferred this tick, or whose launch the work deadline
698
+ * cut after its execution lease was claimed. Nothing is charged; the build
699
+ * is recorded in `dispatcher.work-deferred` and the next tick runs it
700
+ * first. */
694
701
  recoveryDeferred: number
695
- /** One line per build whose deadline-gated work (a provision or a recovery
696
- * step) this tick deferred for budget, naming the step. */
702
+ /** One line per build whose deadline-gated work (a provision, a cut launch
703
+ * or a recovery step) this tick deferred for budget, naming the step. */
697
704
  deferredDiagnostics: string[]
698
705
  /** Dispatch (§12): builds created and launched. With durable supervision
699
706
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
@@ -873,6 +880,11 @@ interface ProvisionContinuation {
873
880
  readonly instance: string
874
881
  readonly controller: AbortController
875
882
  promise: Promise<void>
883
+ /** The provider's latest reported stage and when it began (clock ms);
884
+ * teardown names it in the abandonment fact. */
885
+ progress?: { label: string; since: number }
886
+ /** When teardown signalled this continuation (clock ms). */
887
+ abortedAt?: number
876
888
  }
877
889
 
878
890
  export interface DispatcherOpts {
@@ -963,8 +975,17 @@ export interface TickOpts {
963
975
  }
964
976
 
965
977
  /** Deadline-gated work a bounded invocation can defer for budget: a
966
- * provision, or a stopped-sandbox recovery step. */
967
- export type DeferredWorkStep = 'provision' | WorkspaceRecoveryStep
978
+ * provision, a runner launch the work deadline cut, or a stopped-sandbox
979
+ * recovery step. */
980
+ export type DeferredWorkStep = 'provision' | 'launch' | WorkspaceRecoveryStep
981
+
982
+ /** One `dispatcher.work-deferred` entry. `instance` names a deadline-cut
983
+ * execution whose exact-holder lease teardown could not settle. */
984
+ interface DeferredWorkEntry {
985
+ slug: string
986
+ step: DeferredWorkStep
987
+ instance?: string
988
+ }
968
989
 
969
990
  /** Most entries one `dispatcher.work-deferred` hint carries. */
970
991
  const MAX_DEFERRED_WORK = 64
@@ -1126,6 +1147,14 @@ function errorText(error: unknown): string {
1126
1147
  return error instanceof Error ? error.message : String(error)
1127
1148
  }
1128
1149
 
1150
+ /** The report and dispatch-log line naming one deferral by build and step. */
1151
+ function deferralLine(slug: string, deferral: { step: DeferredWorkStep; detail?: string }): string {
1152
+ return (
1153
+ `build ${slug}: ${deferral.step} deferred by the invocation budget; the next invocation runs it first` +
1154
+ (deferral.detail !== undefined ? ` — ${deferral.detail}` : '')
1155
+ )
1156
+ }
1157
+
1129
1158
  function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1130
1159
  return error instanceof MissingAccountCredentialsError
1131
1160
  ? error
@@ -1387,7 +1416,16 @@ export class Dispatcher {
1387
1416
  private tickLaunched: ReadonlySet<string> = new Set()
1388
1417
  /** Per tick, in insertion order: builds whose deadline-gated work this tick
1389
1418
  * deferred for budget, with the first step seen and an optional detail. */
1390
- private readonly tickDeferrals = new Map<string, { step: DeferredWorkStep; detail?: string }>()
1419
+ private readonly tickDeferrals = new Map<
1420
+ string,
1421
+ { step: DeferredWorkStep; detail?: string; instance?: string }
1422
+ >()
1423
+ /** Per tick: deferrals already named in a report or teardown line. */
1424
+ private readonly reportedDeferrals = new Set<string>()
1425
+ /** Runner starts in flight in this process, including a deadline-cut
1426
+ * launch's settlement and an intake claim's first dispatch. Bounded
1427
+ * teardown awaits them (`settleCutStarts`). */
1428
+ private readonly startsInFlight = new Set<Promise<unknown>>()
1391
1429
  /** Per tick: carried builds the early stage took up, which the lease sweep
1392
1430
  * then skips so no build is swept twice in one tick. */
1393
1431
  private readonly tickPrioritized = new Set<string>()
@@ -1396,10 +1434,10 @@ export class Dispatcher {
1396
1434
  * after its own early-stage pass showed it no longer needs priority. */
1397
1435
  private readonly carriedOutstanding = new Map<
1398
1436
  string,
1399
- { step: DeferredWorkStep; visited: boolean }
1437
+ { step: DeferredWorkStep; visited: boolean; instance?: string }
1400
1438
  >()
1401
1439
  /** The durable hint as last read or written. */
1402
- private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1440
+ private recordedDeferrals: DeferredWorkEntry[] = []
1403
1441
  /** The current tick's options, for writes made from deferral sites. */
1404
1442
  private tickOpts: TickOpts = {}
1405
1443
  /** Serializes hint writes so concurrent deferral notes never race. */
@@ -1523,7 +1561,8 @@ export class Dispatcher {
1523
1561
  }
1524
1562
 
1525
1563
  /**
1526
- * One cron-friendly pass (§3.3): deferred deadline-gated work → settlement →
1564
+ * One cron-friendly pass (§3.3): deferred deadline-gated work (carried
1565
+ * provisions, cut launches and recoveries) → settlement →
1527
1566
  * janitor → interrupted dispatch recovery → optional startup resume →
1528
1567
  * lease sweep → dispatch. Startup resume is opt-in
1529
1568
  * because the CLI invokes it
@@ -1725,6 +1764,8 @@ export class Dispatcher {
1725
1764
  this.parkedSettled.clear()
1726
1765
  this.deferredAdmissions.clear()
1727
1766
  this.tickDeferrals.clear()
1767
+ this.reportedDeferrals.clear()
1768
+ this.deferralsFinished = false
1728
1769
  this.tickPrioritized.clear()
1729
1770
  this.carriedOutstanding.clear()
1730
1771
  this.deferralWriteFailure = undefined
@@ -1739,7 +1780,11 @@ export class Dispatcher {
1739
1780
  // The durable deferral hint from the previous invocation: zero extra
1740
1781
  // reads, it is part of the repository facts the refresh reduced.
1741
1782
  this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1742
- ({ slug, step }) => ({ slug, step }),
1783
+ ({ slug, step, instance }) => ({
1784
+ slug,
1785
+ step,
1786
+ ...(instance !== undefined ? { instance } : {}),
1787
+ }),
1743
1788
  )
1744
1789
  // The rotated loops' positions, from the same reduced facts: no read.
1745
1790
  this.passCursors =
@@ -1747,9 +1792,13 @@ export class Dispatcher {
1747
1792
  ? {}
1748
1793
  : { ...(this.store.repositoryFacts().passCursors?.cursors ?? {}) }
1749
1794
  this.nextPassCursors = { ...this.passCursors }
1750
- for (const { slug, step } of this.recordedDeferrals)
1795
+ for (const { slug, step, instance } of this.recordedDeferrals)
1751
1796
  if (!this.carriedOutstanding.has(slug))
1752
- this.carriedOutstanding.set(slug, { step, visited: false })
1797
+ this.carriedOutstanding.set(slug, {
1798
+ step,
1799
+ visited: false,
1800
+ ...(instance !== undefined ? { instance } : {}),
1801
+ })
1753
1802
  // A pending start request measures capacity from the facts this tick's
1754
1803
  // fleet-wide stages read anyway; keep them only then.
1755
1804
  this.store.retainBuildFacts(
@@ -1792,9 +1841,9 @@ export class Dispatcher {
1792
1841
  // open the first record listing of the next stage; each stage's own
1793
1842
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1794
1843
  if (this.outOfBudget(opts)) return report
1795
- // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1796
- // recovery an earlier invocation deferred for budget are swept first,
1797
- // within half of the window that remains.
1844
+ // Stage −1 — DEFERRED WORK: builds whose provision, cut launch or
1845
+ // stopped-sandbox recovery an earlier invocation deferred for budget are
1846
+ // served first, within half of the window that remains.
1798
1847
  if (!opts.observationOnly)
1799
1848
  await this.runStage('deferred', opts, (stageOpts) =>
1800
1849
  this.serviceDeferredWork(report, launched, paused, stageOpts),
@@ -1886,9 +1935,11 @@ export class Dispatcher {
1886
1935
  opts: TickOpts,
1887
1936
  run: (stageOpts: TickOpts) => Promise<void>,
1888
1937
  ): Promise<void> {
1938
+ // Hosted requests made inside the stage, and work it starts, name it.
1889
1939
  // Unbounded: the helpers' own promise, scheduled exactly as before.
1890
- if (opts.deadlineAt === undefined) return run(opts)
1891
- return this.runBoundedStage(stage, opts, opts.deadlineAt, run)
1940
+ const deadlineAt = opts.deadlineAt
1941
+ if (deadlineAt === undefined) return withCallerStage(stage, () => run(opts))
1942
+ return withCallerStage(stage, () => this.runBoundedStage(stage, opts, deadlineAt, run))
1892
1943
  }
1893
1944
 
1894
1945
  private async runBoundedStage(
@@ -1982,10 +2033,20 @@ export class Dispatcher {
1982
2033
  passReport(): TickReport | undefined {
1983
2034
  if (this.inFlightReport === undefined || this.tickOpts.deadlineAt === undefined)
1984
2035
  return undefined
1985
- return { ...structuredClone(this.inFlightReport), stages: this.pass.summary() }
2036
+ const report = structuredClone(this.inFlightReport)
2037
+ // The deferrals so far, counted as the finished tick would count them;
2038
+ // a finished tick already counted them on its report.
2039
+ if (!this.deferralsFinished)
2040
+ for (const [slug, deferral] of this.tickDeferrals) {
2041
+ if (deferral.step !== 'provision') report.recoveryDeferred += 1
2042
+ report.deferredDiagnostics.push(deferralLine(slug, deferral))
2043
+ }
2044
+ return { ...report, stages: this.pass.summary() }
1986
2045
  }
1987
2046
 
1988
2047
  private inFlightReport: TickReport | undefined
2048
+ /** Whether this tick's report already counts its deferrals. */
2049
+ private deferralsFinished = false
1989
2050
 
1990
2051
  /** The repository listing every tick stage reads: unfiltered in a bounded
1991
2052
  * pass, where each build acted on is checked by `checkCompatibility`;
@@ -2995,7 +3056,22 @@ export class Dispatcher {
2995
3056
  /** The one guarded runner start. Every dispatcher path that starts a runner
2996
3057
  * goes through here, so the no-progress policy cannot depend on which path
2997
3058
  * runs. */
2998
- private async startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
3059
+ private startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
3060
+ return this.trackStart(this.guardedStart(slug, report))
3061
+ }
3062
+
3063
+ /** Register a start in flight until it settles, so bounded teardown can
3064
+ * await a launch the work deadline cut mid-flight (`settleCutStarts`). */
3065
+ private trackStart<T>(start: Promise<T>): Promise<T> {
3066
+ this.startsInFlight.add(start)
3067
+ const forget = () => {
3068
+ this.startsInFlight.delete(start)
3069
+ }
3070
+ start.then(forget, forget)
3071
+ return start
3072
+ }
3073
+
3074
+ private async guardedStart(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
2999
3075
  if (
3000
3076
  !(await ensureExecutionProgress(
3001
3077
  this.store,
@@ -3010,6 +3086,13 @@ export class Dispatcher {
3010
3086
  try {
3011
3087
  return await this.deps.launchRunner(slug)
3012
3088
  } catch (error) {
3089
+ // A launch the work deadline cut after claiming its execution lease:
3090
+ // settle that lease in teardown and carry the launch to the next
3091
+ // invocation, which runs it first.
3092
+ if (isLaunchCutByDeadline(error)) {
3093
+ await this.settleCutLaunch(error.cut)
3094
+ return 'already-active'
3095
+ }
3013
3096
  // A launch waiting on a stopped-sandbox recovery the budget deferred:
3014
3097
  // nothing started and nothing is charged. Record it so the next
3015
3098
  // invocation runs it first; callers see the same result as before.
@@ -3538,12 +3621,21 @@ export class Dispatcher {
3538
3621
  }
3539
3622
  : {}),
3540
3623
  ...(input.adoptAbandoned ? { adoptAbandoned: true } : {}),
3624
+ signal: entry.controller.signal,
3625
+ onProgress: (progress) => {
3626
+ if (entry.controller.signal.aborted) return
3627
+ entry.progress = {
3628
+ label: describeProvisionProgress(progress),
3629
+ since: this.deps.clock().getTime(),
3630
+ }
3631
+ },
3541
3632
  },
3542
3633
  entry.controller.signal,
3543
3634
  )
3544
- // The provisioned fact is true and welcome even when a teardown signal
3545
- // landed mid-call; the token check below still prevents a superseded
3546
- // supervisor from launching.
3635
+ // Providers receive the teardown signal and usually reject promptly, but
3636
+ // one that ignores it may still complete: the provisioned fact is then
3637
+ // true and welcome even though the signal landed mid-call. The token
3638
+ // check below still prevents a superseded supervisor from launching.
3547
3639
  await store.append(slug, {
3548
3640
  actor: DISPATCHER,
3549
3641
  type: 'workspace.provisioned',
@@ -3680,8 +3772,10 @@ export class Dispatcher {
3680
3772
  payload: {
3681
3773
  stage: 'workspace',
3682
3774
  attempt,
3683
- error:
3684
- 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3775
+ error: provisioningAbandonmentMessage(
3776
+ entry.progress,
3777
+ entry.abortedAt ?? this.deps.clock().getTime(),
3778
+ ),
3685
3779
  abandoned: 'teardown',
3686
3780
  },
3687
3781
  })
@@ -3705,6 +3799,7 @@ export class Dispatcher {
3705
3799
  abortProvisioning(): void {
3706
3800
  for (const entry of this.continuations.values()) {
3707
3801
  this.abortedContinuations.set(entry.instance, entry)
3802
+ entry.abortedAt ??= this.deps.clock().getTime()
3708
3803
  entry.controller.abort()
3709
3804
  }
3710
3805
  }
@@ -8529,7 +8624,9 @@ export class Dispatcher {
8529
8624
  if (
8530
8625
  record.ticket === undefined ||
8531
8626
  launched.has(record.slug) ||
8532
- this.continuations.has(record.slug)
8627
+ this.continuations.has(record.slug) ||
8628
+ // The early stage already served it this tick.
8629
+ this.tickPrioritized.has(record.slug)
8533
8630
  ) {
8534
8631
  loop.skip()
8535
8632
  continue
@@ -8947,40 +9044,59 @@ export class Dispatcher {
8947
9044
  launched: Set<string>,
8948
9045
  paused: boolean,
8949
9046
  now: number,
9047
+ carried?: { facts: CurrentBuildFacts },
8950
9048
  ): Promise<'done' | 'waiting' | 'failed'> {
8951
9049
  try {
8952
- return await this.sweepBuild(record, report, launched, paused, now)
9050
+ return await this.sweepBuild(record, report, launched, paused, now, carried)
8953
9051
  } catch (error) {
8954
- rethrowAuthorityLapse(error)
8955
- if (isRecoveryDeferred(error)) {
8956
- await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
8957
- return 'waiting'
8958
- }
8959
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
8960
- return 'waiting'
8961
- if (error instanceof ForgeCooldown) throw error
8962
- const message =
8963
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8964
- report.janitorFailed += 1
8965
- report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8966
- return 'failed'
9052
+ return this.containBuildFailure(record.slug, report, error, 'lease sweep')
8967
9053
  }
8968
9054
  }
8969
9055
 
9056
+ /** The per-build containment the lease sweep and the deferred stage share:
9057
+ * an authority lapse or a repository-wide forge cooldown escapes; a budget
9058
+ * deferral is noted for the next invocation; a forge or mixed-version
9059
+ * deferral waits; anything else is reported as this build's failure. */
9060
+ private async containBuildFailure(
9061
+ slug: string,
9062
+ report: TickReport,
9063
+ error: unknown,
9064
+ what: string,
9065
+ ): Promise<'waiting' | 'failed'> {
9066
+ rethrowAuthorityLapse(error)
9067
+ if (isRecoveryDeferred(error)) {
9068
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
9069
+ return 'waiting'
9070
+ }
9071
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
9072
+ return 'waiting'
9073
+ if (error instanceof ForgeCooldown) throw error
9074
+ const message = error instanceof Error || isForgeFailure(error) ? error.message : String(error)
9075
+ report.janitorFailed += 1
9076
+ report.janitorDiagnostics.push(`build ${slug}: ${what} failed — ${message}`)
9077
+ return 'failed'
9078
+ }
9079
+
8970
9080
  /**
8971
9081
  * Stage −1 — deferred deadline-gated work. Builds the previous invocation
8972
- * recorded in `dispatcher.work-deferred` (a provision or a stopped-sandbox
8973
- * recovery the budget deferred) get the ordinary `sweepBuild` pass first,
8974
- * before settlement and the janitor spend the window. The hint is never
8975
- * authority: each pass re-derives every decision from fresh build state,
8976
- * and a stale entry does nothing and is retired.
9082
+ * recorded in `dispatcher.work-deferred` (a provision, a launch the work
9083
+ * deadline cut, or a stopped-sandbox recovery the budget deferred) are
9084
+ * served first, before settlement and the janitor spend the window, by the
9085
+ * path that finishes their start (`serviceCarriedStart`): a cut launch's
9086
+ * exact-holder lease first, dispatch completion for a build still queued,
9087
+ * the ordinary `sweepBuild` pass otherwise. The hint is never authority:
9088
+ * each pass re-derives every decision from fresh build state, and a stale
9089
+ * entry does nothing and is retired.
8977
9090
  *
8978
9091
  * Per-tick cost: zero reads when nothing is carried (the hint comes from
8979
9092
  * the repository facts the tick already reduced). Otherwise the record
8980
9093
  * listing and digests from this tick's epoch cache, with no fleet-wide
8981
9094
  * compatibility pass, plus one reduced `buildFacts` read per carried build
8982
- * visited — a read the lease sweep would otherwise make later, and which
8983
- * it now skips. Writes: at most one hint append when the list changes.
9095
+ * visited — a read the recovery stage or the lease sweep would otherwise
9096
+ * make later, and which both now skip. A cut holder still holding its
9097
+ * lease adds at most one provider fence, one exact-holder release and one
9098
+ * record read. At most `MAX_DEFERRED_WORK` entries. Writes: at most one
9099
+ * hint append when the list changes.
8984
9100
  */
8985
9101
  private async serviceDeferredWork(
8986
9102
  report: TickReport,
@@ -9009,13 +9125,7 @@ export class Dispatcher {
9009
9125
  this.retireCarried(slug)
9010
9126
  continue
9011
9127
  }
9012
- const outcome = await this.sweepContained(
9013
- found.record,
9014
- report,
9015
- launched,
9016
- paused,
9017
- this.deps.clock().getTime(),
9018
- )
9128
+ const outcome = await this.serviceCarriedStart(found.record, entry, report, launched, paused)
9019
9129
  // The invocation's deadline, not the stage's cut: in-flight work is
9020
9130
  // never cancelled at a cut.
9021
9131
  const interrupted = this.budgetSpent(this.tickOpts)
@@ -9025,6 +9135,221 @@ export class Dispatcher {
9025
9135
  await this.persistDeferrals()
9026
9136
  }
9027
9137
 
9138
+ /**
9139
+ * One carried entry's early-stage pass, by the path that finishes its
9140
+ * start. A cut launch's exact holder is settled first (fenced when its
9141
+ * entry still owes the fence, then released), never from attach history.
9142
+ * A build still `queued` completes its dispatch through the same
9143
+ * fact-driven helper as `recoverDispatches`, so a first provision the
9144
+ * budget deferred after a claim is provisioned here rather than retired
9145
+ * by a sweep that never completes a dispatch. Anything else gets the
9146
+ * ordinary sweep pass, without the first-claim grace: a carried entry
9147
+ * names a start this dispatcher deferred or cut, with no runner pending.
9148
+ */
9149
+ private async serviceCarriedStart(
9150
+ record: BuildRecord,
9151
+ entry: { step: DeferredWorkStep; instance?: string },
9152
+ report: TickReport,
9153
+ launched: Set<string>,
9154
+ paused: boolean,
9155
+ ): Promise<'done' | 'waiting' | 'failed'> {
9156
+ const slug = record.slug
9157
+ // A provision already in flight in this process owns the start.
9158
+ if (this.continuations.has(slug)) return 'waiting'
9159
+ try {
9160
+ let facts: CurrentBuildFacts | undefined
9161
+ if (entry.instance !== undefined && record.lease?.holder === entry.instance) {
9162
+ facts = await this.store.buildFacts(slug)
9163
+ const owed = entry.step === 'fence' ? 'fence' : 'launch'
9164
+ if ((await this.settleCutHolder(slug, entry.instance, owed, facts)) !== 'released')
9165
+ return 'waiting'
9166
+ delete entry.instance
9167
+ // The release appended nothing: only the record's lease changed.
9168
+ record = (await this.store.getBuild(slug)) ?? record
9169
+ } else if (entry.instance !== undefined) {
9170
+ // Someone else's lease is the exclusivity gate; the ordinary pass
9171
+ // decides. The cut holder no longer holds anything to settle.
9172
+ delete entry.instance
9173
+ }
9174
+ facts ??= await this.store.buildFacts(slug)
9175
+ const state = facts.state
9176
+ // A mixed-version deferral keeps the entry waiting, as the sweep does.
9177
+ if (state.status !== 'queued' || mixedVersionDeferred(state))
9178
+ return await this.sweepContained(
9179
+ record,
9180
+ report,
9181
+ launched,
9182
+ paused,
9183
+ this.deps.clock().getTime(),
9184
+ { facts },
9185
+ )
9186
+ if (
9187
+ record.ticket === undefined ||
9188
+ state.discardRequest !== undefined ||
9189
+ dispatcherAcknowledgesAbort(state) ||
9190
+ heldByRepositoryPause(state, paused)
9191
+ )
9192
+ return 'done'
9193
+ const outcome = await this.attemptDispatchCompletion(record, launched, report)
9194
+ switch (outcome) {
9195
+ case 'completed':
9196
+ report.recovered += 1
9197
+ return 'done'
9198
+ case 'deferred':
9199
+ // A budget wait re-noted it; a kicked, in-flight or foreign-live
9200
+ // provision is owned elsewhere.
9201
+ return 'done'
9202
+ case 'parked':
9203
+ // Missing accounts hold the start; anything else is a durable park.
9204
+ return this.accountsAvailable() ? 'done' : 'waiting'
9205
+ case 'failed':
9206
+ launched.add(slug)
9207
+ return 'failed'
9208
+ }
9209
+ } catch (error) {
9210
+ return this.containBuildFailure(slug, report, error, 'deferred start')
9211
+ }
9212
+ }
9213
+
9214
+ /** A claimed build whose first dispatch the work deadline cut after
9215
+ * `build.created` admitted it (the preparation resolution or the dispatch
9216
+ * completion): it keeps its slot, and the next invocation runs its
9217
+ * provision first. Rethrows `error`. */
9218
+ private async carryCutFirstDispatch(slug: string, error: unknown): Promise<never> {
9219
+ if (this.budgetSpent(this.tickOpts))
9220
+ await this.noteDeferral(
9221
+ slug,
9222
+ 'provision',
9223
+ 'the work deadline cut the first dispatch after its claim',
9224
+ ).catch(() => {})
9225
+ throw error
9226
+ }
9227
+
9228
+ /** Run one write or provider call in the tick's scope: the work window, or
9229
+ * the bounded teardown scope once the work signal aborted. */
9230
+ private scoped<T>(run: () => Promise<T>): Promise<T> {
9231
+ if (this.tickOpts.workSignal?.aborted !== true) return run()
9232
+ const teardown = this.tickOpts.teardownWrite
9233
+ if (teardown === undefined)
9234
+ return Promise.reject(new Error('no teardown scope for work after the work deadline'))
9235
+ return teardown(run)
9236
+ }
9237
+
9238
+ /**
9239
+ * Settle a launch the work deadline cut after it claimed the build's
9240
+ * execution lease (GitHub #1415). Runs in bounded teardown, before the
9241
+ * repository lease is released: a start never requested only releases the
9242
+ * exact holder; a requested start is fenced first, and released only once
9243
+ * the fence is confirmed. Whatever teardown cannot finish is carried with
9244
+ * the cut instance, and the next invocation finishes it first.
9245
+ */
9246
+ private async settleCutLaunch(cut: CutLaunch): Promise<void> {
9247
+ const outcome = await this.settleCutHolder(
9248
+ cut.slug,
9249
+ cut.instance,
9250
+ cut.startRequested ? 'fence' : 'launch',
9251
+ )
9252
+ if (outcome === 'released')
9253
+ await this.noteDeferral(
9254
+ cut.slug,
9255
+ 'launch',
9256
+ `the work deadline cut the launch ${cut.startRequested ? 'after its provider start; the sandbox was fenced and' : 'before its provider start;'} its execution lease was released`,
9257
+ )
9258
+ }
9259
+
9260
+ /**
9261
+ * Fence (when `owed` is `fence`) and release a cut launch's exact-holder
9262
+ * execution lease. A lease is released only for a start never requested
9263
+ * or after a confirmed or absent fence, so a released-but-running guest can
9264
+ * never re-claim it beside a replacement. A pending outcome is noted with
9265
+ * the instance and the step still owed. Every call goes through `scoped`.
9266
+ */
9267
+ private async settleCutHolder(
9268
+ slug: string,
9269
+ instance: string,
9270
+ owed: 'launch' | 'fence',
9271
+ known?: CurrentBuildFacts,
9272
+ ): Promise<'released' | 'fence-pending' | 'release-pending'> {
9273
+ const kept = (step: 'fence' | 'launch', detail: string) =>
9274
+ this.noteDeferral(
9275
+ slug,
9276
+ step,
9277
+ `${detail}; execution lease kept for the next invocation to ${step === 'fence' ? 'fence' : 'release'}`,
9278
+ instance,
9279
+ )
9280
+ if (owed === 'fence') {
9281
+ try {
9282
+ const facts = known ?? (await this.scoped(() => this.store.buildFacts(slug)))
9283
+ const open = openWorkspace(facts)
9284
+ const recovery = open === null ? undefined : this.workspaceOwner(open)?.recovery
9285
+ // No open workspace, or a local provider: nothing remote can run.
9286
+ if (open !== null && recovery !== undefined) {
9287
+ if (recovery.fence === undefined) {
9288
+ if (!(await this.scoped(() => this.reapStaleWorkspace(slug, facts, 'replacement')))) {
9289
+ await kept('fence', 'the sandbox could not be reaped')
9290
+ return 'fence-pending'
9291
+ }
9292
+ } else {
9293
+ const teardown = this.tickOpts.workSignal?.aborted === true
9294
+ const fenced = await this.scoped(() =>
9295
+ recovery.fence!(
9296
+ {
9297
+ provider: open.provider,
9298
+ ref: open.ref,
9299
+ path: open.path ?? open.ref,
9300
+ ...(open.localPath !== undefined ? { localPath: open.localPath } : {}),
9301
+ branch: open.branch,
9302
+ },
9303
+ teardown ? { teardown } : undefined,
9304
+ ),
9305
+ )
9306
+ if (fenced.outcome === 'unknown') {
9307
+ await this.scoped(() =>
9308
+ this.recordInfrastructureFailure(slug, facts, {
9309
+ provider: open.provider,
9310
+ workspaceRef: open.ref,
9311
+ operation: 'reconcile',
9312
+ error: stepAttributed('fence', new Error(fenced.error)),
9313
+ cleanupPending: true,
9314
+ }),
9315
+ ).catch((error: unknown) => rethrowAuthorityLapse(error))
9316
+ await kept('fence', `the sandbox stop is unconfirmed — ${fenced.error}`)
9317
+ return 'fence-pending'
9318
+ }
9319
+ }
9320
+ }
9321
+ } catch (error) {
9322
+ rethrowAuthorityLapse(error)
9323
+ await kept('fence', errorText(error))
9324
+ return 'fence-pending'
9325
+ }
9326
+ }
9327
+ try {
9328
+ await this.scoped(() => this.store.releaseLease(slug, instance))
9329
+ } catch (error) {
9330
+ rethrowAuthorityLapse(error)
9331
+ await kept('launch', `the execution lease release failed — ${errorText(error)}`)
9332
+ return 'release-pending'
9333
+ }
9334
+ return 'released'
9335
+ }
9336
+
9337
+ /** Bounded teardown (#1415): wait for runner starts the work deadline cut
9338
+ * mid-flight to settle (fence, lease release, hint) and for hint writes to
9339
+ * finish, then name each deferral this tick has not yet reported, as the
9340
+ * tick report would. No reads; never rejects. */
9341
+ async settleCutStarts(): Promise<string[]> {
9342
+ while (this.startsInFlight.size > 0) await Promise.allSettled([...this.startsInFlight])
9343
+ await this.deferralWrites
9344
+ const lines: string[] = []
9345
+ for (const [slug, deferral] of this.tickDeferrals) {
9346
+ if (this.reportedDeferrals.has(slug)) continue
9347
+ this.reportedDeferrals.add(slug)
9348
+ lines.push(deferralLine(slug, deferral))
9349
+ }
9350
+ return lines
9351
+ }
9352
+
9028
9353
  /** A carried hint entry whose own pass showed it no longer needs priority.
9029
9354
  * Never writes: the next hint write simply omits it. */
9030
9355
  private retireCarried(slug: string): void {
@@ -9032,10 +9357,22 @@ export class Dispatcher {
9032
9357
  }
9033
9358
 
9034
9359
  /** Record that this tick deferred `slug`'s deadline-gated `step` for
9035
- * budget, and keep the durable hint current. */
9036
- private async noteDeferral(slug: string, step: DeferredWorkStep, detail?: string): Promise<void> {
9037
- if (!this.tickDeferrals.has(slug))
9038
- this.tickDeferrals.set(slug, { step, ...(detail !== undefined ? { detail } : {}) })
9360
+ * budget, and keep the durable hint current. `instance` names a cut
9361
+ * execution whose lease the next invocation settles first. */
9362
+ private async noteDeferral(
9363
+ slug: string,
9364
+ step: DeferredWorkStep,
9365
+ detail?: string,
9366
+ instance?: string,
9367
+ ): Promise<void> {
9368
+ // The first step noted wins, except that a kept cut-execution lease
9369
+ // always reaches the hint: the next invocation must settle it first.
9370
+ if (!this.tickDeferrals.has(slug) || instance !== undefined)
9371
+ this.tickDeferrals.set(slug, {
9372
+ step,
9373
+ ...(detail !== undefined ? { detail } : {}),
9374
+ ...(instance !== undefined ? { instance } : {}),
9375
+ })
9039
9376
  await this.persistDeferrals()
9040
9377
  }
9041
9378
 
@@ -9043,18 +9380,22 @@ export class Dispatcher {
9043
9380
  * carried order; then visited carried entries that are still outstanding
9044
9381
  * (re-deferred or interrupted); then this tick's new deferrals. Capped
9045
9382
  * from the tail, so new entries are dropped first. */
9046
- private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
9047
- const list: { slug: string; step: DeferredWorkStep }[] = []
9383
+ private nextDeferralList(): DeferredWorkEntry[] {
9384
+ const list: DeferredWorkEntry[] = []
9048
9385
  const seen = new Set<string>()
9049
- const push = (slug: string, step: DeferredWorkStep) => {
9386
+ const push = (slug: string, entry: { step: DeferredWorkStep; instance?: string }) => {
9050
9387
  if (seen.has(slug)) return
9051
9388
  seen.add(slug)
9052
- list.push({ slug, step })
9389
+ list.push({
9390
+ slug,
9391
+ step: entry.step,
9392
+ ...(entry.instance !== undefined ? { instance: entry.instance } : {}),
9393
+ })
9053
9394
  }
9054
- for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry.step)
9395
+ for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry)
9055
9396
  for (const [slug, entry] of this.carriedOutstanding)
9056
- if (entry.visited) push(slug, this.tickDeferrals.get(slug)?.step ?? entry.step)
9057
- for (const [slug, { step }] of this.tickDeferrals) push(slug, step)
9397
+ if (entry.visited) push(slug, this.tickDeferrals.get(slug) ?? entry)
9398
+ for (const [slug, deferral] of this.tickDeferrals) push(slug, deferral)
9058
9399
  return list.slice(0, MAX_DEFERRED_WORK)
9059
9400
  }
9060
9401
 
@@ -9070,7 +9411,10 @@ export class Dispatcher {
9070
9411
  if (
9071
9412
  next.length === recorded.length &&
9072
9413
  next.every(
9073
- (entry, i) => entry.slug === recorded[i]!.slug && entry.step === recorded[i]!.step,
9414
+ (entry, i) =>
9415
+ entry.slug === recorded[i]!.slug &&
9416
+ entry.step === recorded[i]!.step &&
9417
+ entry.instance === recorded[i]!.instance,
9074
9418
  )
9075
9419
  )
9076
9420
  return
@@ -9140,12 +9484,13 @@ export class Dispatcher {
9140
9484
  /** Count and name this tick's deferrals on its report. Runs in `tick()`,
9141
9485
  * so every early return of `runTick` is covered. */
9142
9486
  private finishDeferrals(report: TickReport): void {
9143
- for (const [slug, { step, detail }] of this.tickDeferrals) {
9144
- if (step !== 'provision') report.recoveryDeferred += 1
9145
- report.deferredDiagnostics.push(
9146
- `build ${slug}: ${step} deferred by the invocation budget; the next invocation runs it first` +
9147
- (detail !== undefined ? ` — ${detail}` : ''),
9148
- )
9487
+ this.deferralsFinished = true
9488
+ for (const [slug, deferral] of this.tickDeferrals) {
9489
+ if (deferral.step !== 'provision') report.recoveryDeferred += 1
9490
+ // Bounded teardown may already have named it.
9491
+ if (this.reportedDeferrals.has(slug)) continue
9492
+ this.reportedDeferrals.add(slug)
9493
+ report.deferredDiagnostics.push(deferralLine(slug, deferral))
9149
9494
  }
9150
9495
  if (this.deferralWriteFailure !== undefined)
9151
9496
  report.deferredDiagnostics.push(
@@ -9218,21 +9563,25 @@ export class Dispatcher {
9218
9563
  launched: Set<string>,
9219
9564
  paused: boolean,
9220
9565
  now: number,
9566
+ carried?: { facts: CurrentBuildFacts },
9221
9567
  ): Promise<'done' | 'waiting'> {
9222
- return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
9568
+ return (await this.sweepBuildPass(record, report, launched, paused, now, carried)) ?? 'done'
9223
9569
  }
9224
9570
 
9571
+ /** `carried` is a deferred-work entry's pass: its facts are already read,
9572
+ * and the first-claim grace does not apply. */
9225
9573
  private async sweepBuildPass(
9226
9574
  record: BuildRecord,
9227
9575
  report: TickReport,
9228
9576
  launched: Set<string>,
9229
9577
  paused: boolean,
9230
9578
  now: number,
9579
+ carried?: { facts: CurrentBuildFacts },
9231
9580
  ): Promise<'waiting' | undefined> {
9232
9581
  if (record.lease) {
9233
9582
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
9234
9583
  }
9235
- const facts = await this.store.buildFacts(record.slug)
9584
+ const facts = carried?.facts ?? (await this.store.buildFacts(record.slug))
9236
9585
  const state = facts.state
9237
9586
  if (mixedVersionDeferred(state)) {
9238
9587
  return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
@@ -9307,6 +9656,7 @@ export class Dispatcher {
9307
9656
  (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
9308
9657
  const cleanup = state.verifyStage.cleanupExecutionSeq
9309
9658
  if (
9659
+ carried === undefined &&
9310
9660
  !record.lease &&
9311
9661
  now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
9312
9662
  facts.lastExecution !== 'relaunch' &&
@@ -9560,6 +9910,43 @@ export class Dispatcher {
9560
9910
  )
9561
9911
  }
9562
9912
 
9913
+ /** The builds that can answer an attempt's creation: at most two point
9914
+ * reads at its proposed slug and the slug its own key derives. */
9915
+ private async creationCandidates(
9916
+ attempt: TicketPreparation,
9917
+ slug: string,
9918
+ ): Promise<BuildRecord[]> {
9919
+ const candidates = attempt.creationKey
9920
+ ? [slug, creationBuildSlug(this.deps.repo, slug, attempt.creationKey)]
9921
+ : [slug]
9922
+ const found: BuildRecord[] = []
9923
+ for (const candidate of candidates) {
9924
+ const record = await this.store.getBuild(candidate)
9925
+ if (record) found.push(record)
9926
+ }
9927
+ return found
9928
+ }
9929
+
9930
+ /** A create the work deadline cut after it may have committed: the one
9931
+ * build this attempt owns, read back under the teardown scope, or
9932
+ * undefined when that cannot be confirmed (preparation recovery then
9933
+ * decides, as for any rejected create). */
9934
+ private async cutCreation(
9935
+ attempt: TicketPreparation,
9936
+ slug: string,
9937
+ ): Promise<BuildRecord | undefined> {
9938
+ try {
9939
+ return await this.scoped(async () => {
9940
+ const found = await this.creationCandidates(attempt, slug)
9941
+ if (found.length !== 1) return undefined
9942
+ return (await this.preparationOwns(attempt, found[0]!)) ? found[0] : undefined
9943
+ })
9944
+ } catch (error) {
9945
+ rethrowAuthorityLapse(error)
9946
+ return undefined
9947
+ }
9948
+ }
9949
+
9563
9950
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
9564
9951
  try {
9565
9952
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -9568,14 +9955,7 @@ export class Dispatcher {
9568
9955
  // its own key derives (allocating store): at most two point reads, and
9569
9956
  // never another attempt's build.
9570
9957
  if (attempt.slug) {
9571
- const candidates = attempt.creationKey
9572
- ? [attempt.slug, creationBuildSlug(this.deps.repo, attempt.slug, attempt.creationKey)]
9573
- : [attempt.slug]
9574
- const found: BuildRecord[] = []
9575
- for (const slug of candidates) {
9576
- const record = await this.store.getBuild(slug)
9577
- if (record) found.push(record)
9578
- }
9958
+ const found = await this.creationCandidates(attempt, attempt.slug)
9579
9959
  if (found.length > 1)
9580
9960
  return await this.abandonPreparation(
9581
9961
  attempt,
@@ -10434,21 +10814,44 @@ export class Dispatcher {
10434
10814
  },
10435
10815
  })
10436
10816
  stage = 'create-build'
10437
- record = await store.createBuild({
10438
- slug,
10439
- repo: this.deps.repo,
10440
- ticket: ticket.ref,
10441
- branch,
10442
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
10443
- ...(creationKey !== undefined ? { creationKey } : {}),
10444
- created: {
10445
- actor: DISPATCHER,
10446
- type: 'build.created',
10447
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
10448
- },
10449
- })
10450
- established = true
10451
- await this.preparationResolved(attempt, 'owned')
10817
+ // Tracked from the creation on: `build.created` admits the build, so
10818
+ // a work deadline that cuts anything after it must carry the start.
10819
+ record = await this.trackStart(
10820
+ (async () => {
10821
+ const created = await store
10822
+ .createBuild({
10823
+ slug,
10824
+ repo: this.deps.repo,
10825
+ ticket: ticket.ref,
10826
+ branch,
10827
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
10828
+ ...(creationKey !== undefined ? { creationKey } : {}),
10829
+ created: {
10830
+ actor: DISPATCHER,
10831
+ type: 'build.created',
10832
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
10833
+ },
10834
+ })
10835
+ .catch(async (error: unknown) => {
10836
+ // The deadline may have cut only the acknowledgement: a
10837
+ // committed `build.created` admitted the build, so resolve
10838
+ // the preparation and carry its first provision.
10839
+ if (!this.budgetSpent(this.tickOpts)) throw error
10840
+ const owned = await this.cutCreation(attempt, slug)
10841
+ if (owned === undefined) throw error
10842
+ established = true
10843
+ await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
10844
+ (resolution: unknown) => rethrowAuthorityLapse(resolution),
10845
+ )
10846
+ return this.carryCutFirstDispatch(owned.slug, error)
10847
+ })
10848
+ established = true
10849
+ await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
10850
+ this.carryCutFirstDispatch(created.slug, error),
10851
+ )
10852
+ return created
10853
+ })(),
10854
+ )
10452
10855
  settle(ticket, { outcome: 'started', slug: record.slug })
10453
10856
  } catch (error) {
10454
10857
  // A lapse is not a preparation failure: the successor recovers the
@@ -10491,12 +10894,14 @@ export class Dispatcher {
10491
10894
  report.queued -= 1
10492
10895
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
10493
10896
  else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
10494
- const outcome = await this.attemptDispatchCompletion(record, launched, report, {
10495
- ticket,
10496
- body,
10497
- ...(authoredSession !== undefined ? { authoredSession } : {}),
10498
- ...createdSeed,
10499
- })
10897
+ const outcome = await this.trackStart(
10898
+ this.attemptDispatchCompletion(record, launched, report, {
10899
+ ticket,
10900
+ body,
10901
+ ...(authoredSession !== undefined ? { authoredSession } : {}),
10902
+ ...createdSeed,
10903
+ }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
10904
+ )
10500
10905
  // Accepted dispatches: durable boundaries recorded. A deferred outcome
10501
10906
  // means the remote provisioning continuation owns the rest.
10502
10907
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1