@defrex/autobuild 1.15.0 → 1.16.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.
@@ -360,6 +360,7 @@ import {
360
360
  recoveryStepOf,
361
361
  type WorkspaceRecoveryStep,
362
362
  } from '../ports/workspace/recovery-step'
363
+ import { isLaunchCutByDeadline, type CutLaunch } from './launch-cut'
363
364
  import type {
364
365
  DependencyState,
365
366
  Forge,
@@ -686,14 +687,18 @@ export interface TickReport {
686
687
  provisioning: number
687
688
  /** Builds whose provisioning start was deferred because the bounded
688
689
  * invocation's remaining budget was shorter than the provider's
689
- * provisioning estimate. Nothing is written; a later invocation starts it. */
690
+ * provisioning estimate, including a first provision right after a claim.
691
+ * The build is recorded in `dispatcher.work-deferred` and the next tick
692
+ * provisions it first. */
690
693
  provisioningDeferred: number
691
694
  /** 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. */
695
+ * invocation budget deferred this tick, or whose launch the work deadline
696
+ * cut after its execution lease was claimed. Nothing is charged; the build
697
+ * is recorded in `dispatcher.work-deferred` and the next tick runs it
698
+ * first. */
694
699
  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. */
700
+ /** One line per build whose deadline-gated work (a provision, a cut launch
701
+ * or a recovery step) this tick deferred for budget, naming the step. */
697
702
  deferredDiagnostics: string[]
698
703
  /** Dispatch (§12): builds created and launched. With durable supervision
699
704
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
@@ -963,8 +968,17 @@ export interface TickOpts {
963
968
  }
964
969
 
965
970
  /** 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
971
+ * provision, a runner launch the work deadline cut, or a stopped-sandbox
972
+ * recovery step. */
973
+ export type DeferredWorkStep = 'provision' | 'launch' | WorkspaceRecoveryStep
974
+
975
+ /** One `dispatcher.work-deferred` entry. `instance` names a deadline-cut
976
+ * execution whose exact-holder lease teardown could not settle. */
977
+ interface DeferredWorkEntry {
978
+ slug: string
979
+ step: DeferredWorkStep
980
+ instance?: string
981
+ }
968
982
 
969
983
  /** Most entries one `dispatcher.work-deferred` hint carries. */
970
984
  const MAX_DEFERRED_WORK = 64
@@ -1126,6 +1140,14 @@ function errorText(error: unknown): string {
1126
1140
  return error instanceof Error ? error.message : String(error)
1127
1141
  }
1128
1142
 
1143
+ /** The report and dispatch-log line naming one deferral by build and step. */
1144
+ function deferralLine(slug: string, deferral: { step: DeferredWorkStep; detail?: string }): string {
1145
+ return (
1146
+ `build ${slug}: ${deferral.step} deferred by the invocation budget; the next invocation runs it first` +
1147
+ (deferral.detail !== undefined ? ` — ${deferral.detail}` : '')
1148
+ )
1149
+ }
1150
+
1129
1151
  function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1130
1152
  return error instanceof MissingAccountCredentialsError
1131
1153
  ? error
@@ -1387,7 +1409,16 @@ export class Dispatcher {
1387
1409
  private tickLaunched: ReadonlySet<string> = new Set()
1388
1410
  /** Per tick, in insertion order: builds whose deadline-gated work this tick
1389
1411
  * deferred for budget, with the first step seen and an optional detail. */
1390
- private readonly tickDeferrals = new Map<string, { step: DeferredWorkStep; detail?: string }>()
1412
+ private readonly tickDeferrals = new Map<
1413
+ string,
1414
+ { step: DeferredWorkStep; detail?: string; instance?: string }
1415
+ >()
1416
+ /** Per tick: deferrals already named in a report or teardown line. */
1417
+ private readonly reportedDeferrals = new Set<string>()
1418
+ /** Runner starts in flight in this process, including a deadline-cut
1419
+ * launch's settlement and an intake claim's first dispatch. Bounded
1420
+ * teardown awaits them (`settleCutStarts`). */
1421
+ private readonly startsInFlight = new Set<Promise<unknown>>()
1391
1422
  /** Per tick: carried builds the early stage took up, which the lease sweep
1392
1423
  * then skips so no build is swept twice in one tick. */
1393
1424
  private readonly tickPrioritized = new Set<string>()
@@ -1396,10 +1427,10 @@ export class Dispatcher {
1396
1427
  * after its own early-stage pass showed it no longer needs priority. */
1397
1428
  private readonly carriedOutstanding = new Map<
1398
1429
  string,
1399
- { step: DeferredWorkStep; visited: boolean }
1430
+ { step: DeferredWorkStep; visited: boolean; instance?: string }
1400
1431
  >()
1401
1432
  /** The durable hint as last read or written. */
1402
- private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1433
+ private recordedDeferrals: DeferredWorkEntry[] = []
1403
1434
  /** The current tick's options, for writes made from deferral sites. */
1404
1435
  private tickOpts: TickOpts = {}
1405
1436
  /** Serializes hint writes so concurrent deferral notes never race. */
@@ -1523,7 +1554,8 @@ export class Dispatcher {
1523
1554
  }
1524
1555
 
1525
1556
  /**
1526
- * One cron-friendly pass (§3.3): deferred deadline-gated work → settlement →
1557
+ * One cron-friendly pass (§3.3): deferred deadline-gated work (carried
1558
+ * provisions, cut launches and recoveries) → settlement →
1527
1559
  * janitor → interrupted dispatch recovery → optional startup resume →
1528
1560
  * lease sweep → dispatch. Startup resume is opt-in
1529
1561
  * because the CLI invokes it
@@ -1725,6 +1757,8 @@ export class Dispatcher {
1725
1757
  this.parkedSettled.clear()
1726
1758
  this.deferredAdmissions.clear()
1727
1759
  this.tickDeferrals.clear()
1760
+ this.reportedDeferrals.clear()
1761
+ this.deferralsFinished = false
1728
1762
  this.tickPrioritized.clear()
1729
1763
  this.carriedOutstanding.clear()
1730
1764
  this.deferralWriteFailure = undefined
@@ -1739,7 +1773,11 @@ export class Dispatcher {
1739
1773
  // The durable deferral hint from the previous invocation: zero extra
1740
1774
  // reads, it is part of the repository facts the refresh reduced.
1741
1775
  this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1742
- ({ slug, step }) => ({ slug, step }),
1776
+ ({ slug, step, instance }) => ({
1777
+ slug,
1778
+ step,
1779
+ ...(instance !== undefined ? { instance } : {}),
1780
+ }),
1743
1781
  )
1744
1782
  // The rotated loops' positions, from the same reduced facts: no read.
1745
1783
  this.passCursors =
@@ -1747,9 +1785,13 @@ export class Dispatcher {
1747
1785
  ? {}
1748
1786
  : { ...(this.store.repositoryFacts().passCursors?.cursors ?? {}) }
1749
1787
  this.nextPassCursors = { ...this.passCursors }
1750
- for (const { slug, step } of this.recordedDeferrals)
1788
+ for (const { slug, step, instance } of this.recordedDeferrals)
1751
1789
  if (!this.carriedOutstanding.has(slug))
1752
- this.carriedOutstanding.set(slug, { step, visited: false })
1790
+ this.carriedOutstanding.set(slug, {
1791
+ step,
1792
+ visited: false,
1793
+ ...(instance !== undefined ? { instance } : {}),
1794
+ })
1753
1795
  // A pending start request measures capacity from the facts this tick's
1754
1796
  // fleet-wide stages read anyway; keep them only then.
1755
1797
  this.store.retainBuildFacts(
@@ -1792,9 +1834,9 @@ export class Dispatcher {
1792
1834
  // open the first record listing of the next stage; each stage's own
1793
1835
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1794
1836
  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.
1837
+ // Stage −1 — DEFERRED WORK: builds whose provision, cut launch or
1838
+ // stopped-sandbox recovery an earlier invocation deferred for budget are
1839
+ // served first, within half of the window that remains.
1798
1840
  if (!opts.observationOnly)
1799
1841
  await this.runStage('deferred', opts, (stageOpts) =>
1800
1842
  this.serviceDeferredWork(report, launched, paused, stageOpts),
@@ -1982,10 +2024,20 @@ export class Dispatcher {
1982
2024
  passReport(): TickReport | undefined {
1983
2025
  if (this.inFlightReport === undefined || this.tickOpts.deadlineAt === undefined)
1984
2026
  return undefined
1985
- return { ...structuredClone(this.inFlightReport), stages: this.pass.summary() }
2027
+ const report = structuredClone(this.inFlightReport)
2028
+ // The deferrals so far, counted as the finished tick would count them;
2029
+ // a finished tick already counted them on its report.
2030
+ if (!this.deferralsFinished)
2031
+ for (const [slug, deferral] of this.tickDeferrals) {
2032
+ if (deferral.step !== 'provision') report.recoveryDeferred += 1
2033
+ report.deferredDiagnostics.push(deferralLine(slug, deferral))
2034
+ }
2035
+ return { ...report, stages: this.pass.summary() }
1986
2036
  }
1987
2037
 
1988
2038
  private inFlightReport: TickReport | undefined
2039
+ /** Whether this tick's report already counts its deferrals. */
2040
+ private deferralsFinished = false
1989
2041
 
1990
2042
  /** The repository listing every tick stage reads: unfiltered in a bounded
1991
2043
  * pass, where each build acted on is checked by `checkCompatibility`;
@@ -2995,7 +3047,22 @@ export class Dispatcher {
2995
3047
  /** The one guarded runner start. Every dispatcher path that starts a runner
2996
3048
  * goes through here, so the no-progress policy cannot depend on which path
2997
3049
  * runs. */
2998
- private async startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
3050
+ private startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
3051
+ return this.trackStart(this.guardedStart(slug, report))
3052
+ }
3053
+
3054
+ /** Register a start in flight until it settles, so bounded teardown can
3055
+ * await a launch the work deadline cut mid-flight (`settleCutStarts`). */
3056
+ private trackStart<T>(start: Promise<T>): Promise<T> {
3057
+ this.startsInFlight.add(start)
3058
+ const forget = () => {
3059
+ this.startsInFlight.delete(start)
3060
+ }
3061
+ start.then(forget, forget)
3062
+ return start
3063
+ }
3064
+
3065
+ private async guardedStart(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
2999
3066
  if (
3000
3067
  !(await ensureExecutionProgress(
3001
3068
  this.store,
@@ -3010,6 +3077,13 @@ export class Dispatcher {
3010
3077
  try {
3011
3078
  return await this.deps.launchRunner(slug)
3012
3079
  } catch (error) {
3080
+ // A launch the work deadline cut after claiming its execution lease:
3081
+ // settle that lease in teardown and carry the launch to the next
3082
+ // invocation, which runs it first.
3083
+ if (isLaunchCutByDeadline(error)) {
3084
+ await this.settleCutLaunch(error.cut)
3085
+ return 'already-active'
3086
+ }
3013
3087
  // A launch waiting on a stopped-sandbox recovery the budget deferred:
3014
3088
  // nothing started and nothing is charged. Record it so the next
3015
3089
  // invocation runs it first; callers see the same result as before.
@@ -8529,7 +8603,9 @@ export class Dispatcher {
8529
8603
  if (
8530
8604
  record.ticket === undefined ||
8531
8605
  launched.has(record.slug) ||
8532
- this.continuations.has(record.slug)
8606
+ this.continuations.has(record.slug) ||
8607
+ // The early stage already served it this tick.
8608
+ this.tickPrioritized.has(record.slug)
8533
8609
  ) {
8534
8610
  loop.skip()
8535
8611
  continue
@@ -8947,40 +9023,59 @@ export class Dispatcher {
8947
9023
  launched: Set<string>,
8948
9024
  paused: boolean,
8949
9025
  now: number,
9026
+ carried?: { facts: CurrentBuildFacts },
8950
9027
  ): Promise<'done' | 'waiting' | 'failed'> {
8951
9028
  try {
8952
- return await this.sweepBuild(record, report, launched, paused, now)
9029
+ return await this.sweepBuild(record, report, launched, paused, now, carried)
8953
9030
  } 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'
9031
+ return this.containBuildFailure(record.slug, report, error, 'lease sweep')
9032
+ }
9033
+ }
9034
+
9035
+ /** The per-build containment the lease sweep and the deferred stage share:
9036
+ * an authority lapse or a repository-wide forge cooldown escapes; a budget
9037
+ * deferral is noted for the next invocation; a forge or mixed-version
9038
+ * deferral waits; anything else is reported as this build's failure. */
9039
+ private async containBuildFailure(
9040
+ slug: string,
9041
+ report: TickReport,
9042
+ error: unknown,
9043
+ what: string,
9044
+ ): Promise<'waiting' | 'failed'> {
9045
+ rethrowAuthorityLapse(error)
9046
+ if (isRecoveryDeferred(error)) {
9047
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
9048
+ return 'waiting'
8967
9049
  }
9050
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
9051
+ return 'waiting'
9052
+ if (error instanceof ForgeCooldown) throw error
9053
+ const message = error instanceof Error || isForgeFailure(error) ? error.message : String(error)
9054
+ report.janitorFailed += 1
9055
+ report.janitorDiagnostics.push(`build ${slug}: ${what} failed — ${message}`)
9056
+ return 'failed'
8968
9057
  }
8969
9058
 
8970
9059
  /**
8971
9060
  * 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.
9061
+ * recorded in `dispatcher.work-deferred` (a provision, a launch the work
9062
+ * deadline cut, or a stopped-sandbox recovery the budget deferred) are
9063
+ * served first, before settlement and the janitor spend the window, by the
9064
+ * path that finishes their start (`serviceCarriedStart`): a cut launch's
9065
+ * exact-holder lease first, dispatch completion for a build still queued,
9066
+ * the ordinary `sweepBuild` pass otherwise. The hint is never authority:
9067
+ * each pass re-derives every decision from fresh build state, and a stale
9068
+ * entry does nothing and is retired.
8977
9069
  *
8978
9070
  * Per-tick cost: zero reads when nothing is carried (the hint comes from
8979
9071
  * the repository facts the tick already reduced). Otherwise the record
8980
9072
  * listing and digests from this tick's epoch cache, with no fleet-wide
8981
9073
  * 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.
9074
+ * visited — a read the recovery stage or the lease sweep would otherwise
9075
+ * make later, and which both now skip. A cut holder still holding its
9076
+ * lease adds at most one provider fence, one exact-holder release and one
9077
+ * record read. At most `MAX_DEFERRED_WORK` entries. Writes: at most one
9078
+ * hint append when the list changes.
8984
9079
  */
8985
9080
  private async serviceDeferredWork(
8986
9081
  report: TickReport,
@@ -9009,13 +9104,7 @@ export class Dispatcher {
9009
9104
  this.retireCarried(slug)
9010
9105
  continue
9011
9106
  }
9012
- const outcome = await this.sweepContained(
9013
- found.record,
9014
- report,
9015
- launched,
9016
- paused,
9017
- this.deps.clock().getTime(),
9018
- )
9107
+ const outcome = await this.serviceCarriedStart(found.record, entry, report, launched, paused)
9019
9108
  // The invocation's deadline, not the stage's cut: in-flight work is
9020
9109
  // never cancelled at a cut.
9021
9110
  const interrupted = this.budgetSpent(this.tickOpts)
@@ -9025,6 +9114,221 @@ export class Dispatcher {
9025
9114
  await this.persistDeferrals()
9026
9115
  }
9027
9116
 
9117
+ /**
9118
+ * One carried entry's early-stage pass, by the path that finishes its
9119
+ * start. A cut launch's exact holder is settled first (fenced when its
9120
+ * entry still owes the fence, then released), never from attach history.
9121
+ * A build still `queued` completes its dispatch through the same
9122
+ * fact-driven helper as `recoverDispatches`, so a first provision the
9123
+ * budget deferred after a claim is provisioned here rather than retired
9124
+ * by a sweep that never completes a dispatch. Anything else gets the
9125
+ * ordinary sweep pass, without the first-claim grace: a carried entry
9126
+ * names a start this dispatcher deferred or cut, with no runner pending.
9127
+ */
9128
+ private async serviceCarriedStart(
9129
+ record: BuildRecord,
9130
+ entry: { step: DeferredWorkStep; instance?: string },
9131
+ report: TickReport,
9132
+ launched: Set<string>,
9133
+ paused: boolean,
9134
+ ): Promise<'done' | 'waiting' | 'failed'> {
9135
+ const slug = record.slug
9136
+ // A provision already in flight in this process owns the start.
9137
+ if (this.continuations.has(slug)) return 'waiting'
9138
+ try {
9139
+ let facts: CurrentBuildFacts | undefined
9140
+ if (entry.instance !== undefined && record.lease?.holder === entry.instance) {
9141
+ facts = await this.store.buildFacts(slug)
9142
+ const owed = entry.step === 'fence' ? 'fence' : 'launch'
9143
+ if ((await this.settleCutHolder(slug, entry.instance, owed, facts)) !== 'released')
9144
+ return 'waiting'
9145
+ delete entry.instance
9146
+ // The release appended nothing: only the record's lease changed.
9147
+ record = (await this.store.getBuild(slug)) ?? record
9148
+ } else if (entry.instance !== undefined) {
9149
+ // Someone else's lease is the exclusivity gate; the ordinary pass
9150
+ // decides. The cut holder no longer holds anything to settle.
9151
+ delete entry.instance
9152
+ }
9153
+ facts ??= await this.store.buildFacts(slug)
9154
+ const state = facts.state
9155
+ // A mixed-version deferral keeps the entry waiting, as the sweep does.
9156
+ if (state.status !== 'queued' || mixedVersionDeferred(state))
9157
+ return await this.sweepContained(
9158
+ record,
9159
+ report,
9160
+ launched,
9161
+ paused,
9162
+ this.deps.clock().getTime(),
9163
+ { facts },
9164
+ )
9165
+ if (
9166
+ record.ticket === undefined ||
9167
+ state.discardRequest !== undefined ||
9168
+ dispatcherAcknowledgesAbort(state) ||
9169
+ heldByRepositoryPause(state, paused)
9170
+ )
9171
+ return 'done'
9172
+ const outcome = await this.attemptDispatchCompletion(record, launched, report)
9173
+ switch (outcome) {
9174
+ case 'completed':
9175
+ report.recovered += 1
9176
+ return 'done'
9177
+ case 'deferred':
9178
+ // A budget wait re-noted it; a kicked, in-flight or foreign-live
9179
+ // provision is owned elsewhere.
9180
+ return 'done'
9181
+ case 'parked':
9182
+ // Missing accounts hold the start; anything else is a durable park.
9183
+ return this.accountsAvailable() ? 'done' : 'waiting'
9184
+ case 'failed':
9185
+ launched.add(slug)
9186
+ return 'failed'
9187
+ }
9188
+ } catch (error) {
9189
+ return this.containBuildFailure(slug, report, error, 'deferred start')
9190
+ }
9191
+ }
9192
+
9193
+ /** A claimed build whose first dispatch the work deadline cut after
9194
+ * `build.created` admitted it (the preparation resolution or the dispatch
9195
+ * completion): it keeps its slot, and the next invocation runs its
9196
+ * provision first. Rethrows `error`. */
9197
+ private async carryCutFirstDispatch(slug: string, error: unknown): Promise<never> {
9198
+ if (this.budgetSpent(this.tickOpts))
9199
+ await this.noteDeferral(
9200
+ slug,
9201
+ 'provision',
9202
+ 'the work deadline cut the first dispatch after its claim',
9203
+ ).catch(() => {})
9204
+ throw error
9205
+ }
9206
+
9207
+ /** Run one write or provider call in the tick's scope: the work window, or
9208
+ * the bounded teardown scope once the work signal aborted. */
9209
+ private scoped<T>(run: () => Promise<T>): Promise<T> {
9210
+ if (this.tickOpts.workSignal?.aborted !== true) return run()
9211
+ const teardown = this.tickOpts.teardownWrite
9212
+ if (teardown === undefined)
9213
+ return Promise.reject(new Error('no teardown scope for work after the work deadline'))
9214
+ return teardown(run)
9215
+ }
9216
+
9217
+ /**
9218
+ * Settle a launch the work deadline cut after it claimed the build's
9219
+ * execution lease (GitHub #1415). Runs in bounded teardown, before the
9220
+ * repository lease is released: a start never requested only releases the
9221
+ * exact holder; a requested start is fenced first, and released only once
9222
+ * the fence is confirmed. Whatever teardown cannot finish is carried with
9223
+ * the cut instance, and the next invocation finishes it first.
9224
+ */
9225
+ private async settleCutLaunch(cut: CutLaunch): Promise<void> {
9226
+ const outcome = await this.settleCutHolder(
9227
+ cut.slug,
9228
+ cut.instance,
9229
+ cut.startRequested ? 'fence' : 'launch',
9230
+ )
9231
+ if (outcome === 'released')
9232
+ await this.noteDeferral(
9233
+ cut.slug,
9234
+ 'launch',
9235
+ `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`,
9236
+ )
9237
+ }
9238
+
9239
+ /**
9240
+ * Fence (when `owed` is `fence`) and release a cut launch's exact-holder
9241
+ * execution lease. A lease is released only for a start never requested
9242
+ * or after a confirmed or absent fence, so a released-but-running guest can
9243
+ * never re-claim it beside a replacement. A pending outcome is noted with
9244
+ * the instance and the step still owed. Every call goes through `scoped`.
9245
+ */
9246
+ private async settleCutHolder(
9247
+ slug: string,
9248
+ instance: string,
9249
+ owed: 'launch' | 'fence',
9250
+ known?: CurrentBuildFacts,
9251
+ ): Promise<'released' | 'fence-pending' | 'release-pending'> {
9252
+ const kept = (step: 'fence' | 'launch', detail: string) =>
9253
+ this.noteDeferral(
9254
+ slug,
9255
+ step,
9256
+ `${detail}; execution lease kept for the next invocation to ${step === 'fence' ? 'fence' : 'release'}`,
9257
+ instance,
9258
+ )
9259
+ if (owed === 'fence') {
9260
+ try {
9261
+ const facts = known ?? (await this.scoped(() => this.store.buildFacts(slug)))
9262
+ const open = openWorkspace(facts)
9263
+ const recovery = open === null ? undefined : this.workspaceOwner(open)?.recovery
9264
+ // No open workspace, or a local provider: nothing remote can run.
9265
+ if (open !== null && recovery !== undefined) {
9266
+ if (recovery.fence === undefined) {
9267
+ if (!(await this.scoped(() => this.reapStaleWorkspace(slug, facts, 'replacement')))) {
9268
+ await kept('fence', 'the sandbox could not be reaped')
9269
+ return 'fence-pending'
9270
+ }
9271
+ } else {
9272
+ const teardown = this.tickOpts.workSignal?.aborted === true
9273
+ const fenced = await this.scoped(() =>
9274
+ recovery.fence!(
9275
+ {
9276
+ provider: open.provider,
9277
+ ref: open.ref,
9278
+ path: open.path ?? open.ref,
9279
+ ...(open.localPath !== undefined ? { localPath: open.localPath } : {}),
9280
+ branch: open.branch,
9281
+ },
9282
+ teardown ? { teardown } : undefined,
9283
+ ),
9284
+ )
9285
+ if (fenced.outcome === 'unknown') {
9286
+ await this.scoped(() =>
9287
+ this.recordInfrastructureFailure(slug, facts, {
9288
+ provider: open.provider,
9289
+ workspaceRef: open.ref,
9290
+ operation: 'reconcile',
9291
+ error: stepAttributed('fence', new Error(fenced.error)),
9292
+ cleanupPending: true,
9293
+ }),
9294
+ ).catch((error: unknown) => rethrowAuthorityLapse(error))
9295
+ await kept('fence', `the sandbox stop is unconfirmed — ${fenced.error}`)
9296
+ return 'fence-pending'
9297
+ }
9298
+ }
9299
+ }
9300
+ } catch (error) {
9301
+ rethrowAuthorityLapse(error)
9302
+ await kept('fence', errorText(error))
9303
+ return 'fence-pending'
9304
+ }
9305
+ }
9306
+ try {
9307
+ await this.scoped(() => this.store.releaseLease(slug, instance))
9308
+ } catch (error) {
9309
+ rethrowAuthorityLapse(error)
9310
+ await kept('launch', `the execution lease release failed — ${errorText(error)}`)
9311
+ return 'release-pending'
9312
+ }
9313
+ return 'released'
9314
+ }
9315
+
9316
+ /** Bounded teardown (#1415): wait for runner starts the work deadline cut
9317
+ * mid-flight to settle (fence, lease release, hint) and for hint writes to
9318
+ * finish, then name each deferral this tick has not yet reported, as the
9319
+ * tick report would. No reads; never rejects. */
9320
+ async settleCutStarts(): Promise<string[]> {
9321
+ while (this.startsInFlight.size > 0) await Promise.allSettled([...this.startsInFlight])
9322
+ await this.deferralWrites
9323
+ const lines: string[] = []
9324
+ for (const [slug, deferral] of this.tickDeferrals) {
9325
+ if (this.reportedDeferrals.has(slug)) continue
9326
+ this.reportedDeferrals.add(slug)
9327
+ lines.push(deferralLine(slug, deferral))
9328
+ }
9329
+ return lines
9330
+ }
9331
+
9028
9332
  /** A carried hint entry whose own pass showed it no longer needs priority.
9029
9333
  * Never writes: the next hint write simply omits it. */
9030
9334
  private retireCarried(slug: string): void {
@@ -9032,10 +9336,22 @@ export class Dispatcher {
9032
9336
  }
9033
9337
 
9034
9338
  /** 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 } : {}) })
9339
+ * budget, and keep the durable hint current. `instance` names a cut
9340
+ * execution whose lease the next invocation settles first. */
9341
+ private async noteDeferral(
9342
+ slug: string,
9343
+ step: DeferredWorkStep,
9344
+ detail?: string,
9345
+ instance?: string,
9346
+ ): Promise<void> {
9347
+ // The first step noted wins, except that a kept cut-execution lease
9348
+ // always reaches the hint: the next invocation must settle it first.
9349
+ if (!this.tickDeferrals.has(slug) || instance !== undefined)
9350
+ this.tickDeferrals.set(slug, {
9351
+ step,
9352
+ ...(detail !== undefined ? { detail } : {}),
9353
+ ...(instance !== undefined ? { instance } : {}),
9354
+ })
9039
9355
  await this.persistDeferrals()
9040
9356
  }
9041
9357
 
@@ -9043,18 +9359,22 @@ export class Dispatcher {
9043
9359
  * carried order; then visited carried entries that are still outstanding
9044
9360
  * (re-deferred or interrupted); then this tick's new deferrals. Capped
9045
9361
  * from the tail, so new entries are dropped first. */
9046
- private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
9047
- const list: { slug: string; step: DeferredWorkStep }[] = []
9362
+ private nextDeferralList(): DeferredWorkEntry[] {
9363
+ const list: DeferredWorkEntry[] = []
9048
9364
  const seen = new Set<string>()
9049
- const push = (slug: string, step: DeferredWorkStep) => {
9365
+ const push = (slug: string, entry: { step: DeferredWorkStep; instance?: string }) => {
9050
9366
  if (seen.has(slug)) return
9051
9367
  seen.add(slug)
9052
- list.push({ slug, step })
9368
+ list.push({
9369
+ slug,
9370
+ step: entry.step,
9371
+ ...(entry.instance !== undefined ? { instance: entry.instance } : {}),
9372
+ })
9053
9373
  }
9054
- for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry.step)
9374
+ for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry)
9055
9375
  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)
9376
+ if (entry.visited) push(slug, this.tickDeferrals.get(slug) ?? entry)
9377
+ for (const [slug, deferral] of this.tickDeferrals) push(slug, deferral)
9058
9378
  return list.slice(0, MAX_DEFERRED_WORK)
9059
9379
  }
9060
9380
 
@@ -9070,7 +9390,10 @@ export class Dispatcher {
9070
9390
  if (
9071
9391
  next.length === recorded.length &&
9072
9392
  next.every(
9073
- (entry, i) => entry.slug === recorded[i]!.slug && entry.step === recorded[i]!.step,
9393
+ (entry, i) =>
9394
+ entry.slug === recorded[i]!.slug &&
9395
+ entry.step === recorded[i]!.step &&
9396
+ entry.instance === recorded[i]!.instance,
9074
9397
  )
9075
9398
  )
9076
9399
  return
@@ -9140,12 +9463,13 @@ export class Dispatcher {
9140
9463
  /** Count and name this tick's deferrals on its report. Runs in `tick()`,
9141
9464
  * so every early return of `runTick` is covered. */
9142
9465
  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
- )
9466
+ this.deferralsFinished = true
9467
+ for (const [slug, deferral] of this.tickDeferrals) {
9468
+ if (deferral.step !== 'provision') report.recoveryDeferred += 1
9469
+ // Bounded teardown may already have named it.
9470
+ if (this.reportedDeferrals.has(slug)) continue
9471
+ this.reportedDeferrals.add(slug)
9472
+ report.deferredDiagnostics.push(deferralLine(slug, deferral))
9149
9473
  }
9150
9474
  if (this.deferralWriteFailure !== undefined)
9151
9475
  report.deferredDiagnostics.push(
@@ -9218,21 +9542,25 @@ export class Dispatcher {
9218
9542
  launched: Set<string>,
9219
9543
  paused: boolean,
9220
9544
  now: number,
9545
+ carried?: { facts: CurrentBuildFacts },
9221
9546
  ): Promise<'done' | 'waiting'> {
9222
- return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
9547
+ return (await this.sweepBuildPass(record, report, launched, paused, now, carried)) ?? 'done'
9223
9548
  }
9224
9549
 
9550
+ /** `carried` is a deferred-work entry's pass: its facts are already read,
9551
+ * and the first-claim grace does not apply. */
9225
9552
  private async sweepBuildPass(
9226
9553
  record: BuildRecord,
9227
9554
  report: TickReport,
9228
9555
  launched: Set<string>,
9229
9556
  paused: boolean,
9230
9557
  now: number,
9558
+ carried?: { facts: CurrentBuildFacts },
9231
9559
  ): Promise<'waiting' | undefined> {
9232
9560
  if (record.lease) {
9233
9561
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
9234
9562
  }
9235
- const facts = await this.store.buildFacts(record.slug)
9563
+ const facts = carried?.facts ?? (await this.store.buildFacts(record.slug))
9236
9564
  const state = facts.state
9237
9565
  if (mixedVersionDeferred(state)) {
9238
9566
  return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
@@ -9307,6 +9635,7 @@ export class Dispatcher {
9307
9635
  (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
9308
9636
  const cleanup = state.verifyStage.cleanupExecutionSeq
9309
9637
  if (
9638
+ carried === undefined &&
9310
9639
  !record.lease &&
9311
9640
  now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
9312
9641
  facts.lastExecution !== 'relaunch' &&
@@ -9560,6 +9889,43 @@ export class Dispatcher {
9560
9889
  )
9561
9890
  }
9562
9891
 
9892
+ /** The builds that can answer an attempt's creation: at most two point
9893
+ * reads at its proposed slug and the slug its own key derives. */
9894
+ private async creationCandidates(
9895
+ attempt: TicketPreparation,
9896
+ slug: string,
9897
+ ): Promise<BuildRecord[]> {
9898
+ const candidates = attempt.creationKey
9899
+ ? [slug, creationBuildSlug(this.deps.repo, slug, attempt.creationKey)]
9900
+ : [slug]
9901
+ const found: BuildRecord[] = []
9902
+ for (const candidate of candidates) {
9903
+ const record = await this.store.getBuild(candidate)
9904
+ if (record) found.push(record)
9905
+ }
9906
+ return found
9907
+ }
9908
+
9909
+ /** A create the work deadline cut after it may have committed: the one
9910
+ * build this attempt owns, read back under the teardown scope, or
9911
+ * undefined when that cannot be confirmed (preparation recovery then
9912
+ * decides, as for any rejected create). */
9913
+ private async cutCreation(
9914
+ attempt: TicketPreparation,
9915
+ slug: string,
9916
+ ): Promise<BuildRecord | undefined> {
9917
+ try {
9918
+ return await this.scoped(async () => {
9919
+ const found = await this.creationCandidates(attempt, slug)
9920
+ if (found.length !== 1) return undefined
9921
+ return (await this.preparationOwns(attempt, found[0]!)) ? found[0] : undefined
9922
+ })
9923
+ } catch (error) {
9924
+ rethrowAuthorityLapse(error)
9925
+ return undefined
9926
+ }
9927
+ }
9928
+
9563
9929
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
9564
9930
  try {
9565
9931
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -9568,14 +9934,7 @@ export class Dispatcher {
9568
9934
  // its own key derives (allocating store): at most two point reads, and
9569
9935
  // never another attempt's build.
9570
9936
  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
- }
9937
+ const found = await this.creationCandidates(attempt, attempt.slug)
9579
9938
  if (found.length > 1)
9580
9939
  return await this.abandonPreparation(
9581
9940
  attempt,
@@ -10434,21 +10793,44 @@ export class Dispatcher {
10434
10793
  },
10435
10794
  })
10436
10795
  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')
10796
+ // Tracked from the creation on: `build.created` admits the build, so
10797
+ // a work deadline that cuts anything after it must carry the start.
10798
+ record = await this.trackStart(
10799
+ (async () => {
10800
+ const created = await store
10801
+ .createBuild({
10802
+ slug,
10803
+ repo: this.deps.repo,
10804
+ ticket: ticket.ref,
10805
+ branch,
10806
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
10807
+ ...(creationKey !== undefined ? { creationKey } : {}),
10808
+ created: {
10809
+ actor: DISPATCHER,
10810
+ type: 'build.created',
10811
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
10812
+ },
10813
+ })
10814
+ .catch(async (error: unknown) => {
10815
+ // The deadline may have cut only the acknowledgement: a
10816
+ // committed `build.created` admitted the build, so resolve
10817
+ // the preparation and carry its first provision.
10818
+ if (!this.budgetSpent(this.tickOpts)) throw error
10819
+ const owned = await this.cutCreation(attempt, slug)
10820
+ if (owned === undefined) throw error
10821
+ established = true
10822
+ await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
10823
+ (resolution: unknown) => rethrowAuthorityLapse(resolution),
10824
+ )
10825
+ return this.carryCutFirstDispatch(owned.slug, error)
10826
+ })
10827
+ established = true
10828
+ await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
10829
+ this.carryCutFirstDispatch(created.slug, error),
10830
+ )
10831
+ return created
10832
+ })(),
10833
+ )
10452
10834
  settle(ticket, { outcome: 'started', slug: record.slug })
10453
10835
  } catch (error) {
10454
10836
  // A lapse is not a preparation failure: the successor recovers the
@@ -10491,12 +10873,14 @@ export class Dispatcher {
10491
10873
  report.queued -= 1
10492
10874
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
10493
10875
  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
- })
10876
+ const outcome = await this.trackStart(
10877
+ this.attemptDispatchCompletion(record, launched, report, {
10878
+ ticket,
10879
+ body,
10880
+ ...(authoredSession !== undefined ? { authoredSession } : {}),
10881
+ ...createdSeed,
10882
+ }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
10883
+ )
10500
10884
  // Accepted dispatches: durable boundaries recorded. A deferred outcome
10501
10885
  // means the remote provisioning continuation owns the rest.
10502
10886
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1