@defrex/autobuild 1.13.0 → 1.15.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 (47) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +61 -11
  3. package/docs/answering-blocked-builds.md +5 -3
  4. package/docs/architecture.md +29 -0
  5. package/docs/configuration.md +16 -8
  6. package/docs/dispatcher-hosting.md +10 -0
  7. package/docs/operating.md +8 -0
  8. package/docs/operator-api.md +1 -1
  9. package/docs/operator-surfaces.md +1 -1
  10. package/docs/remote-store-protocol.md +1 -1
  11. package/docs/troubleshooting.md +35 -1
  12. package/package.json +3 -3
  13. package/packages/core/src/cli/dispatch.ts +105 -5
  14. package/packages/core/src/cli/repository-status.ts +15 -0
  15. package/packages/core/src/config/schema.ts +2 -2
  16. package/packages/core/src/events/policy.ts +2 -0
  17. package/packages/core/src/events/repository.ts +102 -0
  18. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +4 -0
  19. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  20. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/23d33121de6d3325.json +107 -0
  21. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  23. package/packages/core/src/kernel/done-escalations.ts +8 -4
  24. package/packages/core/src/kernel/reducer-revisions.ts +6 -0
  25. package/packages/core/src/kernel/reducer.ts +15 -1
  26. package/packages/core/src/kernel/repository-read-facts.ts +18 -0
  27. package/packages/core/src/ports/workspace/build-execution.ts +9 -1
  28. package/packages/core/src/ports/workspace/vercel-sandbox.ts +99 -12
  29. package/packages/core/src/processes/dispatcher.ts +957 -185
  30. package/packages/core/src/processes/execution-settlement.ts +24 -3
  31. package/packages/core/src/processes/pass-stages.ts +294 -0
  32. package/packages/core/src/processes/tick-publication.ts +1 -0
  33. package/packages/core/src/store/contract.ts +7 -0
  34. package/packages/core/src/store/reducer-value-shapes.json +5733 -5345
  35. package/packages/core/src/store/reducer-value-validation.ts +7 -0
  36. package/packages/core/src/store/remote/released-clients.json +22 -0
  37. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  38. package/packages/core/src/store/remote/released-reducer-values/1.15.0.json +36354 -0
  39. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  40. package/packages/core/src/store/repo-state-events.ts +2 -0
  41. package/packages/core/src/testing/dispatch-read-budget.ts +12 -2
  42. package/packages/core/src/testing/reduced-read-budget.ts +405 -1
  43. package/skills/guide/SKILL.md +29 -9
  44. package/skills/guide/references/operator-api.md +1 -1
  45. package/skills/guide/references/remote-store-protocol.md +1 -1
  46. package/skills/operate/SKILL.md +64 -5
  47. 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,
@@ -345,6 +357,7 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
345
357
  import {
346
358
  attributeRecoveryStep,
347
359
  isRecoveryDeferred,
360
+ recoveryStepOf,
348
361
  type WorkspaceRecoveryStep,
349
362
  } from '../ports/workspace/recovery-step'
350
363
  import type {
@@ -675,6 +688,13 @@ export interface TickReport {
675
688
  * invocation's remaining budget was shorter than the provider's
676
689
  * provisioning estimate. Nothing is written; a later invocation starts it. */
677
690
  provisioningDeferred: number
691
+ /** Builds whose stopped-sandbox recovery, or a launch waiting on one, the
692
+ * invocation budget deferred this tick. Nothing is charged; the build is
693
+ * recorded in `dispatcher.work-deferred` and the next tick runs it first. */
694
+ recoveryDeferred: number
695
+ /** One line per build whose deadline-gated work (a provision or a recovery
696
+ * step) this tick deferred for budget, naming the step. */
697
+ deferredDiagnostics: string[]
678
698
  /** Dispatch (§12): builds created and launched. With durable supervision
679
699
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
680
700
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -723,6 +743,9 @@ export interface TickReport {
723
743
  /** Agent-context stage (`processes/agent-context.ts`): typed problems this
724
744
  * tick found capturing the base branch's skills and agent instructions. */
725
745
  agentContextDiagnostics: AgentContextDiagnostic[]
746
+ /** A bounded pass's time and items per stage (#1409); absent for an
747
+ * unbounded pass. Display only: never a reason to publish. */
748
+ stages?: PassStageRecord[]
726
749
  }
727
750
 
728
751
  export function emptyTickReport(): TickReport {
@@ -742,6 +765,8 @@ export function emptyTickReport(): TickReport {
742
765
  settled: 0,
743
766
  provisioning: 0,
744
767
  provisioningDeferred: 0,
768
+ recoveryDeferred: 0,
769
+ deferredDiagnostics: [],
745
770
  dispatched: 0,
746
771
  authored: 0,
747
772
  bounced: 0,
@@ -928,8 +953,22 @@ export interface TickOpts {
928
953
  * requests made through the budgeted adapters are cancelled by the same
929
954
  * signal. Absent ⇒ only `deadlineAt` bounds the tick. */
930
955
  workSignal?: AbortSignal
956
+ /** Bounded invocation's teardown write scope: runs one write under the
957
+ * cleanup phase's signal. A budget deferral noted after `workSignal`
958
+ * aborted (a recovery whose cleanup stop ran into the work deadline) still
959
+ * records its `dispatcher.work-deferred` hint through it, while the
960
+ * repository lease is held, so the next invocation serves it first. Absent
961
+ * ⇒ such a late hint write is skipped. */
962
+ teardownWrite?: <T>(write: () => Promise<T>) => Promise<T>
931
963
  }
932
964
 
965
+ /** Deadline-gated work a bounded invocation can defer for budget: a
966
+ * provision, or a stopped-sandbox recovery step. */
967
+ export type DeferredWorkStep = 'provision' | WorkspaceRecoveryStep
968
+
969
+ /** Most entries one `dispatcher.work-deferred` hint carries. */
970
+ const MAX_DEFERRED_WORK = 64
971
+
933
972
  /** Process-local launch coordination result. Durable lease acquisition remains
934
973
  * the BuildRunner's responsibility; "scheduled" means only that this process
935
974
  * accepted a runner launch rather than suppressing a known in-flight slug. */
@@ -1083,6 +1122,10 @@ export const SWEEP_PIN_CACHE_CAPACITY = 128
1083
1122
  /** Name the recovery step a workspace failure happened in. Missing account
1084
1123
  * credentials stay unwrapped: the dispatcher holds for them by type instead
1085
1124
  * of recording a failure. */
1125
+ function errorText(error: unknown): string {
1126
+ return error instanceof Error ? error.message : String(error)
1127
+ }
1128
+
1086
1129
  function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1087
1130
  return error instanceof MissingAccountCredentialsError
1088
1131
  ? error
@@ -1142,11 +1185,15 @@ export class Dispatcher {
1142
1185
  slug: string
1143
1186
  state: Pick<BuildState, 'pollingActivity'>
1144
1187
  }[] = []
1145
- for (const { record, digest } of await this.repoBuildDigests()) {
1188
+ for (const entry of await this.tickDigests()) {
1189
+ const { record, digest } = entry
1146
1190
  if (record.slug === slug) continue
1147
1191
  // The digest names every node a build ever targeted, so a build it does
1148
1192
  // not name can never be this node's child and needs no facts read.
1149
1193
  if (!digestNodeTargets(digest).includes(slug)) continue
1194
+ // A bounded pass lists unfiltered: a deferred child stays out, as the
1195
+ // filtered listing kept it out.
1196
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
1150
1197
  const known = this.nodePollingBuilds.get(record.slug)
1151
1198
  // Only node relationships can move. Unrelated known work never needs
1152
1199
  // another full-facts read, even while it is running.
@@ -1338,6 +1385,39 @@ export class Dispatcher {
1338
1385
  /** Per tick, rebuilt from durable state: builds launched so far, which
1339
1386
  * occupy a slot before their runner claims a lease. */
1340
1387
  private tickLaunched: ReadonlySet<string> = new Set()
1388
+ /** Per tick, in insertion order: builds whose deadline-gated work this tick
1389
+ * deferred for budget, with the first step seen and an optional detail. */
1390
+ private readonly tickDeferrals = new Map<string, { step: DeferredWorkStep; detail?: string }>()
1391
+ /** Per tick: carried builds the early stage took up, which the lease sweep
1392
+ * then skips so no build is swept twice in one tick. */
1393
+ private readonly tickPrioritized = new Set<string>()
1394
+ /** Per tick, in carried order: the durable `dispatcher.work-deferred` hint
1395
+ * entries not yet retired. An entry leaves only through `retireCarried`,
1396
+ * after its own early-stage pass showed it no longer needs priority. */
1397
+ private readonly carriedOutstanding = new Map<
1398
+ string,
1399
+ { step: DeferredWorkStep; visited: boolean }
1400
+ >()
1401
+ /** The durable hint as last read or written. */
1402
+ private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1403
+ /** The current tick's options, for writes made from deferral sites. */
1404
+ private tickOpts: TickOpts = {}
1405
+ /** Serializes hint writes so concurrent deferral notes never race. */
1406
+ private deferralWrites: Promise<void> = Promise.resolve()
1407
+ /** Per tick: time and items per stage of a bounded pass (#1409). */
1408
+ private pass = new PassStageTracker(() => this.deps.clock().getTime())
1409
+ /** Per tick: the rotated loops' positions read from the durable
1410
+ * `dispatcher.pass-cursors` hint, and those this pass leaves. */
1411
+ private passCursors: PassCursors = {}
1412
+ private nextPassCursors: PassCursors = {}
1413
+ private passCursorsPersisted = false
1414
+ private passCursorWriteFailure: string | undefined
1415
+ /** True while a bounded pass runs: its listings are unfiltered and each
1416
+ * build acted on is checked for mixed-version deferral itself (#1409). */
1417
+ private boundedListings = false
1418
+ /** Per bounded pass: each build's mixed-version verdict, checked at most
1419
+ * once and only when something acts on that build. */
1420
+ private readonly compatibilityVerdicts = new Map<string, Promise<boolean>>()
1341
1421
  /** Per tick: finished leaves the admission gate turned away or deferred,
1342
1422
  * with their priority. Intake reserves their slots. */
1343
1423
  private readonly slotWaiters = new Map<string, BuildPriority>()
@@ -1443,8 +1523,9 @@ export class Dispatcher {
1443
1523
  }
1444
1524
 
1445
1525
  /**
1446
- * One cron-friendly pass (§3.3): janitor → interrupted dispatch recovery →
1447
- * optional startup resume → lease sweep → dispatch. Startup resume is opt-in
1526
+ * One cron-friendly pass (§3.3): deferred deadline-gated work → settlement →
1527
+ * janitor → interrupted dispatch recovery → optional startup resume →
1528
+ * lease sweep → dispatch. Startup resume is opt-in
1448
1529
  * because the CLI invokes it
1449
1530
  * once per command, while ordinary watch ticks must preserve policy parks.
1450
1531
  */
@@ -1574,16 +1655,32 @@ export class Dispatcher {
1574
1655
  }
1575
1656
  }
1576
1657
  this.lastForgeRequests = undefined
1658
+ this.pass = new PassStageTracker(() => this.deps.clock().getTime())
1659
+ this.passCursorsPersisted = false
1660
+ this.passCursorWriteFailure = undefined
1661
+ this.compatibilityVerdicts.clear()
1662
+ this.boundedListings = opts.deadlineAt !== undefined
1577
1663
  try {
1578
1664
  const report = await (this.deps.forge.withReadScope
1579
1665
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1580
1666
  : this.runTick(opts))
1581
1667
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1668
+ // Every early return of `runTick` still leaves its positions.
1669
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1670
+ this.finishDeferrals(report)
1582
1671
  report.janitorDiagnostics.push(...this.tickAbandonments)
1672
+ const stages = opts.deadlineAt === undefined ? [] : this.pass.summary()
1673
+ if (stages.length > 0) report.stages = stages
1583
1674
  return report
1584
1675
  } catch (error) {
1676
+ try {
1677
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1678
+ } catch {
1679
+ // The tick's own failure is the one reported.
1680
+ }
1585
1681
  throw this.withTickAbandonments(error)
1586
1682
  } finally {
1683
+ this.boundedListings = false
1587
1684
  this.tickAbandonments = []
1588
1685
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1589
1686
  stop?.()
@@ -1627,6 +1724,11 @@ export class Dispatcher {
1627
1724
  this.startBarrier = undefined
1628
1725
  this.parkedSettled.clear()
1629
1726
  this.deferredAdmissions.clear()
1727
+ this.tickDeferrals.clear()
1728
+ this.tickPrioritized.clear()
1729
+ this.carriedOutstanding.clear()
1730
+ this.deferralWriteFailure = undefined
1731
+ this.tickOpts = opts
1630
1732
  this.admissionBoundary = false
1631
1733
  this.claimsEvaluated = false
1632
1734
  this.forcedDeferralKey = undefined
@@ -1634,6 +1736,20 @@ export class Dispatcher {
1634
1736
  // tick is observed by the next tick, never half-way through this one.
1635
1737
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1636
1738
  if (opts.viewRefreshed !== true) await this.store.refresh()
1739
+ // The durable deferral hint from the previous invocation: zero extra
1740
+ // reads, it is part of the repository facts the refresh reduced.
1741
+ this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1742
+ ({ slug, step }) => ({ slug, step }),
1743
+ )
1744
+ // The rotated loops' positions, from the same reduced facts: no read.
1745
+ this.passCursors =
1746
+ opts.deadlineAt === undefined
1747
+ ? {}
1748
+ : { ...(this.store.repositoryFacts().passCursors?.cursors ?? {}) }
1749
+ this.nextPassCursors = { ...this.passCursors }
1750
+ for (const { slug, step } of this.recordedDeferrals)
1751
+ if (!this.carriedOutstanding.has(slug))
1752
+ this.carriedOutstanding.set(slug, { step, visited: false })
1637
1753
  // A pending start request measures capacity from the facts this tick's
1638
1754
  // fleet-wide stages read anyway; keep them only then.
1639
1755
  this.store.retainBuildFacts(
@@ -1641,6 +1757,7 @@ export class Dispatcher {
1641
1757
  )
1642
1758
  const autoMergeUser = undefined
1643
1759
  const report = emptyTickReport()
1760
+ this.inFlightReport = report
1644
1761
  this.restoreScan(report)
1645
1762
  /** Builds already launched this tick — a janitor/startup re-attach must
1646
1763
  * not be doubled by the sweep, nor a fresh dispatch by anything. */
@@ -1675,68 +1792,244 @@ export class Dispatcher {
1675
1792
  // open the first record listing of the next stage; each stage's own
1676
1793
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1677
1794
  if (this.outOfBudget(opts)) return report
1678
- await this.settleForeignExecutions(report, opts)
1679
- if (this.outOfBudget(opts)) return report
1680
- await this.settleHarvestExecutions(opts)
1795
+ // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1796
+ // recovery an earlier invocation deferred for budget are swept first,
1797
+ // within half of the window that remains.
1798
+ if (!opts.observationOnly)
1799
+ await this.runStage('deferred', opts, (stageOpts) =>
1800
+ this.serviceDeferredWork(report, launched, paused, stageOpts),
1801
+ )
1681
1802
  if (this.outOfBudget(opts)) return report
1682
- await this.settleOrchestratorSandboxes(report, opts)
1803
+ await this.runStage('settlement', opts, async (stageOpts) => {
1804
+ await this.settleForeignExecutions(report, stageOpts)
1805
+ if (this.outOfBudget(opts)) return
1806
+ await this.settleHarvestExecutions(stageOpts)
1807
+ if (this.outOfBudget(opts)) return
1808
+ await this.settleOrchestratorSandboxes(report, stageOpts)
1809
+ })
1683
1810
  if (opts.observationOnly) return report
1684
1811
  if (this.outOfBudget(opts)) return report
1685
- // The default fan-out runs before the janitor so one tick both records the
1686
- // consent and lets the janitor act on it (the janitor reduces a fresh read
1687
- // inside `checkPr`). Independent of intake and `acceptNewWork` — the
1688
- // durable fact drives it, so a second dispatcher polling the same
1689
- // repository converges the same state.
1690
- if (this.outOfBudget(opts)) return report
1691
- await this.recoverTicketPreparations(report, opts)
1692
- if (this.outOfBudget(opts)) return report
1693
- await this.janitor(report, launched, opts)
1694
- if (this.outOfBudget(opts)) return report
1695
- await this.settleHandbacks()
1696
- if (this.outOfBudget(opts)) return report
1697
- await this.recoverDispatches(report, launched, paused, opts)
1812
+ await this.runStage('preparations', opts, (stageOpts) =>
1813
+ this.recoverTicketPreparations(report, stageOpts),
1814
+ )
1698
1815
  if (this.outOfBudget(opts)) return report
1699
- if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, opts)
1816
+ await this.runStage('janitor', opts, (stageOpts) => this.janitor(report, launched, stageOpts))
1700
1817
  if (this.outOfBudget(opts)) return report
1701
- await this.leaseSweep(report, launched, paused, opts)
1818
+ await this.runStage('recovery', opts, async (stageOpts) => {
1819
+ await this.settleHandbacks(stageOpts)
1820
+ if (this.outOfBudget(opts)) return
1821
+ await this.recoverDispatches(report, launched, paused, stageOpts)
1822
+ if (this.outOfBudget(opts)) return
1823
+ if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, stageOpts)
1824
+ })
1702
1825
  if (this.outOfBudget(opts)) return report
1703
- // Nodes with a durable verification or propose request take freed slots
1704
- // before intake, whether or not idle node polling visited them this tick.
1705
- // The same pass advances optimization nodes' proposers first.
1706
- await this.admitWaitingNodes(report, launched, opts)
1826
+ await this.runStage('sweep', opts, (stageOpts) =>
1827
+ this.leaseSweep(report, launched, paused, stageOpts),
1828
+ )
1829
+ // Every rotated loop has run: record where the next pass continues.
1830
+ if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1707
1831
  if (this.outOfBudget(opts)) return report
1708
- // Operator start requests are independent of intake: they claim only the
1709
- // named tickets, and read nothing when none is pending. Manual and urgent
1710
- // requests run here, ahead of ordinary claims; high, normal and low
1711
- // requests run inside intake, after higher-level claims and before their
1712
- // own level's ready tickets, or after intake when it reaches no ticket of
1713
- // their level (SPEC §12 "Slot admission order").
1714
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
1832
+ await this.runStage('admission', opts, async (stageOpts) => {
1833
+ // Nodes with a durable verification or propose request take freed slots
1834
+ // before intake, whether or not idle node polling visited them this tick.
1835
+ // The same pass advances optimization nodes' proposers first.
1836
+ await this.admitWaitingNodes(report, launched, stageOpts)
1837
+ if (this.outOfBudget(opts)) return
1838
+ // Operator start requests are independent of intake: they claim only the
1839
+ // named tickets, and read nothing when none is pending. Manual and urgent
1840
+ // requests run here, ahead of ordinary claims; high, normal and low
1841
+ // requests run inside intake, after higher-level claims and before their
1842
+ // own level's ready tickets, or after intake when it reaches no ticket of
1843
+ // their level (SPEC §12 "Slot admission order").
1844
+ await this.honorStartRequests(
1845
+ report,
1846
+ launched,
1847
+ autoMergeUser,
1848
+ paused,
1849
+ stageOpts,
1850
+ EARLY_START_TIERS,
1851
+ )
1852
+ })
1715
1853
  if (this.outOfBudget(opts)) return report
1716
- if (opts.acceptNewWork !== false) {
1717
- await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1718
- }
1719
- await this.admitDeferredParked(report, launched, paused, opts)
1720
- // Late tiers intake did not reach: ordinary claims left their reserved
1721
- // slots free.
1722
- const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1723
- if (!this.outOfBudget(opts) && lateTiers.length > 0)
1724
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1725
- // Fire-and-forget by contract: long synthesize/review sessions must not
1726
- // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1727
- // watch ticks. Durable pause and infrastructure-error stops suppress
1728
- // launch. Pending control commands still launch the runner so the kernel
1729
- // can settle them under the repository lease.
1730
- if (!this.budgetSpent(opts)) await this.triggerHarvest()
1731
- await this.captureAgentContext(report, opts)
1854
+ await this.runStage('intake', opts, async (stageOpts) => {
1855
+ if (opts.acceptNewWork !== false) {
1856
+ await this.dispatch(report, launched, autoMergeUser, paused, stageOpts, autoMergeSeedFact)
1857
+ }
1858
+ await this.admitDeferredParked(report, launched, paused, stageOpts)
1859
+ // Late tiers intake did not reach: ordinary claims left their reserved
1860
+ // slots free.
1861
+ const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1862
+ if (!this.outOfBudget(opts) && lateTiers.length > 0)
1863
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, stageOpts, lateTiers)
1864
+ // Fire-and-forget by contract: long synthesize/review sessions must not
1865
+ // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1866
+ // watch ticks. Durable pause and infrastructure-error stops suppress
1867
+ // launch. Pending control commands still launch the runner so the kernel
1868
+ // can settle them under the repository lease.
1869
+ if (!this.budgetSpent(opts)) {
1870
+ this.pass.item('harvest-trigger')
1871
+ this.pass.total('harvest-trigger', 1)
1872
+ await this.triggerHarvest()
1873
+ }
1874
+ await this.captureAgentContext(report, stageOpts)
1875
+ })
1732
1876
  return report
1733
1877
  }
1734
1878
 
1879
+ /** Run one stage of the pass (#1409). A bounded pass gives the stage's
1880
+ * helpers a stage-scoped copy of `opts` whose `deadlineAt` is the stage's
1881
+ * cut, and records the stage's time and items; an unbounded pass passes
1882
+ * `opts` itself and records nothing. A throw leaves the stage running, so
1883
+ * `passSummary` reports it as in flight. */
1884
+ private runStage(
1885
+ stage: PassStage,
1886
+ opts: TickOpts,
1887
+ run: (stageOpts: TickOpts) => Promise<void>,
1888
+ ): Promise<void> {
1889
+ // Unbounded: the helpers' own promise, scheduled exactly as before.
1890
+ if (opts.deadlineAt === undefined) return run(opts)
1891
+ return this.runBoundedStage(stage, opts, opts.deadlineAt, run)
1892
+ }
1893
+
1894
+ private async runBoundedStage(
1895
+ stage: PassStage,
1896
+ opts: TickOpts,
1897
+ deadlineAt: number,
1898
+ run: (stageOpts: TickOpts) => Promise<void>,
1899
+ ): Promise<void> {
1900
+ this.pass.begin(stage)
1901
+ await run({ ...opts, deadlineAt: stageCut(stage, this.deps.clock().getTime(), deadlineAt) })
1902
+ // A final item that crossed the work deadline met no later gate.
1903
+ this.pass.end(this.outOfBudget(this.tickOpts))
1904
+ }
1905
+
1906
+ /** The per-item gate of every stage loop (#1409): stop once the invocation
1907
+ * budget is spent, or once the stage's cut has passed and `part` has
1908
+ * already started an item this pass, so each helper always gets its first
1909
+ * item. Without a deadline this is `outOfBudget(opts)`. */
1910
+ private stageGate(stageOpts: TickOpts, part: PassStagePart): boolean {
1911
+ if (this.outOfBudget(this.tickOpts)) {
1912
+ this.pass.stop(part, 'deadline')
1913
+ return true
1914
+ }
1915
+ if (stageOpts !== this.tickOpts && this.outOfBudget(stageOpts) && this.pass.started(part) > 0) {
1916
+ this.pass.stop(part, 'share')
1917
+ return true
1918
+ }
1919
+ return false
1920
+ }
1921
+
1922
+ /** `stageGate` for one item, counting it when it starts. */
1923
+ private passItem(stageOpts: TickOpts, part: PassStagePart): boolean {
1924
+ if (this.stageGate(stageOpts, part)) return false
1925
+ this.pass.item(part)
1926
+ return true
1927
+ }
1928
+
1929
+ /** A rotated loop's items and continuation (#1409). A bounded pass visits
1930
+ * them in key order after the saved position, wrapping. Each started item's
1931
+ * key becomes the live position at once, so a pass abandoned at the work
1932
+ * deadline mid-visit still continues after it; `finish` clears the
1933
+ * position once every item was reached. An unbounded pass keeps the
1934
+ * listing order and saves nothing. */
1935
+ private rotated<T>(part: RotatedPassPart, list: readonly T[], key: (item: T) => string) {
1936
+ const bounded = this.tickOpts.deadlineAt !== undefined
1937
+ const previous = this.passCursors[part]
1938
+ const items = bounded ? rotateFrom(list, key, previous) : [...list]
1939
+ let lastStarted: string | undefined
1940
+ let stopped = false
1941
+ this.pass.total(part, items.length)
1942
+ return {
1943
+ items,
1944
+ /** Gate `item`; false stops the loop. */
1945
+ start: (stageOpts: TickOpts, item: T): boolean => {
1946
+ if (!this.passItem(stageOpts, part)) {
1947
+ stopped = true
1948
+ return false
1949
+ }
1950
+ lastStarted = key(item)
1951
+ if (bounded) this.nextPassCursors[part] = lastStarted
1952
+ return true
1953
+ },
1954
+ /** An item reached and passed over without starting work. */
1955
+ skip: () => this.pass.item(part, false),
1956
+ finish: () => {
1957
+ if (!bounded) return
1958
+ const next = nextPosition({ lastStarted, reachedAll: !stopped, previous })
1959
+ if (next === undefined) delete this.nextPassCursors[part]
1960
+ else this.nextPassCursors[part] = next
1961
+ },
1962
+ }
1963
+ }
1964
+
1965
+ /** Bounded teardown's write of the live rotated positions (#1409): a pass
1966
+ * the work deadline abandoned mid-visit records where its loops reached,
1967
+ * through the tick's authorized teardown scope. Once a pass, best effort,
1968
+ * and nothing when no position changed or the pass already recorded them. */
1969
+ persistPassPositions(): Promise<void> {
1970
+ return this.persistPassCursors()
1971
+ }
1972
+
1973
+ /** This bounded pass's stage records, with a stage still in flight closed
1974
+ * as stopped by the deadline. Never mutates the pass. */
1975
+ passSummary(): PassStageRecord[] {
1976
+ return this.pass.summary()
1977
+ }
1978
+
1979
+ /** The current tick's report so far, with `passSummary` as its stages: what
1980
+ * bounded teardown records for a pass the work deadline abandoned.
1981
+ * Undefined before a bounded tick starts. */
1982
+ passReport(): TickReport | undefined {
1983
+ if (this.inFlightReport === undefined || this.tickOpts.deadlineAt === undefined)
1984
+ return undefined
1985
+ return { ...structuredClone(this.inFlightReport), stages: this.pass.summary() }
1986
+ }
1987
+
1988
+ private inFlightReport: TickReport | undefined
1989
+
1990
+ /** The repository listing every tick stage reads: unfiltered in a bounded
1991
+ * pass, where each build acted on is checked by `checkCompatibility`;
1992
+ * filtered for mixed-version deferral otherwise. */
1993
+ private tickDigests(): ReturnType<Dispatcher['repoBuildDigests']> {
1994
+ return this.repoBuildDigests(this.boundedListings)
1995
+ }
1996
+
1997
+ /** A bounded pass's targeted mixed-version check (#1409): true when this
1998
+ * runtime must make no decision on the build, recording the deferral once
1999
+ * per boundary. With `state` already read it decides from that state;
2000
+ * otherwise a digest without decisive facts answers false with no read.
2001
+ * At most one facts read per build per pass. Always false in an unbounded
2002
+ * pass, whose listings already excluded deferred builds. */
2003
+ private checkCompatibility(
2004
+ entry: { record: { slug: string }; digest?: BuildDigest },
2005
+ state?: Pick<BuildState, 'compatibility'>,
2006
+ ): Promise<boolean> {
2007
+ if (!this.boundedListings) return Promise.resolve(false)
2008
+ if (
2009
+ state !== undefined
2010
+ ? !mixedVersionDeferred(state)
2011
+ : (entry.digest?.compatibility?.decisiveFacts ?? 0) === 0
2012
+ )
2013
+ return Promise.resolve(false)
2014
+ const slug = entry.record.slug
2015
+ let verdict = this.compatibilityVerdicts.get(slug)
2016
+ if (verdict === undefined) {
2017
+ const store = this.store
2018
+ const readFacts = (slug: string) =>
2019
+ this.startPass ? store.servedBuildFacts(slug) : store.buildFacts(slug)
2020
+ verdict = deferMixedVersion(store, slug, undefined, readFacts)
2021
+ this.compatibilityVerdicts.set(slug, verdict)
2022
+ }
2023
+ return verdict
2024
+ }
2025
+
1735
2026
  /** Agent-context stage: contained, so a capture failure never fails the
1736
2027
  * tick; only an authority lapse escapes. */
1737
2028
  private async captureAgentContext(report: TickReport, opts: TickOpts): Promise<void> {
1738
2029
  const stage = this.deps.agentContext
1739
2030
  if (stage === undefined || this.outOfBudget(opts)) return
2031
+ this.pass.total('context', 1)
2032
+ this.pass.item('context')
1740
2033
  try {
1741
2034
  report.agentContextDiagnostics.push(
1742
2035
  ...(await stage.run({
@@ -1809,10 +2102,8 @@ export class Dispatcher {
1809
2102
 
1810
2103
  /** Builds with no terminal fact: the only ones whose tick duties change
1811
2104
  * their state (decide, resume, lease sweep, capacity). */
1812
- private async nonterminalBuilds(): Promise<BuildRecord[]> {
1813
- return (await this.repoBuildDigests())
1814
- .filter(({ digest }) => digest.terminal === undefined)
1815
- .map(({ record }) => record)
2105
+ private async nonterminalEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2106
+ return (await this.tickDigests()).filter(({ digest }) => digest.terminal === undefined)
1816
2107
  }
1817
2108
 
1818
2109
  /** Builds that still have work: nonterminal ones, plus terminal builds whose
@@ -1820,10 +2111,10 @@ export class Dispatcher {
1820
2111
  * cleanup's `build.completed`, a `done` build with an unreclaimed release
1821
2112
  * asset, or any build with an execution the provider has not been seen to
1822
2113
  * end. A terminal, settled build costs no event reads. */
1823
- private async workBuilds(): Promise<BuildRecord[]> {
1824
- return (await this.repoBuildDigests())
1825
- .filter(({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true)
1826
- .map(({ record }) => record)
2114
+ private async workEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2115
+ return (await this.tickDigests()).filter(
2116
+ ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2117
+ )
1827
2118
  }
1828
2119
 
1829
2120
  private async sourceCondition(
@@ -1952,17 +2243,24 @@ export class Dispatcher {
1952
2243
 
1953
2244
  /** Settle reported build hand-backs whose build is complete (or gone).
1954
2245
  * Zero reads and appends while no hand-back is open. */
1955
- private async settleHandbacks(): Promise<void> {
2246
+ private async settleHandbacks(opts: TickOpts = {}): Promise<void> {
1956
2247
  const open = Object.keys(this.store.repositoryFacts().handbacks)
1957
- if (open.length === 0) return
2248
+ if (open.length === 0) return this.pass.total('handbacks', 0)
1958
2249
  const digests = new Map(
1959
2250
  (await this.repoBuildDigests(true)).map(({ record, digest }) => [record.slug, digest]),
1960
2251
  )
1961
- for (const identity of open) {
2252
+ const loop = this.rotated('handbacks', open, (identity) => identity)
2253
+ for (const identity of loop.items) {
1962
2254
  const slug = identity.slice('build:'.length)
1963
2255
  const digest = digests.get(slug)
1964
- if (digest === undefined || digest.terminal === 'done') await this.settleBuildHandback(slug)
2256
+ if (digest !== undefined && digest.terminal !== 'done') {
2257
+ loop.skip()
2258
+ continue
2259
+ }
2260
+ if (!loop.start(opts, identity)) break
2261
+ await this.settleBuildHandback(slug)
1965
2262
  }
2263
+ loop.finish()
1966
2264
  }
1967
2265
 
1968
2266
  /** Admit pending operator start requests of the given tiers through
@@ -1982,6 +2280,7 @@ export class Dispatcher {
1982
2280
  tiers: readonly StartTier[],
1983
2281
  ): Promise<StartPassResult> {
1984
2282
  const result: StartPassResult = { settled: [] }
2283
+ this.pass.total('starts', 0)
1985
2284
  for (const tier of tiers)
1986
2285
  if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
1987
2286
  await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
@@ -2044,8 +2343,12 @@ export class Dispatcher {
2044
2343
  const identities = this.store.repositoryFacts().ticketStarts.identities
2045
2344
  const lifecycle = ticketLifecycle(config.tickets)
2046
2345
  const candidates: { request: PendingTicketStart; ticket: Ticket }[] = []
2346
+ this.pass.total('starts', pending.length)
2347
+ // The stage's share stops further lookups only: every request already
2348
+ // looked up goes on to its claim, so each pass settles or claims its
2349
+ // prefix and the next pass never repeats work this one lost (#1409).
2047
2350
  for (const request of pending) {
2048
- if (this.outOfBudget(opts)) return
2351
+ if (!this.passItem(opts, 'starts')) break
2049
2352
  let ref: TicketRef | undefined
2050
2353
  try {
2051
2354
  ref = resolveTicketRef(migrations, request.ticket, tickets.name)
@@ -2102,7 +2405,10 @@ export class Dispatcher {
2102
2405
  if (this.preparing(ticket.ref.source, ticket.ref.id)) continue
2103
2406
  candidates.push({ request, ticket })
2104
2407
  }
2105
- if (candidates.length === 0 || this.outOfBudget(opts)) return
2408
+ // A looked-up request's claim is in-flight work: only the invocation
2409
+ // budget stops it, never the stage's cut.
2410
+ const claimOpts = this.tickOpts.deadlineAt === undefined ? opts : this.tickOpts
2411
+ if (candidates.length === 0 || this.outOfBudget(claimOpts)) return
2106
2412
  // Capacity is measured from the facts this tick's janitor, recovery and
2107
2413
  // lease sweep already read (`servedBuildFacts`): a build is read again
2108
2414
  // only when the tick skipped it or wrote to it since, so neither a wait
@@ -2147,7 +2453,7 @@ export class Dispatcher {
2147
2453
  const scratch = emptyTickReport()
2148
2454
  this.startPass = true
2149
2455
  try {
2150
- await this.dispatch(scratch, launched, autoMergeUser, paused, opts, undefined, targeted)
2456
+ await this.dispatch(scratch, launched, autoMergeUser, paused, claimOpts, undefined, targeted)
2151
2457
  } finally {
2152
2458
  this.startPass = false
2153
2459
  for (const counter of [
@@ -2340,7 +2646,8 @@ export class Dispatcher {
2340
2646
  private async activeTicketIdentities(refs: TicketRef[], listed: Ticket[]): Promise<Set<string>> {
2341
2647
  const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
2342
2648
  const migrations = this.store.repositoryFacts().ticketMigrations
2343
- const records = await this.repoBuildDigests()
2649
+ // Identity only: a deferred build's slug names its own ticket.
2650
+ const records = await this.tickDigests()
2344
2651
  const normalized = refs.map((ref) => {
2345
2652
  try {
2346
2653
  return resolveTicketRef(
@@ -2377,7 +2684,22 @@ export class Dispatcher {
2377
2684
  * disabled. It shares the active-ticket exclusion with dispatch but performs
2378
2685
  * no dependency fetch, claim, bounce, build, workspace, or launch side
2379
2686
  * effect, and deliberately does not alter TickReport compatibility. */
2380
- async observeReady(opts: Pick<TickOpts, 'viewRefreshed'> = {}): Promise<{
2687
+ async observeReady(opts: Pick<TickOpts, 'viewRefreshed' | 'deadlineAt'> = {}): Promise<{
2688
+ queued: number
2689
+ invalidTickets: number
2690
+ ticketDiagnostics: string[]
2691
+ }> {
2692
+ // A bounded invocation's listings are unfiltered: this observation only
2693
+ // asks which tickets are active, so a deferred build's ticket stays active.
2694
+ this.boundedListings = opts.deadlineAt !== undefined
2695
+ try {
2696
+ return await this.observeReadyListing(opts)
2697
+ } finally {
2698
+ this.boundedListings = false
2699
+ }
2700
+ }
2701
+
2702
+ private async observeReadyListing(opts: Pick<TickOpts, 'viewRefreshed'>): Promise<{
2381
2703
  queued: number
2382
2704
  invalidTickets: number
2383
2705
  ticketDiagnostics: string[]
@@ -2390,7 +2712,7 @@ export class Dispatcher {
2390
2712
  if (checkpoint.due) {
2391
2713
  const listing = await this.listReady()
2392
2714
  const refs: TicketRef[] = []
2393
- for (const { record, digest } of await this.repoBuildDigests()) {
2715
+ for (const { record, digest } of await this.tickDigests()) {
2394
2716
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
2395
2717
  }
2396
2718
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
@@ -2454,7 +2776,8 @@ export class Dispatcher {
2454
2776
  /** `force` makes the scan due now, skipping the interval and the journal
2455
2777
  * deferral: a deferred admission waits on this tick's higher-level claims. */
2456
2778
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2457
- const digest = (await this.repoBuildDigests())
2779
+ // A fingerprint of readiness digests: no decision reads a build's state.
2780
+ const digest = (await this.tickDigests())
2458
2781
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
2459
2782
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
2460
2783
  .sort(([a], [b]) => a.localeCompare(b))
@@ -2684,7 +3007,16 @@ export class Dispatcher {
2684
3007
  ) {
2685
3008
  return 'already-active'
2686
3009
  }
2687
- return this.deps.launchRunner(slug)
3010
+ try {
3011
+ return await this.deps.launchRunner(slug)
3012
+ } catch (error) {
3013
+ // A launch waiting on a stopped-sandbox recovery the budget deferred:
3014
+ // nothing started and nothing is charged. Record it so the next
3015
+ // invocation runs it first; callers see the same result as before.
3016
+ if (!isRecoveryDeferred(error)) throw error
3017
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
3018
+ return 'already-active'
3019
+ }
2688
3020
  }
2689
3021
 
2690
3022
  // ── 0. Settlement stage (durable supervision) ──────────────────────────────
@@ -2704,11 +3036,19 @@ export class Dispatcher {
2704
3036
  * the stage still settles. */
2705
3037
  private async settleForeignExecutions(report: TickReport, opts: TickOpts = {}): Promise<void> {
2706
3038
  const active = this.deps.activeExecutions?.() ?? new Set<string>()
2707
- for (const record of await this.workBuilds()) {
2708
- if (active.has(record.slug)) continue
2709
- // Budget gate: once spent, stop settling further foreign executions.
2710
- if (this.outOfBudget(opts)) break
3039
+ const loop = this.rotated('executions', await this.workEntries(), (entry) => entry.record.slug)
3040
+ for (const entry of loop.items) {
3041
+ const { record } = entry
3042
+ // The early stage already observed and settled it this tick.
3043
+ if (active.has(record.slug) || this.tickPrioritized.has(record.slug)) {
3044
+ loop.skip()
3045
+ continue
3046
+ }
3047
+ // Budget gate: once the stage's share or the budget is spent, stop
3048
+ // settling further foreign executions.
3049
+ if (!loop.start(opts, entry)) break
2711
3050
  try {
3051
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
2712
3052
  const { open } = await this.store.buildFacts(record.slug)
2713
3053
  if (open === null) continue
2714
3054
  const owner = this.executionOwner(open.provider)
@@ -2722,16 +3062,21 @@ export class Dispatcher {
2722
3062
  ...(this.settlePublication !== undefined
2723
3063
  ? { settlePublication: this.settlePublication }
2724
3064
  : {}),
3065
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
2725
3066
  },
2726
3067
  record.slug,
2727
3068
  open,
2728
3069
  )
2729
3070
  if (settlement === 'settled') report.settled += 1
2730
- } catch {
3071
+ } catch (error) {
2731
3072
  // An unobservable build must not stall settlement of the rest; the
2732
- // next tick retries it.
3073
+ // next tick retries it. A budget deferral is recorded so the next
3074
+ // invocation observes it first.
3075
+ if (isRecoveryDeferred(error))
3076
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2733
3077
  }
2734
3078
  }
3079
+ loop.finish()
2735
3080
  }
2736
3081
 
2737
3082
  /** Durable settlement for hosted-harvest executions (AUT-305), next to the
@@ -2752,11 +3097,17 @@ export class Dispatcher {
2752
3097
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
2753
3098
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
2754
3099
  const facts = this.store.repositoryFacts()
2755
- for (const execution of facts.openHarvest) {
2756
- if (active.has(execution.execution)) continue
3100
+ const loop = this.rotated('harvest', facts.openHarvest, (execution) =>
3101
+ JSON.stringify(execution.execution),
3102
+ )
3103
+ for (const execution of loop.items) {
3104
+ if (active.has(execution.execution)) {
3105
+ loop.skip()
3106
+ continue
3107
+ }
2757
3108
  // Budget gate: once spent, stop settling further harvest executions;
2758
3109
  // the next tick retries what remains.
2759
- if (this.outOfBudget(opts)) break
3110
+ if (!loop.start(opts, execution)) break
2760
3111
  try {
2761
3112
  const owner = this.executionOwner(execution.provider)
2762
3113
  const capability = owner?.harvestExecution
@@ -2837,6 +3188,7 @@ export class Dispatcher {
2837
3188
  // settlement stage; the next tick retries it.
2838
3189
  }
2839
3190
  }
3191
+ loop.finish()
2840
3192
  }
2841
3193
 
2842
3194
  /** A foreign hosted-harvest execution still open after this tick's
@@ -2886,15 +3238,20 @@ export class Dispatcher {
2886
3238
  const providerName = this.deps.workspaces.name
2887
3239
  const facts = this.store.repositoryFacts()
2888
3240
  const idleMs = config.orchestrator.sandbox.idleMinutes * 60_000
2889
- for (let environment of facts.sandboxes) {
2890
- if (environment.state !== 'live') continue
2891
- // Budget gate: once spent, stop settling further environments; the
2892
- // next tick retries what remains.
2893
- if (this.outOfBudget(opts)) break
3241
+ const loop = this.rotated(
3242
+ 'sandboxes',
3243
+ facts.sandboxes.filter((environment) => environment.state === 'live'),
3244
+ (environment) => `${environment.operator}\u0000${environment.environmentId}`,
3245
+ )
3246
+ for (let environment of loop.items) {
2894
3247
  const lastEvidence = Date.parse(environment.lastEvidenceTs)
2895
3248
  if (Number.isFinite(lastEvidence) && this.deps.clock().getTime() - lastEvidence < idleMs) {
3249
+ loop.skip()
2896
3250
  continue
2897
3251
  }
3252
+ // Budget gate: once spent, stop settling further environments; the
3253
+ // next tick retries what remains.
3254
+ if (!loop.start(opts, environment)) break
2898
3255
  try {
2899
3256
  // Other processes may have recorded activity while earlier tick work
2900
3257
  // awaited an outside read. Revalidate only an impending disposition.
@@ -2982,6 +3339,7 @@ export class Dispatcher {
2982
3339
  )
2983
3340
  }
2984
3341
  }
3342
+ loop.finish()
2985
3343
  }
2986
3344
 
2987
3345
  // ── Background provisioning (durable supervision) ──────────────────────────
@@ -3049,8 +3407,14 @@ export class Dispatcher {
3049
3407
  estimate !== undefined &&
3050
3408
  this.tickDeadlineAt !== undefined &&
3051
3409
  this.tickDeadlineAt - this.deps.clock().getTime() < estimate
3052
- )
3410
+ ) {
3411
+ await this.noteDeferral(
3412
+ slug,
3413
+ 'provision',
3414
+ `${Math.max(0, this.tickDeadlineAt - this.deps.clock().getTime())} ms remain but a provision needs about ${estimate} ms`,
3415
+ )
3053
3416
  return 'budget-wait'
3417
+ }
3054
3418
  // A finished leaf waits for a slot before its continuation reserves one.
3055
3419
  // Nothing is written: the wait costs no attempt and raises no attention.
3056
3420
  if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
@@ -3362,16 +3726,15 @@ export class Dispatcher {
3362
3726
  // builds are another dispatcher's duty; settled terminal builds cost no
3363
3727
  // event reads).
3364
3728
  // Unfiltered, so optimization stop enforcement sees terminal attempt builds.
3365
- const builds = await this.repoBuildDigests()
3366
- const entries = builds.filter(
3729
+ const allBuilds = await this.tickDigests()
3730
+ const entries = allBuilds.filter(
3367
3731
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
3368
3732
  )
3369
3733
  this.janitorEntries = entries
3370
3734
  this.nodeChildren = undefined
3371
- // Receipt reporting requires no forge call, capacity or workspace. Recover
3372
- // every episode before the transport-budget and janitor-backoff gates.
3373
- for (const { record, digest } of entries) {
3374
- if (digest.kind !== 'node' || !digest.nodeOpened || digest.terminal) continue
3735
+ // Receipt reporting requires no forge call, capacity or workspace.
3736
+ const recoverReceipts = async (record: BuildRecord, digest: BuildDigest) => {
3737
+ if (digest.kind !== 'node' || !digest.nodeOpened || digest.terminal) return
3375
3738
  try {
3376
3739
  await reportIntegrationFailures(this.store, record.slug)
3377
3740
  } catch (error) {
@@ -3381,13 +3744,24 @@ export class Dispatcher {
3381
3744
  )
3382
3745
  }
3383
3746
  }
3384
- for (const { record, digest } of entries) {
3747
+ // A bounded pass recovers each node's receipts at the start of its own
3748
+ // visit, so the janitor's share bounds the work and its rotation covers
3749
+ // every node (#1409). Otherwise every episode is recovered first, before
3750
+ // the transport-budget and janitor-backoff gates.
3751
+ const bounded = this.tickOpts.deadlineAt !== undefined
3752
+ if (!bounded) for (const { record, digest } of entries) await recoverReceipts(record, digest)
3753
+ const loop = this.rotated('janitor', entries, (entry) => entry.record.slug)
3754
+ for (const entry of loop.items) {
3755
+ const { record, digest } = entry
3385
3756
  // Budget gate: the janitor's per-build path issues forge/store transport
3386
- // calls (PR probes, closePr, deleteBranch); once the budget is spent,
3387
- // stop starting new ones. The remaining builds stay janitor due — the
3388
- // next invocation re-runs them (§3.3 idempotency).
3389
- if (this.outOfBudget(opts)) break
3757
+ // calls (PR probes, closePr, deleteBranch); once its share or the budget
3758
+ // is spent, stop starting new ones. The remaining builds stay janitor
3759
+ // due — the next invocation continues after the last one started
3760
+ // (§3.3 idempotency).
3761
+ if (!loop.start(opts, entry)) break
3762
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
3390
3763
  await withForgeRequestContext({ build: record.slug }, async () => {
3764
+ if (bounded) await recoverReceipts(record, digest)
3391
3765
  let previous: BuildState['janitor']
3392
3766
  // The stage in progress, named if this attempt's failure escalates.
3393
3767
  let operation: JanitorOperation = 'build state read'
@@ -3414,6 +3788,9 @@ export class Dispatcher {
3414
3788
  // Every tick, independent of janitor backoff and idle node polling: an
3415
3789
  // hours budget must fire on a node with no other activity.
3416
3790
  if (state.optimization !== undefined && !mixedVersionDeferred(state)) {
3791
+ const builds = this.boundedListings
3792
+ ? await this.compatibleAttempts(record.slug, allBuilds)
3793
+ : allBuilds
3417
3794
  const deps = {
3418
3795
  store: this.store,
3419
3796
  clock: this.deps.clock,
@@ -3513,7 +3890,7 @@ export class Dispatcher {
3513
3890
  incompleteObservation ||
3514
3891
  executionLeaseLive ||
3515
3892
  report.janitorDiagnostics.length !== diagnosticsBefore ||
3516
- this.outOfBudget(opts)
3893
+ this.outOfBudget(this.tickOpts)
3517
3894
  )
3518
3895
  return
3519
3896
  const current = (await this.store.buildFacts(record.slug)).state
@@ -3644,6 +4021,8 @@ export class Dispatcher {
3644
4021
  payload: {},
3645
4022
  })
3646
4023
  if (command.command === 'abort') {
4024
+ // The abort ended the janitor episode (§15.5).
4025
+ previous = undefined
3647
4026
  operation = 'abort cleanup'
3648
4027
  await this.cleanupAborted(record, await history(), report)
3649
4028
  }
@@ -3724,7 +4103,9 @@ export class Dispatcher {
3724
4103
  refreshOnly: true,
3725
4104
  })
3726
4105
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3727
- await this.cascadeNode(record, state, report, launched, opts)
4106
+ // In-flight work is never cancelled at the janitor's cut: the
4107
+ // node transaction answers to the invocation budget.
4108
+ await this.cascadeNode(record, state, report, launched, this.tickOpts)
3728
4109
  loaded = undefined
3729
4110
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3730
4111
  }
@@ -3754,6 +4135,8 @@ export class Dispatcher {
3754
4135
  type: 'build.aborted',
3755
4136
  payload: {},
3756
4137
  } satisfies EventWrite<'build.aborted'>)
4138
+ // The abort ended the janitor episode (§15.5).
4139
+ previous = undefined
3757
4140
  // The view folded the acknowledgement it just appended.
3758
4141
  loaded = undefined
3759
4142
  operation = 'abort cleanup'
@@ -3887,6 +4270,12 @@ export class Dispatcher {
3887
4270
  // this build's janitor episode.
3888
4271
  if (janitorDeferral(error)) {
3889
4272
  attempted = false
4273
+ if (isRecoveryDeferred(error))
4274
+ await this.noteDeferral(
4275
+ record.slug,
4276
+ recoveryStepOf(error) ?? 'cleanup',
4277
+ errorText(error),
4278
+ )
3890
4279
  return
3891
4280
  }
3892
4281
  if (error instanceof MixedVersionDeferral) {
@@ -3917,6 +4306,63 @@ export class Dispatcher {
3917
4306
  }
3918
4307
  })
3919
4308
  }
4309
+ loop.finish()
4310
+ }
4311
+
4312
+ /** The intake preflight's dependency listing (#1409). In a bounded pass the
4313
+ * listing is unfiltered, so each ready ticket's blocker build is checked
4314
+ * and a deferred one dropped (an older generation may then answer, as in
4315
+ * the filtered listing). `decidable` tells whether a build may count as
4316
+ * built: one with decisive facts only once checked. Unbounded, the listing
4317
+ * is already filtered and returned as is. */
4318
+ private async compatibleBlockers(
4319
+ entries: { record: BuildRecord; digest: BuildDigest }[],
4320
+ ready: readonly Ticket[],
4321
+ identity: (ref: TicketRef, build?: string) => string,
4322
+ ): Promise<{
4323
+ entries: { record: BuildRecord; digest: BuildDigest }[]
4324
+ decidable: (slug: string, digest: BuildDigest) => boolean
4325
+ }> {
4326
+ if (!this.boundedListings) return { entries, decidable: () => true }
4327
+ const kept = [...entries]
4328
+ const checked = new Set<string>()
4329
+ for (const ticket of ready)
4330
+ for (const id of ticket.blockedBy ?? [])
4331
+ for (;;) {
4332
+ const build = blockerBuild(kept, ticket.ref.source, id, identity)
4333
+ if (build === undefined || typeof build === 'string' || checked.has(build.record.slug))
4334
+ break
4335
+ if (!(this.boundedListings && (await this.checkCompatibility(build)))) {
4336
+ checked.add(build.record.slug)
4337
+ break
4338
+ }
4339
+ kept.splice(kept.indexOf(build as (typeof kept)[number]), 1)
4340
+ }
4341
+ return {
4342
+ entries: kept,
4343
+ decidable: (slug, digest) =>
4344
+ (digest.compatibility?.decisiveFacts ?? 0) === 0 || checked.has(slug),
4345
+ }
4346
+ }
4347
+
4348
+ /** `builds` without the mixed-version deferred builds targeting `node`, in
4349
+ * a bounded pass (#1409): the optimization duties decide and write for a
4350
+ * node's attempt builds, and its unfiltered listing must not hand them a
4351
+ * build this runtime cannot decide. Reads only attempts with decisive facts,
4352
+ * at most once a pass. */
4353
+ private async compatibleAttempts(
4354
+ node: string,
4355
+ builds: { record: BuildRecord; digest: BuildDigest }[],
4356
+ ): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
4357
+ if (!this.boundedListings) return builds
4358
+ const kept: { record: BuildRecord; digest: BuildDigest }[] = []
4359
+ for (const entry of builds)
4360
+ if (
4361
+ !digestNodeTargets(entry.digest).includes(node) ||
4362
+ !(this.boundedListings && (await this.checkCompatibility(entry)))
4363
+ )
4364
+ kept.push(entry)
4365
+ return kept
3920
4366
  }
3921
4367
 
3922
4368
  /** Priming saves requests but must not block parent recovery or ordinary observations. */
@@ -4449,6 +4895,7 @@ export class Dispatcher {
4449
4895
  ): Promise<void> {
4450
4896
  const deferred = [...this.deferredAdmissions]
4451
4897
  this.deferredAdmissions.clear()
4898
+ this.pass.total('parked', 0)
4452
4899
  if (deferred.length === 0) {
4453
4900
  this.lastForcedDeferralKey = undefined
4454
4901
  return
@@ -4458,8 +4905,9 @@ export class Dispatcher {
4458
4905
  // the parked builds stay durable work for the next invocation.
4459
4906
  if (this.budgetSpent(opts)) return
4460
4907
  this.admissionBoundary = false
4908
+ this.pass.total('parked', deferred.length)
4461
4909
  for (const [slug, kind] of deferred) {
4462
- if (this.outOfBudget(opts)) return
4910
+ if (!this.passItem(opts, 'parked')) return
4463
4911
  if (launched.has(slug)) continue
4464
4912
  try {
4465
4913
  const record = await this.store.getBuild(slug)
@@ -4479,12 +4927,11 @@ export class Dispatcher {
4479
4927
  }
4480
4928
  } catch (error) {
4481
4929
  rethrowAuthorityLapse(error)
4482
- if (
4483
- error instanceof ForgeRequestDeferred ||
4484
- error instanceof MixedVersionDeferral ||
4485
- isRecoveryDeferred(error)
4486
- )
4930
+ if (isRecoveryDeferred(error)) {
4931
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
4487
4932
  continue
4933
+ }
4934
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4488
4935
  if (error instanceof ForgeCooldown) throw error
4489
4936
  const message =
4490
4937
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -4510,7 +4957,9 @@ export class Dispatcher {
4510
4957
  launched: Set<string>,
4511
4958
  opts: TickOpts,
4512
4959
  ): Promise<void> {
4513
- const entries = await this.repoBuildDigests()
4960
+ this.pass.total('nodes', 0)
4961
+ // A deferred node counts as open: it only makes the stage look further.
4962
+ const entries = await this.tickDigests()
4514
4963
  if (!entries.some(({ digest }) => digest.kind === 'node' && digest.terminal === undefined))
4515
4964
  return
4516
4965
  // An optimization node's proposer: exhausted stops, filings and new
@@ -4519,12 +4968,14 @@ export class Dispatcher {
4519
4968
  // accepted. One clock reading serves every stage of the pass.
4520
4969
  const now = this.deps.clock()
4521
4970
  await this.advanceOptimizationNodes(report, opts, entries, now)
4522
- if (this.outOfBudget(opts)) return
4971
+ // Between steps only the invocation budget stops admission: each step's
4972
+ // own loop gets its first item past the stage's cut (#1409).
4973
+ if (this.outOfBudget(this.tickOpts)) return
4523
4974
  const builds = (await this.capacityBuilds()).sort((a, b) =>
4524
4975
  a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0,
4525
4976
  )
4526
4977
  await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4527
- if (this.outOfBudget(opts)) return
4978
+ if (this.outOfBudget(this.tickOpts)) return
4528
4979
  await this.adoptLegacyNodeRunners(builds, now, report)
4529
4980
  // A node asking for a verification slot, and one admitted for
4530
4981
  // verification whose runner never started or was lost: nothing else
@@ -4532,9 +4983,11 @@ export class Dispatcher {
4532
4983
  const waiting = builds.filter((build) => nodeRunnerWork(build, now)?.request === 'verification')
4533
4984
  const admitted = new Set<string>()
4534
4985
  this.passNodeAdmissions = admitted
4986
+ this.pass.total('nodes', waiting.length)
4535
4987
  try {
4536
4988
  for (const build of waiting) {
4537
- if (this.outOfBudget(opts)) return
4989
+ if (!this.passItem(opts, 'nodes')) return
4990
+ if (this.boundedListings && (await this.checkCompatibility(build, build.state))) continue
4538
4991
  await this.admitNode(build, now, report, launched)
4539
4992
  }
4540
4993
  } finally {
@@ -4623,7 +5076,8 @@ export class Dispatcher {
4623
5076
  ): Promise<void> {
4624
5077
  for (const build of builds) {
4625
5078
  if (launched.has(build.record.slug) || !strandedNodeWorkspace(build, now)) continue
4626
- if (this.outOfBudget(opts)) return
5079
+ this.pass.total('nodes', 1)
5080
+ if (!this.passItem(opts, 'nodes')) return
4627
5081
  const { record } = build
4628
5082
  await withForgeRequestContext({ build: record.slug }, async () => {
4629
5083
  try {
@@ -4673,8 +5127,9 @@ export class Dispatcher {
4673
5127
  startRequests: this.startClaims(),
4674
5128
  })
4675
5129
  let occupied = projection.occupied
5130
+ this.pass.total('nodes', proposers.length)
4676
5131
  for (const build of proposers) {
4677
- if (this.outOfBudget(opts)) return
5132
+ if (!this.passItem(opts, 'nodes')) return
4678
5133
  const { record, state } = build
4679
5134
  if (
4680
5135
  launched.has(record.slug) ||
@@ -4747,7 +5202,8 @@ export class Dispatcher {
4747
5202
  failure?: string
4748
5203
  }> {
4749
5204
  const holds = new Map<string, { node: string; request: string }>()
4750
- for (const { record, digest } of await this.repoBuildDigests()) {
5205
+ // Digest signals only: a deferred node's deposit still holds its tickets.
5206
+ for (const { record, digest } of await this.tickDigests()) {
4751
5207
  if (digest.terminal !== undefined) continue
4752
5208
  let signal: ReturnType<typeof digestOptimization>
4753
5209
  try {
@@ -4839,9 +5295,14 @@ export class Dispatcher {
4839
5295
  entries: { record: BuildRecord; digest: BuildDigest }[],
4840
5296
  now: Date,
4841
5297
  ): Promise<void> {
4842
- const due: { record: BuildRecord; kind: 'exhausted' | 'filing' | 'request' }[] = []
5298
+ const due: {
5299
+ entry: { record: BuildRecord; digest: BuildDigest }
5300
+ record: BuildRecord
5301
+ kind: 'exhausted' | 'filing' | 'request'
5302
+ }[] = []
4843
5303
  try {
4844
- for (const { record, digest } of entries) {
5304
+ for (const entry of entries) {
5305
+ const { record, digest } = entry
4845
5306
  if (digest.terminal !== undefined || !digest.nodeOpened) continue
4846
5307
  const signal = digestOptimization(digest)
4847
5308
  if (!signal) continue
@@ -4852,17 +5313,19 @@ export class Dispatcher {
4852
5313
  (digest.executionOpen === true || this.hasLiveExecutionLease(record))
4853
5314
  )
4854
5315
  continue
4855
- if (kind !== undefined) due.push({ record, kind })
5316
+ if (kind !== undefined) due.push({ entry, record, kind })
4856
5317
  }
4857
5318
  } catch (error) {
4858
5319
  if (!(error instanceof BuildDigestCapabilityError)) throw error
4859
5320
  report.janitorDiagnostics.push(`optimization proposing skipped — ${error.message}`)
4860
5321
  return
4861
5322
  }
4862
- for (const { record, kind } of due) {
4863
- if (this.outOfBudget(opts)) return
5323
+ this.pass.total('nodes', due.length)
5324
+ for (const { entry, record, kind } of due) {
5325
+ if (!this.passItem(opts, 'nodes')) return
4864
5326
  await withForgeRequestContext({ build: record.slug }, async () => {
4865
5327
  try {
5328
+ if (this.boundedListings && (await this.checkCompatibility(entry))) return
4866
5329
  if (kind === 'exhausted') await this.recordExhausted(record.slug)
4867
5330
  else if (kind === 'filing') await this.fileProposedAttempts(record, now)
4868
5331
  else await this.requestProposal(record, now)
@@ -5281,6 +5744,11 @@ export class Dispatcher {
5281
5744
  for (const other of this.childrenOf(nodeSlug)) {
5282
5745
  if (other.slug === record.slug || !wanted.has(key(other.ticket!))) continue
5283
5746
  const otherState = (await this.store.buildFacts(other.slug)).state
5747
+ if (
5748
+ this.boundedListings &&
5749
+ (await this.checkCompatibility({ record: other }, otherState))
5750
+ )
5751
+ continue
5284
5752
  if (otherState.target?.build !== nodeSlug) continue
5285
5753
  candidates.push({ slug: other.slug, ticket: other.ticket!, state: otherState })
5286
5754
  }
@@ -6050,7 +6518,7 @@ export class Dispatcher {
6050
6518
  kind?: 'work' | 'node',
6051
6519
  ): Promise<{ sha: string; buildTrailerPresent?: boolean }> {
6052
6520
  if (kind === 'node')
6053
- await this.recoverNodeContributions(await this.repoBuildDigests(), {
6521
+ await this.recoverNodeContributions(await this.tickDigests(), {
6054
6522
  slug: record.slug,
6055
6523
  sha,
6056
6524
  })
@@ -7396,8 +7864,11 @@ export class Dispatcher {
7396
7864
  // build's failure; the tick-level handlers own it.
7397
7865
  if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
7398
7866
  // The invocation deadline cut recovery short: nothing failed, so keep
7399
- // the workspace and record nothing; the next invocation retries.
7400
- if (isRecoveryDeferred(error)) return false
7867
+ // the workspace and charge nothing; the next invocation runs it first.
7868
+ if (isRecoveryDeferred(error)) {
7869
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? step, errorText(error))
7870
+ return false
7871
+ }
7401
7872
  // Any other preservation or settlement failure (an unknown fence, a
7402
7873
  // checkout that could not be inspected) retains the workspace and its
7403
7874
  // pending work and is attributed to this build, never to the tick.
@@ -7444,7 +7915,10 @@ export class Dispatcher {
7444
7915
  rethrowAuthorityLapse(error)
7445
7916
  // A cleanup the invocation deadline cut short is retried next time; it
7446
7917
  // is neither a cleanup attempt nor a failure.
7447
- if (isRecoveryDeferred(error)) return false
7918
+ if (isRecoveryDeferred(error)) {
7919
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'cleanup', errorText(error))
7920
+ return false
7921
+ }
7448
7922
  const failure = stepAttributed('cleanup', error)
7449
7923
  const message =
7450
7924
  failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
@@ -8045,16 +8519,24 @@ export class Dispatcher {
8045
8519
  paused: boolean,
8046
8520
  opts: TickOpts = {},
8047
8521
  ): Promise<void> {
8048
- for (const record of await this.nonterminalBuilds()) {
8522
+ const loop = this.rotated(
8523
+ 'dispatches',
8524
+ await this.nonterminalEntries(),
8525
+ (entry) => entry.record.slug,
8526
+ )
8527
+ for (const entry of loop.items) {
8528
+ const { record } = entry
8049
8529
  if (
8050
8530
  record.ticket === undefined ||
8051
8531
  launched.has(record.slug) ||
8052
8532
  this.continuations.has(record.slug)
8053
8533
  ) {
8534
+ loop.skip()
8054
8535
  continue
8055
8536
  }
8056
8537
  // Budget gate: recovery issues store transport calls per build.
8057
- if (this.outOfBudget(opts)) break
8538
+ if (!loop.start(opts, entry)) break
8539
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8058
8540
  const { state } = await this.store.buildFacts(record.slug)
8059
8541
  if (
8060
8542
  state.status !== 'queued' ||
@@ -8075,6 +8557,7 @@ export class Dispatcher {
8075
8557
  // must not bypass the unfinished dispatch boundary later in the tick.
8076
8558
  if (outcome === 'failed') launched.add(record.slug)
8077
8559
  }
8560
+ loop.finish()
8078
8561
  }
8079
8562
 
8080
8563
  // ── c. Dispatch-command startup resume (SPEC §2.2, §15.6-C) ────────────────
@@ -8097,10 +8580,20 @@ export class Dispatcher {
8097
8580
  opts: TickOpts = {},
8098
8581
  ): Promise<void> {
8099
8582
  const store = this.store
8100
- for (const record of await this.nonterminalBuilds()) {
8101
- if (launched.has(record.slug)) continue
8583
+ const loop = this.rotated(
8584
+ 'resume',
8585
+ await this.nonterminalEntries(),
8586
+ (entry) => entry.record.slug,
8587
+ )
8588
+ for (const entry of loop.items) {
8589
+ const { record } = entry
8590
+ if (launched.has(record.slug)) {
8591
+ loop.skip()
8592
+ continue
8593
+ }
8102
8594
  // Budget gate: resume launches runners (transport-backed work).
8103
- if (this.outOfBudget(opts)) break
8595
+ if (!loop.start(opts, entry)) break
8596
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8104
8597
 
8105
8598
  const facts = await store.buildFacts(record.slug)
8106
8599
  const state = facts.state
@@ -8139,6 +8632,7 @@ export class Dispatcher {
8139
8632
  const result = await this.launch(record.slug, launched, report)
8140
8633
  if (result === 'scheduled') report.resumed += 1
8141
8634
  }
8635
+ loop.finish()
8142
8636
  }
8143
8637
 
8144
8638
  // ── c'. Ticket waits (SPEC §11 "Ticket waits") ─────────────────────────────
@@ -8302,15 +8796,21 @@ export class Dispatcher {
8302
8796
  ): Promise<void> {
8303
8797
  const tickets = this.deps.tickets
8304
8798
  const migrations = this.store.repositoryFacts().ticketMigrations
8305
- const waiting: { record: BuildRecord; wait: BuildDigestTicketWait; ids: string[] }[] = []
8306
- for (const { record, digest } of entries) {
8799
+ const waiting: {
8800
+ entry: { record: BuildRecord; digest: BuildDigest }
8801
+ record: BuildRecord
8802
+ wait: BuildDigestTicketWait
8803
+ ids: string[]
8804
+ }[] = []
8805
+ for (const entry of entries) {
8806
+ const { record, digest } = entry
8307
8807
  const wait = digest.ticketWait
8308
8808
  if (digest.terminal !== undefined || digest.kind === 'node' || wait === undefined) continue
8309
8809
  try {
8310
8810
  const ids = wait.tickets.map(
8311
8811
  (ref) => resolveTicketRef(migrations, ref, tickets.name, record.slug).id,
8312
8812
  )
8313
- waiting.push({ record, wait, ids })
8813
+ waiting.push({ entry, record, wait, ids })
8314
8814
  } catch (error) {
8315
8815
  const message = error instanceof Error ? error.message : String(error)
8316
8816
  report.janitorFailed += 1
@@ -8319,6 +8819,7 @@ export class Dispatcher {
8319
8819
  )
8320
8820
  }
8321
8821
  }
8822
+ this.pass.total('waits', waiting.length)
8322
8823
  if (waiting.length === 0 || this.outOfBudget(opts)) return
8323
8824
  const nodes = new Map<string, DependencyNode>()
8324
8825
  try {
@@ -8333,11 +8834,15 @@ export class Dispatcher {
8333
8834
  report.janitorDiagnostics.push(`ticket waits not checked — ${message}`)
8334
8835
  return
8335
8836
  }
8336
- for (const { record, wait, ids } of waiting) {
8837
+ for (const { entry, record, wait, ids } of waiting) {
8337
8838
  const release = ticketWaitRelease(ids, nodes)
8338
- if (release === undefined) continue
8339
- if (this.outOfBudget(opts)) return
8839
+ if (release === undefined) {
8840
+ this.pass.item('waits', false)
8841
+ continue
8842
+ }
8843
+ if (!this.passItem(opts, 'waits')) return
8340
8844
  try {
8845
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8341
8846
  const { state } = await this.store.buildFacts(record.slug)
8342
8847
  const open = openTicketWait(state)
8343
8848
  if (open?.id !== wait.id) continue
@@ -8406,37 +8911,252 @@ export class Dispatcher {
8406
8911
  opts: TickOpts = {},
8407
8912
  ): Promise<void> {
8408
8913
  const now = this.deps.clock().getTime()
8409
- const entries = await this.repoBuildDigests()
8914
+ const entries = await this.tickDigests()
8410
8915
  await this.releaseTicketWaits(entries, report, opts)
8411
8916
  // Terminal builds are filtered on the digest before the lease and TTL
8412
8917
  // checks, so a zero TTL cannot fall through to a log read.
8413
- for (const { record, digest } of entries) {
8414
- if (digest.terminal !== undefined) continue
8918
+ const loop = this.rotated(
8919
+ 'sweep',
8920
+ entries.filter(({ digest }) => digest.terminal === undefined),
8921
+ (entry) => entry.record.slug,
8922
+ )
8923
+ for (const entry of loop.items) {
8924
+ const { record, digest } = entry
8415
8925
  // Budget gate: the sweep re-attaches runners per expired build.
8416
- if (this.outOfBudget(opts)) break
8926
+ if (!loop.start(opts, entry)) break
8927
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8417
8928
  if (digest.waitPending && digest.kind !== 'node')
8418
8929
  await this.serviceWaitRequests(record, report)
8419
8930
  if (launched.has(record.slug)) continue
8420
- try {
8421
- await this.sweepBuild(record, report, launched, paused, now)
8422
- } catch (error) {
8423
- rethrowAuthorityLapse(error)
8424
- // Per-build containment: one build's failure never stops the sweep
8425
- // from advancing the others. Workspace failures are already durable
8426
- // against the build; a repository-wide cooldown still ends the tick.
8427
- if (
8428
- error instanceof ForgeRequestDeferred ||
8429
- error instanceof MixedVersionDeferral ||
8430
- isRecoveryDeferred(error)
8431
- )
8432
- continue
8433
- if (error instanceof ForgeCooldown) throw error
8434
- const message =
8435
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8436
- report.janitorFailed += 1
8437
- report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8931
+ // The early stage already swept it this tick.
8932
+ if (this.tickPrioritized.has(record.slug)) continue
8933
+ await this.sweepContained(record, report, launched, paused, now)
8934
+ }
8935
+ loop.finish()
8936
+ }
8937
+
8938
+ /** One build's lease-sweep pass under the sweep's per-build containment:
8939
+ * one build's failure never stops the caller from advancing the others.
8940
+ * Workspace failures are already durable against the build; a
8941
+ * repository-wide cooldown or an authority lapse still ends the tick.
8942
+ * `waiting` is a try-again-later outcome (a forge, mixed-version or budget
8943
+ * deferral); `failed` is a contained failure reported in diagnostics. */
8944
+ private async sweepContained(
8945
+ record: BuildRecord,
8946
+ report: TickReport,
8947
+ launched: Set<string>,
8948
+ paused: boolean,
8949
+ now: number,
8950
+ ): Promise<'done' | 'waiting' | 'failed'> {
8951
+ try {
8952
+ return await this.sweepBuild(record, report, launched, paused, now)
8953
+ } catch (error) {
8954
+ rethrowAuthorityLapse(error)
8955
+ if (isRecoveryDeferred(error)) {
8956
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
8957
+ return 'waiting'
8958
+ }
8959
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
8960
+ return 'waiting'
8961
+ if (error instanceof ForgeCooldown) throw error
8962
+ const message =
8963
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8964
+ report.janitorFailed += 1
8965
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8966
+ return 'failed'
8967
+ }
8968
+ }
8969
+
8970
+ /**
8971
+ * Stage −1 — deferred deadline-gated work. Builds the previous invocation
8972
+ * recorded in `dispatcher.work-deferred` (a provision or a stopped-sandbox
8973
+ * recovery the budget deferred) get the ordinary `sweepBuild` pass first,
8974
+ * before settlement and the janitor spend the window. The hint is never
8975
+ * authority: each pass re-derives every decision from fresh build state,
8976
+ * and a stale entry does nothing and is retired.
8977
+ *
8978
+ * Per-tick cost: zero reads when nothing is carried (the hint comes from
8979
+ * the repository facts the tick already reduced). Otherwise the record
8980
+ * listing and digests from this tick's epoch cache, with no fleet-wide
8981
+ * compatibility pass, plus one reduced `buildFacts` read per carried build
8982
+ * visited — a read the lease sweep would otherwise make later, and which
8983
+ * it now skips. Writes: at most one hint append when the list changes.
8984
+ */
8985
+ private async serviceDeferredWork(
8986
+ report: TickReport,
8987
+ launched: Set<string>,
8988
+ paused: boolean,
8989
+ opts: TickOpts,
8990
+ ): Promise<void> {
8991
+ if (this.carriedOutstanding.size === 0) return this.pass.total('deferred', 0)
8992
+ // Never the default form: it would run the mixed-version check for every
8993
+ // compatibility-bearing build. `sweepBuild` checks each carried build.
8994
+ const entries = new Map(
8995
+ (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
8996
+ )
8997
+ this.pass.total('deferred', this.carriedOutstanding.size)
8998
+ for (const slug of [...this.carriedOutstanding.keys()]) {
8999
+ if (!this.passItem(opts, 'deferred')) break
9000
+ const entry = this.carriedOutstanding.get(slug)!
9001
+ const found = entries.get(slug)
9002
+ if (found === undefined || found.digest.terminal !== undefined) {
9003
+ this.retireCarried(slug)
9004
+ continue
8438
9005
  }
9006
+ entry.visited = true
9007
+ this.tickPrioritized.add(slug)
9008
+ if (launched.has(slug)) {
9009
+ this.retireCarried(slug)
9010
+ continue
9011
+ }
9012
+ const outcome = await this.sweepContained(
9013
+ found.record,
9014
+ report,
9015
+ launched,
9016
+ paused,
9017
+ this.deps.clock().getTime(),
9018
+ )
9019
+ // The invocation's deadline, not the stage's cut: in-flight work is
9020
+ // never cancelled at a cut.
9021
+ const interrupted = this.budgetSpent(this.tickOpts)
9022
+ if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
9023
+ this.retireCarried(slug)
9024
+ }
9025
+ await this.persistDeferrals()
9026
+ }
9027
+
9028
+ /** A carried hint entry whose own pass showed it no longer needs priority.
9029
+ * Never writes: the next hint write simply omits it. */
9030
+ private retireCarried(slug: string): void {
9031
+ this.carriedOutstanding.delete(slug)
9032
+ }
9033
+
9034
+ /** Record that this tick deferred `slug`'s deadline-gated `step` for
9035
+ * budget, and keep the durable hint current. */
9036
+ private async noteDeferral(slug: string, step: DeferredWorkStep, detail?: string): Promise<void> {
9037
+ if (!this.tickDeferrals.has(slug))
9038
+ this.tickDeferrals.set(slug, { step, ...(detail !== undefined ? { detail } : {}) })
9039
+ await this.persistDeferrals()
9040
+ }
9041
+
9042
+ /** The hint this tick would write: unvisited carried entries first, in
9043
+ * carried order; then visited carried entries that are still outstanding
9044
+ * (re-deferred or interrupted); then this tick's new deferrals. Capped
9045
+ * from the tail, so new entries are dropped first. */
9046
+ private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
9047
+ const list: { slug: string; step: DeferredWorkStep }[] = []
9048
+ const seen = new Set<string>()
9049
+ const push = (slug: string, step: DeferredWorkStep) => {
9050
+ if (seen.has(slug)) return
9051
+ seen.add(slug)
9052
+ list.push({ slug, step })
9053
+ }
9054
+ for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry.step)
9055
+ for (const [slug, entry] of this.carriedOutstanding)
9056
+ if (entry.visited) push(slug, this.tickDeferrals.get(slug)?.step ?? entry.step)
9057
+ for (const [slug, { step }] of this.tickDeferrals) push(slug, step)
9058
+ return list.slice(0, MAX_DEFERRED_WORK)
9059
+ }
9060
+
9061
+ /** Append the merged hint when it differs from the one last read or
9062
+ * written. Every write keeps every unretired carried entry, so a pass cut
9063
+ * short at any point leaves a durable superset of what still needs
9064
+ * priority. A deferral noted after the work signal aborted is written in
9065
+ * the tick's teardown scope. Best effort: a failure costs only the hint. */
9066
+ private persistDeferrals(): Promise<void> {
9067
+ const write = this.deferralWrites.then(async () => {
9068
+ const next = this.nextDeferralList()
9069
+ const recorded = this.recordedDeferrals
9070
+ if (
9071
+ next.length === recorded.length &&
9072
+ next.every(
9073
+ (entry, i) => entry.slug === recorded[i]!.slug && entry.step === recorded[i]!.step,
9074
+ )
9075
+ )
9076
+ return
9077
+ const outcome = await this.writeHint(() =>
9078
+ this.store.appendRepo(this.deps.repo, {
9079
+ actor: DISPATCHER,
9080
+ type: 'dispatcher.work-deferred',
9081
+ payload: { builds: next },
9082
+ }),
9083
+ )
9084
+ if (outcome === true) this.recordedDeferrals = next
9085
+ else if (outcome !== false) this.deferralWriteFailure = outcome
9086
+ })
9087
+ this.deferralWrites = write.catch(() => {})
9088
+ return write
9089
+ }
9090
+
9091
+ /** The write discipline every scheduling hint shares: nothing once
9092
+ * authority is lost; past the work deadline, abandoned work writes only
9093
+ * through the bounded, authorized teardown scope. Best effort: true when
9094
+ * written, false when skipped, the failure text otherwise. An authority
9095
+ * lapse escapes. */
9096
+ private async writeHint(append: () => Promise<unknown>): Promise<boolean | string> {
9097
+ if (this.deps.holdsRepoAuthority?.() === false) return false
9098
+ const late = this.tickOpts.workSignal?.aborted === true
9099
+ const teardown = this.tickOpts.teardownWrite
9100
+ if (late && teardown === undefined) return false
9101
+ try {
9102
+ await (late ? teardown!(append) : append())
9103
+ return true
9104
+ } catch (error) {
9105
+ rethrowAuthorityLapse(error)
9106
+ return errorText(error)
9107
+ }
9108
+ }
9109
+
9110
+ /** Append the rotated loops' positions once per bounded pass, only when one
9111
+ * changed (#1409). A pass that cut no loop leaves them clear and writes
9112
+ * nothing, so the next refresh reads no new row. Best effort: a failure
9113
+ * costs only the continuation, which then restarts from the first key. */
9114
+ private persistPassCursors(): Promise<void> {
9115
+ if (this.passCursorsPersisted || this.tickOpts.deadlineAt === undefined)
9116
+ return Promise.resolve()
9117
+ this.passCursorsPersisted = true
9118
+ const next = { ...this.nextPassCursors }
9119
+ const previous = this.passCursors
9120
+ const keys = new Set([...Object.keys(next), ...Object.keys(previous)]) as Set<RotatedPassPart>
9121
+ if ([...keys].every((key) => next[key] === previous[key])) return Promise.resolve()
9122
+ const write = this.deferralWrites.then(async () => {
9123
+ const outcome = await this.writeHint(async () => {
9124
+ await this.store.ensureRepo(this.deps.repo)
9125
+ await this.store.appendRepo(this.deps.repo, {
9126
+ actor: DISPATCHER,
9127
+ type: 'dispatcher.pass-cursors',
9128
+ payload: { cursors: next },
9129
+ })
9130
+ })
9131
+ if (typeof outcome === 'string') this.passCursorWriteFailure = outcome
9132
+ })
9133
+ this.deferralWrites = write.catch(() => {})
9134
+ return write
9135
+ }
9136
+
9137
+ /** A hint write failure this tick, reported once in the tick's diagnostics. */
9138
+ private deferralWriteFailure: string | undefined
9139
+
9140
+ /** Count and name this tick's deferrals on its report. Runs in `tick()`,
9141
+ * so every early return of `runTick` is covered. */
9142
+ private finishDeferrals(report: TickReport): void {
9143
+ for (const [slug, { step, detail }] of this.tickDeferrals) {
9144
+ if (step !== 'provision') report.recoveryDeferred += 1
9145
+ report.deferredDiagnostics.push(
9146
+ `build ${slug}: ${step} deferred by the invocation budget; the next invocation runs it first` +
9147
+ (detail !== undefined ? ` — ${detail}` : ''),
9148
+ )
8439
9149
  }
9150
+ if (this.deferralWriteFailure !== undefined)
9151
+ report.deferredDiagnostics.push(
9152
+ `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
9153
+ )
9154
+ this.deferralWriteFailure = undefined
9155
+ if (this.passCursorWriteFailure !== undefined)
9156
+ report.deferredDiagnostics.push(
9157
+ `pass positions not recorded for the next invocation — ${this.passCursorWriteFailure}`,
9158
+ )
9159
+ this.passCursorWriteFailure = undefined
8440
9160
  }
8441
9161
 
8442
9162
  /**
@@ -8489,22 +9209,33 @@ export class Dispatcher {
8489
9209
  })
8490
9210
  }
8491
9211
 
8492
- /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
9212
+ /** One build's lease-sweep pass; `sweepContained` contains its failures.
9213
+ * Resolves `waiting` when a mixed-version deferral holds the build, and
9214
+ * `done` otherwise. */
8493
9215
  private async sweepBuild(
8494
9216
  record: BuildRecord,
8495
9217
  report: TickReport,
8496
9218
  launched: Set<string>,
8497
9219
  paused: boolean,
8498
9220
  now: number,
8499
- ): Promise<void> {
9221
+ ): Promise<'done' | 'waiting'> {
9222
+ return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
9223
+ }
9224
+
9225
+ private async sweepBuildPass(
9226
+ record: BuildRecord,
9227
+ report: TickReport,
9228
+ launched: Set<string>,
9229
+ paused: boolean,
9230
+ now: number,
9231
+ ): Promise<'waiting' | undefined> {
8500
9232
  if (record.lease) {
8501
9233
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
8502
9234
  }
8503
9235
  const facts = await this.store.buildFacts(record.slug)
8504
9236
  const state = facts.state
8505
9237
  if (mixedVersionDeferred(state)) {
8506
- await deferMixedVersion(this.store, record.slug)
8507
- return
9238
+ return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
8508
9239
  }
8509
9240
  // The janitor owns this abort: a sweep must never reap, provision or
8510
9241
  // launch a runner only to acknowledge it.
@@ -8640,6 +9371,7 @@ export class Dispatcher {
8640
9371
  ...(this.settlePublication !== undefined
8641
9372
  ? { settlePublication: this.settlePublication }
8642
9373
  : {}),
9374
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
8643
9375
  },
8644
9376
  record.slug,
8645
9377
  foreignExecution,
@@ -8773,8 +9505,9 @@ export class Dispatcher {
8773
9505
  )
8774
9506
  .slice(0, 8)
8775
9507
  const failures: unknown[] = []
9508
+ this.pass.total('preparations', pending.length)
8776
9509
  for (const attempt of pending) {
8777
- if (this.outOfBudget(opts)) break
9510
+ if (!this.passItem(opts, 'preparations')) break
8778
9511
  try {
8779
9512
  await this.recoverTicketPreparation(attempt)
8780
9513
  } catch (error) {
@@ -8974,6 +9707,10 @@ export class Dispatcher {
8974
9707
  * each ticket's outcome. The standing report fields are not published. */
8975
9708
  targeted?: TargetedDispatch,
8976
9709
  ): Promise<void> {
9710
+ // Only ordinary intake counts as the intake stage's `tickets`; a start
9711
+ // pass's targeted dispatch is part of its `starts`.
9712
+ const part = targeted ? undefined : ('tickets' as const)
9713
+ if (part) this.pass.total(part, 0)
8977
9714
  if (!this.claimGateOpen()) return
8978
9715
  const store = this.store
8979
9716
  const { tickets, config } = this.deps
@@ -9239,17 +9976,28 @@ export class Dispatcher {
9239
9976
  // failure must leave the entire ready set unclaimed. Publish dependency
9240
9977
  // diagnostics only after the complete preflight succeeds.
9241
9978
  let scanSuccessful = true
9242
- const treeEntries = await this.repoBuildDigests()
9979
+ const listed = await this.tickDigests()
9980
+ // Identity: a deferred node still means nodes exist.
9243
9981
  const hasNodes =
9244
- treeEntries.some(({ digest }) => digest.kind === 'node') ||
9982
+ listed.some(({ digest }) => digest.kind === 'node') ||
9245
9983
  ready.some((ticket) => ticket.kind === 'node')
9246
9984
  let presence: PresenceInputs | undefined
9247
9985
  const migrations = this.store.repositoryFacts().ticketMigrations
9248
9986
  const normalizeTicket = historicalTicketIdentity(migrations, this.deps.tickets.name)
9987
+ // A blocker's build can satisfy a dependency, so a deferred one is
9988
+ // absent, as the filtered listing left it.
9989
+ const dependencyListing = (entries: { record: BuildRecord; digest: BuildDigest }[]) =>
9990
+ this.compatibleBlockers(entries, ready, normalizeTicket)
9991
+ const tree = this.boundedListings
9992
+ ? await dependencyListing(listed)
9993
+ : { entries: listed, decidable: () => true }
9994
+ const treeEntries = tree.entries
9249
9995
  const builtTickets = hasNodes
9250
9996
  ? new Set(
9251
- treeEntries.flatMap(({ record }) =>
9252
- record.ticket ? [normalizeTicket(record.ticket, record.slug)] : [],
9997
+ treeEntries.flatMap(({ record, digest }) =>
9998
+ record.ticket && tree.decidable(record.slug, digest)
9999
+ ? [normalizeTicket(record.ticket, record.slug)]
10000
+ : [],
9253
10001
  ),
9254
10002
  )
9255
10003
  : undefined
@@ -9315,25 +10063,33 @@ export class Dispatcher {
9315
10063
  if (hasNodes) {
9316
10064
  if (!presence && needsPresence(ticket)) {
9317
10065
  await this.recoverNodeContributions(treeEntries)
9318
- const entries = await this.repoBuildDigests()
9319
- const destinations = ready
9320
- .filter(
9321
- (candidate) =>
9322
- needsPresence(candidate) &&
9323
- !withheld.has(candidate.ref.id) &&
9324
- candidate.target !== undefined,
10066
+ const listing = await this.tickDigests()
10067
+ const entries = this.boundedListings
10068
+ ? (await dependencyListing(listing)).entries
10069
+ : listing
10070
+ const destinations: string[] = []
10071
+ for (const candidate of ready) {
10072
+ if (
10073
+ !needsPresence(candidate) ||
10074
+ withheld.has(candidate.ref.id) ||
10075
+ candidate.target === undefined
9325
10076
  )
9326
- .flatMap((candidate) => {
9327
- const node = blockerBuild(
9328
- entries,
9329
- candidate.ref.source,
9330
- candidate.target!,
9331
- normalizeTicket,
9332
- )
9333
- return node && typeof node !== 'string' && node.digest.kind === 'node'
9334
- ? [node.record.slug]
9335
- : []
9336
- })
10077
+ continue
10078
+ const node = blockerBuild(
10079
+ entries,
10080
+ candidate.ref.source,
10081
+ candidate.target,
10082
+ normalizeTicket,
10083
+ )
10084
+ // A destination's state is read and decided from.
10085
+ if (
10086
+ node &&
10087
+ typeof node !== 'string' &&
10088
+ node.digest.kind === 'node' &&
10089
+ !(this.boundedListings && (await this.checkCompatibility(node)))
10090
+ )
10091
+ destinations.push(node.record.slug)
10092
+ }
9337
10093
  presence = await presenceInputs(this.store, entries, destinations)
9338
10094
  }
9339
10095
  const inputs = presence ?? {
@@ -9406,8 +10162,9 @@ export class Dispatcher {
9406
10162
  }
9407
10163
  }
9408
10164
  let claimLoopCompleted = true
10165
+ if (part) this.pass.total(part, ready.length)
9409
10166
  for (const ticket of ready) {
9410
- if (this.outOfBudget(opts)) {
10167
+ if (part ? !this.passItem(opts, part) : this.outOfBudget(opts)) {
9411
10168
  claimLoopCompleted = false
9412
10169
  break
9413
10170
  }
@@ -9802,7 +10559,7 @@ export class Dispatcher {
9802
10559
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9803
10560
  )
9804
10561
  if (candidates.length === 0) return tiers
9805
- const all = await this.repoBuildDigests()
10562
+ const all = await this.tickDigests()
9806
10563
  const nodes = new Map<string, BuildState>()
9807
10564
  const key = this.attemptIdentity()
9808
10565
  for (const ticket of candidates) {
@@ -9819,6 +10576,8 @@ export class Dispatcher {
9819
10576
  throw error
9820
10577
  }
9821
10578
  if (!signal || signal.stopped) continue
10579
+ // A deferred target node lends no tier; its ticket waits on the target.
10580
+ if (this.boundedListings && (await this.checkCompatibility(latest))) continue
9822
10581
  let state = nodes.get(record.slug)
9823
10582
  if (state === undefined) {
9824
10583
  state = (await this.store.buildFacts(record.slug)).state
@@ -9854,7 +10613,7 @@ export class Dispatcher {
9854
10613
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
9855
10614
  if (ticket.target === undefined) return undefined
9856
10615
  const migrations = this.store.repositoryFacts().ticketMigrations
9857
- const all = await this.repoBuildDigests()
10616
+ const all = await this.tickDigests()
9858
10617
  const entries = this.targetBuilds(ticket.target, ticket.ref.source, all)
9859
10618
  const latest = entries[0]
9860
10619
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
@@ -9864,6 +10623,10 @@ export class Dispatcher {
9864
10623
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
9865
10624
  if (digest.terminal || digest.prClosed || digest.merged)
9866
10625
  return `target node ${ticket.target} is ${digest.terminal === 'aborted' ? 'aborted' : digest.merged ? 'landed' : 'closed'}`
10626
+ // The target's state decides the claim: a node this runtime cannot
10627
+ // decide withholds the ticket (#1409).
10628
+ if (this.boundedListings && (await this.checkCompatibility(latest)))
10629
+ return `target node ${ticket.target} is deferred: ${compatibilityDiagnostic(digest.compatibility!) ?? 'kernel decisions deferred'}`
9867
10630
  const state = (await this.store.buildFacts(record.slug)).state
9868
10631
  if (
9869
10632
  state.status === 'done' ||
@@ -10241,9 +11004,10 @@ export class Dispatcher {
10241
11004
  if (result.exitCode !== 0) throw new Error(result.stderr)
10242
11005
  added = true
10243
11006
  const beforeReplay = async (operation: string) => {
10244
- for (const child of await this.repoBuildDigests()) {
11007
+ for (const child of await this.tickDigests()) {
10245
11008
  if (child.digest.terminal || child.digest.kind === 'node') continue
10246
11009
  const childState = (await this.store.buildFacts(child.record.slug)).state
11010
+ if (this.boundedListings && (await this.checkCompatibility(child, childState))) continue
10247
11011
  if (
10248
11012
  childState.target?.build !== record.slug ||
10249
11013
  !childState.pr ||
@@ -10779,11 +11543,15 @@ export class Dispatcher {
10779
11543
  digest.kind === 'node' && (digest.merged || record.slug === merging?.slug),
10780
11544
  )
10781
11545
  if (candidates.length === 0) return
10782
- const pending = candidates.filter(
11546
+ const unrecorded = candidates.filter(
10783
11547
  ({ record, digest }) =>
10784
11548
  digest.nodeContribution?.landing !==
10785
11549
  (record.slug === merging?.slug ? merging.sha : digest.mergedSha),
10786
11550
  )
11551
+ // Each node written to is checked first in a bounded pass (#1409).
11552
+ const pending: typeof unrecorded = []
11553
+ for (const entry of unrecorded)
11554
+ if (!(this.boundedListings && (await this.checkCompatibility(entry)))) pending.push(entry)
10787
11555
  if (pending.length === 0) return
10788
11556
  const inputs = await presenceInputs(
10789
11557
  this.store,
@@ -10838,7 +11606,11 @@ export class Dispatcher {
10838
11606
  for (const child of candidates) {
10839
11607
  if (child.record.slug === slug) continue
10840
11608
  const childState = inputs.states.get(child.record.slug)
10841
- if (childState?.target?.build === slug && childState.mergedSha)
11609
+ if (
11610
+ childState?.target?.build === slug &&
11611
+ childState.mergedSha &&
11612
+ !(this.boundedListings && (await this.checkCompatibility(child, childState)))
11613
+ )
10842
11614
  await recover(child.record.slug)
10843
11615
  }
10844
11616
  const currentIdentities = await ownedContribution(