@defrex/autobuild 1.14.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.
Files changed (35) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +44 -5
  3. package/docs/architecture.md +43 -6
  4. package/docs/configuration.md +8 -3
  5. package/docs/dispatcher-hosting.md +13 -0
  6. package/docs/remote-store-protocol.md +1 -1
  7. package/docs/troubleshooting.md +33 -3
  8. package/docs/workspaces.md +2 -1
  9. package/package.json +3 -3
  10. package/packages/core/src/cli/dispatch.ts +171 -5
  11. package/packages/core/src/cli/repository-status.ts +15 -0
  12. package/packages/core/src/events/policy.ts +1 -0
  13. package/packages/core/src/events/repository.ts +95 -6
  14. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/23d33121de6d3325.json +107 -0
  15. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  16. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  17. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  18. package/packages/core/src/ports/types.ts +10 -4
  19. package/packages/core/src/ports/workspace/vercel-sandbox.ts +281 -75
  20. package/packages/core/src/processes/dispatcher.ts +1142 -265
  21. package/packages/core/src/processes/invocation-budget.ts +6 -0
  22. package/packages/core/src/processes/launch-cut.ts +37 -0
  23. package/packages/core/src/processes/pass-stages.ts +294 -0
  24. package/packages/core/src/store/reducer-value-shapes.json +5285 -5003
  25. package/packages/core/src/store/remote/released-clients.json +22 -0
  26. package/packages/core/src/store/remote/released-reducer-values/1.15.0.json +36354 -0
  27. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  28. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  29. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  30. package/packages/core/src/store/repo-state-events.ts +1 -0
  31. package/packages/core/src/testing/reduced-read-budget.ts +285 -8
  32. package/skills/guide/SKILL.md +25 -3
  33. package/skills/guide/references/remote-store-protocol.md +1 -1
  34. package/skills/operate/SKILL.md +16 -4
  35. package/templates/hosted-service/package.json +2 -2
@@ -71,9 +71,21 @@ import {
71
71
  } from '../kernel/node-restack-demand'
72
72
  import {
73
73
  deferMixedVersion,
74
+ compatibilityDiagnostic,
74
75
  mixedVersionDeferred,
75
76
  MixedVersionDeferral,
76
77
  } from '../kernel/mixed-version'
78
+ import {
79
+ PassStageTracker,
80
+ nextPosition,
81
+ rotateFrom,
82
+ stageCut,
83
+ type PassCursors,
84
+ type PassStage,
85
+ type PassStagePart,
86
+ type PassStageRecord,
87
+ type RotatedPassPart,
88
+ } from './pass-stages'
77
89
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
78
90
  import {
79
91
  CI_FAILURE_PREVIEW,
@@ -348,6 +360,7 @@ import {
348
360
  recoveryStepOf,
349
361
  type WorkspaceRecoveryStep,
350
362
  } from '../ports/workspace/recovery-step'
363
+ import { isLaunchCutByDeadline, type CutLaunch } from './launch-cut'
351
364
  import type {
352
365
  DependencyState,
353
366
  Forge,
@@ -674,14 +687,18 @@ export interface TickReport {
674
687
  provisioning: number
675
688
  /** Builds whose provisioning start was deferred because the bounded
676
689
  * invocation's remaining budget was shorter than the provider's
677
- * 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. */
678
693
  provisioningDeferred: number
679
694
  /** Builds whose stopped-sandbox recovery, or a launch waiting on one, the
680
- * invocation budget deferred this tick. Nothing is charged; the build is
681
- * 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. */
682
699
  recoveryDeferred: number
683
- /** One line per build whose deadline-gated work (a provision or a recovery
684
- * 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. */
685
702
  deferredDiagnostics: string[]
686
703
  /** Dispatch (§12): builds created and launched. With durable supervision
687
704
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
@@ -731,6 +748,9 @@ export interface TickReport {
731
748
  /** Agent-context stage (`processes/agent-context.ts`): typed problems this
732
749
  * tick found capturing the base branch's skills and agent instructions. */
733
750
  agentContextDiagnostics: AgentContextDiagnostic[]
751
+ /** A bounded pass's time and items per stage (#1409); absent for an
752
+ * unbounded pass. Display only: never a reason to publish. */
753
+ stages?: PassStageRecord[]
734
754
  }
735
755
 
736
756
  export function emptyTickReport(): TickReport {
@@ -948,8 +968,17 @@ export interface TickOpts {
948
968
  }
949
969
 
950
970
  /** Deadline-gated work a bounded invocation can defer for budget: a
951
- * provision, or a stopped-sandbox recovery step. */
952
- 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
+ }
953
982
 
954
983
  /** Most entries one `dispatcher.work-deferred` hint carries. */
955
984
  const MAX_DEFERRED_WORK = 64
@@ -1111,6 +1140,14 @@ function errorText(error: unknown): string {
1111
1140
  return error instanceof Error ? error.message : String(error)
1112
1141
  }
1113
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
+
1114
1151
  function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1115
1152
  return error instanceof MissingAccountCredentialsError
1116
1153
  ? error
@@ -1170,11 +1207,15 @@ export class Dispatcher {
1170
1207
  slug: string
1171
1208
  state: Pick<BuildState, 'pollingActivity'>
1172
1209
  }[] = []
1173
- for (const { record, digest } of await this.repoBuildDigests()) {
1210
+ for (const entry of await this.tickDigests()) {
1211
+ const { record, digest } = entry
1174
1212
  if (record.slug === slug) continue
1175
1213
  // The digest names every node a build ever targeted, so a build it does
1176
1214
  // not name can never be this node's child and needs no facts read.
1177
1215
  if (!digestNodeTargets(digest).includes(slug)) continue
1216
+ // A bounded pass lists unfiltered: a deferred child stays out, as the
1217
+ // filtered listing kept it out.
1218
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
1178
1219
  const known = this.nodePollingBuilds.get(record.slug)
1179
1220
  // Only node relationships can move. Unrelated known work never needs
1180
1221
  // another full-facts read, even while it is running.
@@ -1368,7 +1409,16 @@ export class Dispatcher {
1368
1409
  private tickLaunched: ReadonlySet<string> = new Set()
1369
1410
  /** Per tick, in insertion order: builds whose deadline-gated work this tick
1370
1411
  * deferred for budget, with the first step seen and an optional detail. */
1371
- 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>>()
1372
1422
  /** Per tick: carried builds the early stage took up, which the lease sweep
1373
1423
  * then skips so no build is swept twice in one tick. */
1374
1424
  private readonly tickPrioritized = new Set<string>()
@@ -1377,14 +1427,28 @@ export class Dispatcher {
1377
1427
  * after its own early-stage pass showed it no longer needs priority. */
1378
1428
  private readonly carriedOutstanding = new Map<
1379
1429
  string,
1380
- { step: DeferredWorkStep; visited: boolean }
1430
+ { step: DeferredWorkStep; visited: boolean; instance?: string }
1381
1431
  >()
1382
1432
  /** The durable hint as last read or written. */
1383
- private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1433
+ private recordedDeferrals: DeferredWorkEntry[] = []
1384
1434
  /** The current tick's options, for writes made from deferral sites. */
1385
1435
  private tickOpts: TickOpts = {}
1386
1436
  /** Serializes hint writes so concurrent deferral notes never race. */
1387
1437
  private deferralWrites: Promise<void> = Promise.resolve()
1438
+ /** Per tick: time and items per stage of a bounded pass (#1409). */
1439
+ private pass = new PassStageTracker(() => this.deps.clock().getTime())
1440
+ /** Per tick: the rotated loops' positions read from the durable
1441
+ * `dispatcher.pass-cursors` hint, and those this pass leaves. */
1442
+ private passCursors: PassCursors = {}
1443
+ private nextPassCursors: PassCursors = {}
1444
+ private passCursorsPersisted = false
1445
+ private passCursorWriteFailure: string | undefined
1446
+ /** True while a bounded pass runs: its listings are unfiltered and each
1447
+ * build acted on is checked for mixed-version deferral itself (#1409). */
1448
+ private boundedListings = false
1449
+ /** Per bounded pass: each build's mixed-version verdict, checked at most
1450
+ * once and only when something acts on that build. */
1451
+ private readonly compatibilityVerdicts = new Map<string, Promise<boolean>>()
1388
1452
  /** Per tick: finished leaves the admission gate turned away or deferred,
1389
1453
  * with their priority. Intake reserves their slots. */
1390
1454
  private readonly slotWaiters = new Map<string, BuildPriority>()
@@ -1490,7 +1554,8 @@ export class Dispatcher {
1490
1554
  }
1491
1555
 
1492
1556
  /**
1493
- * 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 →
1494
1559
  * janitor → interrupted dispatch recovery → optional startup resume →
1495
1560
  * lease sweep → dispatch. Startup resume is opt-in
1496
1561
  * because the CLI invokes it
@@ -1622,17 +1687,32 @@ export class Dispatcher {
1622
1687
  }
1623
1688
  }
1624
1689
  this.lastForgeRequests = undefined
1690
+ this.pass = new PassStageTracker(() => this.deps.clock().getTime())
1691
+ this.passCursorsPersisted = false
1692
+ this.passCursorWriteFailure = undefined
1693
+ this.compatibilityVerdicts.clear()
1694
+ this.boundedListings = opts.deadlineAt !== undefined
1625
1695
  try {
1626
1696
  const report = await (this.deps.forge.withReadScope
1627
1697
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1628
1698
  : this.runTick(opts))
1629
1699
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1700
+ // Every early return of `runTick` still leaves its positions.
1701
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1630
1702
  this.finishDeferrals(report)
1631
1703
  report.janitorDiagnostics.push(...this.tickAbandonments)
1704
+ const stages = opts.deadlineAt === undefined ? [] : this.pass.summary()
1705
+ if (stages.length > 0) report.stages = stages
1632
1706
  return report
1633
1707
  } catch (error) {
1708
+ try {
1709
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1710
+ } catch {
1711
+ // The tick's own failure is the one reported.
1712
+ }
1634
1713
  throw this.withTickAbandonments(error)
1635
1714
  } finally {
1715
+ this.boundedListings = false
1636
1716
  this.tickAbandonments = []
1637
1717
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1638
1718
  stop?.()
@@ -1677,6 +1757,8 @@ export class Dispatcher {
1677
1757
  this.parkedSettled.clear()
1678
1758
  this.deferredAdmissions.clear()
1679
1759
  this.tickDeferrals.clear()
1760
+ this.reportedDeferrals.clear()
1761
+ this.deferralsFinished = false
1680
1762
  this.tickPrioritized.clear()
1681
1763
  this.carriedOutstanding.clear()
1682
1764
  this.deferralWriteFailure = undefined
@@ -1691,11 +1773,25 @@ export class Dispatcher {
1691
1773
  // The durable deferral hint from the previous invocation: zero extra
1692
1774
  // reads, it is part of the repository facts the refresh reduced.
1693
1775
  this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1694
- ({ slug, step }) => ({ slug, step }),
1776
+ ({ slug, step, instance }) => ({
1777
+ slug,
1778
+ step,
1779
+ ...(instance !== undefined ? { instance } : {}),
1780
+ }),
1695
1781
  )
1696
- for (const { slug, step } of this.recordedDeferrals)
1782
+ // The rotated loops' positions, from the same reduced facts: no read.
1783
+ this.passCursors =
1784
+ opts.deadlineAt === undefined
1785
+ ? {}
1786
+ : { ...(this.store.repositoryFacts().passCursors?.cursors ?? {}) }
1787
+ this.nextPassCursors = { ...this.passCursors }
1788
+ for (const { slug, step, instance } of this.recordedDeferrals)
1697
1789
  if (!this.carriedOutstanding.has(slug))
1698
- this.carriedOutstanding.set(slug, { step, visited: false })
1790
+ this.carriedOutstanding.set(slug, {
1791
+ step,
1792
+ visited: false,
1793
+ ...(instance !== undefined ? { instance } : {}),
1794
+ })
1699
1795
  // A pending start request measures capacity from the facts this tick's
1700
1796
  // fleet-wide stages read anyway; keep them only then.
1701
1797
  this.store.retainBuildFacts(
@@ -1703,6 +1799,7 @@ export class Dispatcher {
1703
1799
  )
1704
1800
  const autoMergeUser = undefined
1705
1801
  const report = emptyTickReport()
1802
+ this.inFlightReport = report
1706
1803
  this.restoreScan(report)
1707
1804
  /** Builds already launched this tick — a janitor/startup re-attach must
1708
1805
  * not be doubled by the sweep, nor a fresh dispatch by anything. */
@@ -1737,73 +1834,254 @@ export class Dispatcher {
1737
1834
  // open the first record listing of the next stage; each stage's own
1738
1835
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1739
1836
  if (this.outOfBudget(opts)) return report
1740
- // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1741
- // recovery an earlier invocation deferred for budget are swept first,
1742
- // while nearly the whole work window remains.
1743
- if (!opts.observationOnly) await this.serviceDeferredWork(report, launched, paused, opts)
1744
- if (this.outOfBudget(opts)) return report
1745
- await this.settleForeignExecutions(report, opts)
1746
- if (this.outOfBudget(opts)) return report
1747
- await this.settleHarvestExecutions(opts)
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.
1840
+ if (!opts.observationOnly)
1841
+ await this.runStage('deferred', opts, (stageOpts) =>
1842
+ this.serviceDeferredWork(report, launched, paused, stageOpts),
1843
+ )
1748
1844
  if (this.outOfBudget(opts)) return report
1749
- await this.settleOrchestratorSandboxes(report, opts)
1845
+ await this.runStage('settlement', opts, async (stageOpts) => {
1846
+ await this.settleForeignExecutions(report, stageOpts)
1847
+ if (this.outOfBudget(opts)) return
1848
+ await this.settleHarvestExecutions(stageOpts)
1849
+ if (this.outOfBudget(opts)) return
1850
+ await this.settleOrchestratorSandboxes(report, stageOpts)
1851
+ })
1750
1852
  if (opts.observationOnly) return report
1751
1853
  if (this.outOfBudget(opts)) return report
1752
- // The default fan-out runs before the janitor so one tick both records the
1753
- // consent and lets the janitor act on it (the janitor reduces a fresh read
1754
- // inside `checkPr`). Independent of intake and `acceptNewWork` — the
1755
- // durable fact drives it, so a second dispatcher polling the same
1756
- // repository converges the same state.
1757
- if (this.outOfBudget(opts)) return report
1758
- await this.recoverTicketPreparations(report, opts)
1759
- if (this.outOfBudget(opts)) return report
1760
- await this.janitor(report, launched, opts)
1761
- if (this.outOfBudget(opts)) return report
1762
- await this.settleHandbacks()
1763
- if (this.outOfBudget(opts)) return report
1764
- await this.recoverDispatches(report, launched, paused, opts)
1854
+ await this.runStage('preparations', opts, (stageOpts) =>
1855
+ this.recoverTicketPreparations(report, stageOpts),
1856
+ )
1765
1857
  if (this.outOfBudget(opts)) return report
1766
- if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, opts)
1858
+ await this.runStage('janitor', opts, (stageOpts) => this.janitor(report, launched, stageOpts))
1767
1859
  if (this.outOfBudget(opts)) return report
1768
- await this.leaseSweep(report, launched, paused, opts)
1860
+ await this.runStage('recovery', opts, async (stageOpts) => {
1861
+ await this.settleHandbacks(stageOpts)
1862
+ if (this.outOfBudget(opts)) return
1863
+ await this.recoverDispatches(report, launched, paused, stageOpts)
1864
+ if (this.outOfBudget(opts)) return
1865
+ if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, stageOpts)
1866
+ })
1769
1867
  if (this.outOfBudget(opts)) return report
1770
- // Nodes with a durable verification or propose request take freed slots
1771
- // before intake, whether or not idle node polling visited them this tick.
1772
- // The same pass advances optimization nodes' proposers first.
1773
- await this.admitWaitingNodes(report, launched, opts)
1868
+ await this.runStage('sweep', opts, (stageOpts) =>
1869
+ this.leaseSweep(report, launched, paused, stageOpts),
1870
+ )
1871
+ // Every rotated loop has run: record where the next pass continues.
1872
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1774
1873
  if (this.outOfBudget(opts)) return report
1775
- // Operator start requests are independent of intake: they claim only the
1776
- // named tickets, and read nothing when none is pending. Manual and urgent
1777
- // requests run here, ahead of ordinary claims; high, normal and low
1778
- // requests run inside intake, after higher-level claims and before their
1779
- // own level's ready tickets, or after intake when it reaches no ticket of
1780
- // their level (SPEC §12 "Slot admission order").
1781
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
1874
+ await this.runStage('admission', opts, async (stageOpts) => {
1875
+ // Nodes with a durable verification or propose request take freed slots
1876
+ // before intake, whether or not idle node polling visited them this tick.
1877
+ // The same pass advances optimization nodes' proposers first.
1878
+ await this.admitWaitingNodes(report, launched, stageOpts)
1879
+ if (this.outOfBudget(opts)) return
1880
+ // Operator start requests are independent of intake: they claim only the
1881
+ // named tickets, and read nothing when none is pending. Manual and urgent
1882
+ // requests run here, ahead of ordinary claims; high, normal and low
1883
+ // requests run inside intake, after higher-level claims and before their
1884
+ // own level's ready tickets, or after intake when it reaches no ticket of
1885
+ // their level (SPEC §12 "Slot admission order").
1886
+ await this.honorStartRequests(
1887
+ report,
1888
+ launched,
1889
+ autoMergeUser,
1890
+ paused,
1891
+ stageOpts,
1892
+ EARLY_START_TIERS,
1893
+ )
1894
+ })
1782
1895
  if (this.outOfBudget(opts)) return report
1783
- if (opts.acceptNewWork !== false) {
1784
- await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1785
- }
1786
- await this.admitDeferredParked(report, launched, paused, opts)
1787
- // Late tiers intake did not reach: ordinary claims left their reserved
1788
- // slots free.
1789
- const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1790
- if (!this.outOfBudget(opts) && lateTiers.length > 0)
1791
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1792
- // Fire-and-forget by contract: long synthesize/review sessions must not
1793
- // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1794
- // watch ticks. Durable pause and infrastructure-error stops suppress
1795
- // launch. Pending control commands still launch the runner so the kernel
1796
- // can settle them under the repository lease.
1797
- if (!this.budgetSpent(opts)) await this.triggerHarvest()
1798
- await this.captureAgentContext(report, opts)
1896
+ await this.runStage('intake', opts, async (stageOpts) => {
1897
+ if (opts.acceptNewWork !== false) {
1898
+ await this.dispatch(report, launched, autoMergeUser, paused, stageOpts, autoMergeSeedFact)
1899
+ }
1900
+ await this.admitDeferredParked(report, launched, paused, stageOpts)
1901
+ // Late tiers intake did not reach: ordinary claims left their reserved
1902
+ // slots free.
1903
+ const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1904
+ if (!this.outOfBudget(opts) && lateTiers.length > 0)
1905
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, stageOpts, lateTiers)
1906
+ // Fire-and-forget by contract: long synthesize/review sessions must not
1907
+ // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1908
+ // watch ticks. Durable pause and infrastructure-error stops suppress
1909
+ // launch. Pending control commands still launch the runner so the kernel
1910
+ // can settle them under the repository lease.
1911
+ if (!this.budgetSpent(opts)) {
1912
+ this.pass.item('harvest-trigger')
1913
+ this.pass.total('harvest-trigger', 1)
1914
+ await this.triggerHarvest()
1915
+ }
1916
+ await this.captureAgentContext(report, stageOpts)
1917
+ })
1799
1918
  return report
1800
1919
  }
1801
1920
 
1921
+ /** Run one stage of the pass (#1409). A bounded pass gives the stage's
1922
+ * helpers a stage-scoped copy of `opts` whose `deadlineAt` is the stage's
1923
+ * cut, and records the stage's time and items; an unbounded pass passes
1924
+ * `opts` itself and records nothing. A throw leaves the stage running, so
1925
+ * `passSummary` reports it as in flight. */
1926
+ private runStage(
1927
+ stage: PassStage,
1928
+ opts: TickOpts,
1929
+ run: (stageOpts: TickOpts) => Promise<void>,
1930
+ ): Promise<void> {
1931
+ // Unbounded: the helpers' own promise, scheduled exactly as before.
1932
+ if (opts.deadlineAt === undefined) return run(opts)
1933
+ return this.runBoundedStage(stage, opts, opts.deadlineAt, run)
1934
+ }
1935
+
1936
+ private async runBoundedStage(
1937
+ stage: PassStage,
1938
+ opts: TickOpts,
1939
+ deadlineAt: number,
1940
+ run: (stageOpts: TickOpts) => Promise<void>,
1941
+ ): Promise<void> {
1942
+ this.pass.begin(stage)
1943
+ await run({ ...opts, deadlineAt: stageCut(stage, this.deps.clock().getTime(), deadlineAt) })
1944
+ // A final item that crossed the work deadline met no later gate.
1945
+ this.pass.end(this.outOfBudget(this.tickOpts))
1946
+ }
1947
+
1948
+ /** The per-item gate of every stage loop (#1409): stop once the invocation
1949
+ * budget is spent, or once the stage's cut has passed and `part` has
1950
+ * already started an item this pass, so each helper always gets its first
1951
+ * item. Without a deadline this is `outOfBudget(opts)`. */
1952
+ private stageGate(stageOpts: TickOpts, part: PassStagePart): boolean {
1953
+ if (this.outOfBudget(this.tickOpts)) {
1954
+ this.pass.stop(part, 'deadline')
1955
+ return true
1956
+ }
1957
+ if (stageOpts !== this.tickOpts && this.outOfBudget(stageOpts) && this.pass.started(part) > 0) {
1958
+ this.pass.stop(part, 'share')
1959
+ return true
1960
+ }
1961
+ return false
1962
+ }
1963
+
1964
+ /** `stageGate` for one item, counting it when it starts. */
1965
+ private passItem(stageOpts: TickOpts, part: PassStagePart): boolean {
1966
+ if (this.stageGate(stageOpts, part)) return false
1967
+ this.pass.item(part)
1968
+ return true
1969
+ }
1970
+
1971
+ /** A rotated loop's items and continuation (#1409). A bounded pass visits
1972
+ * them in key order after the saved position, wrapping. Each started item's
1973
+ * key becomes the live position at once, so a pass abandoned at the work
1974
+ * deadline mid-visit still continues after it; `finish` clears the
1975
+ * position once every item was reached. An unbounded pass keeps the
1976
+ * listing order and saves nothing. */
1977
+ private rotated<T>(part: RotatedPassPart, list: readonly T[], key: (item: T) => string) {
1978
+ const bounded = this.tickOpts.deadlineAt !== undefined
1979
+ const previous = this.passCursors[part]
1980
+ const items = bounded ? rotateFrom(list, key, previous) : [...list]
1981
+ let lastStarted: string | undefined
1982
+ let stopped = false
1983
+ this.pass.total(part, items.length)
1984
+ return {
1985
+ items,
1986
+ /** Gate `item`; false stops the loop. */
1987
+ start: (stageOpts: TickOpts, item: T): boolean => {
1988
+ if (!this.passItem(stageOpts, part)) {
1989
+ stopped = true
1990
+ return false
1991
+ }
1992
+ lastStarted = key(item)
1993
+ if (bounded) this.nextPassCursors[part] = lastStarted
1994
+ return true
1995
+ },
1996
+ /** An item reached and passed over without starting work. */
1997
+ skip: () => this.pass.item(part, false),
1998
+ finish: () => {
1999
+ if (!bounded) return
2000
+ const next = nextPosition({ lastStarted, reachedAll: !stopped, previous })
2001
+ if (next === undefined) delete this.nextPassCursors[part]
2002
+ else this.nextPassCursors[part] = next
2003
+ },
2004
+ }
2005
+ }
2006
+
2007
+ /** Bounded teardown's write of the live rotated positions (#1409): a pass
2008
+ * the work deadline abandoned mid-visit records where its loops reached,
2009
+ * through the tick's authorized teardown scope. Once a pass, best effort,
2010
+ * and nothing when no position changed or the pass already recorded them. */
2011
+ persistPassPositions(): Promise<void> {
2012
+ return this.persistPassCursors()
2013
+ }
2014
+
2015
+ /** This bounded pass's stage records, with a stage still in flight closed
2016
+ * as stopped by the deadline. Never mutates the pass. */
2017
+ passSummary(): PassStageRecord[] {
2018
+ return this.pass.summary()
2019
+ }
2020
+
2021
+ /** The current tick's report so far, with `passSummary` as its stages: what
2022
+ * bounded teardown records for a pass the work deadline abandoned.
2023
+ * Undefined before a bounded tick starts. */
2024
+ passReport(): TickReport | undefined {
2025
+ if (this.inFlightReport === undefined || this.tickOpts.deadlineAt === undefined)
2026
+ return undefined
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() }
2036
+ }
2037
+
2038
+ private inFlightReport: TickReport | undefined
2039
+ /** Whether this tick's report already counts its deferrals. */
2040
+ private deferralsFinished = false
2041
+
2042
+ /** The repository listing every tick stage reads: unfiltered in a bounded
2043
+ * pass, where each build acted on is checked by `checkCompatibility`;
2044
+ * filtered for mixed-version deferral otherwise. */
2045
+ private tickDigests(): ReturnType<Dispatcher['repoBuildDigests']> {
2046
+ return this.repoBuildDigests(this.boundedListings)
2047
+ }
2048
+
2049
+ /** A bounded pass's targeted mixed-version check (#1409): true when this
2050
+ * runtime must make no decision on the build, recording the deferral once
2051
+ * per boundary. With `state` already read it decides from that state;
2052
+ * otherwise a digest without decisive facts answers false with no read.
2053
+ * At most one facts read per build per pass. Always false in an unbounded
2054
+ * pass, whose listings already excluded deferred builds. */
2055
+ private checkCompatibility(
2056
+ entry: { record: { slug: string }; digest?: BuildDigest },
2057
+ state?: Pick<BuildState, 'compatibility'>,
2058
+ ): Promise<boolean> {
2059
+ if (!this.boundedListings) return Promise.resolve(false)
2060
+ if (
2061
+ state !== undefined
2062
+ ? !mixedVersionDeferred(state)
2063
+ : (entry.digest?.compatibility?.decisiveFacts ?? 0) === 0
2064
+ )
2065
+ return Promise.resolve(false)
2066
+ const slug = entry.record.slug
2067
+ let verdict = this.compatibilityVerdicts.get(slug)
2068
+ if (verdict === undefined) {
2069
+ const store = this.store
2070
+ const readFacts = (slug: string) =>
2071
+ this.startPass ? store.servedBuildFacts(slug) : store.buildFacts(slug)
2072
+ verdict = deferMixedVersion(store, slug, undefined, readFacts)
2073
+ this.compatibilityVerdicts.set(slug, verdict)
2074
+ }
2075
+ return verdict
2076
+ }
2077
+
1802
2078
  /** Agent-context stage: contained, so a capture failure never fails the
1803
2079
  * tick; only an authority lapse escapes. */
1804
2080
  private async captureAgentContext(report: TickReport, opts: TickOpts): Promise<void> {
1805
2081
  const stage = this.deps.agentContext
1806
2082
  if (stage === undefined || this.outOfBudget(opts)) return
2083
+ this.pass.total('context', 1)
2084
+ this.pass.item('context')
1807
2085
  try {
1808
2086
  report.agentContextDiagnostics.push(
1809
2087
  ...(await stage.run({
@@ -1876,10 +2154,8 @@ export class Dispatcher {
1876
2154
 
1877
2155
  /** Builds with no terminal fact: the only ones whose tick duties change
1878
2156
  * their state (decide, resume, lease sweep, capacity). */
1879
- private async nonterminalBuilds(): Promise<BuildRecord[]> {
1880
- return (await this.repoBuildDigests())
1881
- .filter(({ digest }) => digest.terminal === undefined)
1882
- .map(({ record }) => record)
2157
+ private async nonterminalEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2158
+ return (await this.tickDigests()).filter(({ digest }) => digest.terminal === undefined)
1883
2159
  }
1884
2160
 
1885
2161
  /** Builds that still have work: nonterminal ones, plus terminal builds whose
@@ -1887,10 +2163,10 @@ export class Dispatcher {
1887
2163
  * cleanup's `build.completed`, a `done` build with an unreclaimed release
1888
2164
  * asset, or any build with an execution the provider has not been seen to
1889
2165
  * end. A terminal, settled build costs no event reads. */
1890
- private async workBuilds(): Promise<BuildRecord[]> {
1891
- return (await this.repoBuildDigests())
1892
- .filter(({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true)
1893
- .map(({ record }) => record)
2166
+ private async workEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2167
+ return (await this.tickDigests()).filter(
2168
+ ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2169
+ )
1894
2170
  }
1895
2171
 
1896
2172
  private async sourceCondition(
@@ -2019,17 +2295,24 @@ export class Dispatcher {
2019
2295
 
2020
2296
  /** Settle reported build hand-backs whose build is complete (or gone).
2021
2297
  * Zero reads and appends while no hand-back is open. */
2022
- private async settleHandbacks(): Promise<void> {
2298
+ private async settleHandbacks(opts: TickOpts = {}): Promise<void> {
2023
2299
  const open = Object.keys(this.store.repositoryFacts().handbacks)
2024
- if (open.length === 0) return
2300
+ if (open.length === 0) return this.pass.total('handbacks', 0)
2025
2301
  const digests = new Map(
2026
2302
  (await this.repoBuildDigests(true)).map(({ record, digest }) => [record.slug, digest]),
2027
2303
  )
2028
- for (const identity of open) {
2304
+ const loop = this.rotated('handbacks', open, (identity) => identity)
2305
+ for (const identity of loop.items) {
2029
2306
  const slug = identity.slice('build:'.length)
2030
2307
  const digest = digests.get(slug)
2031
- if (digest === undefined || digest.terminal === 'done') await this.settleBuildHandback(slug)
2308
+ if (digest !== undefined && digest.terminal !== 'done') {
2309
+ loop.skip()
2310
+ continue
2311
+ }
2312
+ if (!loop.start(opts, identity)) break
2313
+ await this.settleBuildHandback(slug)
2032
2314
  }
2315
+ loop.finish()
2033
2316
  }
2034
2317
 
2035
2318
  /** Admit pending operator start requests of the given tiers through
@@ -2049,6 +2332,7 @@ export class Dispatcher {
2049
2332
  tiers: readonly StartTier[],
2050
2333
  ): Promise<StartPassResult> {
2051
2334
  const result: StartPassResult = { settled: [] }
2335
+ this.pass.total('starts', 0)
2052
2336
  for (const tier of tiers)
2053
2337
  if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
2054
2338
  await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
@@ -2111,8 +2395,12 @@ export class Dispatcher {
2111
2395
  const identities = this.store.repositoryFacts().ticketStarts.identities
2112
2396
  const lifecycle = ticketLifecycle(config.tickets)
2113
2397
  const candidates: { request: PendingTicketStart; ticket: Ticket }[] = []
2398
+ this.pass.total('starts', pending.length)
2399
+ // The stage's share stops further lookups only: every request already
2400
+ // looked up goes on to its claim, so each pass settles or claims its
2401
+ // prefix and the next pass never repeats work this one lost (#1409).
2114
2402
  for (const request of pending) {
2115
- if (this.outOfBudget(opts)) return
2403
+ if (!this.passItem(opts, 'starts')) break
2116
2404
  let ref: TicketRef | undefined
2117
2405
  try {
2118
2406
  ref = resolveTicketRef(migrations, request.ticket, tickets.name)
@@ -2169,7 +2457,10 @@ export class Dispatcher {
2169
2457
  if (this.preparing(ticket.ref.source, ticket.ref.id)) continue
2170
2458
  candidates.push({ request, ticket })
2171
2459
  }
2172
- if (candidates.length === 0 || this.outOfBudget(opts)) return
2460
+ // A looked-up request's claim is in-flight work: only the invocation
2461
+ // budget stops it, never the stage's cut.
2462
+ const claimOpts = this.tickOpts.deadlineAt === undefined ? opts : this.tickOpts
2463
+ if (candidates.length === 0 || this.outOfBudget(claimOpts)) return
2173
2464
  // Capacity is measured from the facts this tick's janitor, recovery and
2174
2465
  // lease sweep already read (`servedBuildFacts`): a build is read again
2175
2466
  // only when the tick skipped it or wrote to it since, so neither a wait
@@ -2214,7 +2505,7 @@ export class Dispatcher {
2214
2505
  const scratch = emptyTickReport()
2215
2506
  this.startPass = true
2216
2507
  try {
2217
- await this.dispatch(scratch, launched, autoMergeUser, paused, opts, undefined, targeted)
2508
+ await this.dispatch(scratch, launched, autoMergeUser, paused, claimOpts, undefined, targeted)
2218
2509
  } finally {
2219
2510
  this.startPass = false
2220
2511
  for (const counter of [
@@ -2407,7 +2698,8 @@ export class Dispatcher {
2407
2698
  private async activeTicketIdentities(refs: TicketRef[], listed: Ticket[]): Promise<Set<string>> {
2408
2699
  const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
2409
2700
  const migrations = this.store.repositoryFacts().ticketMigrations
2410
- const records = await this.repoBuildDigests()
2701
+ // Identity only: a deferred build's slug names its own ticket.
2702
+ const records = await this.tickDigests()
2411
2703
  const normalized = refs.map((ref) => {
2412
2704
  try {
2413
2705
  return resolveTicketRef(
@@ -2444,7 +2736,22 @@ export class Dispatcher {
2444
2736
  * disabled. It shares the active-ticket exclusion with dispatch but performs
2445
2737
  * no dependency fetch, claim, bounce, build, workspace, or launch side
2446
2738
  * effect, and deliberately does not alter TickReport compatibility. */
2447
- async observeReady(opts: Pick<TickOpts, 'viewRefreshed'> = {}): Promise<{
2739
+ async observeReady(opts: Pick<TickOpts, 'viewRefreshed' | 'deadlineAt'> = {}): Promise<{
2740
+ queued: number
2741
+ invalidTickets: number
2742
+ ticketDiagnostics: string[]
2743
+ }> {
2744
+ // A bounded invocation's listings are unfiltered: this observation only
2745
+ // asks which tickets are active, so a deferred build's ticket stays active.
2746
+ this.boundedListings = opts.deadlineAt !== undefined
2747
+ try {
2748
+ return await this.observeReadyListing(opts)
2749
+ } finally {
2750
+ this.boundedListings = false
2751
+ }
2752
+ }
2753
+
2754
+ private async observeReadyListing(opts: Pick<TickOpts, 'viewRefreshed'>): Promise<{
2448
2755
  queued: number
2449
2756
  invalidTickets: number
2450
2757
  ticketDiagnostics: string[]
@@ -2457,7 +2764,7 @@ export class Dispatcher {
2457
2764
  if (checkpoint.due) {
2458
2765
  const listing = await this.listReady()
2459
2766
  const refs: TicketRef[] = []
2460
- for (const { record, digest } of await this.repoBuildDigests()) {
2767
+ for (const { record, digest } of await this.tickDigests()) {
2461
2768
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
2462
2769
  }
2463
2770
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
@@ -2521,7 +2828,8 @@ export class Dispatcher {
2521
2828
  /** `force` makes the scan due now, skipping the interval and the journal
2522
2829
  * deferral: a deferred admission waits on this tick's higher-level claims. */
2523
2830
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2524
- const digest = (await this.repoBuildDigests())
2831
+ // A fingerprint of readiness digests: no decision reads a build's state.
2832
+ const digest = (await this.tickDigests())
2525
2833
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
2526
2834
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
2527
2835
  .sort(([a], [b]) => a.localeCompare(b))
@@ -2739,7 +3047,22 @@ export class Dispatcher {
2739
3047
  /** The one guarded runner start. Every dispatcher path that starts a runner
2740
3048
  * goes through here, so the no-progress policy cannot depend on which path
2741
3049
  * runs. */
2742
- 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> {
2743
3066
  if (
2744
3067
  !(await ensureExecutionProgress(
2745
3068
  this.store,
@@ -2754,6 +3077,13 @@ export class Dispatcher {
2754
3077
  try {
2755
3078
  return await this.deps.launchRunner(slug)
2756
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
+ }
2757
3087
  // A launch waiting on a stopped-sandbox recovery the budget deferred:
2758
3088
  // nothing started and nothing is charged. Record it so the next
2759
3089
  // invocation runs it first; callers see the same result as before.
@@ -2780,13 +3110,19 @@ export class Dispatcher {
2780
3110
  * the stage still settles. */
2781
3111
  private async settleForeignExecutions(report: TickReport, opts: TickOpts = {}): Promise<void> {
2782
3112
  const active = this.deps.activeExecutions?.() ?? new Set<string>()
2783
- for (const record of await this.workBuilds()) {
2784
- if (active.has(record.slug)) continue
3113
+ const loop = this.rotated('executions', await this.workEntries(), (entry) => entry.record.slug)
3114
+ for (const entry of loop.items) {
3115
+ const { record } = entry
2785
3116
  // The early stage already observed and settled it this tick.
2786
- if (this.tickPrioritized.has(record.slug)) continue
2787
- // Budget gate: once spent, stop settling further foreign executions.
2788
- if (this.outOfBudget(opts)) break
3117
+ if (active.has(record.slug) || this.tickPrioritized.has(record.slug)) {
3118
+ loop.skip()
3119
+ continue
3120
+ }
3121
+ // Budget gate: once the stage's share or the budget is spent, stop
3122
+ // settling further foreign executions.
3123
+ if (!loop.start(opts, entry)) break
2789
3124
  try {
3125
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
2790
3126
  const { open } = await this.store.buildFacts(record.slug)
2791
3127
  if (open === null) continue
2792
3128
  const owner = this.executionOwner(open.provider)
@@ -2814,6 +3150,7 @@ export class Dispatcher {
2814
3150
  await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2815
3151
  }
2816
3152
  }
3153
+ loop.finish()
2817
3154
  }
2818
3155
 
2819
3156
  /** Durable settlement for hosted-harvest executions (AUT-305), next to the
@@ -2834,11 +3171,17 @@ export class Dispatcher {
2834
3171
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
2835
3172
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
2836
3173
  const facts = this.store.repositoryFacts()
2837
- for (const execution of facts.openHarvest) {
2838
- if (active.has(execution.execution)) continue
3174
+ const loop = this.rotated('harvest', facts.openHarvest, (execution) =>
3175
+ JSON.stringify(execution.execution),
3176
+ )
3177
+ for (const execution of loop.items) {
3178
+ if (active.has(execution.execution)) {
3179
+ loop.skip()
3180
+ continue
3181
+ }
2839
3182
  // Budget gate: once spent, stop settling further harvest executions;
2840
3183
  // the next tick retries what remains.
2841
- if (this.outOfBudget(opts)) break
3184
+ if (!loop.start(opts, execution)) break
2842
3185
  try {
2843
3186
  const owner = this.executionOwner(execution.provider)
2844
3187
  const capability = owner?.harvestExecution
@@ -2919,6 +3262,7 @@ export class Dispatcher {
2919
3262
  // settlement stage; the next tick retries it.
2920
3263
  }
2921
3264
  }
3265
+ loop.finish()
2922
3266
  }
2923
3267
 
2924
3268
  /** A foreign hosted-harvest execution still open after this tick's
@@ -2968,15 +3312,20 @@ export class Dispatcher {
2968
3312
  const providerName = this.deps.workspaces.name
2969
3313
  const facts = this.store.repositoryFacts()
2970
3314
  const idleMs = config.orchestrator.sandbox.idleMinutes * 60_000
2971
- for (let environment of facts.sandboxes) {
2972
- if (environment.state !== 'live') continue
2973
- // Budget gate: once spent, stop settling further environments; the
2974
- // next tick retries what remains.
2975
- if (this.outOfBudget(opts)) break
3315
+ const loop = this.rotated(
3316
+ 'sandboxes',
3317
+ facts.sandboxes.filter((environment) => environment.state === 'live'),
3318
+ (environment) => `${environment.operator}\u0000${environment.environmentId}`,
3319
+ )
3320
+ for (let environment of loop.items) {
2976
3321
  const lastEvidence = Date.parse(environment.lastEvidenceTs)
2977
3322
  if (Number.isFinite(lastEvidence) && this.deps.clock().getTime() - lastEvidence < idleMs) {
3323
+ loop.skip()
2978
3324
  continue
2979
3325
  }
3326
+ // Budget gate: once spent, stop settling further environments; the
3327
+ // next tick retries what remains.
3328
+ if (!loop.start(opts, environment)) break
2980
3329
  try {
2981
3330
  // Other processes may have recorded activity while earlier tick work
2982
3331
  // awaited an outside read. Revalidate only an impending disposition.
@@ -3064,6 +3413,7 @@ export class Dispatcher {
3064
3413
  )
3065
3414
  }
3066
3415
  }
3416
+ loop.finish()
3067
3417
  }
3068
3418
 
3069
3419
  // ── Background provisioning (durable supervision) ──────────────────────────
@@ -3450,16 +3800,15 @@ export class Dispatcher {
3450
3800
  // builds are another dispatcher's duty; settled terminal builds cost no
3451
3801
  // event reads).
3452
3802
  // Unfiltered, so optimization stop enforcement sees terminal attempt builds.
3453
- const builds = await this.repoBuildDigests()
3454
- const entries = builds.filter(
3803
+ const allBuilds = await this.tickDigests()
3804
+ const entries = allBuilds.filter(
3455
3805
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
3456
3806
  )
3457
3807
  this.janitorEntries = entries
3458
3808
  this.nodeChildren = undefined
3459
- // Receipt reporting requires no forge call, capacity or workspace. Recover
3460
- // every episode before the transport-budget and janitor-backoff gates.
3461
- for (const { record, digest } of entries) {
3462
- if (digest.kind !== 'node' || !digest.nodeOpened || digest.terminal) continue
3809
+ // Receipt reporting requires no forge call, capacity or workspace.
3810
+ const recoverReceipts = async (record: BuildRecord, digest: BuildDigest) => {
3811
+ if (digest.kind !== 'node' || !digest.nodeOpened || digest.terminal) return
3463
3812
  try {
3464
3813
  await reportIntegrationFailures(this.store, record.slug)
3465
3814
  } catch (error) {
@@ -3469,13 +3818,24 @@ export class Dispatcher {
3469
3818
  )
3470
3819
  }
3471
3820
  }
3472
- for (const { record, digest } of entries) {
3821
+ // A bounded pass recovers each node's receipts at the start of its own
3822
+ // visit, so the janitor's share bounds the work and its rotation covers
3823
+ // every node (#1409). Otherwise every episode is recovered first, before
3824
+ // the transport-budget and janitor-backoff gates.
3825
+ const bounded = this.tickOpts.deadlineAt !== undefined
3826
+ if (!bounded) for (const { record, digest } of entries) await recoverReceipts(record, digest)
3827
+ const loop = this.rotated('janitor', entries, (entry) => entry.record.slug)
3828
+ for (const entry of loop.items) {
3829
+ const { record, digest } = entry
3473
3830
  // Budget gate: the janitor's per-build path issues forge/store transport
3474
- // calls (PR probes, closePr, deleteBranch); once the budget is spent,
3475
- // stop starting new ones. The remaining builds stay janitor due — the
3476
- // next invocation re-runs them (§3.3 idempotency).
3477
- if (this.outOfBudget(opts)) break
3831
+ // calls (PR probes, closePr, deleteBranch); once its share or the budget
3832
+ // is spent, stop starting new ones. The remaining builds stay janitor
3833
+ // due — the next invocation continues after the last one started
3834
+ // (§3.3 idempotency).
3835
+ if (!loop.start(opts, entry)) break
3836
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
3478
3837
  await withForgeRequestContext({ build: record.slug }, async () => {
3838
+ if (bounded) await recoverReceipts(record, digest)
3479
3839
  let previous: BuildState['janitor']
3480
3840
  // The stage in progress, named if this attempt's failure escalates.
3481
3841
  let operation: JanitorOperation = 'build state read'
@@ -3502,6 +3862,9 @@ export class Dispatcher {
3502
3862
  // Every tick, independent of janitor backoff and idle node polling: an
3503
3863
  // hours budget must fire on a node with no other activity.
3504
3864
  if (state.optimization !== undefined && !mixedVersionDeferred(state)) {
3865
+ const builds = this.boundedListings
3866
+ ? await this.compatibleAttempts(record.slug, allBuilds)
3867
+ : allBuilds
3505
3868
  const deps = {
3506
3869
  store: this.store,
3507
3870
  clock: this.deps.clock,
@@ -3601,7 +3964,7 @@ export class Dispatcher {
3601
3964
  incompleteObservation ||
3602
3965
  executionLeaseLive ||
3603
3966
  report.janitorDiagnostics.length !== diagnosticsBefore ||
3604
- this.outOfBudget(opts)
3967
+ this.outOfBudget(this.tickOpts)
3605
3968
  )
3606
3969
  return
3607
3970
  const current = (await this.store.buildFacts(record.slug)).state
@@ -3814,7 +4177,9 @@ export class Dispatcher {
3814
4177
  refreshOnly: true,
3815
4178
  })
3816
4179
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3817
- await this.cascadeNode(record, state, report, launched, opts)
4180
+ // In-flight work is never cancelled at the janitor's cut: the
4181
+ // node transaction answers to the invocation budget.
4182
+ await this.cascadeNode(record, state, report, launched, this.tickOpts)
3818
4183
  loaded = undefined
3819
4184
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3820
4185
  }
@@ -4015,6 +4380,63 @@ export class Dispatcher {
4015
4380
  }
4016
4381
  })
4017
4382
  }
4383
+ loop.finish()
4384
+ }
4385
+
4386
+ /** The intake preflight's dependency listing (#1409). In a bounded pass the
4387
+ * listing is unfiltered, so each ready ticket's blocker build is checked
4388
+ * and a deferred one dropped (an older generation may then answer, as in
4389
+ * the filtered listing). `decidable` tells whether a build may count as
4390
+ * built: one with decisive facts only once checked. Unbounded, the listing
4391
+ * is already filtered and returned as is. */
4392
+ private async compatibleBlockers(
4393
+ entries: { record: BuildRecord; digest: BuildDigest }[],
4394
+ ready: readonly Ticket[],
4395
+ identity: (ref: TicketRef, build?: string) => string,
4396
+ ): Promise<{
4397
+ entries: { record: BuildRecord; digest: BuildDigest }[]
4398
+ decidable: (slug: string, digest: BuildDigest) => boolean
4399
+ }> {
4400
+ if (!this.boundedListings) return { entries, decidable: () => true }
4401
+ const kept = [...entries]
4402
+ const checked = new Set<string>()
4403
+ for (const ticket of ready)
4404
+ for (const id of ticket.blockedBy ?? [])
4405
+ for (;;) {
4406
+ const build = blockerBuild(kept, ticket.ref.source, id, identity)
4407
+ if (build === undefined || typeof build === 'string' || checked.has(build.record.slug))
4408
+ break
4409
+ if (!(this.boundedListings && (await this.checkCompatibility(build)))) {
4410
+ checked.add(build.record.slug)
4411
+ break
4412
+ }
4413
+ kept.splice(kept.indexOf(build as (typeof kept)[number]), 1)
4414
+ }
4415
+ return {
4416
+ entries: kept,
4417
+ decidable: (slug, digest) =>
4418
+ (digest.compatibility?.decisiveFacts ?? 0) === 0 || checked.has(slug),
4419
+ }
4420
+ }
4421
+
4422
+ /** `builds` without the mixed-version deferred builds targeting `node`, in
4423
+ * a bounded pass (#1409): the optimization duties decide and write for a
4424
+ * node's attempt builds, and its unfiltered listing must not hand them a
4425
+ * build this runtime cannot decide. Reads only attempts with decisive facts,
4426
+ * at most once a pass. */
4427
+ private async compatibleAttempts(
4428
+ node: string,
4429
+ builds: { record: BuildRecord; digest: BuildDigest }[],
4430
+ ): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
4431
+ if (!this.boundedListings) return builds
4432
+ const kept: { record: BuildRecord; digest: BuildDigest }[] = []
4433
+ for (const entry of builds)
4434
+ if (
4435
+ !digestNodeTargets(entry.digest).includes(node) ||
4436
+ !(this.boundedListings && (await this.checkCompatibility(entry)))
4437
+ )
4438
+ kept.push(entry)
4439
+ return kept
4018
4440
  }
4019
4441
 
4020
4442
  /** Priming saves requests but must not block parent recovery or ordinary observations. */
@@ -4547,6 +4969,7 @@ export class Dispatcher {
4547
4969
  ): Promise<void> {
4548
4970
  const deferred = [...this.deferredAdmissions]
4549
4971
  this.deferredAdmissions.clear()
4972
+ this.pass.total('parked', 0)
4550
4973
  if (deferred.length === 0) {
4551
4974
  this.lastForcedDeferralKey = undefined
4552
4975
  return
@@ -4556,8 +4979,9 @@ export class Dispatcher {
4556
4979
  // the parked builds stay durable work for the next invocation.
4557
4980
  if (this.budgetSpent(opts)) return
4558
4981
  this.admissionBoundary = false
4982
+ this.pass.total('parked', deferred.length)
4559
4983
  for (const [slug, kind] of deferred) {
4560
- if (this.outOfBudget(opts)) return
4984
+ if (!this.passItem(opts, 'parked')) return
4561
4985
  if (launched.has(slug)) continue
4562
4986
  try {
4563
4987
  const record = await this.store.getBuild(slug)
@@ -4607,7 +5031,9 @@ export class Dispatcher {
4607
5031
  launched: Set<string>,
4608
5032
  opts: TickOpts,
4609
5033
  ): Promise<void> {
4610
- const entries = await this.repoBuildDigests()
5034
+ this.pass.total('nodes', 0)
5035
+ // A deferred node counts as open: it only makes the stage look further.
5036
+ const entries = await this.tickDigests()
4611
5037
  if (!entries.some(({ digest }) => digest.kind === 'node' && digest.terminal === undefined))
4612
5038
  return
4613
5039
  // An optimization node's proposer: exhausted stops, filings and new
@@ -4616,12 +5042,14 @@ export class Dispatcher {
4616
5042
  // accepted. One clock reading serves every stage of the pass.
4617
5043
  const now = this.deps.clock()
4618
5044
  await this.advanceOptimizationNodes(report, opts, entries, now)
4619
- if (this.outOfBudget(opts)) return
5045
+ // Between steps only the invocation budget stops admission: each step's
5046
+ // own loop gets its first item past the stage's cut (#1409).
5047
+ if (this.outOfBudget(this.tickOpts)) return
4620
5048
  const builds = (await this.capacityBuilds()).sort((a, b) =>
4621
5049
  a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0,
4622
5050
  )
4623
5051
  await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4624
- if (this.outOfBudget(opts)) return
5052
+ if (this.outOfBudget(this.tickOpts)) return
4625
5053
  await this.adoptLegacyNodeRunners(builds, now, report)
4626
5054
  // A node asking for a verification slot, and one admitted for
4627
5055
  // verification whose runner never started or was lost: nothing else
@@ -4629,9 +5057,11 @@ export class Dispatcher {
4629
5057
  const waiting = builds.filter((build) => nodeRunnerWork(build, now)?.request === 'verification')
4630
5058
  const admitted = new Set<string>()
4631
5059
  this.passNodeAdmissions = admitted
5060
+ this.pass.total('nodes', waiting.length)
4632
5061
  try {
4633
5062
  for (const build of waiting) {
4634
- if (this.outOfBudget(opts)) return
5063
+ if (!this.passItem(opts, 'nodes')) return
5064
+ if (this.boundedListings && (await this.checkCompatibility(build, build.state))) continue
4635
5065
  await this.admitNode(build, now, report, launched)
4636
5066
  }
4637
5067
  } finally {
@@ -4720,7 +5150,8 @@ export class Dispatcher {
4720
5150
  ): Promise<void> {
4721
5151
  for (const build of builds) {
4722
5152
  if (launched.has(build.record.slug) || !strandedNodeWorkspace(build, now)) continue
4723
- if (this.outOfBudget(opts)) return
5153
+ this.pass.total('nodes', 1)
5154
+ if (!this.passItem(opts, 'nodes')) return
4724
5155
  const { record } = build
4725
5156
  await withForgeRequestContext({ build: record.slug }, async () => {
4726
5157
  try {
@@ -4770,8 +5201,9 @@ export class Dispatcher {
4770
5201
  startRequests: this.startClaims(),
4771
5202
  })
4772
5203
  let occupied = projection.occupied
5204
+ this.pass.total('nodes', proposers.length)
4773
5205
  for (const build of proposers) {
4774
- if (this.outOfBudget(opts)) return
5206
+ if (!this.passItem(opts, 'nodes')) return
4775
5207
  const { record, state } = build
4776
5208
  if (
4777
5209
  launched.has(record.slug) ||
@@ -4844,7 +5276,8 @@ export class Dispatcher {
4844
5276
  failure?: string
4845
5277
  }> {
4846
5278
  const holds = new Map<string, { node: string; request: string }>()
4847
- for (const { record, digest } of await this.repoBuildDigests()) {
5279
+ // Digest signals only: a deferred node's deposit still holds its tickets.
5280
+ for (const { record, digest } of await this.tickDigests()) {
4848
5281
  if (digest.terminal !== undefined) continue
4849
5282
  let signal: ReturnType<typeof digestOptimization>
4850
5283
  try {
@@ -4936,9 +5369,14 @@ export class Dispatcher {
4936
5369
  entries: { record: BuildRecord; digest: BuildDigest }[],
4937
5370
  now: Date,
4938
5371
  ): Promise<void> {
4939
- const due: { record: BuildRecord; kind: 'exhausted' | 'filing' | 'request' }[] = []
5372
+ const due: {
5373
+ entry: { record: BuildRecord; digest: BuildDigest }
5374
+ record: BuildRecord
5375
+ kind: 'exhausted' | 'filing' | 'request'
5376
+ }[] = []
4940
5377
  try {
4941
- for (const { record, digest } of entries) {
5378
+ for (const entry of entries) {
5379
+ const { record, digest } = entry
4942
5380
  if (digest.terminal !== undefined || !digest.nodeOpened) continue
4943
5381
  const signal = digestOptimization(digest)
4944
5382
  if (!signal) continue
@@ -4949,17 +5387,19 @@ export class Dispatcher {
4949
5387
  (digest.executionOpen === true || this.hasLiveExecutionLease(record))
4950
5388
  )
4951
5389
  continue
4952
- if (kind !== undefined) due.push({ record, kind })
5390
+ if (kind !== undefined) due.push({ entry, record, kind })
4953
5391
  }
4954
5392
  } catch (error) {
4955
5393
  if (!(error instanceof BuildDigestCapabilityError)) throw error
4956
5394
  report.janitorDiagnostics.push(`optimization proposing skipped — ${error.message}`)
4957
5395
  return
4958
5396
  }
4959
- for (const { record, kind } of due) {
4960
- if (this.outOfBudget(opts)) return
5397
+ this.pass.total('nodes', due.length)
5398
+ for (const { entry, record, kind } of due) {
5399
+ if (!this.passItem(opts, 'nodes')) return
4961
5400
  await withForgeRequestContext({ build: record.slug }, async () => {
4962
5401
  try {
5402
+ if (this.boundedListings && (await this.checkCompatibility(entry))) return
4963
5403
  if (kind === 'exhausted') await this.recordExhausted(record.slug)
4964
5404
  else if (kind === 'filing') await this.fileProposedAttempts(record, now)
4965
5405
  else await this.requestProposal(record, now)
@@ -5378,6 +5818,11 @@ export class Dispatcher {
5378
5818
  for (const other of this.childrenOf(nodeSlug)) {
5379
5819
  if (other.slug === record.slug || !wanted.has(key(other.ticket!))) continue
5380
5820
  const otherState = (await this.store.buildFacts(other.slug)).state
5821
+ if (
5822
+ this.boundedListings &&
5823
+ (await this.checkCompatibility({ record: other }, otherState))
5824
+ )
5825
+ continue
5381
5826
  if (otherState.target?.build !== nodeSlug) continue
5382
5827
  candidates.push({ slug: other.slug, ticket: other.ticket!, state: otherState })
5383
5828
  }
@@ -6147,7 +6592,7 @@ export class Dispatcher {
6147
6592
  kind?: 'work' | 'node',
6148
6593
  ): Promise<{ sha: string; buildTrailerPresent?: boolean }> {
6149
6594
  if (kind === 'node')
6150
- await this.recoverNodeContributions(await this.repoBuildDigests(), {
6595
+ await this.recoverNodeContributions(await this.tickDigests(), {
6151
6596
  slug: record.slug,
6152
6597
  sha,
6153
6598
  })
@@ -8148,16 +8593,26 @@ export class Dispatcher {
8148
8593
  paused: boolean,
8149
8594
  opts: TickOpts = {},
8150
8595
  ): Promise<void> {
8151
- for (const record of await this.nonterminalBuilds()) {
8596
+ const loop = this.rotated(
8597
+ 'dispatches',
8598
+ await this.nonterminalEntries(),
8599
+ (entry) => entry.record.slug,
8600
+ )
8601
+ for (const entry of loop.items) {
8602
+ const { record } = entry
8152
8603
  if (
8153
8604
  record.ticket === undefined ||
8154
8605
  launched.has(record.slug) ||
8155
- 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)
8156
8609
  ) {
8610
+ loop.skip()
8157
8611
  continue
8158
8612
  }
8159
8613
  // Budget gate: recovery issues store transport calls per build.
8160
- if (this.outOfBudget(opts)) break
8614
+ if (!loop.start(opts, entry)) break
8615
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8161
8616
  const { state } = await this.store.buildFacts(record.slug)
8162
8617
  if (
8163
8618
  state.status !== 'queued' ||
@@ -8178,6 +8633,7 @@ export class Dispatcher {
8178
8633
  // must not bypass the unfinished dispatch boundary later in the tick.
8179
8634
  if (outcome === 'failed') launched.add(record.slug)
8180
8635
  }
8636
+ loop.finish()
8181
8637
  }
8182
8638
 
8183
8639
  // ── c. Dispatch-command startup resume (SPEC §2.2, §15.6-C) ────────────────
@@ -8200,10 +8656,20 @@ export class Dispatcher {
8200
8656
  opts: TickOpts = {},
8201
8657
  ): Promise<void> {
8202
8658
  const store = this.store
8203
- for (const record of await this.nonterminalBuilds()) {
8204
- if (launched.has(record.slug)) continue
8659
+ const loop = this.rotated(
8660
+ 'resume',
8661
+ await this.nonterminalEntries(),
8662
+ (entry) => entry.record.slug,
8663
+ )
8664
+ for (const entry of loop.items) {
8665
+ const { record } = entry
8666
+ if (launched.has(record.slug)) {
8667
+ loop.skip()
8668
+ continue
8669
+ }
8205
8670
  // Budget gate: resume launches runners (transport-backed work).
8206
- if (this.outOfBudget(opts)) break
8671
+ if (!loop.start(opts, entry)) break
8672
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8207
8673
 
8208
8674
  const facts = await store.buildFacts(record.slug)
8209
8675
  const state = facts.state
@@ -8242,6 +8708,7 @@ export class Dispatcher {
8242
8708
  const result = await this.launch(record.slug, launched, report)
8243
8709
  if (result === 'scheduled') report.resumed += 1
8244
8710
  }
8711
+ loop.finish()
8245
8712
  }
8246
8713
 
8247
8714
  // ── c'. Ticket waits (SPEC §11 "Ticket waits") ─────────────────────────────
@@ -8405,15 +8872,21 @@ export class Dispatcher {
8405
8872
  ): Promise<void> {
8406
8873
  const tickets = this.deps.tickets
8407
8874
  const migrations = this.store.repositoryFacts().ticketMigrations
8408
- const waiting: { record: BuildRecord; wait: BuildDigestTicketWait; ids: string[] }[] = []
8409
- for (const { record, digest } of entries) {
8875
+ const waiting: {
8876
+ entry: { record: BuildRecord; digest: BuildDigest }
8877
+ record: BuildRecord
8878
+ wait: BuildDigestTicketWait
8879
+ ids: string[]
8880
+ }[] = []
8881
+ for (const entry of entries) {
8882
+ const { record, digest } = entry
8410
8883
  const wait = digest.ticketWait
8411
8884
  if (digest.terminal !== undefined || digest.kind === 'node' || wait === undefined) continue
8412
8885
  try {
8413
8886
  const ids = wait.tickets.map(
8414
8887
  (ref) => resolveTicketRef(migrations, ref, tickets.name, record.slug).id,
8415
8888
  )
8416
- waiting.push({ record, wait, ids })
8889
+ waiting.push({ entry, record, wait, ids })
8417
8890
  } catch (error) {
8418
8891
  const message = error instanceof Error ? error.message : String(error)
8419
8892
  report.janitorFailed += 1
@@ -8422,6 +8895,7 @@ export class Dispatcher {
8422
8895
  )
8423
8896
  }
8424
8897
  }
8898
+ this.pass.total('waits', waiting.length)
8425
8899
  if (waiting.length === 0 || this.outOfBudget(opts)) return
8426
8900
  const nodes = new Map<string, DependencyNode>()
8427
8901
  try {
@@ -8436,11 +8910,15 @@ export class Dispatcher {
8436
8910
  report.janitorDiagnostics.push(`ticket waits not checked — ${message}`)
8437
8911
  return
8438
8912
  }
8439
- for (const { record, wait, ids } of waiting) {
8913
+ for (const { entry, record, wait, ids } of waiting) {
8440
8914
  const release = ticketWaitRelease(ids, nodes)
8441
- if (release === undefined) continue
8442
- if (this.outOfBudget(opts)) return
8915
+ if (release === undefined) {
8916
+ this.pass.item('waits', false)
8917
+ continue
8918
+ }
8919
+ if (!this.passItem(opts, 'waits')) return
8443
8920
  try {
8921
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8444
8922
  const { state } = await this.store.buildFacts(record.slug)
8445
8923
  const open = openTicketWait(state)
8446
8924
  if (open?.id !== wait.id) continue
@@ -8509,14 +8987,20 @@ export class Dispatcher {
8509
8987
  opts: TickOpts = {},
8510
8988
  ): Promise<void> {
8511
8989
  const now = this.deps.clock().getTime()
8512
- const entries = await this.repoBuildDigests()
8990
+ const entries = await this.tickDigests()
8513
8991
  await this.releaseTicketWaits(entries, report, opts)
8514
8992
  // Terminal builds are filtered on the digest before the lease and TTL
8515
8993
  // checks, so a zero TTL cannot fall through to a log read.
8516
- for (const { record, digest } of entries) {
8517
- if (digest.terminal !== undefined) continue
8994
+ const loop = this.rotated(
8995
+ 'sweep',
8996
+ entries.filter(({ digest }) => digest.terminal === undefined),
8997
+ (entry) => entry.record.slug,
8998
+ )
8999
+ for (const entry of loop.items) {
9000
+ const { record, digest } = entry
8518
9001
  // Budget gate: the sweep re-attaches runners per expired build.
8519
- if (this.outOfBudget(opts)) break
9002
+ if (!loop.start(opts, entry)) break
9003
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8520
9004
  if (digest.waitPending && digest.kind !== 'node')
8521
9005
  await this.serviceWaitRequests(record, report)
8522
9006
  if (launched.has(record.slug)) continue
@@ -8524,6 +9008,7 @@ export class Dispatcher {
8524
9008
  if (this.tickPrioritized.has(record.slug)) continue
8525
9009
  await this.sweepContained(record, report, launched, paused, now)
8526
9010
  }
9011
+ loop.finish()
8527
9012
  }
8528
9013
 
8529
9014
  /** One build's lease-sweep pass under the sweep's per-build containment:
@@ -8538,40 +9023,59 @@ export class Dispatcher {
8538
9023
  launched: Set<string>,
8539
9024
  paused: boolean,
8540
9025
  now: number,
9026
+ carried?: { facts: CurrentBuildFacts },
8541
9027
  ): Promise<'done' | 'waiting' | 'failed'> {
8542
9028
  try {
8543
- return await this.sweepBuild(record, report, launched, paused, now)
9029
+ return await this.sweepBuild(record, report, launched, paused, now, carried)
8544
9030
  } catch (error) {
8545
- rethrowAuthorityLapse(error)
8546
- if (isRecoveryDeferred(error)) {
8547
- await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
8548
- return 'waiting'
8549
- }
8550
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
8551
- return 'waiting'
8552
- if (error instanceof ForgeCooldown) throw error
8553
- const message =
8554
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8555
- report.janitorFailed += 1
8556
- report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8557
- return 'failed'
9031
+ return this.containBuildFailure(record.slug, report, error, 'lease sweep')
8558
9032
  }
8559
9033
  }
8560
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'
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'
9057
+ }
9058
+
8561
9059
  /**
8562
9060
  * Stage −1 — deferred deadline-gated work. Builds the previous invocation
8563
- * recorded in `dispatcher.work-deferred` (a provision or a stopped-sandbox
8564
- * recovery the budget deferred) get the ordinary `sweepBuild` pass first,
8565
- * before settlement and the janitor spend the window. The hint is never
8566
- * authority: each pass re-derives every decision from fresh build state,
8567
- * 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.
8568
9069
  *
8569
9070
  * Per-tick cost: zero reads when nothing is carried (the hint comes from
8570
9071
  * the repository facts the tick already reduced). Otherwise the record
8571
9072
  * listing and digests from this tick's epoch cache, with no fleet-wide
8572
9073
  * compatibility pass, plus one reduced `buildFacts` read per carried build
8573
- * visited — a read the lease sweep would otherwise make later, and which
8574
- * 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.
8575
9079
  */
8576
9080
  private async serviceDeferredWork(
8577
9081
  report: TickReport,
@@ -8579,14 +9083,15 @@ export class Dispatcher {
8579
9083
  paused: boolean,
8580
9084
  opts: TickOpts,
8581
9085
  ): Promise<void> {
8582
- if (this.carriedOutstanding.size === 0) return
9086
+ if (this.carriedOutstanding.size === 0) return this.pass.total('deferred', 0)
8583
9087
  // Never the default form: it would run the mixed-version check for every
8584
9088
  // compatibility-bearing build. `sweepBuild` checks each carried build.
8585
9089
  const entries = new Map(
8586
9090
  (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
8587
9091
  )
9092
+ this.pass.total('deferred', this.carriedOutstanding.size)
8588
9093
  for (const slug of [...this.carriedOutstanding.keys()]) {
8589
- if (this.outOfBudget(opts)) break
9094
+ if (!this.passItem(opts, 'deferred')) break
8590
9095
  const entry = this.carriedOutstanding.get(slug)!
8591
9096
  const found = entries.get(slug)
8592
9097
  if (found === undefined || found.digest.terminal !== undefined) {
@@ -8599,20 +9104,231 @@ export class Dispatcher {
8599
9104
  this.retireCarried(slug)
8600
9105
  continue
8601
9106
  }
8602
- const outcome = await this.sweepContained(
8603
- found.record,
8604
- report,
8605
- launched,
8606
- paused,
8607
- this.deps.clock().getTime(),
8608
- )
8609
- const interrupted = this.budgetSpent(opts)
9107
+ const outcome = await this.serviceCarriedStart(found.record, entry, report, launched, paused)
9108
+ // The invocation's deadline, not the stage's cut: in-flight work is
9109
+ // never cancelled at a cut.
9110
+ const interrupted = this.budgetSpent(this.tickOpts)
8610
9111
  if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
8611
9112
  this.retireCarried(slug)
8612
9113
  }
8613
9114
  await this.persistDeferrals()
8614
9115
  }
8615
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
+
8616
9332
  /** A carried hint entry whose own pass showed it no longer needs priority.
8617
9333
  * Never writes: the next hint write simply omits it. */
8618
9334
  private retireCarried(slug: string): void {
@@ -8620,10 +9336,22 @@ export class Dispatcher {
8620
9336
  }
8621
9337
 
8622
9338
  /** Record that this tick deferred `slug`'s deadline-gated `step` for
8623
- * budget, and keep the durable hint current. */
8624
- private async noteDeferral(slug: string, step: DeferredWorkStep, detail?: string): Promise<void> {
8625
- if (!this.tickDeferrals.has(slug))
8626
- 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
+ })
8627
9355
  await this.persistDeferrals()
8628
9356
  }
8629
9357
 
@@ -8631,18 +9359,22 @@ export class Dispatcher {
8631
9359
  * carried order; then visited carried entries that are still outstanding
8632
9360
  * (re-deferred or interrupted); then this tick's new deferrals. Capped
8633
9361
  * from the tail, so new entries are dropped first. */
8634
- private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
8635
- const list: { slug: string; step: DeferredWorkStep }[] = []
9362
+ private nextDeferralList(): DeferredWorkEntry[] {
9363
+ const list: DeferredWorkEntry[] = []
8636
9364
  const seen = new Set<string>()
8637
- const push = (slug: string, step: DeferredWorkStep) => {
9365
+ const push = (slug: string, entry: { step: DeferredWorkStep; instance?: string }) => {
8638
9366
  if (seen.has(slug)) return
8639
9367
  seen.add(slug)
8640
- list.push({ slug, step })
9368
+ list.push({
9369
+ slug,
9370
+ step: entry.step,
9371
+ ...(entry.instance !== undefined ? { instance: entry.instance } : {}),
9372
+ })
8641
9373
  }
8642
- 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)
8643
9375
  for (const [slug, entry] of this.carriedOutstanding)
8644
- if (entry.visited) push(slug, this.tickDeferrals.get(slug)?.step ?? entry.step)
8645
- 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)
8646
9378
  return list.slice(0, MAX_DEFERRED_WORK)
8647
9379
  }
8648
9380
 
@@ -8658,29 +9390,68 @@ export class Dispatcher {
8658
9390
  if (
8659
9391
  next.length === recorded.length &&
8660
9392
  next.every(
8661
- (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,
8662
9397
  )
8663
9398
  )
8664
9399
  return
8665
- if (this.deps.holdsRepoAuthority?.() === false) return
8666
- // Past the work deadline, abandoned work writes nothing, except this
8667
- // hint through the bounded, authorized teardown scope.
8668
- const late = this.tickOpts.workSignal?.aborted === true
8669
- const teardown = this.tickOpts.teardownWrite
8670
- if (late && teardown === undefined) return
8671
- const append = () =>
9400
+ const outcome = await this.writeHint(() =>
8672
9401
  this.store.appendRepo(this.deps.repo, {
8673
9402
  actor: DISPATCHER,
8674
9403
  type: 'dispatcher.work-deferred',
8675
9404
  payload: { builds: next },
9405
+ }),
9406
+ )
9407
+ if (outcome === true) this.recordedDeferrals = next
9408
+ else if (outcome !== false) this.deferralWriteFailure = outcome
9409
+ })
9410
+ this.deferralWrites = write.catch(() => {})
9411
+ return write
9412
+ }
9413
+
9414
+ /** The write discipline every scheduling hint shares: nothing once
9415
+ * authority is lost; past the work deadline, abandoned work writes only
9416
+ * through the bounded, authorized teardown scope. Best effort: true when
9417
+ * written, false when skipped, the failure text otherwise. An authority
9418
+ * lapse escapes. */
9419
+ private async writeHint(append: () => Promise<unknown>): Promise<boolean | string> {
9420
+ if (this.deps.holdsRepoAuthority?.() === false) return false
9421
+ const late = this.tickOpts.workSignal?.aborted === true
9422
+ const teardown = this.tickOpts.teardownWrite
9423
+ if (late && teardown === undefined) return false
9424
+ try {
9425
+ await (late ? teardown!(append) : append())
9426
+ return true
9427
+ } catch (error) {
9428
+ rethrowAuthorityLapse(error)
9429
+ return errorText(error)
9430
+ }
9431
+ }
9432
+
9433
+ /** Append the rotated loops' positions once per bounded pass, only when one
9434
+ * changed (#1409). A pass that cut no loop leaves them clear and writes
9435
+ * nothing, so the next refresh reads no new row. Best effort: a failure
9436
+ * costs only the continuation, which then restarts from the first key. */
9437
+ private persistPassCursors(): Promise<void> {
9438
+ if (this.passCursorsPersisted || this.tickOpts.deadlineAt === undefined)
9439
+ return Promise.resolve()
9440
+ this.passCursorsPersisted = true
9441
+ const next = { ...this.nextPassCursors }
9442
+ const previous = this.passCursors
9443
+ const keys = new Set([...Object.keys(next), ...Object.keys(previous)]) as Set<RotatedPassPart>
9444
+ if ([...keys].every((key) => next[key] === previous[key])) return Promise.resolve()
9445
+ const write = this.deferralWrites.then(async () => {
9446
+ const outcome = await this.writeHint(async () => {
9447
+ await this.store.ensureRepo(this.deps.repo)
9448
+ await this.store.appendRepo(this.deps.repo, {
9449
+ actor: DISPATCHER,
9450
+ type: 'dispatcher.pass-cursors',
9451
+ payload: { cursors: next },
8676
9452
  })
8677
- try {
8678
- await (late ? teardown!(append) : append())
8679
- this.recordedDeferrals = next
8680
- } catch (error) {
8681
- rethrowAuthorityLapse(error)
8682
- this.deferralWriteFailure = errorText(error)
8683
- }
9453
+ })
9454
+ if (typeof outcome === 'string') this.passCursorWriteFailure = outcome
8684
9455
  })
8685
9456
  this.deferralWrites = write.catch(() => {})
8686
9457
  return write
@@ -8692,18 +9463,24 @@ export class Dispatcher {
8692
9463
  /** Count and name this tick's deferrals on its report. Runs in `tick()`,
8693
9464
  * so every early return of `runTick` is covered. */
8694
9465
  private finishDeferrals(report: TickReport): void {
8695
- for (const [slug, { step, detail }] of this.tickDeferrals) {
8696
- if (step !== 'provision') report.recoveryDeferred += 1
8697
- report.deferredDiagnostics.push(
8698
- `build ${slug}: ${step} deferred by the invocation budget; the next invocation runs it first` +
8699
- (detail !== undefined ? ` — ${detail}` : ''),
8700
- )
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))
8701
9473
  }
8702
9474
  if (this.deferralWriteFailure !== undefined)
8703
9475
  report.deferredDiagnostics.push(
8704
9476
  `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
8705
9477
  )
8706
9478
  this.deferralWriteFailure = undefined
9479
+ if (this.passCursorWriteFailure !== undefined)
9480
+ report.deferredDiagnostics.push(
9481
+ `pass positions not recorded for the next invocation — ${this.passCursorWriteFailure}`,
9482
+ )
9483
+ this.passCursorWriteFailure = undefined
8707
9484
  }
8708
9485
 
8709
9486
  /**
@@ -8765,21 +9542,25 @@ export class Dispatcher {
8765
9542
  launched: Set<string>,
8766
9543
  paused: boolean,
8767
9544
  now: number,
9545
+ carried?: { facts: CurrentBuildFacts },
8768
9546
  ): Promise<'done' | 'waiting'> {
8769
- return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
9547
+ return (await this.sweepBuildPass(record, report, launched, paused, now, carried)) ?? 'done'
8770
9548
  }
8771
9549
 
9550
+ /** `carried` is a deferred-work entry's pass: its facts are already read,
9551
+ * and the first-claim grace does not apply. */
8772
9552
  private async sweepBuildPass(
8773
9553
  record: BuildRecord,
8774
9554
  report: TickReport,
8775
9555
  launched: Set<string>,
8776
9556
  paused: boolean,
8777
9557
  now: number,
9558
+ carried?: { facts: CurrentBuildFacts },
8778
9559
  ): Promise<'waiting' | undefined> {
8779
9560
  if (record.lease) {
8780
9561
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
8781
9562
  }
8782
- const facts = await this.store.buildFacts(record.slug)
9563
+ const facts = carried?.facts ?? (await this.store.buildFacts(record.slug))
8783
9564
  const state = facts.state
8784
9565
  if (mixedVersionDeferred(state)) {
8785
9566
  return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
@@ -8854,6 +9635,7 @@ export class Dispatcher {
8854
9635
  (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
8855
9636
  const cleanup = state.verifyStage.cleanupExecutionSeq
8856
9637
  if (
9638
+ carried === undefined &&
8857
9639
  !record.lease &&
8858
9640
  now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
8859
9641
  facts.lastExecution !== 'relaunch' &&
@@ -9052,8 +9834,9 @@ export class Dispatcher {
9052
9834
  )
9053
9835
  .slice(0, 8)
9054
9836
  const failures: unknown[] = []
9837
+ this.pass.total('preparations', pending.length)
9055
9838
  for (const attempt of pending) {
9056
- if (this.outOfBudget(opts)) break
9839
+ if (!this.passItem(opts, 'preparations')) break
9057
9840
  try {
9058
9841
  await this.recoverTicketPreparation(attempt)
9059
9842
  } catch (error) {
@@ -9106,6 +9889,43 @@ export class Dispatcher {
9106
9889
  )
9107
9890
  }
9108
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
+
9109
9929
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
9110
9930
  try {
9111
9931
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -9114,14 +9934,7 @@ export class Dispatcher {
9114
9934
  // its own key derives (allocating store): at most two point reads, and
9115
9935
  // never another attempt's build.
9116
9936
  if (attempt.slug) {
9117
- const candidates = attempt.creationKey
9118
- ? [attempt.slug, creationBuildSlug(this.deps.repo, attempt.slug, attempt.creationKey)]
9119
- : [attempt.slug]
9120
- const found: BuildRecord[] = []
9121
- for (const slug of candidates) {
9122
- const record = await this.store.getBuild(slug)
9123
- if (record) found.push(record)
9124
- }
9937
+ const found = await this.creationCandidates(attempt, attempt.slug)
9125
9938
  if (found.length > 1)
9126
9939
  return await this.abandonPreparation(
9127
9940
  attempt,
@@ -9253,6 +10066,10 @@ export class Dispatcher {
9253
10066
  * each ticket's outcome. The standing report fields are not published. */
9254
10067
  targeted?: TargetedDispatch,
9255
10068
  ): Promise<void> {
10069
+ // Only ordinary intake counts as the intake stage's `tickets`; a start
10070
+ // pass's targeted dispatch is part of its `starts`.
10071
+ const part = targeted ? undefined : ('tickets' as const)
10072
+ if (part) this.pass.total(part, 0)
9256
10073
  if (!this.claimGateOpen()) return
9257
10074
  const store = this.store
9258
10075
  const { tickets, config } = this.deps
@@ -9518,17 +10335,28 @@ export class Dispatcher {
9518
10335
  // failure must leave the entire ready set unclaimed. Publish dependency
9519
10336
  // diagnostics only after the complete preflight succeeds.
9520
10337
  let scanSuccessful = true
9521
- const treeEntries = await this.repoBuildDigests()
10338
+ const listed = await this.tickDigests()
10339
+ // Identity: a deferred node still means nodes exist.
9522
10340
  const hasNodes =
9523
- treeEntries.some(({ digest }) => digest.kind === 'node') ||
10341
+ listed.some(({ digest }) => digest.kind === 'node') ||
9524
10342
  ready.some((ticket) => ticket.kind === 'node')
9525
10343
  let presence: PresenceInputs | undefined
9526
10344
  const migrations = this.store.repositoryFacts().ticketMigrations
9527
10345
  const normalizeTicket = historicalTicketIdentity(migrations, this.deps.tickets.name)
10346
+ // A blocker's build can satisfy a dependency, so a deferred one is
10347
+ // absent, as the filtered listing left it.
10348
+ const dependencyListing = (entries: { record: BuildRecord; digest: BuildDigest }[]) =>
10349
+ this.compatibleBlockers(entries, ready, normalizeTicket)
10350
+ const tree = this.boundedListings
10351
+ ? await dependencyListing(listed)
10352
+ : { entries: listed, decidable: () => true }
10353
+ const treeEntries = tree.entries
9528
10354
  const builtTickets = hasNodes
9529
10355
  ? new Set(
9530
- treeEntries.flatMap(({ record }) =>
9531
- record.ticket ? [normalizeTicket(record.ticket, record.slug)] : [],
10356
+ treeEntries.flatMap(({ record, digest }) =>
10357
+ record.ticket && tree.decidable(record.slug, digest)
10358
+ ? [normalizeTicket(record.ticket, record.slug)]
10359
+ : [],
9532
10360
  ),
9533
10361
  )
9534
10362
  : undefined
@@ -9594,25 +10422,33 @@ export class Dispatcher {
9594
10422
  if (hasNodes) {
9595
10423
  if (!presence && needsPresence(ticket)) {
9596
10424
  await this.recoverNodeContributions(treeEntries)
9597
- const entries = await this.repoBuildDigests()
9598
- const destinations = ready
9599
- .filter(
9600
- (candidate) =>
9601
- needsPresence(candidate) &&
9602
- !withheld.has(candidate.ref.id) &&
9603
- candidate.target !== undefined,
10425
+ const listing = await this.tickDigests()
10426
+ const entries = this.boundedListings
10427
+ ? (await dependencyListing(listing)).entries
10428
+ : listing
10429
+ const destinations: string[] = []
10430
+ for (const candidate of ready) {
10431
+ if (
10432
+ !needsPresence(candidate) ||
10433
+ withheld.has(candidate.ref.id) ||
10434
+ candidate.target === undefined
9604
10435
  )
9605
- .flatMap((candidate) => {
9606
- const node = blockerBuild(
9607
- entries,
9608
- candidate.ref.source,
9609
- candidate.target!,
9610
- normalizeTicket,
9611
- )
9612
- return node && typeof node !== 'string' && node.digest.kind === 'node'
9613
- ? [node.record.slug]
9614
- : []
9615
- })
10436
+ continue
10437
+ const node = blockerBuild(
10438
+ entries,
10439
+ candidate.ref.source,
10440
+ candidate.target,
10441
+ normalizeTicket,
10442
+ )
10443
+ // A destination's state is read and decided from.
10444
+ if (
10445
+ node &&
10446
+ typeof node !== 'string' &&
10447
+ node.digest.kind === 'node' &&
10448
+ !(this.boundedListings && (await this.checkCompatibility(node)))
10449
+ )
10450
+ destinations.push(node.record.slug)
10451
+ }
9616
10452
  presence = await presenceInputs(this.store, entries, destinations)
9617
10453
  }
9618
10454
  const inputs = presence ?? {
@@ -9685,8 +10521,9 @@ export class Dispatcher {
9685
10521
  }
9686
10522
  }
9687
10523
  let claimLoopCompleted = true
10524
+ if (part) this.pass.total(part, ready.length)
9688
10525
  for (const ticket of ready) {
9689
- if (this.outOfBudget(opts)) {
10526
+ if (part ? !this.passItem(opts, part) : this.outOfBudget(opts)) {
9690
10527
  claimLoopCompleted = false
9691
10528
  break
9692
10529
  }
@@ -9956,21 +10793,44 @@ export class Dispatcher {
9956
10793
  },
9957
10794
  })
9958
10795
  stage = 'create-build'
9959
- record = await store.createBuild({
9960
- slug,
9961
- repo: this.deps.repo,
9962
- ticket: ticket.ref,
9963
- branch,
9964
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
9965
- ...(creationKey !== undefined ? { creationKey } : {}),
9966
- created: {
9967
- actor: DISPATCHER,
9968
- type: 'build.created',
9969
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
9970
- },
9971
- })
9972
- established = true
9973
- 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
+ )
9974
10834
  settle(ticket, { outcome: 'started', slug: record.slug })
9975
10835
  } catch (error) {
9976
10836
  // A lapse is not a preparation failure: the successor recovers the
@@ -10013,12 +10873,14 @@ export class Dispatcher {
10013
10873
  report.queued -= 1
10014
10874
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
10015
10875
  else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
10016
- const outcome = await this.attemptDispatchCompletion(record, launched, report, {
10017
- ticket,
10018
- body,
10019
- ...(authoredSession !== undefined ? { authoredSession } : {}),
10020
- ...createdSeed,
10021
- })
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
+ )
10022
10884
  // Accepted dispatches: durable boundaries recorded. A deferred outcome
10023
10885
  // means the remote provisioning continuation owns the rest.
10024
10886
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
@@ -10081,7 +10943,7 @@ export class Dispatcher {
10081
10943
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
10082
10944
  )
10083
10945
  if (candidates.length === 0) return tiers
10084
- const all = await this.repoBuildDigests()
10946
+ const all = await this.tickDigests()
10085
10947
  const nodes = new Map<string, BuildState>()
10086
10948
  const key = this.attemptIdentity()
10087
10949
  for (const ticket of candidates) {
@@ -10098,6 +10960,8 @@ export class Dispatcher {
10098
10960
  throw error
10099
10961
  }
10100
10962
  if (!signal || signal.stopped) continue
10963
+ // A deferred target node lends no tier; its ticket waits on the target.
10964
+ if (this.boundedListings && (await this.checkCompatibility(latest))) continue
10101
10965
  let state = nodes.get(record.slug)
10102
10966
  if (state === undefined) {
10103
10967
  state = (await this.store.buildFacts(record.slug)).state
@@ -10133,7 +10997,7 @@ export class Dispatcher {
10133
10997
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
10134
10998
  if (ticket.target === undefined) return undefined
10135
10999
  const migrations = this.store.repositoryFacts().ticketMigrations
10136
- const all = await this.repoBuildDigests()
11000
+ const all = await this.tickDigests()
10137
11001
  const entries = this.targetBuilds(ticket.target, ticket.ref.source, all)
10138
11002
  const latest = entries[0]
10139
11003
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
@@ -10143,6 +11007,10 @@ export class Dispatcher {
10143
11007
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
10144
11008
  if (digest.terminal || digest.prClosed || digest.merged)
10145
11009
  return `target node ${ticket.target} is ${digest.terminal === 'aborted' ? 'aborted' : digest.merged ? 'landed' : 'closed'}`
11010
+ // The target's state decides the claim: a node this runtime cannot
11011
+ // decide withholds the ticket (#1409).
11012
+ if (this.boundedListings && (await this.checkCompatibility(latest)))
11013
+ return `target node ${ticket.target} is deferred: ${compatibilityDiagnostic(digest.compatibility!) ?? 'kernel decisions deferred'}`
10146
11014
  const state = (await this.store.buildFacts(record.slug)).state
10147
11015
  if (
10148
11016
  state.status === 'done' ||
@@ -10520,9 +11388,10 @@ export class Dispatcher {
10520
11388
  if (result.exitCode !== 0) throw new Error(result.stderr)
10521
11389
  added = true
10522
11390
  const beforeReplay = async (operation: string) => {
10523
- for (const child of await this.repoBuildDigests()) {
11391
+ for (const child of await this.tickDigests()) {
10524
11392
  if (child.digest.terminal || child.digest.kind === 'node') continue
10525
11393
  const childState = (await this.store.buildFacts(child.record.slug)).state
11394
+ if (this.boundedListings && (await this.checkCompatibility(child, childState))) continue
10526
11395
  if (
10527
11396
  childState.target?.build !== record.slug ||
10528
11397
  !childState.pr ||
@@ -11058,11 +11927,15 @@ export class Dispatcher {
11058
11927
  digest.kind === 'node' && (digest.merged || record.slug === merging?.slug),
11059
11928
  )
11060
11929
  if (candidates.length === 0) return
11061
- const pending = candidates.filter(
11930
+ const unrecorded = candidates.filter(
11062
11931
  ({ record, digest }) =>
11063
11932
  digest.nodeContribution?.landing !==
11064
11933
  (record.slug === merging?.slug ? merging.sha : digest.mergedSha),
11065
11934
  )
11935
+ // Each node written to is checked first in a bounded pass (#1409).
11936
+ const pending: typeof unrecorded = []
11937
+ for (const entry of unrecorded)
11938
+ if (!(this.boundedListings && (await this.checkCompatibility(entry)))) pending.push(entry)
11066
11939
  if (pending.length === 0) return
11067
11940
  const inputs = await presenceInputs(
11068
11941
  this.store,
@@ -11117,7 +11990,11 @@ export class Dispatcher {
11117
11990
  for (const child of candidates) {
11118
11991
  if (child.record.slug === slug) continue
11119
11992
  const childState = inputs.states.get(child.record.slug)
11120
- if (childState?.target?.build === slug && childState.mergedSha)
11993
+ if (
11994
+ childState?.target?.build === slug &&
11995
+ childState.mergedSha &&
11996
+ !(this.boundedListings && (await this.checkCompatibility(child, childState)))
11997
+ )
11121
11998
  await recover(child.record.slug)
11122
11999
  }
11123
12000
  const currentIdentities = await ownedContribution(