@defrex/autobuild 1.19.0 → 1.21.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 (63) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +88 -11
  3. package/docs/architecture.md +48 -8
  4. package/docs/assets/headline-wide.png +0 -0
  5. package/docs/dispatcher-hosting.md +6 -1
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/merge-policy.md +2 -1
  8. package/docs/operator-surfaces.md +1 -1
  9. package/docs/plugin-authoring.md +11 -4
  10. package/docs/process-ownership.md +43 -0
  11. package/docs/remote-store-protocol.md +7 -0
  12. package/docs/restacking.md +11 -2
  13. package/docs/setup.md +7 -2
  14. package/docs/troubleshooting.md +6 -0
  15. package/docs/verification.md +1 -1
  16. package/package.json +3 -3
  17. package/packages/core/src/cli/dashboard/model.ts +1 -0
  18. package/packages/core/src/cli/dashboard/vocabulary.ts +3 -0
  19. package/packages/core/src/cli/dispatch.ts +3 -0
  20. package/packages/core/src/events/repository.ts +45 -1
  21. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3f0c4e6d1d54e5bf.json +92 -0
  23. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/b440840a01ea216f.json +115 -0
  24. package/packages/core/src/kernel/dispatch-capacity.ts +47 -6
  25. package/packages/core/src/kernel/engine.ts +15 -2
  26. package/packages/core/src/kernel/janitor-failure.ts +1 -0
  27. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  28. package/packages/core/src/kernel/repository-read-facts.ts +6 -1
  29. package/packages/core/src/processes/build-runner.ts +67 -7
  30. package/packages/core/src/processes/check-termination.ts +44 -0
  31. package/packages/core/src/processes/dispatcher.ts +472 -57
  32. package/packages/core/src/processes/pass-stages.ts +94 -4
  33. package/packages/core/src/processes/publication-loss.ts +29 -0
  34. package/packages/core/src/processes/repo-view.ts +50 -10
  35. package/packages/core/src/store/contract.ts +43 -0
  36. package/packages/core/src/store/digest.ts +19 -1
  37. package/packages/core/src/store/reducer-value-shapes.json +5605 -5454
  38. package/packages/core/src/store/remote/protocol.ts +3 -0
  39. package/packages/core/src/store/remote/released-clients.json +22 -0
  40. package/packages/core/src/store/remote/released-reducer-values/1.20.0.json +36469 -0
  41. package/packages/core/src/store/remote/released-reducer-values/1.21.0.json +36612 -0
  42. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -14
  43. package/packages/core/src/store/types.ts +5 -0
  44. package/packages/core/src/testing/reduced-read-budget.ts +412 -2
  45. package/skills/code-review/SKILL.md +5 -0
  46. package/skills/finalize/SKILL.md +5 -0
  47. package/skills/guide/SKILL.md +36 -9
  48. package/skills/guide/references/merge-policy.md +2 -1
  49. package/skills/guide/references/plugin-authoring.md +11 -4
  50. package/skills/guide/references/process-ownership.md +43 -0
  51. package/skills/guide/references/remote-store-protocol.md +7 -0
  52. package/skills/guide/references/restacking.md +11 -2
  53. package/skills/guide/references/setup.md +7 -2
  54. package/skills/harvest/SKILL.md +5 -0
  55. package/skills/harvest-review/SKILL.md +5 -0
  56. package/skills/implement/SKILL.md +5 -0
  57. package/skills/judge/SKILL.md +4 -0
  58. package/skills/operate/SKILL.md +12 -0
  59. package/skills/plan/SKILL.md +5 -0
  60. package/skills/plan-review/SKILL.md +5 -0
  61. package/skills/propose/SKILL.md +5 -0
  62. package/skills/reconcile/SKILL.md +5 -0
  63. package/templates/hosted-service/package.json +2 -2
@@ -146,7 +146,10 @@ import {
146
146
  nodeHoldsSlot,
147
147
  nodeRunnerWork,
148
148
  nodeSlotNeed,
149
+ nodeSlotTimeDependent,
150
+ occupiesCapacity,
149
151
  reservedAhead,
152
+ slotRequest,
150
153
  settlementDue,
151
154
  settlementKey,
152
155
  startCapacity,
@@ -404,6 +407,7 @@ import type {
404
407
  BuildStore,
405
408
  Clock,
406
409
  } from '../store/types'
410
+ import { compareChangePositions, type ChangedBuilds } from '../store/build-feed'
407
411
  import { creationBuildSlug } from '../kernel/build-creation'
408
412
  import { preparePinnedAssets } from '../store/ticket-assets'
409
413
  import { resolveRepoOrigin } from '../cli/repo-state'
@@ -422,6 +426,7 @@ import { settleOpenExecution } from './execution-settlement'
422
426
  import { isWorkDigest, RepoViewStore } from './repo-view'
423
427
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
424
428
  import {
429
+ mergedHeadCovers,
425
430
  recordPublicationLossBeforeRelease,
426
431
  settlePublicationFactsBeforeRelease,
427
432
  } from './publication-loss'
@@ -1024,6 +1029,36 @@ interface CarriedPreparation {
1024
1029
  /** Most ticket-preparation attempts one hint carries. */
1025
1030
  const MAX_CARRIED_PREPARATIONS = 8
1026
1031
 
1032
+ /** The occupancy a bounded pass measured when it deferred a parked
1033
+ * admission (#1435): the repository change position read before the
1034
+ * measurement, the builds holding a slot, those requesting one with their
1035
+ * level, and the open nodes whose slot state can change without an event
1036
+ * (`nodeSlotTimeDependent`). The next pass rebuilds occupancy from it and
1037
+ * the builds changed since, without measuring the fleet. */
1038
+ interface ParkedWitness {
1039
+ position: string
1040
+ holders: string[]
1041
+ waiters: { slug: string; level: BuildPriority }[]
1042
+ volatile: string[]
1043
+ }
1044
+
1045
+ /** The hint's carried parked admissions (#1435). */
1046
+ interface ParkedCarry {
1047
+ slugs: string[]
1048
+ witness?: ParkedWitness
1049
+ }
1050
+
1051
+ /** Most parked admissions one hint carries, and the witness bounds past
1052
+ * which the next pass falls back to the ordinary sweep visit. */
1053
+ const MAX_CARRIED_ADMISSIONS = 64
1054
+ const MAX_WITNESS_HOLDERS = 256
1055
+ const MAX_WITNESS_WAITERS = 64
1056
+ const MAX_WITNESS_VOLATILE = 64
1057
+
1058
+ function parkedCarryLine(slug: string, level: BuildPriority): string {
1059
+ return `build ${slug} (${level}): parked admission carried to the next pass — this pass's intake did not decide claims`
1060
+ }
1061
+
1027
1062
  /** What one ticket preparation reached: a build `started`; the ticket `left`
1028
1063
  * the queue without a build (claim refused or bounced); it was `blocked` by
1029
1064
  * a blocker the claim found; the work deadline `carried` it to the next
@@ -1551,6 +1586,26 @@ export class Dispatcher {
1551
1586
  * "Slot admission order"). Nothing was written for them;
1552
1587
  * `admitDeferredParked` retries each through its generic path. */
1553
1588
  private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1589
+ /** Per bounded tick: parked leaves this tick deferred whose retry has not
1590
+ * run, with their level (#1435). Whatever remains when the pass ends is
1591
+ * carried to the next pass (`finalizeParkedCarries`). */
1592
+ private readonly pendingParkedRetries = new Map<string, BuildPriority>()
1593
+ /** Per bounded tick: parked leaves this tick carried to the next pass. */
1594
+ private readonly tickParkedCarries = new Map<string, BuildPriority>()
1595
+ /** Per bounded tick: the repository change position, read once before the
1596
+ * first parked admission's capacity measurement. */
1597
+ private tickPosition: string | undefined
1598
+ /** Per bounded tick: the occupancy the latest deferring measurement saw. */
1599
+ private tickWitness: ParkedWitness | undefined
1600
+ /** Per bounded tick, in carried order: the hint's carried parked
1601
+ * admissions. Their admission boundary stays closed for the whole pass;
1602
+ * one is `decided` once admission evaluated it this pass. */
1603
+ private readonly carriedParked = new Map<string, { decided: boolean }>()
1604
+ /** Per bounded tick: the hint's witness for the carried admissions. */
1605
+ private carriedWitness: ParkedWitness | undefined
1606
+ private parkedCarriesFinalized = false
1607
+ /** The hint's `parked` entry as last read or written. */
1608
+ private recordedParked: ParkedCarry | undefined
1554
1609
  /** Nodes `admitWaitingNodes` admitted in its current verification pass, so
1555
1610
  * proposer admission counts them even when provisioning or launch failed. */
1556
1611
  private passNodeAdmissions: Set<string> | undefined
@@ -1792,8 +1847,13 @@ export class Dispatcher {
1792
1847
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1793
1848
  : this.runTick(opts))
1794
1849
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1795
- // Every early return of `runTick` still leaves its positions.
1796
- if (opts.deadlineAt !== undefined) await this.persistPassCursors()
1850
+ // Every early return of `runTick` carries the parked admissions it
1851
+ // deferred and did not retry, and leaves its positions.
1852
+ if (opts.deadlineAt !== undefined) {
1853
+ this.finalizeParkedCarries()
1854
+ await this.persistDeferrals()
1855
+ await this.persistPassCursors()
1856
+ }
1797
1857
  this.finishDeferrals(report)
1798
1858
  report.janitorDiagnostics.push(...this.tickAbandonments)
1799
1859
  const stages = opts.deadlineAt === undefined ? [] : this.pass.summary()
@@ -1851,6 +1911,13 @@ export class Dispatcher {
1851
1911
  this.startBarrier = undefined
1852
1912
  this.parkedSettled.clear()
1853
1913
  this.deferredAdmissions.clear()
1914
+ this.pendingParkedRetries.clear()
1915
+ this.tickParkedCarries.clear()
1916
+ this.tickPosition = undefined
1917
+ this.tickWitness = undefined
1918
+ this.carriedParked.clear()
1919
+ this.carriedWitness = undefined
1920
+ this.parkedCarriesFinalized = false
1854
1921
  this.tickDeferrals.clear()
1855
1922
  this.reportedDeferrals.clear()
1856
1923
  this.deferralsFinished = false
@@ -1883,6 +1950,15 @@ export class Dispatcher {
1883
1950
  for (const { ticket, attempt } of this.recordedPreparationCarries)
1884
1951
  if (!this.carriedPreparationsOutstanding.has(attempt))
1885
1952
  this.carriedPreparationsOutstanding.set(attempt, { ticket, visited: false })
1953
+ // Carried parked admissions (#1435): only a bounded pass decides them;
1954
+ // an unbounded one keeps the entry as it is.
1955
+ this.recordedParked =
1956
+ deferredWork?.parked === undefined ? undefined : structuredClone(deferredWork.parked)
1957
+ if (opts.deadlineAt !== undefined && this.recordedParked !== undefined) {
1958
+ for (const slug of this.recordedParked.slugs)
1959
+ if (!this.carriedParked.has(slug)) this.carriedParked.set(slug, { decided: false })
1960
+ this.carriedWitness = this.recordedParked.witness
1961
+ }
1886
1962
  // The rotated loops' positions, from the same reduced facts: no read.
1887
1963
  this.passCursors =
1888
1964
  opts.deadlineAt === undefined
@@ -2142,6 +2218,8 @@ export class Dispatcher {
2142
2218
  report.preparationsCarried = this.tickPreparationCarries.size
2143
2219
  for (const { ticket, detail } of this.tickPreparationCarries.values())
2144
2220
  report.deferredDiagnostics.push(preparationCarryLine(ticket, detail))
2221
+ for (const [slug, level] of this.tickParkedCarries)
2222
+ report.deferredDiagnostics.push(parkedCarryLine(slug, level))
2145
2223
  }
2146
2224
  return { ...report, stages: this.pass.summary() }
2147
2225
  }
@@ -4043,6 +4121,7 @@ export class Dispatcher {
4043
4121
  if (
4044
4122
  state.status === 'done' &&
4045
4123
  digest.reclaimPending !== true &&
4124
+ digest.releasePending !== true &&
4046
4125
  digest.integrationAuditPending !== true
4047
4126
  )
4048
4127
  return
@@ -4100,7 +4179,13 @@ export class Dispatcher {
4100
4179
  undefined,
4101
4180
  )
4102
4181
  : undefined
4103
- if (state.kind === 'node' && !controlDue && pollSchedule && !pollSchedule.due) {
4182
+ if (
4183
+ state.kind === 'node' &&
4184
+ !controlDue &&
4185
+ digest.releasePending !== true &&
4186
+ pollSchedule &&
4187
+ !pollSchedule.due
4188
+ ) {
4104
4189
  attempted = false
4105
4190
  return
4106
4191
  }
@@ -4221,6 +4306,20 @@ export class Dispatcher {
4221
4306
  )
4222
4307
  }
4223
4308
  if (state.status === 'done') {
4309
+ // A merged build's workspace release is a post-terminal duty: its
4310
+ // completion never waited on it (§15.7).
4311
+ if (
4312
+ digest.releasePending === true &&
4313
+ state.prState === 'merged' &&
4314
+ !executionLeaseLive
4315
+ ) {
4316
+ operation = 'merged workspace release'
4317
+ await this.releaseMergedWorkspace(
4318
+ record,
4319
+ state.mergedSha !== undefined ? { sha: state.mergedSha } : {},
4320
+ this.forgeWorkspacePathOf(workspace),
4321
+ )
4322
+ }
4224
4323
  if (digest.reclaimPending === true) {
4225
4324
  operation = 'PR attachment reclaim'
4226
4325
  await this.reclaimPrAttachments(record.slug, await history())
@@ -4299,7 +4398,8 @@ export class Dispatcher {
4299
4398
  }
4300
4399
  }
4301
4400
  if ((state.status === 'paused' || janitorBlocked(state)) && !state.pr) return
4302
- if (state.nodeOpened && state.baseBranch) {
4401
+ // A merged PR has nothing left to restack onto the target.
4402
+ if (state.nodeOpened && state.baseBranch && state.prState !== 'merged') {
4303
4403
  operation = 'target observation'
4304
4404
  if (
4305
4405
  await this.observeTarget(
@@ -4394,7 +4494,9 @@ export class Dispatcher {
4394
4494
  if (
4395
4495
  state.kind !== 'node' &&
4396
4496
  state.status !== 'aborted' &&
4397
- janitorStatus(state) !== 'queued'
4497
+ janitorStatus(state) !== 'queued' &&
4498
+ // A merged PR has nothing left to restack onto the target.
4499
+ state.prState !== 'merged'
4398
4500
  ) {
4399
4501
  const branch = await readBuildSelector(this.store, record.slug, 'baseBranch')
4400
4502
  if (branch !== undefined) {
@@ -4921,30 +5023,41 @@ export class Dispatcher {
4921
5023
  ? ((allocatedLeaf ? this.store.retainedBuildFacts(record.slug) : undefined) ??
4922
5024
  (await this.store.servedBuildFacts(record.slug)))
4923
5025
  : await this.store.buildFacts(record.slug)
4924
- // A node's marker no longer holds a slot: it feeds the stranded
4925
- // workspace release, the proposer skip and the anchor of a runner an
4926
- // older dispatcher launched (`legacyNodeRunner`).
4927
- const marker =
4928
- digest.kind === 'node'
4929
- ? served
4930
- ? facts.provisionMarker
4931
- : (await readBuildFacts(this.store, record.slug)).value.provisionMarker
4932
- : undefined
4933
- builds.push({
4934
- record,
4935
- state: facts.state,
4936
- workspace: facts.workspace !== null,
4937
- provisioning:
4938
- digest.kind === 'node'
4939
- ? marker !== undefined
4940
- : this.continuations.has(record.slug) || !!launched?.has(record.slug),
4941
- ...(marker !== undefined ? { provisioningSeq: marker.seq } : {}),
4942
- restackDue: landingRestackDue(facts.state, facts.log),
4943
- })
5026
+ builds.push(await this.capacityBuildOf(record, digest, facts, launched, served))
4944
5027
  }
4945
5028
  return builds
4946
5029
  }
4947
5030
 
5031
+ /** One nonterminal build's `CapacityBuild` from facts already read. */
5032
+ private async capacityBuildOf(
5033
+ record: BuildRecord,
5034
+ digest: BuildDigest,
5035
+ facts: CurrentBuildFacts,
5036
+ launched?: ReadonlySet<string>,
5037
+ served = false,
5038
+ ): Promise<CapacityBuild> {
5039
+ // A node's marker no longer holds a slot: it feeds the stranded
5040
+ // workspace release, the proposer skip and the anchor of a runner an
5041
+ // older dispatcher launched (`legacyNodeRunner`).
5042
+ const marker =
5043
+ digest.kind === 'node'
5044
+ ? served
5045
+ ? facts.provisionMarker
5046
+ : (await readBuildFacts(this.store, record.slug)).value.provisionMarker
5047
+ : undefined
5048
+ return {
5049
+ record,
5050
+ state: facts.state,
5051
+ workspace: facts.workspace !== null,
5052
+ provisioning:
5053
+ digest.kind === 'node'
5054
+ ? marker !== undefined
5055
+ : this.continuations.has(record.slug) || !!launched?.has(record.slug),
5056
+ ...(marker !== undefined ? { provisioningSeq: marker.seq } : {}),
5057
+ restackDue: landingRestackDue(facts.state, facts.log),
5058
+ }
5059
+ }
5060
+
4948
5061
  /** Whether this tick's start barrier holds back admission of this kind at
4949
5062
  * this level (`admissionBarred`): the one guard waiting work (parked
4950
5063
  * leaves, nodes and proposers through `slotAdmission`), ordinary claims and
@@ -5005,7 +5118,9 @@ export class Dispatcher {
5005
5118
  * order"): for each level, urgent first, its parked work and then its
5006
5119
  * claims. `occupied` counts every other build holding a slot. A waiter
5007
5120
  * defers while claims can run, this tick's dispatch has not yet evaluated
5008
- * them, and a higher-level claim can exist (`higherClaimsPossible`). */
5121
+ * them, and a higher-level claim can exist (`higherClaimsPossible`). A
5122
+ * parked admission an earlier bounded pass carried never defers again
5123
+ * (#1435): it is decided against the latest durable claim demand. */
5009
5124
  private slotAdmission(
5010
5125
  slug: string,
5011
5126
  priority: BuildPriority,
@@ -5018,6 +5133,7 @@ export class Dispatcher {
5018
5133
  return 'wait'
5019
5134
  const boundary =
5020
5135
  this.admissionBoundary &&
5136
+ !this.carriedParked.has(slug) &&
5021
5137
  this.claimsCanRun({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused) &&
5022
5138
  this.higherClaimsPossible(priority, builds)
5023
5139
  return boundary ? 'defer' : 'admit'
@@ -5035,8 +5151,18 @@ export class Dispatcher {
5035
5151
  * unless one is already in flight or another runner's live lease will
5036
5152
  * refuse this launch; an acknowledgement appends none. A denial or
5037
5153
  * deferral is recorded only in memory, for this tick's intake reservation;
5038
- * a deferral is retried after this tick's dispatch. */
5039
- private async leafAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
5154
+ * a deferral is retried after this tick's dispatch, and a bounded pass
5155
+ * whose retry does not run carries it to the next pass (#1435).
5156
+ * `measured` is the occupancy a carried admission rebuilt
5157
+ * (`serviceCarriedAdmissions`), used instead of measuring the fleet; an
5158
+ * admission updates its own entry in place. */
5159
+ private async leafAdmission(
5160
+ slug: string,
5161
+ measured?: CapacityBuild[],
5162
+ ): Promise<'admit' | 'wait' | 'defer'> {
5163
+ const carried = this.carriedParked.get(slug)
5164
+ if (carried !== undefined) carried.decided = true
5165
+ this.pendingParkedRetries.delete(slug)
5040
5166
  const facts = await this.store.buildFacts(slug)
5041
5167
  const { state } = facts
5042
5168
  const self = { state, restackDue: landingRestackDue(state, facts.log) }
@@ -5064,7 +5190,16 @@ export class Dispatcher {
5064
5190
  )
5065
5191
  )
5066
5192
  return 'admit'
5067
- const builds = await this.capacityBuilds(this.tickLaunched)
5193
+ // A merged leaf never takes a slot (§12): its completion and cleanup are
5194
+ // the janitor's, and nothing a runner could do remains. Not a slot
5195
+ // waiter either, so it reserves no intake.
5196
+ if (state.prState === 'merged') return 'wait'
5197
+ const bounded = this.tickOpts.deadlineAt !== undefined
5198
+ // The position precedes the measurement, so the next pass's
5199
+ // changed-builds feed covers every change the measurement could miss.
5200
+ if (bounded && measured === undefined && this.tickPosition === undefined)
5201
+ this.tickPosition = await this.store.getRepoChangePosition(this.deps.repo)
5202
+ const builds = measured ?? (await this.capacityBuilds(this.tickLaunched))
5068
5203
  const others = builds.filter((build) => build.record.slug !== slug)
5069
5204
  const capacity = this.deps.config.capacity
5070
5205
  const now = this.deps.clock()
@@ -5088,20 +5223,55 @@ export class Dispatcher {
5088
5223
  })
5089
5224
  if (admitted !== null) {
5090
5225
  this.slotWaiters.delete(slug)
5226
+ this.pass.admission('admitted', slug, priority)
5091
5227
  // Retain the admitted facts, so this tick's capacity counts the
5092
5228
  // build as holding its slot from here on.
5093
- await this.store.servedBuildFacts(slug)
5229
+ const served = await this.store.servedBuildFacts(slug)
5230
+ const entry = measured?.find((build) => build.record.slug === slug)
5231
+ if (entry !== undefined) entry.state = served.state
5094
5232
  return 'admit'
5095
5233
  }
5096
5234
  // The state moved under the decision: decide again next tick.
5097
5235
  outcome = 'wait'
5098
5236
  }
5099
5237
  this.slotWaiters.set(slug, priority)
5100
- if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
5101
- this.deferredAdmissions.set(slug, 'leaf')
5238
+ if (outcome === 'defer') {
5239
+ if (!this.deferredAdmissions.has(slug)) this.deferredAdmissions.set(slug, 'leaf')
5240
+ this.pass.admission('deferred', slug, priority)
5241
+ if (bounded) {
5242
+ this.pendingParkedRetries.set(slug, priority)
5243
+ this.tickWitness = this.witnessOf(builds, now)
5244
+ }
5245
+ }
5102
5246
  return outcome
5103
5247
  }
5104
5248
 
5249
+ /** The occupancy one capacity measurement saw, as the carry hint records
5250
+ * it (#1435); undefined without a position or past the witness bounds. */
5251
+ private witnessOf(builds: readonly CapacityBuild[], now: Date): ParkedWitness | undefined {
5252
+ const position = this.tickPosition
5253
+ if (position === undefined) return undefined
5254
+ const bySlug = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
5255
+ const holders: string[] = []
5256
+ const waiters: ParkedWitness['waiters'] = []
5257
+ const volatile: string[] = []
5258
+ for (const build of builds) {
5259
+ const slug = build.record.slug
5260
+ if (occupiesCapacity(build, now)) holders.push(slug)
5261
+ else if (slotRequest(build, now) !== undefined)
5262
+ waiters.push({ slug, level: buildPriority(build.state) })
5263
+ else if (nodeSlotTimeDependent(build.state)) volatile.push(slug)
5264
+ }
5265
+ if (
5266
+ holders.length > MAX_WITNESS_HOLDERS ||
5267
+ waiters.length > MAX_WITNESS_WAITERS ||
5268
+ volatile.length > MAX_WITNESS_VOLATILE
5269
+ )
5270
+ return undefined
5271
+ waiters.sort((a, b) => priorityRank(a.level) - priorityRank(b.level) || bySlug(a.slug, b.slug))
5272
+ return { position, holders: holders.sort(bySlug), waiters, volatile: volatile.sort(bySlug) }
5273
+ }
5274
+
5105
5275
  /**
5106
5276
  * Retry every admission deferred this tick, once this tick's admission scan
5107
5277
  * has evaluated claims at every level. Each retry re-enters its generic path with
@@ -5131,10 +5301,15 @@ export class Dispatcher {
5131
5301
  this.pass.total('parked', deferred.length)
5132
5302
  for (const [slug, kind] of deferred) {
5133
5303
  if (!this.passItem(opts, 'parked')) return
5134
- if (launched.has(slug)) continue
5304
+ if (launched.has(slug)) {
5305
+ this.pendingParkedRetries.delete(slug)
5306
+ continue
5307
+ }
5135
5308
  try {
5136
5309
  const record = await this.store.getBuild(slug)
5137
5310
  if (record === null) continue
5311
+ // The retry runs: nothing is carried for it (#1435).
5312
+ this.pendingParkedRetries.delete(slug)
5138
5313
  if (kind === 'leaf')
5139
5314
  await this.sweepBuild(record, report, launched, paused, this.deps.clock().getTime())
5140
5315
  else if (kind === 'node') {
@@ -6899,7 +7074,13 @@ export class Dispatcher {
6899
7074
  }
6900
7075
  source.observed?.(prState)
6901
7076
  if (state.prState === 'merged' && state.mergedSha)
6902
- prState = { state: 'merged', sha: state.mergedSha }
7077
+ prState = {
7078
+ state: 'merged',
7079
+ sha: state.mergedSha,
7080
+ ...(prState.state === 'merged' && prState.headSha !== undefined
7081
+ ? { headSha: prState.headSha }
7082
+ : {}),
7083
+ }
6903
7084
  let nativeCancelled = false
6904
7085
  if (
6905
7086
  nodeTarget &&
@@ -7747,7 +7928,6 @@ export class Dispatcher {
7747
7928
  // A merged attempt settles `accepted` with the measurement of the
7748
7929
  // head that landed, before the build can become terminal.
7749
7930
  if (nodeTarget) await this.settleMergedAttempt(record, state, prState.sha)
7750
- await this.releaseWorkspace(record.slug, events)
7751
7931
  if (record.ticket) {
7752
7932
  await tickets.transition(await this.currentTicketId(record), this.doneState)
7753
7933
  await tickets.comment(
@@ -7755,6 +7935,10 @@ export class Dispatcher {
7755
7935
  `build ${record.slug} merged: ${pr.url}`,
7756
7936
  )
7757
7937
  }
7938
+ // Complete before any workspace work: the merged commit is on the
7939
+ // target, so a stopped or unreachable workspace never holds the
7940
+ // build open (§15.7). Its release follows and, when it cannot
7941
+ // finish, stays pending on the completed build (`releasePending`).
7758
7942
  await store.append(record.slug, {
7759
7943
  actor: DISPATCHER,
7760
7944
  type: 'build.completed',
@@ -7762,6 +7946,7 @@ export class Dispatcher {
7762
7946
  } satisfies EventWrite<'build.completed'>)
7763
7947
  await this.reclaimPrAttachments(record.slug, events)
7764
7948
  report.merged += 1
7949
+ await this.releaseMergedWorkspace(record, prState, workspacePath)
7765
7950
  return
7766
7951
  }
7767
7952
  case 'closed': {
@@ -8182,12 +8367,6 @@ export class Dispatcher {
8182
8367
  // No live provider can act on this ref; leave the fact open rather than
8183
8368
  // claim a release that never happened.
8184
8369
  if (owner === null) return undefined
8185
- const handle = {
8186
- provider: open.provider,
8187
- ref: open.ref,
8188
- path: open.path ?? open.ref,
8189
- branch: open.branch,
8190
- }
8191
8370
  // Last-chance settlement boundary (AUT-328): settle or durably record the
8192
8371
  // pending publication BEFORE any provider cleanup call, while the
8193
8372
  // workspace still exists. The guard's append failure propagates — the
@@ -8221,6 +8400,28 @@ export class Dispatcher {
8221
8400
  reason,
8222
8401
  )
8223
8402
  }
8403
+ return this.cleanupAndRelease(slug, open, owner, events, reason, { recordFailure: true })
8404
+ }
8405
+
8406
+ /** The provider cleanup every release ends with: reap (recording the
8407
+ * attempt) or release, then `workspace.released`. A deadline deferral
8408
+ * records nothing and propagates. Any other reap failure records the
8409
+ * unknown cleanup attempt, and with `recordFailure` also charges the
8410
+ * build's infrastructure-failure budget, then propagates. */
8411
+ private async cleanupAndRelease(
8412
+ slug: string,
8413
+ open: OpenBuildWorkspace,
8414
+ owner: WorkspaceProvider,
8415
+ events: CurrentBuildFacts,
8416
+ reason: 'completion' | 'abort' | 'pause' | 'blocked' | 'replacement' | 'discard',
8417
+ options: { recordFailure: boolean },
8418
+ ): Promise<AbEvent> {
8419
+ const handle = {
8420
+ provider: open.provider,
8421
+ ref: open.ref,
8422
+ path: open.path ?? open.ref,
8423
+ branch: open.branch,
8424
+ }
8224
8425
  const recovery = owner.recovery
8225
8426
  if (recovery !== undefined) {
8226
8427
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
@@ -8259,13 +8460,14 @@ export class Dispatcher {
8259
8460
  },
8260
8461
  })
8261
8462
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
8262
- await this.recordInfrastructureFailure(slug, events, {
8263
- provider: open.provider,
8264
- workspaceRef: open.ref,
8265
- operation: 'delete',
8266
- error: failure,
8267
- cleanupPending: true,
8268
- })
8463
+ if (options.recordFailure)
8464
+ await this.recordInfrastructureFailure(slug, events, {
8465
+ provider: open.provider,
8466
+ workspaceRef: open.ref,
8467
+ operation: 'delete',
8468
+ error: failure,
8469
+ cleanupPending: true,
8470
+ })
8269
8471
  throw error
8270
8472
  }
8271
8473
  } else {
@@ -8278,6 +8480,63 @@ export class Dispatcher {
8278
8480
  } satisfies EventWrite<'workspace.released'>)
8279
8481
  }
8280
8482
 
8483
+ /** Release a merged build's workspace (SPEC §15.7). The merged commit is on
8484
+ * the target, so nothing is fenced, preserved or resumed. A pending
8485
+ * publication the merged PR already contains is recorded lost without
8486
+ * settlement; one it does not contain is settled as every release does.
8487
+ * Runs after `build.completed`: a deferral or failure here leaves the build
8488
+ * completed with `releasePending` in its digest, and the janitor retries it
8489
+ * under janitor-failure backoff. Log-deduped, so re-runs are no-ops. */
8490
+ private async releaseMergedWorkspace(
8491
+ record: BuildRecord,
8492
+ merged: { sha?: string; headSha?: string },
8493
+ path: string,
8494
+ ): Promise<void> {
8495
+ const slug = record.slug
8496
+ let facts = (await readBuildFacts(this.store, slug)).value
8497
+ const open = openWorkspace(facts)
8498
+ if (open === null) return
8499
+ const owner = this.workspaceOwner(open)
8500
+ if (owner === null)
8501
+ throw new Error(
8502
+ `merged workspace ${open.ref} has no configured provider "${open.provider}"; cleanup stays pending`,
8503
+ )
8504
+ // A live runner still owns the workspace; the next visit releases it.
8505
+ if (this.hasLiveExecutionLease(record)) return
8506
+ const request = facts.publication.latestUncompletedRequest()
8507
+ if (request !== undefined && !facts.publication.lostRecorded(request)) {
8508
+ let headSha = merged.headSha
8509
+ const pr = facts.state.pr
8510
+ if (headSha === undefined && pr !== undefined) {
8511
+ const observed = await this.deps.forge.getPrState(path, pr.number)
8512
+ if (observed.state === 'merged') headSha = observed.headSha
8513
+ }
8514
+ const forge = this.deps.forge
8515
+ const covered = await mergedHeadCovers(
8516
+ request.payload.sha,
8517
+ [headSha, merged.sha],
8518
+ forge.isCommitAncestor
8519
+ ? (ancestor, descendant) => forge.isCommitAncestor!(ancestor, descendant)
8520
+ : undefined,
8521
+ )
8522
+ facts = covered
8523
+ ? await recordPublicationLossBeforeRelease(
8524
+ { store: this.store },
8525
+ slug,
8526
+ facts,
8527
+ `completion: merged PR already contains ${request.payload.sha}`,
8528
+ request,
8529
+ )
8530
+ : await settlePublicationFactsBeforeRelease(
8531
+ { store: this.store, settlePublication: this.settlePublication },
8532
+ slug,
8533
+ facts,
8534
+ 'completion',
8535
+ )
8536
+ }
8537
+ await this.cleanupAndRelease(slug, open, owner, facts, 'completion', { recordFailure: false })
8538
+ }
8539
+
8281
8540
  /**
8282
8541
  * One best-effort preservation attempt ahead of an abort release. Only three
8283
8542
  * refusals stop the release: lost repository authority, a mixed-version
@@ -9172,7 +9431,7 @@ export class Dispatcher {
9172
9431
  launched: Set<string>,
9173
9432
  paused: boolean,
9174
9433
  now: number,
9175
- carried?: { facts: CurrentBuildFacts },
9434
+ carried?: { facts: CurrentBuildFacts; measured?: CapacityBuild[] },
9176
9435
  ): Promise<'done' | 'waiting' | 'failed'> {
9177
9436
  try {
9178
9437
  return await this.sweepBuild(record, report, launched, paused, now, carried)
@@ -9233,11 +9492,17 @@ export class Dispatcher {
9233
9492
  opts: TickOpts,
9234
9493
  ): Promise<void> {
9235
9494
  const carriedPreparations = this.carriedPreparationsOutstanding.size
9236
- if (this.carriedOutstanding.size === 0 && carriedPreparations === 0)
9495
+ const carriedAdmissions = this.carriedParked.size
9496
+ if (this.carriedOutstanding.size === 0 && carriedPreparations === 0 && carriedAdmissions === 0)
9237
9497
  return this.pass.total('deferred', 0)
9238
- this.pass.total('deferred', this.carriedOutstanding.size + carriedPreparations)
9498
+ this.pass.total(
9499
+ 'deferred',
9500
+ this.carriedOutstanding.size + carriedPreparations + carriedAdmissions,
9501
+ )
9239
9502
  if (this.carriedOutstanding.size > 0)
9240
9503
  await this.serviceDeferredBuilds(report, launched, paused, opts)
9504
+ // Carried parked admissions (#1435), decided before any stage can be cut.
9505
+ if (carriedAdmissions > 0) await this.serviceCarriedAdmissions(report, launched, paused, opts)
9241
9506
  // Carried ticket preparations (#1431), after the carried builds: each
9242
9507
  // attempt resumes from its durable boundaries, with no fleet read.
9243
9508
  for (const attempt of [...this.carriedPreparationsOutstanding.keys()]) {
@@ -9268,6 +9533,90 @@ export class Dispatcher {
9268
9533
  await this.persistDeferrals()
9269
9534
  }
9270
9535
 
9536
+ /**
9537
+ * Decide the parked admissions the previous bounded pass deferred and did
9538
+ * not retry (#1435), first and without deferring again, against the latest
9539
+ * durable claim demand, start requests and higher-level waiters. Occupancy
9540
+ * is rebuilt from that pass's witness, never by measuring the fleet: one
9541
+ * changed-builds feed call since the witness position (no event rows),
9542
+ * then one reduced read for each witness holder, waiter and time-dependent
9543
+ * node, each build changed since, and each carried waiter. Every other
9544
+ * open build is unchanged since the measurement and its slot state takes
9545
+ * no clock (`nodeSlotTimeDependent`), so it still holds and requests
9546
+ * nothing. An admitted waiter launches through the ordinary sweep pass and
9547
+ * the lease sweep skips it. Without a usable witness (none recorded, or
9548
+ * the feed reports a reset or rejects) nothing is read here: each carried
9549
+ * waiter keeps only its closed boundary, and the sweep decides it on its
9550
+ * ordinary visit.
9551
+ */
9552
+ private async serviceCarriedAdmissions(
9553
+ report: TickReport,
9554
+ launched: Set<string>,
9555
+ paused: boolean,
9556
+ opts: TickOpts,
9557
+ ): Promise<void> {
9558
+ const witness = this.carriedWitness
9559
+ const pending = [...this.carriedParked].filter(([, entry]) => !entry.decided)
9560
+ if (witness === undefined || pending.length === 0) return
9561
+ let changed: ChangedBuilds
9562
+ try {
9563
+ changed = await this.store.listBuildsChangedSince(this.deps.repo, witness.position)
9564
+ } catch (error) {
9565
+ rethrowAuthorityLapse(error)
9566
+ return
9567
+ }
9568
+ if (compareChangePositions(changed.position, witness.position) < 0) return
9569
+ const entries = new Map(
9570
+ (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
9571
+ )
9572
+ const read = new Set([
9573
+ ...witness.holders,
9574
+ ...witness.waiters.map((waiter) => waiter.slug),
9575
+ ...witness.volatile,
9576
+ ...changed.builds.map((build) => build.slug),
9577
+ ...pending.map(([slug]) => slug),
9578
+ ])
9579
+ const measured: CapacityBuild[] = []
9580
+ const facts = new Map<string, CurrentBuildFacts>()
9581
+ for (const slug of read) {
9582
+ const entry = entries.get(slug)
9583
+ if (entry === undefined || entry.digest.terminal !== undefined) continue
9584
+ const current = await this.store.buildFacts(slug)
9585
+ facts.set(slug, current)
9586
+ measured.push(await this.capacityBuildOf(entry.record, entry.digest, current, launched))
9587
+ }
9588
+ const order = pending.map(([slug]) => slug)
9589
+ const waiting: CapacityBuild[] = []
9590
+ for (const slug of order) {
9591
+ const build = measured.find((candidate) => candidate.record.slug === slug)
9592
+ // Terminal or gone: retired.
9593
+ if (build === undefined || build.state.kind === 'node') this.carriedParked.delete(slug)
9594
+ else waiting.push(build)
9595
+ }
9596
+ waiting.sort(
9597
+ (a, b) =>
9598
+ priorityRank(buildPriority(a.state)) - priorityRank(buildPriority(b.state)) ||
9599
+ order.indexOf(a.record.slug) - order.indexOf(b.record.slug),
9600
+ )
9601
+ for (const build of waiting) {
9602
+ const slug = build.record.slug
9603
+ const entry = this.carriedParked.get(slug)
9604
+ if (entry === undefined || entry.decided) continue
9605
+ if (!this.passItem(opts, 'deferred')) break
9606
+ entry.decided = true
9607
+ if (launched.has(slug)) continue
9608
+ this.tickPrioritized.add(slug)
9609
+ await this.sweepContained(
9610
+ build.record,
9611
+ report,
9612
+ launched,
9613
+ paused,
9614
+ this.deps.clock().getTime(),
9615
+ { facts: facts.get(slug)!, measured },
9616
+ )
9617
+ }
9618
+ }
9619
+
9271
9620
  /** The carried builds of `serviceDeferredWork`. */
9272
9621
  private async serviceDeferredBuilds(
9273
9622
  report: TickReport,
@@ -9508,6 +9857,12 @@ export class Dispatcher {
9508
9857
  * tick report would. No reads; never rejects. */
9509
9858
  async settleCutStarts(): Promise<string[]> {
9510
9859
  while (this.startsInFlight.size > 0) await Promise.allSettled([...this.startsInFlight])
9860
+ // An abandoned pass carries the parked admissions it deferred (#1435);
9861
+ // the write goes through the teardown scope.
9862
+ if (this.tickOpts.deadlineAt !== undefined && this.inFlightReport !== undefined) {
9863
+ this.finalizeParkedCarries()
9864
+ await this.persistDeferrals().catch(() => {})
9865
+ }
9511
9866
  await this.deferralWrites
9512
9867
  const lines: string[] = []
9513
9868
  for (const [slug, deferral] of this.tickDeferrals) {
@@ -9516,9 +9871,55 @@ export class Dispatcher {
9516
9871
  lines.push(deferralLine(slug, deferral))
9517
9872
  }
9518
9873
  lines.push(...this.unreportedPreparationCarries())
9874
+ lines.push(...this.unreportedParkedCarries())
9519
9875
  return lines
9520
9876
  }
9521
9877
 
9878
+ /** This tick's carried parked admissions not yet named in a report or
9879
+ * teardown line, each marked reported. */
9880
+ private unreportedParkedCarries(): string[] {
9881
+ const lines: string[] = []
9882
+ for (const [slug, level] of this.tickParkedCarries) {
9883
+ const key = `parked:${slug}`
9884
+ if (this.reportedDeferrals.has(key)) continue
9885
+ this.reportedDeferrals.add(key)
9886
+ lines.push(parkedCarryLine(slug, level))
9887
+ }
9888
+ return lines
9889
+ }
9890
+
9891
+ /** Carry every parked admission this bounded pass deferred and did not
9892
+ * retry to the next pass (#1435): named on the stage record and the tick
9893
+ * report, and written with the hint. Once per pass. */
9894
+ private finalizeParkedCarries(): void {
9895
+ if (this.tickOpts.deadlineAt === undefined || this.parkedCarriesFinalized) return
9896
+ this.parkedCarriesFinalized = true
9897
+ for (const [slug, level] of this.pendingParkedRetries) {
9898
+ this.tickParkedCarries.set(slug, level)
9899
+ this.pass.carriedAdmission(slug, level)
9900
+ }
9901
+ this.pendingParkedRetries.clear()
9902
+ }
9903
+
9904
+ /** The hint's `parked` entry this tick would write: carried admissions
9905
+ * this pass has not decided, in carried order, then this pass's carries,
9906
+ * capped. A dropped slug is still a waiter, which a later pass defers and
9907
+ * carries again. The witness is this pass's measurement when it carried
9908
+ * anything new (it describes the fleet, so it serves every slug), else the
9909
+ * carried one. An unbounded tick keeps the entry as read. */
9910
+ private nextParked(): ParkedCarry | undefined {
9911
+ if (this.tickOpts.deadlineAt === undefined) return this.recordedParked
9912
+ const slugs = new Set<string>()
9913
+ for (const [slug, entry] of this.carriedParked) if (!entry.decided) slugs.add(slug)
9914
+ for (const slug of this.tickParkedCarries.keys()) slugs.add(slug)
9915
+ if (slugs.size === 0) return undefined
9916
+ const witness = this.tickParkedCarries.size > 0 ? this.tickWitness : this.carriedWitness
9917
+ return {
9918
+ slugs: [...slugs].slice(0, MAX_CARRIED_ADMISSIONS),
9919
+ ...(witness !== undefined ? { witness } : {}),
9920
+ }
9921
+ }
9922
+
9522
9923
  /** This tick's carried preparations not yet named in a report or teardown
9523
9924
  * line, each marked reported. */
9524
9925
  private unreportedPreparationCarries(): string[] {
@@ -9628,7 +10029,9 @@ export class Dispatcher {
9628
10029
  const recorded = this.recordedDeferrals
9629
10030
  const tickets = this.nextPreparationCarryList()
9630
10031
  const recordedTickets = this.recordedPreparationCarries
10032
+ const parked = this.nextParked()
9631
10033
  if (
10034
+ JSON.stringify(parked ?? null) === JSON.stringify(this.recordedParked ?? null) &&
9632
10035
  next.length === recorded.length &&
9633
10036
  next.every(
9634
10037
  (entry, i) =>
@@ -9650,12 +10053,17 @@ export class Dispatcher {
9650
10053
  actor: DISPATCHER,
9651
10054
  type: 'dispatcher.work-deferred',
9652
10055
  // A hint without carried preparations keeps its earlier payload.
9653
- payload: { builds: next, ...(tickets.length > 0 ? { tickets } : {}) },
10056
+ payload: {
10057
+ builds: next,
10058
+ ...(tickets.length > 0 ? { tickets } : {}),
10059
+ ...(parked !== undefined ? { parked } : {}),
10060
+ },
9654
10061
  }),
9655
10062
  )
9656
10063
  if (outcome === true) {
9657
10064
  this.recordedDeferrals = next
9658
10065
  this.recordedPreparationCarries = tickets
10066
+ this.recordedParked = parked
9659
10067
  } else if (outcome !== false) this.deferralWriteFailure = outcome
9660
10068
  })
9661
10069
  this.deferralWrites = write.catch(() => {})
@@ -9725,6 +10133,7 @@ export class Dispatcher {
9725
10133
  if (this.tickPreparationCarries.size > 0)
9726
10134
  report.preparationsCarried = this.tickPreparationCarries.size
9727
10135
  report.deferredDiagnostics.push(...this.unreportedPreparationCarries())
10136
+ report.deferredDiagnostics.push(...this.unreportedParkedCarries())
9728
10137
  if (this.deferralWriteFailure !== undefined)
9729
10138
  report.deferredDiagnostics.push(
9730
10139
  `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
@@ -9796,13 +10205,11 @@ export class Dispatcher {
9796
10205
  launched: Set<string>,
9797
10206
  paused: boolean,
9798
10207
  now: number,
9799
- carried?: { facts: CurrentBuildFacts },
10208
+ carried?: { facts: CurrentBuildFacts; measured?: CapacityBuild[] },
9800
10209
  ): Promise<'done' | 'waiting'> {
9801
10210
  return (await this.sweepBuildPass(record, report, launched, paused, now, carried)) ?? 'done'
9802
10211
  }
9803
10212
 
9804
- /** `carried` is a deferred-work entry's pass: its facts are already read,
9805
- * and the first-claim grace does not apply. */
9806
10213
  /** Settle, in place and without a runner, every session an ended execution
9807
10214
  * left open (SPEC §15.6-C), on running, held and terminal builds alike: an
9808
10215
  * unfinished occurrence with a native handle of a live build is suspended as
@@ -9913,13 +10320,16 @@ export class Dispatcher {
9913
10320
  return wrote
9914
10321
  }
9915
10322
 
10323
+ /** `carried` is a deferred-work entry's pass: its facts are already read,
10324
+ * and the first-claim grace does not apply. A carried parked admission
10325
+ * (#1435) also brings the occupancy it rebuilt (`measured`). */
9916
10326
  private async sweepBuildPass(
9917
10327
  record: BuildRecord,
9918
10328
  report: TickReport,
9919
10329
  launched: Set<string>,
9920
10330
  paused: boolean,
9921
10331
  now: number,
9922
- carried?: { facts: CurrentBuildFacts },
10332
+ carried?: { facts: CurrentBuildFacts; measured?: CapacityBuild[] },
9923
10333
  ): Promise<'waiting' | undefined> {
9924
10334
  if (record.lease) {
9925
10335
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
@@ -10108,7 +10518,12 @@ export class Dispatcher {
10108
10518
  const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
10109
10519
  // A finished leaf with work to run waits for a slot before anything is
10110
10520
  // reaped, provisioned or launched for it.
10111
- if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
10521
+ if (
10522
+ runs &&
10523
+ state.kind !== 'node' &&
10524
+ (await this.leafAdmission(record.slug, carried?.measured)) !== 'admit'
10525
+ )
10526
+ return
10112
10527
  // A node relaunches only for work it holds a slot for: a retained
10113
10528
  // workspace confers none. Abort and pause acknowledgements are ungated.
10114
10529
  if (runs && state.kind === 'node' && !this.nodeRelaunchAdmitted(record, facts)) return