@defrex/autobuild 1.16.0 → 1.18.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +132 -9
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +42 -3
  5. package/docs/configuration.md +44 -7
  6. package/docs/dispatcher-hosting.md +5 -3
  7. package/docs/operator-api.md +29 -6
  8. package/docs/plugin-authoring.md +30 -1
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +37 -2
  11. package/docs/restacking.md +46 -1
  12. package/docs/setup.md +24 -9
  13. package/docs/ticket-sources.md +28 -1
  14. package/docs/troubleshooting.md +54 -2
  15. package/docs/workspaces.md +3 -1
  16. package/package.json +4 -4
  17. package/packages/core/src/cli/accounts.ts +3 -0
  18. package/packages/core/src/cli/binary-direct.ts +14 -1
  19. package/packages/core/src/cli/binary.ts +10 -7
  20. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  21. package/packages/core/src/cli/dispatch.ts +503 -334
  22. package/packages/core/src/cli/secrets.ts +2 -0
  23. package/packages/core/src/config/schema.ts +17 -3
  24. package/packages/core/src/events/payloads.ts +8 -5
  25. package/packages/core/src/events/repository.ts +37 -1
  26. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  27. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  28. package/packages/core/src/kernel/engine.ts +118 -0
  29. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  30. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  31. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  32. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  33. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  34. package/packages/core/src/ontology.ts +1 -0
  35. package/packages/core/src/operator/index.ts +10 -0
  36. package/packages/core/src/operator/merged-builds.ts +51 -0
  37. package/packages/core/src/operator/registry.ts +254 -110
  38. package/packages/core/src/operator/repo-argument.ts +43 -0
  39. package/packages/core/src/operator/tickets.ts +139 -25
  40. package/packages/core/src/plugin-sdk/index.ts +4 -0
  41. package/packages/core/src/plugins/manifest.ts +1 -1
  42. package/packages/core/src/ports/tickets/completion.ts +71 -0
  43. package/packages/core/src/ports/tickets/contract.ts +73 -0
  44. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  45. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  46. package/packages/core/src/ports/tickets/github.ts +18 -6
  47. package/packages/core/src/ports/tickets/grants.ts +2 -0
  48. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  49. package/packages/core/src/ports/tickets/linear.ts +18 -2
  50. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  51. package/packages/core/src/ports/tickets/remote.ts +43 -3
  52. package/packages/core/src/ports/tickets/tree.ts +11 -1
  53. package/packages/core/src/ports/types.ts +47 -4
  54. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  55. package/packages/core/src/ports/workspace/vercel-sandbox.ts +649 -160
  56. package/packages/core/src/processes/build-child.ts +15 -1
  57. package/packages/core/src/processes/build-runner.ts +349 -20
  58. package/packages/core/src/processes/dispatcher.ts +880 -283
  59. package/packages/core/src/processes/harvest-child.ts +21 -1
  60. package/packages/core/src/processes/harvest-runner.ts +82 -35
  61. package/packages/core/src/processes/pass-stages.ts +32 -6
  62. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  63. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  64. package/packages/core/src/processes/repo-view.ts +25 -4
  65. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  66. package/packages/core/src/store/adapter.ts +34 -5
  67. package/packages/core/src/store/build-feed.ts +148 -22
  68. package/packages/core/src/store/build-scope.ts +12 -3
  69. package/packages/core/src/store/caller-attribution.ts +170 -0
  70. package/packages/core/src/store/contract.ts +1038 -165
  71. package/packages/core/src/store/local/schema.ts +12 -1
  72. package/packages/core/src/store/local/store.ts +260 -25
  73. package/packages/core/src/store/memory.ts +156 -9
  74. package/packages/core/src/store/phase-session.ts +23 -3
  75. package/packages/core/src/store/reducer-value-shapes.json +8196 -8118
  76. package/packages/core/src/store/remote/client.ts +90 -11
  77. package/packages/core/src/store/remote/credentials.ts +2 -0
  78. package/packages/core/src/store/remote/index.ts +31 -5
  79. package/packages/core/src/store/remote/protocol.ts +45 -8
  80. package/packages/core/src/store/remote/released-clients.json +22 -0
  81. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  82. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  83. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  84. package/packages/core/src/store/session-handle.ts +12 -3
  85. package/packages/core/src/store/types.ts +48 -3
  86. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  87. package/packages/core/src/testing/index.ts +2 -0
  88. package/packages/core/src/testing/reduced-read-budget.ts +420 -6
  89. package/skills/guide/SKILL.md +67 -13
  90. package/skills/guide/references/operator-api.md +29 -6
  91. package/skills/guide/references/plugin-authoring.md +30 -1
  92. package/skills/guide/references/remote-store-protocol.md +13 -3
  93. package/skills/guide/references/remote-ticket-protocol.md +37 -2
  94. package/skills/guide/references/restacking.md +46 -1
  95. package/skills/guide/references/setup.md +24 -9
  96. package/skills/operate/SKILL.md +42 -4
  97. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import { withCallerStage } from '../store/caller-attribution'
2
3
  import {
3
4
  recordRetention,
4
5
  restoreRetainedHead,
@@ -407,6 +408,7 @@ import {
407
408
  } from '../objective'
408
409
  export { specConformance, type SpecConformance } from '../spec-standard'
409
410
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
411
+ import { describeProvisionProgress, provisioningAbandonmentMessage } from './provisioning-progress'
410
412
  import { settleOpenExecution } from './execution-settlement'
411
413
  import { isWorkDigest, RepoViewStore } from './repo-view'
412
414
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
@@ -697,8 +699,15 @@ export interface TickReport {
697
699
  * is recorded in `dispatcher.work-deferred` and the next tick runs it
698
700
  * first. */
699
701
  recoveryDeferred: number
702
+ /** Ticket preparations this bounded tick carried to the next invocation
703
+ * (#1431): an admission the work deadline left no time to prepare, or a
704
+ * preparation the deadline cut. Recorded in `dispatcher.work-deferred`;
705
+ * the next tick resumes each first, and none is handed back. Absent when
706
+ * none was carried. */
707
+ preparationsCarried?: number
700
708
  /** One line per build whose deadline-gated work (a provision, a cut launch
701
- * or a recovery step) this tick deferred for budget, naming the step. */
709
+ * or a recovery step) this tick deferred for budget, naming the step, and
710
+ * one per carried ticket preparation, naming the ticket. */
702
711
  deferredDiagnostics: string[]
703
712
  /** Dispatch (§12): builds created and launched. With durable supervision
704
713
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
@@ -843,6 +852,11 @@ const IDENTITY_RELEASES_PER_APPEND = 256
843
852
  // ── Dispatcher ───────────────────────────────────────────────────────────────
844
853
 
845
854
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
855
+ /** What one ticket preparation (claim, asset pin, spec import, the slug
856
+ * naming ceiling and its store writes) needs, with headroom: a bounded pass
857
+ * with less time left before its work deadline carries the admission
858
+ * instead of starting it (#1431). */
859
+ const DEFAULT_PREPARATION_ESTIMATE_MS = 30_000
846
860
  /** Bound on -2/-3/… candidates one claim may probe for a free slug. */
847
861
  const MAX_SLUG_CANDIDATES = 100
848
862
  /** Body of the comment dispatch posts on every claimed ticket. The
@@ -878,6 +892,11 @@ interface ProvisionContinuation {
878
892
  readonly instance: string
879
893
  readonly controller: AbortController
880
894
  promise: Promise<void>
895
+ /** The provider's latest reported stage and when it began (clock ms);
896
+ * teardown names it in the abandonment fact. */
897
+ progress?: { label: string; since: number }
898
+ /** When teardown signalled this continuation (clock ms). */
899
+ abortedAt?: number
881
900
  }
882
901
 
883
902
  export interface DispatcherOpts {
@@ -903,6 +922,10 @@ export interface DispatcherOpts {
903
922
  /** Internal deadline for the optional pre-build naming seam. Production is
904
923
  * fixed; injection exists only so timeout behavior is deterministic in tests. */
905
924
  slugNamingTimeoutMs?: number
925
+ /** The time a bounded pass needs left before its work deadline to start a
926
+ * ticket preparation; with less, intake journals the admission and the
927
+ * next invocation prepares it first (#1431). Default 30 s. */
928
+ preparationEstimateMs?: number
906
929
  /** Must match the HarvestRunner's durable outer recovery budget. */
907
930
  maxHarvestRecoveryAttempts?: number
908
931
  /** Backstop for the crash window between a `workspace.provision-started`
@@ -983,6 +1006,42 @@ interface DeferredWorkEntry {
983
1006
  /** Most entries one `dispatcher.work-deferred` hint carries. */
984
1007
  const MAX_DEFERRED_WORK = 64
985
1008
 
1009
+ /** One carried ticket-preparation attempt in `dispatcher.work-deferred`. */
1010
+ interface CarriedPreparation {
1011
+ ticket: TicketRef
1012
+ attempt: string
1013
+ }
1014
+
1015
+ /** Most ticket-preparation attempts one hint carries. */
1016
+ const MAX_CARRIED_PREPARATIONS = 8
1017
+
1018
+ /** What one ticket preparation reached: a build `started`; the ticket `left`
1019
+ * the queue without a build (claim refused or bounced); it was `blocked` by
1020
+ * a blocker the claim found; the work deadline `carried` it to the next
1021
+ * invocation; or nothing durable was started and the loop must `stop`. */
1022
+ type PreparationOutcome = 'started' | 'left' | 'blocked' | 'carried' | 'stop'
1023
+
1024
+ /** One ticket preparation's inputs: the ticket sample it prepares from, its
1025
+ * attempt, the node target and claim level admission resolved, and how the
1026
+ * caller records outcomes. `resume` marks a carried attempt the deferred
1027
+ * stage or preparation recovery continues (#1431). */
1028
+ interface PreparationInput {
1029
+ ticket: Ticket
1030
+ attempt: TicketPreparation
1031
+ target:
1032
+ | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
1033
+ | undefined
1034
+ level: BuildPriority
1035
+ report: TickReport
1036
+ launched: Set<string>
1037
+ settle: (outcome: TargetedOutcome) => void
1038
+ /** The pass part a carry is recorded on. */
1039
+ part: PassStagePart
1040
+ resume?: true
1041
+ autoMergeUser?: string
1042
+ autoMergeSeedFact?: AutoMergeDefaultFact
1043
+ }
1044
+
986
1045
  /** Process-local launch coordination result. Durable lease acquisition remains
987
1046
  * the BuildRunner's responsibility; "scheduled" means only that this process
988
1047
  * accepted a runner launch rather than suppressing a known in-flight slug. */
@@ -1140,6 +1199,14 @@ function errorText(error: unknown): string {
1140
1199
  return error instanceof Error ? error.message : String(error)
1141
1200
  }
1142
1201
 
1202
+ /** The report and dispatch-log line naming one carried ticket preparation. */
1203
+ function preparationCarryLine(ticket: TicketRef, detail?: string): string {
1204
+ return (
1205
+ `ticket ${ticket.id}: preparation carried by the invocation budget; the next invocation runs it first` +
1206
+ (detail !== undefined ? ` — ${detail}` : '')
1207
+ )
1208
+ }
1209
+
1143
1210
  /** The report and dispatch-log line naming one deferral by build and step. */
1144
1211
  function deferralLine(slug: string, deferral: { step: DeferredWorkStep; detail?: string }): string {
1145
1212
  return (
@@ -1399,6 +1466,7 @@ export class Dispatcher {
1399
1466
  )
1400
1467
  }
1401
1468
  private readonly slugNamingTimeoutMs: number
1469
+ private readonly preparationEstimateMs: number
1402
1470
  private readonly maxHarvestRecoveryAttempts: number
1403
1471
  private readonly provisionStaleMs: number
1404
1472
  /** Process-local background provisioning, keyed by slug. A tick that sees a
@@ -1431,6 +1499,23 @@ export class Dispatcher {
1431
1499
  >()
1432
1500
  /** The durable hint as last read or written. */
1433
1501
  private recordedDeferrals: DeferredWorkEntry[] = []
1502
+ /** Per tick, keyed by attempt: ticket preparations this tick carried to
1503
+ * the next invocation (#1431), with the reason. */
1504
+ private readonly tickPreparationCarries = new Map<
1505
+ string,
1506
+ { ticket: TicketRef; detail?: string }
1507
+ >()
1508
+ /** Per tick, in carried order: the hint's carried preparation attempts not
1509
+ * yet retired. */
1510
+ private readonly carriedPreparationsOutstanding = new Map<
1511
+ string,
1512
+ { ticket: TicketRef; visited: boolean }
1513
+ >()
1514
+ /** Per tick: carried attempts the early stage resumed, which preparation
1515
+ * recovery then skips. */
1516
+ private readonly tickResumedAttempts = new Set<string>()
1517
+ /** The hint's preparation entries as last read or written. */
1518
+ private recordedPreparationCarries: CarriedPreparation[] = []
1434
1519
  /** The current tick's options, for writes made from deferral sites. */
1435
1520
  private tickOpts: TickOpts = {}
1436
1521
  /** Serializes hint writes so concurrent deferral notes never race. */
@@ -1548,6 +1633,7 @@ export class Dispatcher {
1548
1633
  })
1549
1634
  this.leaseTtlMs = deps.opts?.leaseTtlMs ?? 0
1550
1635
  this.slugNamingTimeoutMs = deps.opts?.slugNamingTimeoutMs ?? DEFAULT_SLUG_NAMING_TIMEOUT_MS
1636
+ this.preparationEstimateMs = deps.opts?.preparationEstimateMs ?? DEFAULT_PREPARATION_ESTIMATE_MS
1551
1637
  this.maxHarvestRecoveryAttempts =
1552
1638
  deps.opts?.maxHarvestRecoveryAttempts ?? DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS
1553
1639
  this.provisionStaleMs = deps.opts?.provisionStaleMs ?? DEFAULT_PROVISION_STALE_MS
@@ -1761,6 +1847,9 @@ export class Dispatcher {
1761
1847
  this.deferralsFinished = false
1762
1848
  this.tickPrioritized.clear()
1763
1849
  this.carriedOutstanding.clear()
1850
+ this.tickPreparationCarries.clear()
1851
+ this.carriedPreparationsOutstanding.clear()
1852
+ this.tickResumedAttempts.clear()
1764
1853
  this.deferralWriteFailure = undefined
1765
1854
  this.tickOpts = opts
1766
1855
  this.admissionBoundary = false
@@ -1772,13 +1861,19 @@ export class Dispatcher {
1772
1861
  if (opts.viewRefreshed !== true) await this.store.refresh()
1773
1862
  // The durable deferral hint from the previous invocation: zero extra
1774
1863
  // reads, it is part of the repository facts the refresh reduced.
1775
- this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1776
- ({ slug, step, instance }) => ({
1777
- slug,
1778
- step,
1779
- ...(instance !== undefined ? { instance } : {}),
1780
- }),
1781
- )
1864
+ const deferredWork = this.store.repositoryFacts().deferredWork
1865
+ this.recordedDeferrals = (deferredWork?.builds ?? []).map(({ slug, step, instance }) => ({
1866
+ slug,
1867
+ step,
1868
+ ...(instance !== undefined ? { instance } : {}),
1869
+ }))
1870
+ this.recordedPreparationCarries = (deferredWork?.tickets ?? []).map(({ ticket, attempt }) => ({
1871
+ ticket,
1872
+ attempt,
1873
+ }))
1874
+ for (const { ticket, attempt } of this.recordedPreparationCarries)
1875
+ if (!this.carriedPreparationsOutstanding.has(attempt))
1876
+ this.carriedPreparationsOutstanding.set(attempt, { ticket, visited: false })
1782
1877
  // The rotated loops' positions, from the same reduced facts: no read.
1783
1878
  this.passCursors =
1784
1879
  opts.deadlineAt === undefined
@@ -1852,7 +1947,7 @@ export class Dispatcher {
1852
1947
  if (opts.observationOnly) return report
1853
1948
  if (this.outOfBudget(opts)) return report
1854
1949
  await this.runStage('preparations', opts, (stageOpts) =>
1855
- this.recoverTicketPreparations(report, stageOpts),
1950
+ this.recoverTicketPreparations(report, launched, paused, stageOpts),
1856
1951
  )
1857
1952
  if (this.outOfBudget(opts)) return report
1858
1953
  await this.runStage('janitor', opts, (stageOpts) => this.janitor(report, launched, stageOpts))
@@ -1928,9 +2023,11 @@ export class Dispatcher {
1928
2023
  opts: TickOpts,
1929
2024
  run: (stageOpts: TickOpts) => Promise<void>,
1930
2025
  ): Promise<void> {
2026
+ // Hosted requests made inside the stage, and work it starts, name it.
1931
2027
  // Unbounded: the helpers' own promise, scheduled exactly as before.
1932
- if (opts.deadlineAt === undefined) return run(opts)
1933
- return this.runBoundedStage(stage, opts, opts.deadlineAt, run)
2028
+ const deadlineAt = opts.deadlineAt
2029
+ if (deadlineAt === undefined) return withCallerStage(stage, () => run(opts))
2030
+ return withCallerStage(stage, () => this.runBoundedStage(stage, opts, deadlineAt, run))
1934
2031
  }
1935
2032
 
1936
2033
  private async runBoundedStage(
@@ -2027,11 +2124,16 @@ export class Dispatcher {
2027
2124
  const report = structuredClone(this.inFlightReport)
2028
2125
  // The deferrals so far, counted as the finished tick would count them;
2029
2126
  // a finished tick already counted them on its report.
2030
- if (!this.deferralsFinished)
2127
+ if (!this.deferralsFinished) {
2031
2128
  for (const [slug, deferral] of this.tickDeferrals) {
2032
2129
  if (deferral.step !== 'provision') report.recoveryDeferred += 1
2033
2130
  report.deferredDiagnostics.push(deferralLine(slug, deferral))
2034
2131
  }
2132
+ if (this.tickPreparationCarries.size > 0)
2133
+ report.preparationsCarried = this.tickPreparationCarries.size
2134
+ for (const { ticket, detail } of this.tickPreparationCarries.values())
2135
+ report.deferredDiagnostics.push(preparationCarryLine(ticket, detail))
2136
+ }
2035
2137
  return { ...report, stages: this.pass.summary() }
2036
2138
  }
2037
2139
 
@@ -2470,7 +2572,7 @@ export class Dispatcher {
2470
2572
  // checked, needs the pass.
2471
2573
  const now = this.deps.clock()
2472
2574
  const measured = await this.capacityBuilds(launched, true)
2473
- const projection = dispatchCapacity(measured, config.capacity, now, {
2575
+ const projection = this.measureCapacity(measured, config.capacity, now, {
2474
2576
  claims: this.claims(),
2475
2577
  startRequests: this.startClaims(),
2476
2578
  })
@@ -3612,12 +3714,21 @@ export class Dispatcher {
3612
3714
  }
3613
3715
  : {}),
3614
3716
  ...(input.adoptAbandoned ? { adoptAbandoned: true } : {}),
3717
+ signal: entry.controller.signal,
3718
+ onProgress: (progress) => {
3719
+ if (entry.controller.signal.aborted) return
3720
+ entry.progress = {
3721
+ label: describeProvisionProgress(progress),
3722
+ since: this.deps.clock().getTime(),
3723
+ }
3724
+ },
3615
3725
  },
3616
3726
  entry.controller.signal,
3617
3727
  )
3618
- // The provisioned fact is true and welcome even when a teardown signal
3619
- // landed mid-call; the token check below still prevents a superseded
3620
- // supervisor from launching.
3728
+ // Providers receive the teardown signal and usually reject promptly, but
3729
+ // one that ignores it may still complete: the provisioned fact is then
3730
+ // true and welcome even though the signal landed mid-call. The token
3731
+ // check below still prevents a superseded supervisor from launching.
3621
3732
  await store.append(slug, {
3622
3733
  actor: DISPATCHER,
3623
3734
  type: 'workspace.provisioned',
@@ -3754,8 +3865,10 @@ export class Dispatcher {
3754
3865
  payload: {
3755
3866
  stage: 'workspace',
3756
3867
  attempt,
3757
- error:
3758
- 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3868
+ error: provisioningAbandonmentMessage(
3869
+ entry.progress,
3870
+ entry.abortedAt ?? this.deps.clock().getTime(),
3871
+ ),
3759
3872
  abandoned: 'teardown',
3760
3873
  },
3761
3874
  })
@@ -3779,6 +3892,7 @@ export class Dispatcher {
3779
3892
  abortProvisioning(): void {
3780
3893
  for (const entry of this.continuations.values()) {
3781
3894
  this.abortedContinuations.set(entry.instance, entry)
3895
+ entry.abortedAt ??= this.deps.clock().getTime()
3782
3896
  entry.controller.abort()
3783
3897
  }
3784
3898
  }
@@ -4923,8 +5037,8 @@ export class Dispatcher {
4923
5037
  let outcome = this.slotAdmission(
4924
5038
  slug,
4925
5039
  priority,
4926
- dispatchCapacity(others, capacity, now).occupied,
4927
- dispatchCapacity(builds, capacity, now, {
5040
+ this.measureCapacity(others, capacity, now).occupied,
5041
+ this.measureCapacity(builds, capacity, now, {
4928
5042
  claims: this.claims(),
4929
5043
  startRequests: this.startClaims(),
4930
5044
  }),
@@ -5196,7 +5310,7 @@ export class Dispatcher {
5196
5310
  (only === undefined || build.record.slug === only),
5197
5311
  )
5198
5312
  if (proposers.length === 0) return
5199
- const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
5313
+ const projection = this.measureCapacity(builds, this.deps.config.capacity, now, {
5200
5314
  claims: this.claims(),
5201
5315
  startRequests: this.startClaims(),
5202
5316
  })
@@ -5626,12 +5740,12 @@ export class Dispatcher {
5626
5740
  const outcome = this.slotAdmission(
5627
5741
  slug,
5628
5742
  buildPriority(node.state),
5629
- dispatchCapacity(
5743
+ this.measureCapacity(
5630
5744
  builds.filter((build) => build.record.slug !== slug),
5631
5745
  capacity,
5632
5746
  now,
5633
5747
  ).occupied,
5634
- dispatchCapacity(builds, capacity, now, {
5748
+ this.measureCapacity(builds, capacity, now, {
5635
5749
  claims: this.claims(),
5636
5750
  startRequests: this.startClaims(),
5637
5751
  }),
@@ -9083,13 +9197,54 @@ export class Dispatcher {
9083
9197
  paused: boolean,
9084
9198
  opts: TickOpts,
9085
9199
  ): Promise<void> {
9086
- if (this.carriedOutstanding.size === 0) return this.pass.total('deferred', 0)
9200
+ const carriedPreparations = this.carriedPreparationsOutstanding.size
9201
+ if (this.carriedOutstanding.size === 0 && carriedPreparations === 0)
9202
+ return this.pass.total('deferred', 0)
9203
+ this.pass.total('deferred', this.carriedOutstanding.size + carriedPreparations)
9204
+ if (this.carriedOutstanding.size > 0)
9205
+ await this.serviceDeferredBuilds(report, launched, paused, opts)
9206
+ // Carried ticket preparations (#1431), after the carried builds: each
9207
+ // attempt resumes from its durable boundaries, with no fleet read.
9208
+ for (const attempt of [...this.carriedPreparationsOutstanding.keys()]) {
9209
+ if (!this.passItem(opts, 'deferred')) break
9210
+ const entry = this.carriedPreparationsOutstanding.get(attempt)!
9211
+ const held = this.store.repositoryFacts().preparation[attempt]
9212
+ if (held === undefined) {
9213
+ this.carriedPreparationsOutstanding.delete(attempt)
9214
+ continue
9215
+ }
9216
+ entry.visited = true
9217
+ this.tickResumedAttempts.add(attempt)
9218
+ let outcome: 'done' | 'waiting' | 'failed'
9219
+ try {
9220
+ outcome = await this.resumeCarriedPreparation(held, report, launched, paused, 'deferred')
9221
+ } catch (error) {
9222
+ rethrowAuthorityLapse(error)
9223
+ // Contained like a recovery failure; the attempt's stamp resumes it
9224
+ // in a later pass.
9225
+ report.janitorFailed += 1
9226
+ report.janitorDiagnostics.push(String(error))
9227
+ outcome = 'failed'
9228
+ }
9229
+ const interrupted = this.budgetSpent(this.tickOpts)
9230
+ if (outcome !== 'waiting' && !interrupted && !this.tickPreparationCarries.has(attempt))
9231
+ this.carriedPreparationsOutstanding.delete(attempt)
9232
+ }
9233
+ await this.persistDeferrals()
9234
+ }
9235
+
9236
+ /** The carried builds of `serviceDeferredWork`. */
9237
+ private async serviceDeferredBuilds(
9238
+ report: TickReport,
9239
+ launched: Set<string>,
9240
+ paused: boolean,
9241
+ opts: TickOpts,
9242
+ ): Promise<void> {
9087
9243
  // Never the default form: it would run the mixed-version check for every
9088
9244
  // compatibility-bearing build. `sweepBuild` checks each carried build.
9089
9245
  const entries = new Map(
9090
9246
  (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
9091
9247
  )
9092
- this.pass.total('deferred', this.carriedOutstanding.size)
9093
9248
  for (const slug of [...this.carriedOutstanding.keys()]) {
9094
9249
  if (!this.passItem(opts, 'deferred')) break
9095
9250
  const entry = this.carriedOutstanding.get(slug)!
@@ -9111,7 +9266,6 @@ export class Dispatcher {
9111
9266
  if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
9112
9267
  this.retireCarried(slug)
9113
9268
  }
9114
- await this.persistDeferrals()
9115
9269
  }
9116
9270
 
9117
9271
  /**
@@ -9326,9 +9480,59 @@ export class Dispatcher {
9326
9480
  this.reportedDeferrals.add(slug)
9327
9481
  lines.push(deferralLine(slug, deferral))
9328
9482
  }
9483
+ lines.push(...this.unreportedPreparationCarries())
9484
+ return lines
9485
+ }
9486
+
9487
+ /** This tick's carried preparations not yet named in a report or teardown
9488
+ * line, each marked reported. */
9489
+ private unreportedPreparationCarries(): string[] {
9490
+ const lines: string[] = []
9491
+ for (const [attempt, { ticket, detail }] of this.tickPreparationCarries) {
9492
+ const key = `prep:${attempt}`
9493
+ if (this.reportedDeferrals.has(key)) continue
9494
+ this.reportedDeferrals.add(key)
9495
+ lines.push(preparationCarryLine(ticket, detail))
9496
+ }
9329
9497
  return lines
9330
9498
  }
9331
9499
 
9500
+ /** Record that this tick carried `attempt`'s ticket preparation to the
9501
+ * next invocation (#1431), and keep the durable hint current. The first
9502
+ * reason noted wins. */
9503
+ private async notePreparationCarry(
9504
+ attempt: string,
9505
+ ticket: TicketRef,
9506
+ detail?: string,
9507
+ ): Promise<void> {
9508
+ if (!this.tickPreparationCarries.has(attempt))
9509
+ this.tickPreparationCarries.set(attempt, {
9510
+ ticket,
9511
+ ...(detail !== undefined ? { detail } : {}),
9512
+ })
9513
+ await this.persistDeferrals()
9514
+ }
9515
+
9516
+ /** The hint's preparation entries this tick would write, ordered as
9517
+ * `nextDeferralList` orders builds and capped from the tail. A dropped
9518
+ * entry is still resumed: its attempt carries the work-deadline stamp
9519
+ * preparation recovery resumes from. */
9520
+ private nextPreparationCarryList(): CarriedPreparation[] {
9521
+ const list: CarriedPreparation[] = []
9522
+ const seen = new Set<string>()
9523
+ const push = (attempt: string, ticket: TicketRef) => {
9524
+ if (seen.has(attempt)) return
9525
+ seen.add(attempt)
9526
+ list.push({ ticket, attempt })
9527
+ }
9528
+ for (const [attempt, entry] of this.carriedPreparationsOutstanding)
9529
+ if (!entry.visited) push(attempt, entry.ticket)
9530
+ for (const [attempt, entry] of this.carriedPreparationsOutstanding)
9531
+ if (entry.visited) push(attempt, entry.ticket)
9532
+ for (const [attempt, { ticket }] of this.tickPreparationCarries) push(attempt, ticket)
9533
+ return list.slice(0, MAX_CARRIED_PREPARATIONS)
9534
+ }
9535
+
9332
9536
  /** A carried hint entry whose own pass showed it no longer needs priority.
9333
9537
  * Never writes: the next hint write simply omits it. */
9334
9538
  private retireCarried(slug: string): void {
@@ -9387,6 +9591,8 @@ export class Dispatcher {
9387
9591
  const write = this.deferralWrites.then(async () => {
9388
9592
  const next = this.nextDeferralList()
9389
9593
  const recorded = this.recordedDeferrals
9594
+ const tickets = this.nextPreparationCarryList()
9595
+ const recordedTickets = this.recordedPreparationCarries
9390
9596
  if (
9391
9597
  next.length === recorded.length &&
9392
9598
  next.every(
@@ -9394,6 +9600,13 @@ export class Dispatcher {
9394
9600
  entry.slug === recorded[i]!.slug &&
9395
9601
  entry.step === recorded[i]!.step &&
9396
9602
  entry.instance === recorded[i]!.instance,
9603
+ ) &&
9604
+ tickets.length === recordedTickets.length &&
9605
+ tickets.every(
9606
+ (entry, i) =>
9607
+ entry.attempt === recordedTickets[i]!.attempt &&
9608
+ entry.ticket.source === recordedTickets[i]!.ticket.source &&
9609
+ entry.ticket.id === recordedTickets[i]!.ticket.id,
9397
9610
  )
9398
9611
  )
9399
9612
  return
@@ -9401,11 +9614,14 @@ export class Dispatcher {
9401
9614
  this.store.appendRepo(this.deps.repo, {
9402
9615
  actor: DISPATCHER,
9403
9616
  type: 'dispatcher.work-deferred',
9404
- payload: { builds: next },
9617
+ // A hint without carried preparations keeps its earlier payload.
9618
+ payload: { builds: next, ...(tickets.length > 0 ? { tickets } : {}) },
9405
9619
  }),
9406
9620
  )
9407
- if (outcome === true) this.recordedDeferrals = next
9408
- else if (outcome !== false) this.deferralWriteFailure = outcome
9621
+ if (outcome === true) {
9622
+ this.recordedDeferrals = next
9623
+ this.recordedPreparationCarries = tickets
9624
+ } else if (outcome !== false) this.deferralWriteFailure = outcome
9409
9625
  })
9410
9626
  this.deferralWrites = write.catch(() => {})
9411
9627
  return write
@@ -9471,6 +9687,9 @@ export class Dispatcher {
9471
9687
  this.reportedDeferrals.add(slug)
9472
9688
  report.deferredDiagnostics.push(deferralLine(slug, deferral))
9473
9689
  }
9690
+ if (this.tickPreparationCarries.size > 0)
9691
+ report.preparationsCarried = this.tickPreparationCarries.size
9692
+ report.deferredDiagnostics.push(...this.unreportedPreparationCarries())
9474
9693
  if (this.deferralWriteFailure !== undefined)
9475
9694
  report.deferredDiagnostics.push(
9476
9695
  `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
@@ -9821,10 +10040,24 @@ export class Dispatcher {
9821
10040
 
9822
10041
  /** Retry a fixed batch under the same repository ownership as intake.
9823
10042
  * No provider calls for parked deadlines; no history or orphan scans. */
9824
- private async recoverTicketPreparations(report: TickReport, opts: TickOpts): Promise<void> {
9825
- const pending = Object.values(this.store.repositoryFacts().preparation)
10043
+ private async recoverTicketPreparations(
10044
+ report: TickReport,
10045
+ launched: Set<string>,
10046
+ paused: boolean,
10047
+ opts: TickOpts,
10048
+ ): Promise<void> {
10049
+ const attempts = Object.values(this.store.repositoryFacts().preparation)
10050
+ // Read the clock only when an attempt needs scheduling.
10051
+ const now = attempts.length ? this.deps.clock().getTime() : 0
10052
+ const pending = attempts
9826
10053
  .filter(
9827
- (attempt) => !attempt.retryAt || Date.parse(attempt.retryAt) <= this.deps.clock().getTime(),
10054
+ (attempt) =>
10055
+ // The early stage resumed it this tick.
10056
+ !this.tickResumedAttempts.has(attempt.attempt) &&
10057
+ // A deadline stamp not yet passed belongs to an invocation still
10058
+ // running (or a skewed clock): a later pass decides it.
10059
+ !(this.interruptedByDeadline(attempt) && Date.parse(attempt.workDeadlineAt!) > now) &&
10060
+ (!attempt.retryAt || Date.parse(attempt.retryAt) <= now),
9828
10061
  )
9829
10062
  .sort(
9830
10063
  (a, b) =>
@@ -9838,7 +10071,12 @@ export class Dispatcher {
9838
10071
  for (const attempt of pending) {
9839
10072
  if (!this.passItem(opts, 'preparations')) break
9840
10073
  try {
9841
- await this.recoverTicketPreparation(attempt)
10074
+ // A preparation its invocation's work deadline interrupted resumes,
10075
+ // even when its carry hint was lost (#1431); everything else
10076
+ // recovers as before.
10077
+ if (this.interruptedByDeadline(attempt))
10078
+ await this.resumeCarriedPreparation(attempt, report, launched, paused, 'preparations')
10079
+ else await this.recoverTicketPreparation(attempt)
9842
10080
  } catch (error) {
9843
10081
  rethrowAuthorityLapse(error)
9844
10082
  failures.push(error)
@@ -9926,39 +10164,251 @@ export class Dispatcher {
9926
10164
  }
9927
10165
  }
9928
10166
 
9929
- private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
9930
- try {
9931
- // A rejected create can have committed. Unavailable or conflicting readback
9932
- // is never absence and must not authorize a ticket transition. A keyed
9933
- // attempt's build is at its proposed slug (exact-slug store) or the slug
9934
- // its own key derives (allocating store): at most two point reads, and
9935
- // never another attempt's build.
9936
- if (attempt.slug) {
9937
- const found = await this.creationCandidates(attempt, attempt.slug)
9938
- if (found.length > 1)
9939
- return await this.abandonPreparation(
10167
+ /** Whether an attempt's selected creation committed: the one build it
10168
+ * owns, `absent` when no build answers it (or it selected no slug), or
10169
+ * `abandoned` once an ambiguous, conflicting or unprovable outcome was
10170
+ * durably abandoned. */
10171
+ private async creationReadback(
10172
+ attempt: TicketPreparation,
10173
+ ): Promise<{ owned: BuildRecord } | 'absent' | 'abandoned'> {
10174
+ // A rejected create can have committed. Unavailable or conflicting readback
10175
+ // is never absence and must not authorize a ticket transition. A keyed
10176
+ // attempt's build is at its proposed slug (exact-slug store) or the slug
10177
+ // its own key derives (allocating store): at most two point reads, and
10178
+ // never another attempt's build.
10179
+ if (!attempt.slug) return 'absent'
10180
+ const found = await this.creationCandidates(attempt, attempt.slug)
10181
+ if (found.length > 1) {
10182
+ await this.abandonPreparation(
10183
+ attempt,
10184
+ `Ambiguous creation identity: builds at ${found.map((record) => record.slug).join(' and ')} both answer this attempt; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10185
+ )
10186
+ return 'abandoned'
10187
+ }
10188
+ const [record] = found
10189
+ if (record) {
10190
+ if (!(await this.preparationOwns(attempt, record))) {
10191
+ await this.abandonPreparation(
10192
+ attempt,
10193
+ `Conflicting build ownership at ${record.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10194
+ )
10195
+ return 'abandoned'
10196
+ }
10197
+ return { owned: record }
10198
+ }
10199
+ // Absence is evidence only where the creation slug is known: an
10200
+ // allocating store may have committed an unkeyed create under a slug
10201
+ // no point read can find, and enumerating builds is never a fallback.
10202
+ if (!attempt.creationKey && (await this.store.buildCreationIdentity?.()) !== undefined) {
10203
+ await this.abandonPreparation(
10204
+ attempt,
10205
+ `Creation outcome unknown: the build store allocates canonical slugs and this attempt recorded no creation key, so a build created under an unrecorded slug cannot be ruled out; ticket unchanged. Inspect the repository's builds for ticket ${attempt.ticket.id} before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10206
+ )
10207
+ return 'abandoned'
10208
+ }
10209
+ return 'absent'
10210
+ }
10211
+
10212
+ /** `dispatchCapacity` with every outstanding admitted preparation holding
10213
+ * its slot (#1431). A carried attempt was admitted when its `intended` was
10214
+ * written and finishes without re-measuring capacity, so until it resolves
10215
+ * no later admission (intake, start requests, parked or node slot
10216
+ * admission) may spend its slot, however many passes its resume takes.
10217
+ * In memory over the tick's repository facts: no read. */
10218
+ private measureCapacity(
10219
+ ...args: Parameters<typeof dispatchCapacity>
10220
+ ): ReturnType<typeof dispatchCapacity> {
10221
+ const capacity = dispatchCapacity(...args)
10222
+ const reserved = this.reservedPreparations()
10223
+ return reserved === 0 ? capacity : { ...capacity, occupied: capacity.occupied + reserved }
10224
+ }
10225
+
10226
+ /** Unresolved ticket preparations a bounded pass admitted and its work
10227
+ * deadline interrupted (or deferred), each holding one slot until it
10228
+ * resolves. A node ticket's attempt reserves too, at most until its next
10229
+ * resume: the attempt does not record the ticket's kind. */
10230
+ private reservedPreparations(): number {
10231
+ let reserved = 0
10232
+ for (const attempt of Object.values(this.store.repositoryFacts().preparation))
10233
+ if (this.interruptedByDeadline(attempt)) reserved++
10234
+ return reserved
10235
+ }
10236
+
10237
+ /** Whether the work deadline of the invocation that wrote this attempt
10238
+ * interrupted it (#1431): stamped by a bounded pass, that deadline passed,
10239
+ * and no failure or bounce was recorded. Such an attempt resumes; it is
10240
+ * never handed back. */
10241
+ private interruptedByDeadline(attempt: TicketPreparation): boolean {
10242
+ return (
10243
+ attempt.workDeadlineAt !== undefined &&
10244
+ attempt.stage === undefined &&
10245
+ attempt.handback === undefined
10246
+ )
10247
+ }
10248
+
10249
+ /**
10250
+ * Continue one carried ticket preparation (#1431) from its last durable
10251
+ * boundary: the claim, the claim confirmation, or the creation readback.
10252
+ * Admission was decided when its `intended` was written, so nothing here
10253
+ * re-measures capacity. Never hands a ticket back for the interruption;
10254
+ * a resumed preparation that fails for real takes the ordinary failure
10255
+ * path, and one the deadline cuts again is carried again under the same
10256
+ * attempt. Reads: one `tickets.get`, plus the existing creation readback
10257
+ * when a slug was selected and a target node's facts for a node child.
10258
+ */
10259
+ private async resumeCarriedPreparation(
10260
+ held: TicketPreparation,
10261
+ report: TickReport,
10262
+ launched: Set<string>,
10263
+ paused: boolean,
10264
+ part: PassStagePart,
10265
+ ): Promise<'done' | 'waiting' | 'failed'> {
10266
+ // Nothing claims while the repository is paused; the entry waits.
10267
+ if (paused) return 'waiting'
10268
+ const attempt: TicketPreparation = structuredClone(held)
10269
+ // A selected bounce is a real outcome: finish it.
10270
+ if (attempt.handback !== undefined) {
10271
+ await this.recoverTicketPreparation(attempt)
10272
+ return 'done'
10273
+ }
10274
+ const readback = await this.creationReadback(attempt)
10275
+ if (readback === 'abandoned') return 'done'
10276
+ if (readback !== 'absent') {
10277
+ await this.preparationResolved(attempt, 'owned')
10278
+ return this.serviceCarriedStart(
10279
+ readback.owned,
10280
+ { step: 'provision' },
10281
+ report,
10282
+ launched,
10283
+ paused,
10284
+ )
10285
+ }
10286
+ const ref = resolveTicketRef(
10287
+ this.store.repositoryFacts().ticketMigrations,
10288
+ attempt.ticket,
10289
+ this.deps.tickets.name,
10290
+ attempt.slug ?? attempt.attempt,
10291
+ )
10292
+ const ticket = await this.deps.tickets.get(ref.id)
10293
+ if (!ticket) {
10294
+ await this.abandonPreparation(attempt, 'Ticket no longer exists; ticket unchanged.')
10295
+ return 'done'
10296
+ }
10297
+ if (ticket.state === undefined) {
10298
+ await this.abandonPreparation(
10299
+ attempt,
10300
+ 'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
10301
+ )
10302
+ return 'done'
10303
+ }
10304
+ const is = (state: string) => ticket.state!.toLowerCase() === state.toLowerCase()
10305
+ if (!attempt.claimed) {
10306
+ if (is(attempt.readyState)) {
10307
+ // Still Ready: no claim applied. A ticket that no longer qualifies
10308
+ // is released with no tracker write, and intake re-evaluates it.
10309
+ if (!this.tickAcceptsNewWork) {
10310
+ await this.preparationResolved(
9940
10311
  attempt,
9941
- `Ambiguous creation identity: builds at ${found.map((record) => record.slug).join(' and ')} both answer this attempt; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10312
+ 'lost-claim',
10313
+ 'intake turned off before its carried claim',
9942
10314
  )
9943
- const [record] = found
9944
- if (record) {
9945
- if (!(await this.preparationOwns(attempt, record)))
9946
- return await this.abandonPreparation(
9947
- attempt,
9948
- `Conflicting build ownership at ${record.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
9949
- )
9950
- await this.preparationResolved(attempt, 'owned')
9951
- return
10315
+ return 'done'
9952
10316
  }
9953
- // Absence is evidence only where the creation slug is known: an
9954
- // allocating store may have committed an unkeyed create under a slug
9955
- // no point read can find, and enumerating builds is never a fallback.
9956
- if (!attempt.creationKey && (await this.store.buildCreationIdentity?.()) !== undefined)
9957
- return await this.abandonPreparation(
10317
+ if (ticket.blockersResolved === false) {
10318
+ await this.preparationResolved(
9958
10319
  attempt,
9959
- `Creation outcome unknown: the build store allocates canonical slugs and this attempt recorded no creation key, so a build created under an unrecorded slug cannot be ruled out; ticket unchanged. Inspect the repository's builds for ticket ${attempt.ticket.id} before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10320
+ 'lost-claim',
10321
+ 'unresolved blockers before its carried claim',
9960
10322
  )
10323
+ return 'done'
10324
+ }
10325
+ } else if (attempt.claimDeferred) {
10326
+ // No claim call was ever made: the ticket is not ours.
10327
+ await this.preparationResolved(
10328
+ attempt,
10329
+ 'lost-claim',
10330
+ `ticket left ${attempt.readyState} (${ticket.state}) before its carried claim`,
10331
+ )
10332
+ return 'done'
10333
+ } else if (is(attempt.claimedState)) {
10334
+ // The claim applied but its confirmation was cut.
10335
+ await this.store.appendRepo(this.deps.repo, {
10336
+ actor: DISPATCHER,
10337
+ type: 'ticket-preparation.claimed',
10338
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket },
10339
+ })
10340
+ attempt.claimed = true
10341
+ } else {
10342
+ await this.abandonPreparation(
10343
+ attempt,
10344
+ `Claim outcome uncertain: the claim request did not confirm and the provider may have applied it; ticket observed in state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10345
+ )
10346
+ return 'done'
10347
+ }
10348
+ } else if (!is(attempt.claimedState)) {
10349
+ await this.abandonPreparation(
10350
+ attempt,
10351
+ `Confirmed claim but ticket externally changed to state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10352
+ )
10353
+ return 'done'
10354
+ }
10355
+ const target = await this.resolveNodeTarget(ticket, {
10356
+ listed: new Set(),
10357
+ foreign: new Map(),
10358
+ generation: ++this.foreignScanGeneration,
10359
+ })
10360
+ if (typeof target === 'string') {
10361
+ if (!attempt.claimed) {
10362
+ await this.preparationResolved(attempt, 'lost-claim', target)
10363
+ return 'done'
9961
10364
  }
10365
+ return this.failPreparation(attempt, 'target', new Error(target))
10366
+ }
10367
+ if (!attempt.claimed && attempt.claimDeferred) {
10368
+ // The claim-started boundary: from here on the claim may have applied,
10369
+ // so recovery confirms it from the ticket's state rather than
10370
+ // releasing the ticket. Nothing has reached the tracker yet.
10371
+ try {
10372
+ await this.appendIntended(attempt)
10373
+ } catch (error) {
10374
+ rethrowAuthorityLapse(error)
10375
+ if (!this.budgetSpent(this.tickOpts)) throw error
10376
+ await this.notePreparationCarry(
10377
+ attempt.attempt,
10378
+ attempt.ticket,
10379
+ 'the work deadline cut its preparation (claim)',
10380
+ ).catch(() => {})
10381
+ this.pass.carry(part, attempt.ticket.id)
10382
+ return 'waiting'
10383
+ }
10384
+ }
10385
+ // The level admission decided (a start request's own level included),
10386
+ // recorded with the attempt. An attempt without one is re-derived as
10387
+ // intake derives an ordinary claim's: an optimization attempt's node
10388
+ // priority, else the ticket's.
10389
+ const level =
10390
+ attempt.level ??
10391
+ (await this.attemptClaimTiers([ticket])).get(ticket.ref.id) ??
10392
+ (this.deps.tickets.priority ? ticketPriority(ticket) : 'normal')
10393
+ const outcome = await this.prepareTicket({
10394
+ ticket,
10395
+ attempt,
10396
+ target,
10397
+ level,
10398
+ report,
10399
+ launched,
10400
+ settle: () => {},
10401
+ part,
10402
+ resume: true,
10403
+ })
10404
+ return outcome === 'started' || outcome === 'left' || outcome === 'blocked' ? 'done' : 'waiting'
10405
+ }
10406
+
10407
+ private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
10408
+ try {
10409
+ const readback = await this.creationReadback(attempt)
10410
+ if (readback === 'abandoned') return
10411
+ if (readback !== 'absent') return await this.preparationResolved(attempt, 'owned')
9962
10412
  // A committed `ticket.handed-back` whose acknowledgement or resolution
9963
10413
  // was lost means the hand-back already happened, and a watcher may have
9964
10414
  // moved the ticket since. Resolve without touching the ticket.
@@ -10081,7 +10531,7 @@ export class Dispatcher {
10081
10531
  if (!targeted && this.deferredAdmissions.size > 0) {
10082
10532
  deferralBuilds = await this.capacityBuilds(launched)
10083
10533
  const key = this.deferralKey(
10084
- dispatchCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
10534
+ this.measureCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
10085
10535
  )
10086
10536
  if (key !== this.lastForcedDeferralKey) {
10087
10537
  force = true
@@ -10126,7 +10576,7 @@ export class Dispatcher {
10126
10576
  // tell a reserved request from one filed since.
10127
10577
  const pendingStarts = this.store.repositoryFacts().ticketStarts.pending
10128
10578
  const startDemand = this.startClaims()
10129
- const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
10579
+ const projection = this.measureCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
10130
10580
  openPrs: { policy: config.policy, engaged },
10131
10581
  startRequests: startDemand,
10132
10582
  })
@@ -10628,23 +11078,94 @@ export class Dispatcher {
10628
11078
  }
10629
11079
  // Cancellation and a priority change are checked again before claiming.
10630
11080
  if (targeted && !(await this.startStillPending(targeted, ticket))) continue
10631
- await store.appendRepo(this.deps.repo, {
10632
- actor: DISPATCHER,
10633
- type: 'ticket-preparation.intended',
10634
- payload: {
10635
- attempt: attempt.attempt,
10636
- ticket: attempt.ticket,
10637
- readyState: attempt.readyState,
10638
- claimedState: attempt.claimedState,
10639
- },
11081
+ // A bounded pass does not start a preparation it cannot finish before
11082
+ // its work deadline (#1431). Intake's admission is journaled and the
11083
+ // next invocation prepares it first; a start request's own pending
11084
+ // request is already its carry. Time only shrinks: stop claiming.
11085
+ if (this.preparationWontFit()) {
11086
+ claimLoopCompleted = false
11087
+ attempt.level = this.claimedLevel(ticket, startTier(ticket), tierOf)
11088
+ if (!targeted && (await this.deferPreparation(attempt, part ?? 'tickets'))) {
11089
+ report.queued -= 1
11090
+ if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
11091
+ }
11092
+ break
11093
+ }
11094
+ const outcome = await this.prepareTicket({
11095
+ ticket,
11096
+ attempt,
11097
+ target,
11098
+ level: this.claimedLevel(ticket, startTier(ticket), tierOf),
11099
+ report,
11100
+ launched,
11101
+ settle: (outcome) => settle(ticket, outcome),
11102
+ part: part ?? 'starts',
11103
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
11104
+ ...(autoMergeSeedFact !== undefined ? { autoMergeSeedFact } : {}),
10640
11105
  })
10641
- let stage = 'claim'
10642
- let established = false
10643
- let record: BuildRecord
10644
- let body = ticket.body
10645
- let authoredSession: string | undefined
10646
- let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
11106
+ if (outcome === 'blocked') continue
11107
+ if (outcome === 'stop') {
11108
+ claimLoopCompleted = false
11109
+ break
11110
+ }
11111
+ report.queued -= 1
11112
+ if (outcome === 'left') continue
11113
+ // A carried admission holds its slot until the next invocation
11114
+ // prepares it.
11115
+ if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
11116
+ else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
11117
+ if (outcome === 'carried') {
11118
+ claimLoopCompleted = false
11119
+ break
11120
+ }
11121
+ }
11122
+ if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
11123
+ await this.completeScan(checkpoint, report, waiting)
11124
+ // The only other place this tick authorizes deferred admissions.
11125
+ if (claimLoopCompleted) this.claimsEvaluated = true
11126
+ }
11127
+ }
11128
+
11129
+ /**
11130
+ * One ticket preparation (SPEC §6.3), from the `intended` append through
11131
+ * the first dispatch: claim → `.claimed` → asset pin → spec → naming →
11132
+ * `.creation-selected` → `createBuild` → `.resolved owned` → first
11133
+ * dispatch. With `resume`, a carried attempt (#1431) continues from its
11134
+ * claim when unclaimed, or from its asset pin when claimed, appending no
11135
+ * `intended`. Tracked as a start in flight, so bounded teardown awaits a
11136
+ * preparation the work deadline cut. A preparation the deadline cuts
11137
+ * before `build.created` is carried to the next invocation: nothing is
11138
+ * marked failed, nothing is handed back and the tracker is not touched.
11139
+ * Every other failure keeps its failure record and recovery.
11140
+ */
11141
+ private prepareTicket(input: PreparationInput): Promise<PreparationOutcome> {
11142
+ return this.trackStart(this.runPreparation(input))
11143
+ }
11144
+
11145
+ private async runPreparation(input: PreparationInput): Promise<PreparationOutcome> {
11146
+ const { ticket, attempt, target, level, report, launched, settle, resume } = input
11147
+ const { autoMergeUser, autoMergeSeedFact } = input
11148
+ const store = this.store
11149
+ const { tickets } = this.deps
11150
+ if (!resume) {
11151
+ attempt.level = level
10647
11152
  try {
11153
+ await this.appendIntended(attempt)
11154
+ } catch (error) {
11155
+ rethrowAuthorityLapse(error)
11156
+ // Nothing durable began: the next scan admits the ticket again.
11157
+ if (this.budgetSpent(this.tickOpts)) return 'stop'
11158
+ throw error
11159
+ }
11160
+ }
11161
+ let stage = attempt.claimed ? 'assets' : 'claim'
11162
+ let established = false
11163
+ let record: BuildRecord
11164
+ let body = ticket.body
11165
+ let authoredSession: string | undefined
11166
+ let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
11167
+ try {
11168
+ if (!attempt.claimed) {
10648
11169
  let claimed: boolean
10649
11170
  try {
10650
11171
  claimed = await tickets.claim(ticket.ref.id, { blockedBy: ticket.blockedBy ?? [] })
@@ -10656,18 +11177,17 @@ export class Dispatcher {
10656
11177
  await this.preparationResolved(attempt, 'lost-claim', error.message)
10657
11178
  report.dependencyBlocked += 1
10658
11179
  report.dependencyDiagnostics.push(detail)
10659
- settle(ticket, { outcome: 'blocked', detail })
10660
- continue
11180
+ settle({ outcome: 'blocked', detail })
11181
+ return 'blocked'
10661
11182
  }
10662
11183
  if (!claimed) {
10663
11184
  await this.preparationResolved(attempt, 'lost-claim')
10664
- settle(ticket, {
11185
+ settle({
10665
11186
  outcome: 'claim-refused',
10666
11187
  detail: `the ${tickets.name} ticket source refused the claim of ${ticket.ref.id}`,
10667
11188
  })
10668
11189
  report.claimRaces += 1
10669
- report.queued -= 1
10670
- continue
11190
+ return 'left'
10671
11191
  }
10672
11192
  attempt.claimed = true
10673
11193
  stage = 'claim-confirmation'
@@ -10676,220 +11196,297 @@ export class Dispatcher {
10676
11196
  type: 'ticket-preparation.claimed',
10677
11197
  payload: { attempt: attempt.attempt, ticket: attempt.ticket },
10678
11198
  })
10679
- stage = 'assets'
10680
- // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
10681
- // spec-authoring interval so edits made during it are never pinned.
10682
- const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
10683
-
10684
- // Quality gate (§6.3): import a conforming ticket body as the spec;
10685
- // author one for thin-but-groomed tickets; otherwise bounce.
10686
- stage = 'spec'
10687
- // An objective refusal bounces before any authoring: an authored spec
10688
- // could strip the block and open a plain node instead (SPEC §13.1).
10689
- const refusals = objectiveRefusals(body, {
10690
- kind: ticket.kind ?? 'work',
10691
- rejectedState: this.rejectedState(),
10692
- })
10693
- let conformance =
10694
- refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
10695
- if (
10696
- !conformance.conforms &&
10697
- refusals.length === 0 &&
10698
- objectiveBlocks(body).length === 0 &&
10699
- this.deps.authorSpec
10700
- ) {
10701
- const authored = await this.deps.authorSpec(ticket)
10702
- // An authored spec never gains the marker the ticket did not carry.
10703
- if (authored !== null && objectiveBlocks(authored).length === 0) {
10704
- conformance = specConformance(authored)
10705
- if (conformance.conforms) {
10706
- body = authored
10707
- authoredSession = this.deps.ids('s')
10708
- }
11199
+ }
11200
+ stage = 'assets'
11201
+ // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
11202
+ // spec-authoring interval so edits made during it are never pinned.
11203
+ const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
11204
+
11205
+ // Quality gate (§6.3): import a conforming ticket body as the spec;
11206
+ // author one for thin-but-groomed tickets; otherwise bounce.
11207
+ stage = 'spec'
11208
+ // An objective refusal bounces before any authoring: an authored spec
11209
+ // could strip the block and open a plain node instead (SPEC §13.1).
11210
+ const refusals = objectiveRefusals(body, {
11211
+ kind: ticket.kind ?? 'work',
11212
+ rejectedState: this.rejectedState(),
11213
+ })
11214
+ let conformance =
11215
+ refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
11216
+ if (
11217
+ !conformance.conforms &&
11218
+ refusals.length === 0 &&
11219
+ objectiveBlocks(body).length === 0 &&
11220
+ this.deps.authorSpec
11221
+ ) {
11222
+ const authored = await this.deps.authorSpec(ticket)
11223
+ // An authored spec never gains the marker the ticket did not carry.
11224
+ if (authored !== null && objectiveBlocks(authored).length === 0) {
11225
+ conformance = specConformance(authored)
11226
+ if (conformance.conforms) {
11227
+ body = authored
11228
+ authoredSession = this.deps.ids('s')
10709
11229
  }
10710
11230
  }
10711
- if (!conformance.conforms) {
10712
- attempt.handback = this.triageState()
10713
- const missing = conformance.missing.length > 0 ? conformance.missing : undefined
10714
- if (missing) attempt.missing = missing
10715
- await store.appendRepo(this.deps.repo, {
10716
- actor: DISPATCHER,
10717
- type: 'ticket-preparation.handback-selected',
10718
- payload: {
10719
- attempt: attempt.attempt,
10720
- ticket: attempt.ticket,
10721
- state: attempt.handback,
10722
- ...(missing ? { missing } : {}),
10723
- },
10724
- })
10725
- stage = 'bounce'
10726
- await this.bounce(ticket, conformance.missing, refusals.length > 0)
10727
- stage = 'handback-report'
10728
- await this.reportPreparationHandback(attempt, {
10729
- ticket: ticket.ref,
10730
- attempt: attempt.attempt,
10731
- cause: 'spec-bounce',
10732
- state: attempt.handback,
10733
- role: 'triage',
10734
- ...(missing ? { missing } : {}),
10735
- })
10736
- await this.preparationResolved(attempt, 'bounced')
10737
- settle(ticket, {
10738
- outcome: 'invalid',
10739
- detail: `bounced to ${attempt.handback}${
10740
- conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
10741
- }`,
10742
- })
10743
- report.bounced += 1
10744
- report.queued -= 1
10745
- continue
10746
- }
10747
-
10748
- stage = 'naming'
10749
- const baseSlug = await this.chooseSlugBase(ticket.title, body)
10750
- const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
10751
- const slug = await this.uniqueSlug(baseSlug, prefix)
10752
- const branch = `${prefix}/${slug}`
10753
- const repoOrigin = await this.resolveRepoOriginOnce()
10754
- // Recorded only on the store's attestation, so recovery never treats
10755
- // an unkeyed creation's absence at the derived slug as evidence.
10756
- const creationKey =
10757
- (await store.buildCreationIdentity?.()) === 'keyed' ? attempt.attempt : undefined
10758
- createdSeed = {
10759
- ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
10760
- ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
10761
- ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
10762
- // Claim-time provenance: the newest durable default fact that agrees
10763
- // with the launch sample, recorded on `build.created` so the fan-out's
10764
- // seq comparison sees the claim as already answering that fact — and
10765
- // so a newer opposite fact (an interleaved toggle) stays strictly
10766
- // ahead of it and reconciles this build on the next tick (f_b851c0e8).
10767
- ...(autoMergeSeedFact !== undefined
10768
- ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
10769
- : {}),
10770
- assets,
10771
- // Frozen from the same claimed ticket sample as the body (SPEC
10772
- // "Forge issue links"); later ticket edits never reach this build.
10773
- ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
10774
- // Fixed at claim from the same sample: relabelling never changes it.
10775
- ...this.selectedProfile(ticket),
10776
- // `manual` is admission-only: a build started by any other request
10777
- // takes the request's level, every other build its ticket's.
10778
- ...createdPriorityFields(this.claimedLevel(ticket, startTier(ticket), tierOf)),
10779
- }
10780
- // `build.created` rides with the record so the pinned assets and the
10781
- // record exist together or not at all.
10782
- stage = 'creation-identity'
10783
- attempt.slug = slug
10784
- if (creationKey !== undefined) attempt.creationKey = creationKey
11231
+ }
11232
+ if (!conformance.conforms) {
11233
+ attempt.handback = this.triageState()
11234
+ const missing = conformance.missing.length > 0 ? conformance.missing : undefined
11235
+ if (missing) attempt.missing = missing
10785
11236
  await store.appendRepo(this.deps.repo, {
10786
11237
  actor: DISPATCHER,
10787
- type: 'ticket-preparation.creation-selected',
11238
+ type: 'ticket-preparation.handback-selected',
10788
11239
  payload: {
10789
11240
  attempt: attempt.attempt,
10790
11241
  ticket: attempt.ticket,
10791
- slug,
10792
- ...(creationKey !== undefined ? { creationKey } : {}),
11242
+ state: attempt.handback,
11243
+ ...(missing ? { missing } : {}),
10793
11244
  },
10794
11245
  })
10795
- stage = 'create-build'
10796
- // Tracked from the creation on: `build.created` admits the build, so
10797
- // a work deadline that cuts anything after it must carry the start.
10798
- record = await this.trackStart(
10799
- (async () => {
10800
- const created = await store
10801
- .createBuild({
10802
- slug,
10803
- repo: this.deps.repo,
10804
- ticket: ticket.ref,
10805
- branch,
10806
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
10807
- ...(creationKey !== undefined ? { creationKey } : {}),
10808
- created: {
10809
- actor: DISPATCHER,
10810
- type: 'build.created',
10811
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
10812
- },
10813
- })
10814
- .catch(async (error: unknown) => {
10815
- // The deadline may have cut only the acknowledgement: a
10816
- // committed `build.created` admitted the build, so resolve
10817
- // the preparation and carry its first provision.
10818
- if (!this.budgetSpent(this.tickOpts)) throw error
10819
- const owned = await this.cutCreation(attempt, slug)
10820
- if (owned === undefined) throw error
10821
- established = true
10822
- await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
10823
- (resolution: unknown) => rethrowAuthorityLapse(resolution),
10824
- )
10825
- return this.carryCutFirstDispatch(owned.slug, error)
10826
- })
10827
- established = true
10828
- await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
10829
- this.carryCutFirstDispatch(created.slug, error),
10830
- )
10831
- return created
10832
- })(),
10833
- )
10834
- settle(ticket, { outcome: 'started', slug: record.slug })
10835
- } catch (error) {
10836
- // A lapse is not a preparation failure: the successor recovers the
10837
- // intended attempt through `recoverTicketPreparations`.
10838
- rethrowAuthorityLapse(error)
10839
- // Settlement and completion errors after successful creation cannot
10840
- // release the claim. A later tick settles the retained creation identity.
10841
- if (established) throw error
10842
- const errors: unknown[] = [error]
10843
- attempt.error =
10844
- (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
10845
- 'unknown preparation failure'
10846
- attempt.stage = stage
10847
- try {
10848
- await store.appendRepo(this.deps.repo, {
10849
- actor: DISPATCHER,
10850
- type: 'ticket-preparation.failed',
10851
- payload: {
10852
- attempt: attempt.attempt,
10853
- ticket: attempt.ticket,
10854
- stage,
10855
- claimed: attempt.claimed,
10856
- handback: attempt.handback ?? attempt.readyState,
10857
- error: attempt.error,
10858
- },
10859
- })
10860
- } catch (diagnosticError) {
10861
- errors.push(diagnosticError)
10862
- }
10863
- try {
10864
- await this.recoverTicketPreparation(attempt)
10865
- } catch (recoveryError) {
10866
- errors.push(recoveryError)
10867
- }
10868
- throw new AggregateError(
10869
- errors,
10870
- `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
10871
- )
11246
+ stage = 'bounce'
11247
+ await this.bounce(ticket, conformance.missing, refusals.length > 0)
11248
+ stage = 'handback-report'
11249
+ await this.reportPreparationHandback(attempt, {
11250
+ ticket: ticket.ref,
11251
+ attempt: attempt.attempt,
11252
+ cause: 'spec-bounce',
11253
+ state: attempt.handback,
11254
+ role: 'triage',
11255
+ ...(missing ? { missing } : {}),
11256
+ })
11257
+ await this.preparationResolved(attempt, 'bounced')
11258
+ settle({
11259
+ outcome: 'invalid',
11260
+ detail: `bounced to ${attempt.handback}${
11261
+ conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
11262
+ }`,
11263
+ })
11264
+ report.bounced += 1
11265
+ return 'left'
10872
11266
  }
10873
- report.queued -= 1
10874
- if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
10875
- else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
10876
- const outcome = await this.trackStart(
10877
- this.attemptDispatchCompletion(record, launched, report, {
10878
- ticket,
10879
- body,
10880
- ...(authoredSession !== undefined ? { authoredSession } : {}),
10881
- ...createdSeed,
10882
- }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
11267
+
11268
+ stage = 'naming'
11269
+ const baseSlug = await this.chooseSlugBase(ticket.title, body)
11270
+ const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
11271
+ const slug = await this.uniqueSlug(baseSlug, prefix)
11272
+ const branch = `${prefix}/${slug}`
11273
+ const repoOrigin = await this.resolveRepoOriginOnce()
11274
+ // Recorded only on the store's attestation, so recovery never treats
11275
+ // an unkeyed creation's absence at the derived slug as evidence.
11276
+ const creationKey =
11277
+ (await store.buildCreationIdentity?.()) === 'keyed' ? attempt.attempt : undefined
11278
+ createdSeed = {
11279
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
11280
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
11281
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
11282
+ // Claim-time provenance: the newest durable default fact that agrees
11283
+ // with the launch sample, recorded on `build.created` so the fan-out's
11284
+ // seq comparison sees the claim as already answering that fact — and
11285
+ // so a newer opposite fact (an interleaved toggle) stays strictly
11286
+ // ahead of it and reconciles this build on the next tick (f_b851c0e8).
11287
+ ...(autoMergeSeedFact !== undefined ? { autoMergeDefaultSeq: autoMergeSeedFact.seq } : {}),
11288
+ assets,
11289
+ // Frozen from the same claimed ticket sample as the body (SPEC
11290
+ // "Forge issue links"); later ticket edits never reach this build.
11291
+ ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
11292
+ // Fixed at claim from the same sample: relabelling never changes it.
11293
+ ...this.selectedProfile(ticket),
11294
+ // `manual` is admission-only: a build started by any other request
11295
+ // takes the request's level, every other build its ticket's.
11296
+ ...createdPriorityFields(level),
11297
+ }
11298
+ // `build.created` rides with the record so the pinned assets and the
11299
+ // record exist together or not at all.
11300
+ stage = 'creation-identity'
11301
+ attempt.slug = slug
11302
+ if (creationKey !== undefined) attempt.creationKey = creationKey
11303
+ await store.appendRepo(this.deps.repo, {
11304
+ actor: DISPATCHER,
11305
+ type: 'ticket-preparation.creation-selected',
11306
+ payload: {
11307
+ attempt: attempt.attempt,
11308
+ ticket: attempt.ticket,
11309
+ slug,
11310
+ ...(creationKey !== undefined ? { creationKey } : {}),
11311
+ },
11312
+ })
11313
+ stage = 'create-build'
11314
+ // Tracked from the creation on: `build.created` admits the build, so
11315
+ // a work deadline that cuts anything after it must carry the start.
11316
+ record = await this.trackStart(
11317
+ (async () => {
11318
+ const created = await store
11319
+ .createBuild({
11320
+ slug,
11321
+ repo: this.deps.repo,
11322
+ ticket: ticket.ref,
11323
+ branch,
11324
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
11325
+ ...(creationKey !== undefined ? { creationKey } : {}),
11326
+ created: {
11327
+ actor: DISPATCHER,
11328
+ type: 'build.created',
11329
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
11330
+ },
11331
+ })
11332
+ .catch(async (error: unknown) => {
11333
+ // The deadline may have cut only the acknowledgement: a
11334
+ // committed `build.created` admitted the build, so resolve
11335
+ // the preparation and carry its first provision.
11336
+ if (!this.budgetSpent(this.tickOpts)) throw error
11337
+ const owned = await this.cutCreation(attempt, slug)
11338
+ if (owned === undefined) throw error
11339
+ established = true
11340
+ await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
11341
+ (resolution: unknown) => rethrowAuthorityLapse(resolution),
11342
+ )
11343
+ return this.carryCutFirstDispatch(owned.slug, error)
11344
+ })
11345
+ established = true
11346
+ await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
11347
+ this.carryCutFirstDispatch(created.slug, error),
11348
+ )
11349
+ return created
11350
+ })(),
10883
11351
  )
10884
- // Accepted dispatches: durable boundaries recorded. A deferred outcome
10885
- // means the remote provisioning continuation owns the rest.
10886
- if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
11352
+ settle({ outcome: 'started', slug: record.slug })
11353
+ } catch (error) {
11354
+ // A lapse is not a preparation failure: the successor recovers the
11355
+ // intended attempt through `recoverTicketPreparations`.
11356
+ rethrowAuthorityLapse(error)
11357
+ // Settlement and completion errors after successful creation cannot
11358
+ // release the claim. A later tick settles the retained creation identity.
11359
+ if (established) throw error
11360
+ // The work deadline cut the preparation before `build.created`: carry
11361
+ // the attempt, which resumes first next invocation from its durable
11362
+ // boundaries. Its `workDeadlineAt` stamp is the backstop when this
11363
+ // hint write is lost.
11364
+ if (this.budgetSpent(this.tickOpts)) {
11365
+ await this.notePreparationCarry(
11366
+ attempt.attempt,
11367
+ ticket.ref,
11368
+ `the work deadline cut its preparation (${stage})`,
11369
+ ).catch(() => {})
11370
+ this.pass.carry(input.part, ticket.ref.id)
11371
+ return 'carried'
11372
+ }
11373
+ return this.failPreparation(attempt, stage, error)
11374
+ }
11375
+ const outcome = await this.trackStart(
11376
+ this.attemptDispatchCompletion(record, launched, report, {
11377
+ ticket,
11378
+ body,
11379
+ ...(authoredSession !== undefined ? { authoredSession } : {}),
11380
+ ...createdSeed,
11381
+ }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
11382
+ )
11383
+ // Accepted dispatches: durable boundaries recorded. A deferred outcome
11384
+ // means the remote provisioning continuation owns the rest.
11385
+ if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
11386
+ return 'started'
11387
+ }
11388
+
11389
+ /** A real preparation failure (SPEC §6.3): record it, then recover the
11390
+ * attempt at once, handing a confirmed claim back. Always throws. */
11391
+ private async failPreparation(
11392
+ attempt: TicketPreparation,
11393
+ stage: string,
11394
+ error: unknown,
11395
+ ): Promise<never> {
11396
+ const errors: unknown[] = [error]
11397
+ attempt.error =
11398
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
11399
+ 'unknown preparation failure'
11400
+ attempt.stage = stage
11401
+ try {
11402
+ await this.store.appendRepo(this.deps.repo, {
11403
+ actor: DISPATCHER,
11404
+ type: 'ticket-preparation.failed',
11405
+ payload: {
11406
+ attempt: attempt.attempt,
11407
+ ticket: attempt.ticket,
11408
+ stage,
11409
+ claimed: attempt.claimed,
11410
+ handback: attempt.handback ?? attempt.readyState,
11411
+ error: attempt.error,
11412
+ },
11413
+ })
11414
+ } catch (diagnosticError) {
11415
+ errors.push(diagnosticError)
10887
11416
  }
10888
- if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
10889
- await this.completeScan(checkpoint, report, waiting)
10890
- // The only other place this tick authorizes deferred admissions.
10891
- if (claimLoopCompleted) this.claimsEvaluated = true
11417
+ try {
11418
+ await this.recoverTicketPreparation(attempt)
11419
+ } catch (recoveryError) {
11420
+ errors.push(recoveryError)
10892
11421
  }
11422
+ throw new AggregateError(
11423
+ errors,
11424
+ `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
11425
+ )
11426
+ }
11427
+
11428
+ /** Append an attempt's `intended`, stamped with the work deadline in a
11429
+ * bounded pass, with the admitted level (`attempt.level`). `claimDeferred`
11430
+ * journals an admission made without a claim call. */
11431
+ private async appendIntended(attempt: TicketPreparation, claimDeferred = false): Promise<void> {
11432
+ const deadline = this.tickOpts.deadlineAt
11433
+ const workDeadlineAt = deadline !== undefined ? new Date(deadline).toISOString() : undefined
11434
+ await this.store.appendRepo(this.deps.repo, {
11435
+ actor: DISPATCHER,
11436
+ type: 'ticket-preparation.intended',
11437
+ payload: {
11438
+ attempt: attempt.attempt,
11439
+ ticket: attempt.ticket,
11440
+ readyState: attempt.readyState,
11441
+ claimedState: attempt.claimedState,
11442
+ ...(workDeadlineAt !== undefined ? { workDeadlineAt } : {}),
11443
+ ...(claimDeferred ? { claimDeferred: true as const } : {}),
11444
+ // Admission's level travels with the stamp, so a carried attempt
11445
+ // resumes at the level it was admitted at.
11446
+ ...(workDeadlineAt !== undefined && attempt.level !== undefined
11447
+ ? { level: attempt.level }
11448
+ : {}),
11449
+ },
11450
+ })
11451
+ if (workDeadlineAt !== undefined) attempt.workDeadlineAt = workDeadlineAt
11452
+ if (claimDeferred) attempt.claimDeferred = true
11453
+ else delete attempt.claimDeferred
11454
+ }
11455
+
11456
+ /** Whether a bounded pass has too little time left before its work
11457
+ * deadline to start a ticket preparation. Pure clock arithmetic. */
11458
+ private preparationWontFit(): boolean {
11459
+ const deadline = this.tickOpts.deadlineAt
11460
+ return (
11461
+ deadline !== undefined && deadline - this.deps.clock().getTime() < this.preparationEstimateMs
11462
+ )
11463
+ }
11464
+
11465
+ /** Journal intake's admission of a ticket it has no time to prepare: one
11466
+ * `intended` with `claimDeferred` and no tracker call (#1431). The
11467
+ * unresolved attempt withholds the ticket from later scans, and the next
11468
+ * invocation claims and prepares it first. True when the admission was
11469
+ * journaled. */
11470
+ private deferPreparation(attempt: TicketPreparation, part: PassStagePart): Promise<boolean> {
11471
+ return this.trackStart(
11472
+ (async () => {
11473
+ const remaining = Math.max(0, (this.tickOpts.deadlineAt ?? 0) - this.deps.clock().getTime())
11474
+ try {
11475
+ await this.appendIntended(attempt, true)
11476
+ } catch (error) {
11477
+ rethrowAuthorityLapse(error)
11478
+ if (this.budgetSpent(this.tickOpts)) return false
11479
+ throw error
11480
+ }
11481
+ await this.notePreparationCarry(
11482
+ attempt.attempt,
11483
+ attempt.ticket,
11484
+ `${remaining} ms remain but a ticket preparation needs about ${this.preparationEstimateMs} ms`,
11485
+ )
11486
+ this.pass.carry(part, attempt.ticket.id)
11487
+ return true
11488
+ })(),
11489
+ )
10893
11490
  }
10894
11491
 
10895
11492
  /** Builds whose ticket resolves to `target` under the repository's