@defrex/autobuild 1.14.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.
@@ -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,
@@ -731,6 +743,9 @@ export interface TickReport {
731
743
  /** Agent-context stage (`processes/agent-context.ts`): typed problems this
732
744
  * tick found capturing the base branch's skills and agent instructions. */
733
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[]
734
749
  }
735
750
 
736
751
  export function emptyTickReport(): TickReport {
@@ -1170,11 +1185,15 @@ export class Dispatcher {
1170
1185
  slug: string
1171
1186
  state: Pick<BuildState, 'pollingActivity'>
1172
1187
  }[] = []
1173
- for (const { record, digest } of await this.repoBuildDigests()) {
1188
+ for (const entry of await this.tickDigests()) {
1189
+ const { record, digest } = entry
1174
1190
  if (record.slug === slug) continue
1175
1191
  // The digest names every node a build ever targeted, so a build it does
1176
1192
  // not name can never be this node's child and needs no facts read.
1177
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
1178
1197
  const known = this.nodePollingBuilds.get(record.slug)
1179
1198
  // Only node relationships can move. Unrelated known work never needs
1180
1199
  // another full-facts read, even while it is running.
@@ -1385,6 +1404,20 @@ export class Dispatcher {
1385
1404
  private tickOpts: TickOpts = {}
1386
1405
  /** Serializes hint writes so concurrent deferral notes never race. */
1387
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>>()
1388
1421
  /** Per tick: finished leaves the admission gate turned away or deferred,
1389
1422
  * with their priority. Intake reserves their slots. */
1390
1423
  private readonly slotWaiters = new Map<string, BuildPriority>()
@@ -1622,17 +1655,32 @@ export class Dispatcher {
1622
1655
  }
1623
1656
  }
1624
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
1625
1663
  try {
1626
1664
  const report = await (this.deps.forge.withReadScope
1627
1665
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1628
1666
  : this.runTick(opts))
1629
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()
1630
1670
  this.finishDeferrals(report)
1631
1671
  report.janitorDiagnostics.push(...this.tickAbandonments)
1672
+ const stages = opts.deadlineAt === undefined ? [] : this.pass.summary()
1673
+ if (stages.length > 0) report.stages = stages
1632
1674
  return report
1633
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
+ }
1634
1681
  throw this.withTickAbandonments(error)
1635
1682
  } finally {
1683
+ this.boundedListings = false
1636
1684
  this.tickAbandonments = []
1637
1685
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1638
1686
  stop?.()
@@ -1693,6 +1741,12 @@ export class Dispatcher {
1693
1741
  this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1694
1742
  ({ slug, step }) => ({ slug, step }),
1695
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 }
1696
1750
  for (const { slug, step } of this.recordedDeferrals)
1697
1751
  if (!this.carriedOutstanding.has(slug))
1698
1752
  this.carriedOutstanding.set(slug, { step, visited: false })
@@ -1703,6 +1757,7 @@ export class Dispatcher {
1703
1757
  )
1704
1758
  const autoMergeUser = undefined
1705
1759
  const report = emptyTickReport()
1760
+ this.inFlightReport = report
1706
1761
  this.restoreScan(report)
1707
1762
  /** Builds already launched this tick — a janitor/startup re-attach must
1708
1763
  * not be doubled by the sweep, nor a fresh dispatch by anything. */
@@ -1739,71 +1794,242 @@ export class Dispatcher {
1739
1794
  if (this.outOfBudget(opts)) return report
1740
1795
  // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1741
1796
  // recovery an earlier invocation deferred for budget are swept first,
1742
- // while nearly the whole work window remains.
1743
- if (!opts.observationOnly) await this.serviceDeferredWork(report, launched, paused, opts)
1744
- if (this.outOfBudget(opts)) return report
1745
- await this.settleForeignExecutions(report, opts)
1746
- if (this.outOfBudget(opts)) return report
1747
- await this.settleHarvestExecutions(opts)
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
+ )
1748
1802
  if (this.outOfBudget(opts)) return report
1749
- 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
+ })
1750
1810
  if (opts.observationOnly) return report
1751
1811
  if (this.outOfBudget(opts)) return report
1752
- // The default fan-out runs before the janitor so one tick both records the
1753
- // consent and lets the janitor act on it (the janitor reduces a fresh read
1754
- // inside `checkPr`). Independent of intake and `acceptNewWork` — the
1755
- // durable fact drives it, so a second dispatcher polling the same
1756
- // repository converges the same state.
1757
- if (this.outOfBudget(opts)) return report
1758
- await this.recoverTicketPreparations(report, opts)
1759
- if (this.outOfBudget(opts)) return report
1760
- await this.janitor(report, launched, opts)
1761
- if (this.outOfBudget(opts)) return report
1762
- await this.settleHandbacks()
1763
- if (this.outOfBudget(opts)) return report
1764
- await this.recoverDispatches(report, launched, paused, opts)
1812
+ await this.runStage('preparations', opts, (stageOpts) =>
1813
+ this.recoverTicketPreparations(report, stageOpts),
1814
+ )
1765
1815
  if (this.outOfBudget(opts)) return report
1766
- if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, opts)
1816
+ await this.runStage('janitor', opts, (stageOpts) => this.janitor(report, launched, stageOpts))
1767
1817
  if (this.outOfBudget(opts)) return report
1768
- 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
+ })
1769
1825
  if (this.outOfBudget(opts)) return report
1770
- // Nodes with a durable verification or propose request take freed slots
1771
- // before intake, whether or not idle node polling visited them this tick.
1772
- // The same pass advances optimization nodes' proposers first.
1773
- await this.admitWaitingNodes(report, launched, opts)
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()
1774
1831
  if (this.outOfBudget(opts)) return report
1775
- // Operator start requests are independent of intake: they claim only the
1776
- // named tickets, and read nothing when none is pending. Manual and urgent
1777
- // requests run here, ahead of ordinary claims; high, normal and low
1778
- // requests run inside intake, after higher-level claims and before their
1779
- // own level's ready tickets, or after intake when it reaches no ticket of
1780
- // their level (SPEC §12 "Slot admission order").
1781
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
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
+ })
1782
1853
  if (this.outOfBudget(opts)) return report
1783
- if (opts.acceptNewWork !== false) {
1784
- await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1785
- }
1786
- await this.admitDeferredParked(report, launched, paused, opts)
1787
- // Late tiers intake did not reach: ordinary claims left their reserved
1788
- // slots free.
1789
- const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1790
- if (!this.outOfBudget(opts) && lateTiers.length > 0)
1791
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1792
- // Fire-and-forget by contract: long synthesize/review sessions must not
1793
- // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1794
- // watch ticks. Durable pause and infrastructure-error stops suppress
1795
- // launch. Pending control commands still launch the runner so the kernel
1796
- // can settle them under the repository lease.
1797
- if (!this.budgetSpent(opts)) await this.triggerHarvest()
1798
- await this.captureAgentContext(report, opts)
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
+ })
1799
1876
  return report
1800
1877
  }
1801
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
+
1802
2026
  /** Agent-context stage: contained, so a capture failure never fails the
1803
2027
  * tick; only an authority lapse escapes. */
1804
2028
  private async captureAgentContext(report: TickReport, opts: TickOpts): Promise<void> {
1805
2029
  const stage = this.deps.agentContext
1806
2030
  if (stage === undefined || this.outOfBudget(opts)) return
2031
+ this.pass.total('context', 1)
2032
+ this.pass.item('context')
1807
2033
  try {
1808
2034
  report.agentContextDiagnostics.push(
1809
2035
  ...(await stage.run({
@@ -1876,10 +2102,8 @@ export class Dispatcher {
1876
2102
 
1877
2103
  /** Builds with no terminal fact: the only ones whose tick duties change
1878
2104
  * their state (decide, resume, lease sweep, capacity). */
1879
- private async nonterminalBuilds(): Promise<BuildRecord[]> {
1880
- return (await this.repoBuildDigests())
1881
- .filter(({ digest }) => digest.terminal === undefined)
1882
- .map(({ record }) => record)
2105
+ private async nonterminalEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2106
+ return (await this.tickDigests()).filter(({ digest }) => digest.terminal === undefined)
1883
2107
  }
1884
2108
 
1885
2109
  /** Builds that still have work: nonterminal ones, plus terminal builds whose
@@ -1887,10 +2111,10 @@ export class Dispatcher {
1887
2111
  * cleanup's `build.completed`, a `done` build with an unreclaimed release
1888
2112
  * asset, or any build with an execution the provider has not been seen to
1889
2113
  * end. A terminal, settled build costs no event reads. */
1890
- private async workBuilds(): Promise<BuildRecord[]> {
1891
- return (await this.repoBuildDigests())
1892
- .filter(({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true)
1893
- .map(({ record }) => record)
2114
+ private async workEntries(): Promise<{ record: BuildRecord; digest: BuildDigest }[]> {
2115
+ return (await this.tickDigests()).filter(
2116
+ ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2117
+ )
1894
2118
  }
1895
2119
 
1896
2120
  private async sourceCondition(
@@ -2019,17 +2243,24 @@ export class Dispatcher {
2019
2243
 
2020
2244
  /** Settle reported build hand-backs whose build is complete (or gone).
2021
2245
  * Zero reads and appends while no hand-back is open. */
2022
- private async settleHandbacks(): Promise<void> {
2246
+ private async settleHandbacks(opts: TickOpts = {}): Promise<void> {
2023
2247
  const open = Object.keys(this.store.repositoryFacts().handbacks)
2024
- if (open.length === 0) return
2248
+ if (open.length === 0) return this.pass.total('handbacks', 0)
2025
2249
  const digests = new Map(
2026
2250
  (await this.repoBuildDigests(true)).map(({ record, digest }) => [record.slug, digest]),
2027
2251
  )
2028
- for (const identity of open) {
2252
+ const loop = this.rotated('handbacks', open, (identity) => identity)
2253
+ for (const identity of loop.items) {
2029
2254
  const slug = identity.slice('build:'.length)
2030
2255
  const digest = digests.get(slug)
2031
- 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)
2032
2262
  }
2263
+ loop.finish()
2033
2264
  }
2034
2265
 
2035
2266
  /** Admit pending operator start requests of the given tiers through
@@ -2049,6 +2280,7 @@ export class Dispatcher {
2049
2280
  tiers: readonly StartTier[],
2050
2281
  ): Promise<StartPassResult> {
2051
2282
  const result: StartPassResult = { settled: [] }
2283
+ this.pass.total('starts', 0)
2052
2284
  for (const tier of tiers)
2053
2285
  if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
2054
2286
  await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
@@ -2111,8 +2343,12 @@ export class Dispatcher {
2111
2343
  const identities = this.store.repositoryFacts().ticketStarts.identities
2112
2344
  const lifecycle = ticketLifecycle(config.tickets)
2113
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).
2114
2350
  for (const request of pending) {
2115
- if (this.outOfBudget(opts)) return
2351
+ if (!this.passItem(opts, 'starts')) break
2116
2352
  let ref: TicketRef | undefined
2117
2353
  try {
2118
2354
  ref = resolveTicketRef(migrations, request.ticket, tickets.name)
@@ -2169,7 +2405,10 @@ export class Dispatcher {
2169
2405
  if (this.preparing(ticket.ref.source, ticket.ref.id)) continue
2170
2406
  candidates.push({ request, ticket })
2171
2407
  }
2172
- 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
2173
2412
  // Capacity is measured from the facts this tick's janitor, recovery and
2174
2413
  // lease sweep already read (`servedBuildFacts`): a build is read again
2175
2414
  // only when the tick skipped it or wrote to it since, so neither a wait
@@ -2214,7 +2453,7 @@ export class Dispatcher {
2214
2453
  const scratch = emptyTickReport()
2215
2454
  this.startPass = true
2216
2455
  try {
2217
- await this.dispatch(scratch, launched, autoMergeUser, paused, opts, undefined, targeted)
2456
+ await this.dispatch(scratch, launched, autoMergeUser, paused, claimOpts, undefined, targeted)
2218
2457
  } finally {
2219
2458
  this.startPass = false
2220
2459
  for (const counter of [
@@ -2407,7 +2646,8 @@ export class Dispatcher {
2407
2646
  private async activeTicketIdentities(refs: TicketRef[], listed: Ticket[]): Promise<Set<string>> {
2408
2647
  const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
2409
2648
  const migrations = this.store.repositoryFacts().ticketMigrations
2410
- const records = await this.repoBuildDigests()
2649
+ // Identity only: a deferred build's slug names its own ticket.
2650
+ const records = await this.tickDigests()
2411
2651
  const normalized = refs.map((ref) => {
2412
2652
  try {
2413
2653
  return resolveTicketRef(
@@ -2444,7 +2684,22 @@ export class Dispatcher {
2444
2684
  * disabled. It shares the active-ticket exclusion with dispatch but performs
2445
2685
  * no dependency fetch, claim, bounce, build, workspace, or launch side
2446
2686
  * effect, and deliberately does not alter TickReport compatibility. */
2447
- 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<{
2448
2703
  queued: number
2449
2704
  invalidTickets: number
2450
2705
  ticketDiagnostics: string[]
@@ -2457,7 +2712,7 @@ export class Dispatcher {
2457
2712
  if (checkpoint.due) {
2458
2713
  const listing = await this.listReady()
2459
2714
  const refs: TicketRef[] = []
2460
- for (const { record, digest } of await this.repoBuildDigests()) {
2715
+ for (const { record, digest } of await this.tickDigests()) {
2461
2716
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
2462
2717
  }
2463
2718
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
@@ -2521,7 +2776,8 @@ export class Dispatcher {
2521
2776
  /** `force` makes the scan due now, skipping the interval and the journal
2522
2777
  * deferral: a deferred admission waits on this tick's higher-level claims. */
2523
2778
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2524
- const digest = (await this.repoBuildDigests())
2779
+ // A fingerprint of readiness digests: no decision reads a build's state.
2780
+ const digest = (await this.tickDigests())
2525
2781
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
2526
2782
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
2527
2783
  .sort(([a], [b]) => a.localeCompare(b))
@@ -2780,13 +3036,19 @@ export class Dispatcher {
2780
3036
  * the stage still settles. */
2781
3037
  private async settleForeignExecutions(report: TickReport, opts: TickOpts = {}): Promise<void> {
2782
3038
  const active = this.deps.activeExecutions?.() ?? new Set<string>()
2783
- for (const record of await this.workBuilds()) {
2784
- if (active.has(record.slug)) continue
3039
+ const loop = this.rotated('executions', await this.workEntries(), (entry) => entry.record.slug)
3040
+ for (const entry of loop.items) {
3041
+ const { record } = entry
2785
3042
  // The early stage already observed and settled it this tick.
2786
- if (this.tickPrioritized.has(record.slug)) continue
2787
- // Budget gate: once spent, stop settling further foreign executions.
2788
- if (this.outOfBudget(opts)) break
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
2789
3050
  try {
3051
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
2790
3052
  const { open } = await this.store.buildFacts(record.slug)
2791
3053
  if (open === null) continue
2792
3054
  const owner = this.executionOwner(open.provider)
@@ -2814,6 +3076,7 @@ export class Dispatcher {
2814
3076
  await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2815
3077
  }
2816
3078
  }
3079
+ loop.finish()
2817
3080
  }
2818
3081
 
2819
3082
  /** Durable settlement for hosted-harvest executions (AUT-305), next to the
@@ -2834,11 +3097,17 @@ export class Dispatcher {
2834
3097
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
2835
3098
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
2836
3099
  const facts = this.store.repositoryFacts()
2837
- for (const execution of facts.openHarvest) {
2838
- 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
+ }
2839
3108
  // Budget gate: once spent, stop settling further harvest executions;
2840
3109
  // the next tick retries what remains.
2841
- if (this.outOfBudget(opts)) break
3110
+ if (!loop.start(opts, execution)) break
2842
3111
  try {
2843
3112
  const owner = this.executionOwner(execution.provider)
2844
3113
  const capability = owner?.harvestExecution
@@ -2919,6 +3188,7 @@ export class Dispatcher {
2919
3188
  // settlement stage; the next tick retries it.
2920
3189
  }
2921
3190
  }
3191
+ loop.finish()
2922
3192
  }
2923
3193
 
2924
3194
  /** A foreign hosted-harvest execution still open after this tick's
@@ -2968,15 +3238,20 @@ export class Dispatcher {
2968
3238
  const providerName = this.deps.workspaces.name
2969
3239
  const facts = this.store.repositoryFacts()
2970
3240
  const idleMs = config.orchestrator.sandbox.idleMinutes * 60_000
2971
- for (let environment of facts.sandboxes) {
2972
- if (environment.state !== 'live') continue
2973
- // Budget gate: once spent, stop settling further environments; the
2974
- // next tick retries what remains.
2975
- if (this.outOfBudget(opts)) break
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) {
2976
3247
  const lastEvidence = Date.parse(environment.lastEvidenceTs)
2977
3248
  if (Number.isFinite(lastEvidence) && this.deps.clock().getTime() - lastEvidence < idleMs) {
3249
+ loop.skip()
2978
3250
  continue
2979
3251
  }
3252
+ // Budget gate: once spent, stop settling further environments; the
3253
+ // next tick retries what remains.
3254
+ if (!loop.start(opts, environment)) break
2980
3255
  try {
2981
3256
  // Other processes may have recorded activity while earlier tick work
2982
3257
  // awaited an outside read. Revalidate only an impending disposition.
@@ -3064,6 +3339,7 @@ export class Dispatcher {
3064
3339
  )
3065
3340
  }
3066
3341
  }
3342
+ loop.finish()
3067
3343
  }
3068
3344
 
3069
3345
  // ── Background provisioning (durable supervision) ──────────────────────────
@@ -3450,16 +3726,15 @@ export class Dispatcher {
3450
3726
  // builds are another dispatcher's duty; settled terminal builds cost no
3451
3727
  // event reads).
3452
3728
  // Unfiltered, so optimization stop enforcement sees terminal attempt builds.
3453
- const builds = await this.repoBuildDigests()
3454
- const entries = builds.filter(
3729
+ const allBuilds = await this.tickDigests()
3730
+ const entries = allBuilds.filter(
3455
3731
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
3456
3732
  )
3457
3733
  this.janitorEntries = entries
3458
3734
  this.nodeChildren = undefined
3459
- // Receipt reporting requires no forge call, capacity or workspace. Recover
3460
- // every episode before the transport-budget and janitor-backoff gates.
3461
- for (const { record, digest } of entries) {
3462
- if (digest.kind !== 'node' || !digest.nodeOpened || digest.terminal) continue
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
3463
3738
  try {
3464
3739
  await reportIntegrationFailures(this.store, record.slug)
3465
3740
  } catch (error) {
@@ -3469,13 +3744,24 @@ export class Dispatcher {
3469
3744
  )
3470
3745
  }
3471
3746
  }
3472
- 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
3473
3756
  // Budget gate: the janitor's per-build path issues forge/store transport
3474
- // calls (PR probes, closePr, deleteBranch); once the budget is spent,
3475
- // stop starting new ones. The remaining builds stay janitor due — the
3476
- // next invocation re-runs them (§3.3 idempotency).
3477
- if (this.outOfBudget(opts)) break
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
3478
3763
  await withForgeRequestContext({ build: record.slug }, async () => {
3764
+ if (bounded) await recoverReceipts(record, digest)
3479
3765
  let previous: BuildState['janitor']
3480
3766
  // The stage in progress, named if this attempt's failure escalates.
3481
3767
  let operation: JanitorOperation = 'build state read'
@@ -3502,6 +3788,9 @@ export class Dispatcher {
3502
3788
  // Every tick, independent of janitor backoff and idle node polling: an
3503
3789
  // hours budget must fire on a node with no other activity.
3504
3790
  if (state.optimization !== undefined && !mixedVersionDeferred(state)) {
3791
+ const builds = this.boundedListings
3792
+ ? await this.compatibleAttempts(record.slug, allBuilds)
3793
+ : allBuilds
3505
3794
  const deps = {
3506
3795
  store: this.store,
3507
3796
  clock: this.deps.clock,
@@ -3601,7 +3890,7 @@ export class Dispatcher {
3601
3890
  incompleteObservation ||
3602
3891
  executionLeaseLive ||
3603
3892
  report.janitorDiagnostics.length !== diagnosticsBefore ||
3604
- this.outOfBudget(opts)
3893
+ this.outOfBudget(this.tickOpts)
3605
3894
  )
3606
3895
  return
3607
3896
  const current = (await this.store.buildFacts(record.slug)).state
@@ -3814,7 +4103,9 @@ export class Dispatcher {
3814
4103
  refreshOnly: true,
3815
4104
  })
3816
4105
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3817
- 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)
3818
4109
  loaded = undefined
3819
4110
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
3820
4111
  }
@@ -4015,6 +4306,63 @@ export class Dispatcher {
4015
4306
  }
4016
4307
  })
4017
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
4018
4366
  }
4019
4367
 
4020
4368
  /** Priming saves requests but must not block parent recovery or ordinary observations. */
@@ -4547,6 +4895,7 @@ export class Dispatcher {
4547
4895
  ): Promise<void> {
4548
4896
  const deferred = [...this.deferredAdmissions]
4549
4897
  this.deferredAdmissions.clear()
4898
+ this.pass.total('parked', 0)
4550
4899
  if (deferred.length === 0) {
4551
4900
  this.lastForcedDeferralKey = undefined
4552
4901
  return
@@ -4556,8 +4905,9 @@ export class Dispatcher {
4556
4905
  // the parked builds stay durable work for the next invocation.
4557
4906
  if (this.budgetSpent(opts)) return
4558
4907
  this.admissionBoundary = false
4908
+ this.pass.total('parked', deferred.length)
4559
4909
  for (const [slug, kind] of deferred) {
4560
- if (this.outOfBudget(opts)) return
4910
+ if (!this.passItem(opts, 'parked')) return
4561
4911
  if (launched.has(slug)) continue
4562
4912
  try {
4563
4913
  const record = await this.store.getBuild(slug)
@@ -4607,7 +4957,9 @@ export class Dispatcher {
4607
4957
  launched: Set<string>,
4608
4958
  opts: TickOpts,
4609
4959
  ): Promise<void> {
4610
- 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()
4611
4963
  if (!entries.some(({ digest }) => digest.kind === 'node' && digest.terminal === undefined))
4612
4964
  return
4613
4965
  // An optimization node's proposer: exhausted stops, filings and new
@@ -4616,12 +4968,14 @@ export class Dispatcher {
4616
4968
  // accepted. One clock reading serves every stage of the pass.
4617
4969
  const now = this.deps.clock()
4618
4970
  await this.advanceOptimizationNodes(report, opts, entries, now)
4619
- 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
4620
4974
  const builds = (await this.capacityBuilds()).sort((a, b) =>
4621
4975
  a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0,
4622
4976
  )
4623
4977
  await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4624
- if (this.outOfBudget(opts)) return
4978
+ if (this.outOfBudget(this.tickOpts)) return
4625
4979
  await this.adoptLegacyNodeRunners(builds, now, report)
4626
4980
  // A node asking for a verification slot, and one admitted for
4627
4981
  // verification whose runner never started or was lost: nothing else
@@ -4629,9 +4983,11 @@ export class Dispatcher {
4629
4983
  const waiting = builds.filter((build) => nodeRunnerWork(build, now)?.request === 'verification')
4630
4984
  const admitted = new Set<string>()
4631
4985
  this.passNodeAdmissions = admitted
4986
+ this.pass.total('nodes', waiting.length)
4632
4987
  try {
4633
4988
  for (const build of waiting) {
4634
- if (this.outOfBudget(opts)) return
4989
+ if (!this.passItem(opts, 'nodes')) return
4990
+ if (this.boundedListings && (await this.checkCompatibility(build, build.state))) continue
4635
4991
  await this.admitNode(build, now, report, launched)
4636
4992
  }
4637
4993
  } finally {
@@ -4720,7 +5076,8 @@ export class Dispatcher {
4720
5076
  ): Promise<void> {
4721
5077
  for (const build of builds) {
4722
5078
  if (launched.has(build.record.slug) || !strandedNodeWorkspace(build, now)) continue
4723
- if (this.outOfBudget(opts)) return
5079
+ this.pass.total('nodes', 1)
5080
+ if (!this.passItem(opts, 'nodes')) return
4724
5081
  const { record } = build
4725
5082
  await withForgeRequestContext({ build: record.slug }, async () => {
4726
5083
  try {
@@ -4770,8 +5127,9 @@ export class Dispatcher {
4770
5127
  startRequests: this.startClaims(),
4771
5128
  })
4772
5129
  let occupied = projection.occupied
5130
+ this.pass.total('nodes', proposers.length)
4773
5131
  for (const build of proposers) {
4774
- if (this.outOfBudget(opts)) return
5132
+ if (!this.passItem(opts, 'nodes')) return
4775
5133
  const { record, state } = build
4776
5134
  if (
4777
5135
  launched.has(record.slug) ||
@@ -4844,7 +5202,8 @@ export class Dispatcher {
4844
5202
  failure?: string
4845
5203
  }> {
4846
5204
  const holds = new Map<string, { node: string; request: string }>()
4847
- 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()) {
4848
5207
  if (digest.terminal !== undefined) continue
4849
5208
  let signal: ReturnType<typeof digestOptimization>
4850
5209
  try {
@@ -4936,9 +5295,14 @@ export class Dispatcher {
4936
5295
  entries: { record: BuildRecord; digest: BuildDigest }[],
4937
5296
  now: Date,
4938
5297
  ): Promise<void> {
4939
- 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
+ }[] = []
4940
5303
  try {
4941
- for (const { record, digest } of entries) {
5304
+ for (const entry of entries) {
5305
+ const { record, digest } = entry
4942
5306
  if (digest.terminal !== undefined || !digest.nodeOpened) continue
4943
5307
  const signal = digestOptimization(digest)
4944
5308
  if (!signal) continue
@@ -4949,17 +5313,19 @@ export class Dispatcher {
4949
5313
  (digest.executionOpen === true || this.hasLiveExecutionLease(record))
4950
5314
  )
4951
5315
  continue
4952
- if (kind !== undefined) due.push({ record, kind })
5316
+ if (kind !== undefined) due.push({ entry, record, kind })
4953
5317
  }
4954
5318
  } catch (error) {
4955
5319
  if (!(error instanceof BuildDigestCapabilityError)) throw error
4956
5320
  report.janitorDiagnostics.push(`optimization proposing skipped — ${error.message}`)
4957
5321
  return
4958
5322
  }
4959
- for (const { record, kind } of due) {
4960
- 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
4961
5326
  await withForgeRequestContext({ build: record.slug }, async () => {
4962
5327
  try {
5328
+ if (this.boundedListings && (await this.checkCompatibility(entry))) return
4963
5329
  if (kind === 'exhausted') await this.recordExhausted(record.slug)
4964
5330
  else if (kind === 'filing') await this.fileProposedAttempts(record, now)
4965
5331
  else await this.requestProposal(record, now)
@@ -5378,6 +5744,11 @@ export class Dispatcher {
5378
5744
  for (const other of this.childrenOf(nodeSlug)) {
5379
5745
  if (other.slug === record.slug || !wanted.has(key(other.ticket!))) continue
5380
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
5381
5752
  if (otherState.target?.build !== nodeSlug) continue
5382
5753
  candidates.push({ slug: other.slug, ticket: other.ticket!, state: otherState })
5383
5754
  }
@@ -6147,7 +6518,7 @@ export class Dispatcher {
6147
6518
  kind?: 'work' | 'node',
6148
6519
  ): Promise<{ sha: string; buildTrailerPresent?: boolean }> {
6149
6520
  if (kind === 'node')
6150
- await this.recoverNodeContributions(await this.repoBuildDigests(), {
6521
+ await this.recoverNodeContributions(await this.tickDigests(), {
6151
6522
  slug: record.slug,
6152
6523
  sha,
6153
6524
  })
@@ -8148,16 +8519,24 @@ export class Dispatcher {
8148
8519
  paused: boolean,
8149
8520
  opts: TickOpts = {},
8150
8521
  ): Promise<void> {
8151
- 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
8152
8529
  if (
8153
8530
  record.ticket === undefined ||
8154
8531
  launched.has(record.slug) ||
8155
8532
  this.continuations.has(record.slug)
8156
8533
  ) {
8534
+ loop.skip()
8157
8535
  continue
8158
8536
  }
8159
8537
  // Budget gate: recovery issues store transport calls per build.
8160
- if (this.outOfBudget(opts)) break
8538
+ if (!loop.start(opts, entry)) break
8539
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8161
8540
  const { state } = await this.store.buildFacts(record.slug)
8162
8541
  if (
8163
8542
  state.status !== 'queued' ||
@@ -8178,6 +8557,7 @@ export class Dispatcher {
8178
8557
  // must not bypass the unfinished dispatch boundary later in the tick.
8179
8558
  if (outcome === 'failed') launched.add(record.slug)
8180
8559
  }
8560
+ loop.finish()
8181
8561
  }
8182
8562
 
8183
8563
  // ── c. Dispatch-command startup resume (SPEC §2.2, §15.6-C) ────────────────
@@ -8200,10 +8580,20 @@ export class Dispatcher {
8200
8580
  opts: TickOpts = {},
8201
8581
  ): Promise<void> {
8202
8582
  const store = this.store
8203
- for (const record of await this.nonterminalBuilds()) {
8204
- 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
+ }
8205
8594
  // Budget gate: resume launches runners (transport-backed work).
8206
- if (this.outOfBudget(opts)) break
8595
+ if (!loop.start(opts, entry)) break
8596
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8207
8597
 
8208
8598
  const facts = await store.buildFacts(record.slug)
8209
8599
  const state = facts.state
@@ -8242,6 +8632,7 @@ export class Dispatcher {
8242
8632
  const result = await this.launch(record.slug, launched, report)
8243
8633
  if (result === 'scheduled') report.resumed += 1
8244
8634
  }
8635
+ loop.finish()
8245
8636
  }
8246
8637
 
8247
8638
  // ── c'. Ticket waits (SPEC §11 "Ticket waits") ─────────────────────────────
@@ -8405,15 +8796,21 @@ export class Dispatcher {
8405
8796
  ): Promise<void> {
8406
8797
  const tickets = this.deps.tickets
8407
8798
  const migrations = this.store.repositoryFacts().ticketMigrations
8408
- const waiting: { record: BuildRecord; wait: BuildDigestTicketWait; ids: string[] }[] = []
8409
- 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
8410
8807
  const wait = digest.ticketWait
8411
8808
  if (digest.terminal !== undefined || digest.kind === 'node' || wait === undefined) continue
8412
8809
  try {
8413
8810
  const ids = wait.tickets.map(
8414
8811
  (ref) => resolveTicketRef(migrations, ref, tickets.name, record.slug).id,
8415
8812
  )
8416
- waiting.push({ record, wait, ids })
8813
+ waiting.push({ entry, record, wait, ids })
8417
8814
  } catch (error) {
8418
8815
  const message = error instanceof Error ? error.message : String(error)
8419
8816
  report.janitorFailed += 1
@@ -8422,6 +8819,7 @@ export class Dispatcher {
8422
8819
  )
8423
8820
  }
8424
8821
  }
8822
+ this.pass.total('waits', waiting.length)
8425
8823
  if (waiting.length === 0 || this.outOfBudget(opts)) return
8426
8824
  const nodes = new Map<string, DependencyNode>()
8427
8825
  try {
@@ -8436,11 +8834,15 @@ export class Dispatcher {
8436
8834
  report.janitorDiagnostics.push(`ticket waits not checked — ${message}`)
8437
8835
  return
8438
8836
  }
8439
- for (const { record, wait, ids } of waiting) {
8837
+ for (const { entry, record, wait, ids } of waiting) {
8440
8838
  const release = ticketWaitRelease(ids, nodes)
8441
- if (release === undefined) continue
8442
- 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
8443
8844
  try {
8845
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8444
8846
  const { state } = await this.store.buildFacts(record.slug)
8445
8847
  const open = openTicketWait(state)
8446
8848
  if (open?.id !== wait.id) continue
@@ -8509,14 +8911,20 @@ export class Dispatcher {
8509
8911
  opts: TickOpts = {},
8510
8912
  ): Promise<void> {
8511
8913
  const now = this.deps.clock().getTime()
8512
- const entries = await this.repoBuildDigests()
8914
+ const entries = await this.tickDigests()
8513
8915
  await this.releaseTicketWaits(entries, report, opts)
8514
8916
  // Terminal builds are filtered on the digest before the lease and TTL
8515
8917
  // checks, so a zero TTL cannot fall through to a log read.
8516
- for (const { record, digest } of entries) {
8517
- if (digest.terminal !== undefined) continue
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
8518
8925
  // Budget gate: the sweep re-attaches runners per expired build.
8519
- if (this.outOfBudget(opts)) break
8926
+ if (!loop.start(opts, entry)) break
8927
+ if (this.boundedListings && (await this.checkCompatibility(entry))) continue
8520
8928
  if (digest.waitPending && digest.kind !== 'node')
8521
8929
  await this.serviceWaitRequests(record, report)
8522
8930
  if (launched.has(record.slug)) continue
@@ -8524,6 +8932,7 @@ export class Dispatcher {
8524
8932
  if (this.tickPrioritized.has(record.slug)) continue
8525
8933
  await this.sweepContained(record, report, launched, paused, now)
8526
8934
  }
8935
+ loop.finish()
8527
8936
  }
8528
8937
 
8529
8938
  /** One build's lease-sweep pass under the sweep's per-build containment:
@@ -8579,14 +8988,15 @@ export class Dispatcher {
8579
8988
  paused: boolean,
8580
8989
  opts: TickOpts,
8581
8990
  ): Promise<void> {
8582
- if (this.carriedOutstanding.size === 0) return
8991
+ if (this.carriedOutstanding.size === 0) return this.pass.total('deferred', 0)
8583
8992
  // Never the default form: it would run the mixed-version check for every
8584
8993
  // compatibility-bearing build. `sweepBuild` checks each carried build.
8585
8994
  const entries = new Map(
8586
8995
  (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
8587
8996
  )
8997
+ this.pass.total('deferred', this.carriedOutstanding.size)
8588
8998
  for (const slug of [...this.carriedOutstanding.keys()]) {
8589
- if (this.outOfBudget(opts)) break
8999
+ if (!this.passItem(opts, 'deferred')) break
8590
9000
  const entry = this.carriedOutstanding.get(slug)!
8591
9001
  const found = entries.get(slug)
8592
9002
  if (found === undefined || found.digest.terminal !== undefined) {
@@ -8606,7 +9016,9 @@ export class Dispatcher {
8606
9016
  paused,
8607
9017
  this.deps.clock().getTime(),
8608
9018
  )
8609
- const interrupted = this.budgetSpent(opts)
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)
8610
9022
  if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
8611
9023
  this.retireCarried(slug)
8612
9024
  }
@@ -8662,25 +9074,61 @@ export class Dispatcher {
8662
9074
  )
8663
9075
  )
8664
9076
  return
8665
- if (this.deps.holdsRepoAuthority?.() === false) return
8666
- // Past the work deadline, abandoned work writes nothing, except this
8667
- // hint through the bounded, authorized teardown scope.
8668
- const late = this.tickOpts.workSignal?.aborted === true
8669
- const teardown = this.tickOpts.teardownWrite
8670
- if (late && teardown === undefined) return
8671
- const append = () =>
9077
+ const outcome = await this.writeHint(() =>
8672
9078
  this.store.appendRepo(this.deps.repo, {
8673
9079
  actor: DISPATCHER,
8674
9080
  type: 'dispatcher.work-deferred',
8675
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 },
8676
9129
  })
8677
- try {
8678
- await (late ? teardown!(append) : append())
8679
- this.recordedDeferrals = next
8680
- } catch (error) {
8681
- rethrowAuthorityLapse(error)
8682
- this.deferralWriteFailure = errorText(error)
8683
- }
9130
+ })
9131
+ if (typeof outcome === 'string') this.passCursorWriteFailure = outcome
8684
9132
  })
8685
9133
  this.deferralWrites = write.catch(() => {})
8686
9134
  return write
@@ -8704,6 +9152,11 @@ export class Dispatcher {
8704
9152
  `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
8705
9153
  )
8706
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
8707
9160
  }
8708
9161
 
8709
9162
  /**
@@ -9052,8 +9505,9 @@ export class Dispatcher {
9052
9505
  )
9053
9506
  .slice(0, 8)
9054
9507
  const failures: unknown[] = []
9508
+ this.pass.total('preparations', pending.length)
9055
9509
  for (const attempt of pending) {
9056
- if (this.outOfBudget(opts)) break
9510
+ if (!this.passItem(opts, 'preparations')) break
9057
9511
  try {
9058
9512
  await this.recoverTicketPreparation(attempt)
9059
9513
  } catch (error) {
@@ -9253,6 +9707,10 @@ export class Dispatcher {
9253
9707
  * each ticket's outcome. The standing report fields are not published. */
9254
9708
  targeted?: TargetedDispatch,
9255
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)
9256
9714
  if (!this.claimGateOpen()) return
9257
9715
  const store = this.store
9258
9716
  const { tickets, config } = this.deps
@@ -9518,17 +9976,28 @@ export class Dispatcher {
9518
9976
  // failure must leave the entire ready set unclaimed. Publish dependency
9519
9977
  // diagnostics only after the complete preflight succeeds.
9520
9978
  let scanSuccessful = true
9521
- const treeEntries = await this.repoBuildDigests()
9979
+ const listed = await this.tickDigests()
9980
+ // Identity: a deferred node still means nodes exist.
9522
9981
  const hasNodes =
9523
- treeEntries.some(({ digest }) => digest.kind === 'node') ||
9982
+ listed.some(({ digest }) => digest.kind === 'node') ||
9524
9983
  ready.some((ticket) => ticket.kind === 'node')
9525
9984
  let presence: PresenceInputs | undefined
9526
9985
  const migrations = this.store.repositoryFacts().ticketMigrations
9527
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
9528
9995
  const builtTickets = hasNodes
9529
9996
  ? new Set(
9530
- treeEntries.flatMap(({ record }) =>
9531
- 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
+ : [],
9532
10001
  ),
9533
10002
  )
9534
10003
  : undefined
@@ -9594,25 +10063,33 @@ export class Dispatcher {
9594
10063
  if (hasNodes) {
9595
10064
  if (!presence && needsPresence(ticket)) {
9596
10065
  await this.recoverNodeContributions(treeEntries)
9597
- const entries = await this.repoBuildDigests()
9598
- const destinations = ready
9599
- .filter(
9600
- (candidate) =>
9601
- needsPresence(candidate) &&
9602
- !withheld.has(candidate.ref.id) &&
9603
- candidate.target !== undefined,
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
9604
10076
  )
9605
- .flatMap((candidate) => {
9606
- const node = blockerBuild(
9607
- entries,
9608
- candidate.ref.source,
9609
- candidate.target!,
9610
- normalizeTicket,
9611
- )
9612
- return node && typeof node !== 'string' && node.digest.kind === 'node'
9613
- ? [node.record.slug]
9614
- : []
9615
- })
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
+ }
9616
10093
  presence = await presenceInputs(this.store, entries, destinations)
9617
10094
  }
9618
10095
  const inputs = presence ?? {
@@ -9685,8 +10162,9 @@ export class Dispatcher {
9685
10162
  }
9686
10163
  }
9687
10164
  let claimLoopCompleted = true
10165
+ if (part) this.pass.total(part, ready.length)
9688
10166
  for (const ticket of ready) {
9689
- if (this.outOfBudget(opts)) {
10167
+ if (part ? !this.passItem(opts, part) : this.outOfBudget(opts)) {
9690
10168
  claimLoopCompleted = false
9691
10169
  break
9692
10170
  }
@@ -10081,7 +10559,7 @@ export class Dispatcher {
10081
10559
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
10082
10560
  )
10083
10561
  if (candidates.length === 0) return tiers
10084
- const all = await this.repoBuildDigests()
10562
+ const all = await this.tickDigests()
10085
10563
  const nodes = new Map<string, BuildState>()
10086
10564
  const key = this.attemptIdentity()
10087
10565
  for (const ticket of candidates) {
@@ -10098,6 +10576,8 @@ export class Dispatcher {
10098
10576
  throw error
10099
10577
  }
10100
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
10101
10581
  let state = nodes.get(record.slug)
10102
10582
  if (state === undefined) {
10103
10583
  state = (await this.store.buildFacts(record.slug)).state
@@ -10133,7 +10613,7 @@ export class Dispatcher {
10133
10613
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
10134
10614
  if (ticket.target === undefined) return undefined
10135
10615
  const migrations = this.store.repositoryFacts().ticketMigrations
10136
- const all = await this.repoBuildDigests()
10616
+ const all = await this.tickDigests()
10137
10617
  const entries = this.targetBuilds(ticket.target, ticket.ref.source, all)
10138
10618
  const latest = entries[0]
10139
10619
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
@@ -10143,6 +10623,10 @@ export class Dispatcher {
10143
10623
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
10144
10624
  if (digest.terminal || digest.prClosed || digest.merged)
10145
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'}`
10146
10630
  const state = (await this.store.buildFacts(record.slug)).state
10147
10631
  if (
10148
10632
  state.status === 'done' ||
@@ -10520,9 +11004,10 @@ export class Dispatcher {
10520
11004
  if (result.exitCode !== 0) throw new Error(result.stderr)
10521
11005
  added = true
10522
11006
  const beforeReplay = async (operation: string) => {
10523
- for (const child of await this.repoBuildDigests()) {
11007
+ for (const child of await this.tickDigests()) {
10524
11008
  if (child.digest.terminal || child.digest.kind === 'node') continue
10525
11009
  const childState = (await this.store.buildFacts(child.record.slug)).state
11010
+ if (this.boundedListings && (await this.checkCompatibility(child, childState))) continue
10526
11011
  if (
10527
11012
  childState.target?.build !== record.slug ||
10528
11013
  !childState.pr ||
@@ -11058,11 +11543,15 @@ export class Dispatcher {
11058
11543
  digest.kind === 'node' && (digest.merged || record.slug === merging?.slug),
11059
11544
  )
11060
11545
  if (candidates.length === 0) return
11061
- const pending = candidates.filter(
11546
+ const unrecorded = candidates.filter(
11062
11547
  ({ record, digest }) =>
11063
11548
  digest.nodeContribution?.landing !==
11064
11549
  (record.slug === merging?.slug ? merging.sha : digest.mergedSha),
11065
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)
11066
11555
  if (pending.length === 0) return
11067
11556
  const inputs = await presenceInputs(
11068
11557
  this.store,
@@ -11117,7 +11606,11 @@ export class Dispatcher {
11117
11606
  for (const child of candidates) {
11118
11607
  if (child.record.slug === slug) continue
11119
11608
  const childState = inputs.states.get(child.record.slug)
11120
- 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
+ )
11121
11614
  await recover(child.record.slug)
11122
11615
  }
11123
11616
  const currentIdentities = await ownedContribution(