@defrex/autobuild 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +61 -11
  3. package/docs/answering-blocked-builds.md +5 -3
  4. package/docs/architecture.md +29 -0
  5. package/docs/configuration.md +16 -8
  6. package/docs/dispatcher-hosting.md +10 -0
  7. package/docs/operating.md +8 -0
  8. package/docs/operator-api.md +1 -1
  9. package/docs/operator-surfaces.md +1 -1
  10. package/docs/remote-store-protocol.md +1 -1
  11. package/docs/troubleshooting.md +35 -1
  12. package/package.json +3 -3
  13. package/packages/core/src/cli/dispatch.ts +105 -5
  14. package/packages/core/src/cli/repository-status.ts +15 -0
  15. package/packages/core/src/config/schema.ts +2 -2
  16. package/packages/core/src/events/policy.ts +2 -0
  17. package/packages/core/src/events/repository.ts +102 -0
  18. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +4 -0
  19. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  20. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/23d33121de6d3325.json +107 -0
  21. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  23. package/packages/core/src/kernel/done-escalations.ts +8 -4
  24. package/packages/core/src/kernel/reducer-revisions.ts +6 -0
  25. package/packages/core/src/kernel/reducer.ts +15 -1
  26. package/packages/core/src/kernel/repository-read-facts.ts +18 -0
  27. package/packages/core/src/ports/workspace/build-execution.ts +9 -1
  28. package/packages/core/src/ports/workspace/vercel-sandbox.ts +99 -12
  29. package/packages/core/src/processes/dispatcher.ts +957 -185
  30. package/packages/core/src/processes/execution-settlement.ts +24 -3
  31. package/packages/core/src/processes/pass-stages.ts +294 -0
  32. package/packages/core/src/processes/tick-publication.ts +1 -0
  33. package/packages/core/src/store/contract.ts +7 -0
  34. package/packages/core/src/store/reducer-value-shapes.json +5733 -5345
  35. package/packages/core/src/store/reducer-value-validation.ts +7 -0
  36. package/packages/core/src/store/remote/released-clients.json +22 -0
  37. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  38. package/packages/core/src/store/remote/released-reducer-values/1.15.0.json +36354 -0
  39. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  40. package/packages/core/src/store/repo-state-events.ts +2 -0
  41. package/packages/core/src/testing/dispatch-read-budget.ts +12 -2
  42. package/packages/core/src/testing/reduced-read-budget.ts +405 -1
  43. package/skills/guide/SKILL.md +29 -9
  44. package/skills/guide/references/operator-api.md +1 -1
  45. package/skills/guide/references/remote-store-protocol.md +1 -1
  46. package/skills/operate/SKILL.md +64 -5
  47. package/templates/hosted-service/package.json +2 -2
@@ -19,6 +19,11 @@ import type {
19
19
  BuildExecutionIdentity,
20
20
  ExecutionObservation,
21
21
  } from '../ports/workspace/build-execution'
22
+ import {
23
+ isRecoveryDeferred,
24
+ recoveryStepOf,
25
+ type WorkspaceRecoveryStep,
26
+ } from '../ports/workspace/recovery-step'
22
27
  import { readBuildFacts } from '../store/reduced-reads'
23
28
  import { defineReducer } from '../kernel/incremental'
24
29
  import type { BuildStore } from '../store/types'
@@ -130,6 +135,10 @@ export interface ExecutionSettlementDeps {
130
135
  execution: BuildExecution
131
136
  /** Trusted publication settlement, invoked only after a recorded completion. */
132
137
  settlePublication?: (slug: string) => Promise<void>
138
+ /** Told when the invocation budget deferred the observation (a `running`
139
+ * observation marked `deferred`, or a thrown recovery deferral). Settlement
140
+ * still returns `running`: a deferral is never exit or loss. */
141
+ onDeferred?: (slug: string, step: WorkspaceRecoveryStep, detail: string) => Promise<void> | void
133
142
  }
134
143
 
135
144
  /** Release the open execution's exact lease, but only while that instance
@@ -162,7 +171,9 @@ export function settleExecution(
162
171
  /** `settleExecution` over an already-derived open execution, for callers that
163
172
  * hold the projection (a reducer snapshot advanced to the log tail) and so
164
173
  * never need the event array. A `running` result or an observation error
165
- * touches no event rows unless the provider also reports actionable attention. */
174
+ * touches no event rows unless the provider also reports actionable attention.
175
+ * An observation the invocation budget deferred reaches `deps.onDeferred`
176
+ * with its step and still reads as `running`. */
166
177
  export async function settleOpenExecution(
167
178
  deps: ExecutionSettlementDeps,
168
179
  slug: string,
@@ -173,7 +184,13 @@ export async function settleOpenExecution(
173
184
  let observation: ExecutionObservation
174
185
  try {
175
186
  observation = await deps.execution.observe(observationIdentity(open))
176
- } catch {
187
+ } catch (error) {
188
+ if (isRecoveryDeferred(error))
189
+ await deps.onDeferred?.(
190
+ slug,
191
+ recoveryStepOf(error) ?? 'resume',
192
+ error instanceof Error ? error.message : String(error),
193
+ )
177
194
  return 'running'
178
195
  }
179
196
  if (observation.attention) {
@@ -192,7 +209,11 @@ export async function settleOpenExecution(
192
209
  },
193
210
  })
194
211
  }
195
- if (observation.state === 'running') return 'running'
212
+ if (observation.state === 'running') {
213
+ if (observation.deferred)
214
+ await deps.onDeferred?.(slug, observation.deferred.step, observation.deferred.detail)
215
+ return 'running'
216
+ }
196
217
 
197
218
  const request = (await readBuildFacts(deps.store, slug)).value.state.drainingExecutions?.[
198
219
  open.instance
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Stage fairness for a bounded dispatcher pass (#1409). Pure: shares, the
3
+ * rotation rule, the per-pass stage record and its rendering. The Dispatcher
4
+ * owns the clock reads and the store writes.
5
+ *
6
+ * A stage that starts at `t` with `R = deadlineAt − t` left may start new
7
+ * items until `t + share × R`; intake runs to the work deadline. Each part (a
8
+ * loop or single-call helper) inside a stage always gets its first item while
9
+ * the work deadline has not passed, so one helper cannot starve its siblings
10
+ * and no stage can consume a whole pass.
11
+ */
12
+ import { PASS_STAGE_NAMES, PASS_STAGE_PART_NAMES, ROTATED_PASS_PARTS } from '../events/repository'
13
+
14
+ export { PASS_STAGE_NAMES, PASS_STAGE_PART_NAMES, ROTATED_PASS_PARTS }
15
+
16
+ export type PassStage = (typeof PASS_STAGE_NAMES)[number]
17
+ export type PassStagePart = (typeof PASS_STAGE_PART_NAMES)[number]
18
+ export type RotatedPassPart = (typeof ROTATED_PASS_PARTS)[number]
19
+ export type PassStop = 'share' | 'deadline'
20
+ export type PassCursors = Partial<Record<RotatedPassPart, string>>
21
+
22
+ /** Each stage's parts, in the order its helpers run. */
23
+ export const PASS_STAGE_PARTS: Record<PassStage, readonly PassStagePart[]> = {
24
+ deferred: ['deferred'],
25
+ settlement: ['executions', 'harvest', 'sandboxes'],
26
+ preparations: ['preparations'],
27
+ janitor: ['janitor'],
28
+ recovery: ['handbacks', 'dispatches', 'resume'],
29
+ sweep: ['waits', 'sweep'],
30
+ admission: ['nodes', 'starts'],
31
+ intake: ['tickets', 'parked', 'starts', 'harvest-trigger', 'context'],
32
+ }
33
+
34
+ /** The share of the time left when a stage starts that it may spend starting
35
+ * new items. Intake's 1 runs it to the work deadline. */
36
+ export const PASS_STAGE_SHARES: Record<PassStage, number> = {
37
+ deferred: 1 / 2,
38
+ settlement: 1 / 4,
39
+ preparations: 1 / 4,
40
+ janitor: 1 / 2,
41
+ recovery: 1 / 4,
42
+ sweep: 1 / 2,
43
+ admission: 1 / 4,
44
+ intake: 1,
45
+ }
46
+
47
+ /** The instant after which `stage` starts no further item, beyond the first
48
+ * one of each of its parts. */
49
+ export function stageCut(stage: PassStage, startedAt: number, deadlineAt: number): number {
50
+ if (stage === 'intake') return deadlineAt
51
+ return startedAt + PASS_STAGE_SHARES[stage] * Math.max(0, deadlineAt - startedAt)
52
+ }
53
+
54
+ /** `items` in canonical key order (plain code-unit comparison), starting at
55
+ * the first key strictly greater than `after` and wrapping around. The
56
+ * listing's own order never matters. */
57
+ export function rotateFrom<T>(items: readonly T[], key: (item: T) => string, after?: string): T[] {
58
+ const sorted = [...items].sort((a, b) => {
59
+ const left = key(a)
60
+ const right = key(b)
61
+ return left < right ? -1 : left > right ? 1 : 0
62
+ })
63
+ if (after === undefined) return sorted
64
+ const start = sorted.findIndex((item) => key(item) > after)
65
+ if (start <= 0) return sorted
66
+ return [...sorted.slice(start), ...sorted.slice(0, start)]
67
+ }
68
+
69
+ /** A rotated loop's next position: cleared once the loop reached every item,
70
+ * the last item it started when it stopped early, and unchanged when it
71
+ * stopped before starting any. */
72
+ export function nextPosition(input: {
73
+ lastStarted: string | undefined
74
+ reachedAll: boolean
75
+ previous: string | undefined
76
+ }): string | undefined {
77
+ if (input.reachedAll) return undefined
78
+ return input.lastStarted ?? input.previous
79
+ }
80
+
81
+ export interface PassStagePartRecord {
82
+ part: PassStagePart
83
+ items: number
84
+ total?: number
85
+ stopped?: PassStop
86
+ }
87
+
88
+ export interface PassStageRecord {
89
+ stage: PassStage
90
+ ms: number
91
+ items: number
92
+ total?: number
93
+ stopped?: PassStop
94
+ parts?: PassStagePartRecord[]
95
+ }
96
+
97
+ function strongest(a: PassStop | undefined, b: PassStop | undefined): PassStop | undefined {
98
+ if (a === 'deadline' || b === 'deadline') return 'deadline'
99
+ return a ?? b
100
+ }
101
+
102
+ /** One stage's record from its parts: items and totals add, a part with no
103
+ * reported total leaves the stage total unknown, and the strongest stop
104
+ * marker wins. `parts` is kept only for a stage with more than one part. */
105
+ export function aggregateStage(
106
+ stage: PassStage,
107
+ ms: number,
108
+ parts: readonly PassStagePartRecord[],
109
+ ): PassStageRecord {
110
+ let items = 0
111
+ let total: number | undefined = 0
112
+ let stopped: PassStop | undefined
113
+ for (const part of parts) {
114
+ items += part.items
115
+ total = total === undefined || part.total === undefined ? undefined : total + part.total
116
+ stopped = strongest(stopped, part.stopped)
117
+ }
118
+ return {
119
+ stage,
120
+ ms: Math.max(0, Math.round(ms)),
121
+ items,
122
+ ...(total !== undefined ? { total } : {}),
123
+ ...(stopped !== undefined ? { stopped } : {}),
124
+ ...(parts.length > 1 ? { parts: parts.map((part) => ({ ...part })) } : {}),
125
+ }
126
+ }
127
+
128
+ const progress = (items: number, total: number | undefined) =>
129
+ total === undefined ? `${items}` : `${items}/${total}`
130
+
131
+ /** The dispatch log's `stages:` summary, for example
132
+ * `settlement 3.1s 6/11 (executions 5/9, harvest 1/2, sandboxes 0/0) · janitor 131.4s 4/12 (share)`. */
133
+ export function formatPassStages(records: readonly PassStageRecord[]): string {
134
+ return records
135
+ .map((record) => {
136
+ const parts = record.parts
137
+ ? ` (${record.parts
138
+ .map(
139
+ (part) =>
140
+ `${part.part} ${progress(part.items, part.total)}${part.stopped ? ` ${part.stopped}` : ''}`,
141
+ )
142
+ .join(', ')})`
143
+ : ''
144
+ const stopped = record.stopped ? ` (${record.stopped})` : ''
145
+ return `${record.stage} ${(record.ms / 1000).toFixed(1)}s ${progress(record.items, record.total)}${parts}${stopped}`
146
+ })
147
+ .join(' · ')
148
+ }
149
+
150
+ const ofTotal = (items: number, total: number | undefined) =>
151
+ total === undefined ? `${items} started` : `${items} of ${total}`
152
+
153
+ /** Where the work deadline stopped a pass: the stage and the part in
154
+ * flight, for example `settlement: harvest 1 of 2 (6 of 11 overall)`.
155
+ * Undefined when no stage stopped at the deadline. */
156
+ export function deadlineStopDetail(records: readonly PassStageRecord[]): string | undefined {
157
+ const record = records.findLast((candidate) => candidate.stopped === 'deadline')
158
+ if (record === undefined) return undefined
159
+ const part = record.parts?.findLast((candidate) => candidate.stopped === 'deadline')
160
+ if (part === undefined) return `${record.stage} (${ofTotal(record.items, record.total)})`
161
+ return (
162
+ `${record.stage}: ${part.part} ${ofTotal(part.items, part.total)} ` +
163
+ `(${ofTotal(record.items, record.total)} overall)`
164
+ )
165
+ }
166
+
167
+ /** The dispatch log's deadline line for a pass the work deadline cut short,
168
+ * for example `work deadline reached during janitor (1 of 1)`. */
169
+ export function formatDeadlineStop(records: readonly PassStageRecord[]): string | undefined {
170
+ const detail = deadlineStopDetail(records)
171
+ return detail === undefined ? undefined : `work deadline reached during ${detail}`
172
+ }
173
+
174
+ interface PartState {
175
+ part: PassStagePart
176
+ items: number
177
+ /** Items the part's gate let start: the first-item rule counts these. */
178
+ started: number
179
+ total?: number
180
+ stopped?: PassStop
181
+ }
182
+
183
+ interface RunningStage {
184
+ stage: PassStage
185
+ startedAt: number
186
+ parts: PartState[]
187
+ current?: PartState
188
+ /** The part whose item started last: the one in flight when a helper
189
+ * returns after the work deadline. */
190
+ lastStarted?: PartState
191
+ }
192
+
193
+ /**
194
+ * The per-pass stage tracker. A stage opens with `begin`; its loops report
195
+ * `total`, `item` and `stop` against a named part, which also becomes the
196
+ * part in flight. Calls made while no stage is open (an unbounded pass) are
197
+ * no-ops.
198
+ */
199
+ export class PassStageTracker {
200
+ readonly records: PassStageRecord[] = []
201
+ private running: RunningStage | undefined
202
+
203
+ constructor(private readonly clock: () => number) {}
204
+
205
+ begin(stage: PassStage): void {
206
+ this.running = { stage, startedAt: this.clock(), parts: [] }
207
+ }
208
+
209
+ /** `part` of the running stage, opened if new, and made the part in flight. */
210
+ private enter(part: PassStagePart): PartState | undefined {
211
+ const running = this.running
212
+ if (running === undefined) return undefined
213
+ let state = running.parts.find((candidate) => candidate.part === part)
214
+ if (state === undefined) {
215
+ state = { part, items: 0, started: 0 }
216
+ running.parts.push(state)
217
+ }
218
+ running.current = state
219
+ return state
220
+ }
221
+
222
+ /** Add `n` to `part`'s total. */
223
+ total(part: PassStagePart, n: number): void {
224
+ const state = this.enter(part)
225
+ if (state !== undefined) state.total = (state.total ?? 0) + n
226
+ }
227
+
228
+ /** Count one item `part` reached; `started` when its gate let it start (a
229
+ * cheap skip is reached, not started). */
230
+ item(part: PassStagePart, started = true): void {
231
+ const state = this.enter(part)
232
+ if (state === undefined) return
233
+ state.items++
234
+ if (started) {
235
+ state.started++
236
+ this.running!.lastStarted = state
237
+ }
238
+ }
239
+
240
+ /** Items `part` of the running stage has started this pass. */
241
+ started(part: PassStagePart): number {
242
+ return this.running?.parts.find((candidate) => candidate.part === part)?.started ?? 0
243
+ }
244
+
245
+ stop(part: PassStagePart, stopped: PassStop): void {
246
+ const state = this.enter(part)
247
+ if (state !== undefined) state.stopped = strongest(state.stopped, stopped)
248
+ }
249
+
250
+ /** Close the running stage into `records`. */
251
+ /** `deadline` when the stage's helpers returned after the work deadline:
252
+ * the item that crossed it, the last one started, had no later gate to
253
+ * mark it, so it is marked here and the stage closes stopped by the
254
+ * deadline. */
255
+ end(deadline = false): void {
256
+ const running = this.running
257
+ if (running === undefined) return
258
+ if (deadline && !running.parts.some((part) => part.stopped === 'deadline')) {
259
+ const crossed = running.lastStarted ?? running.current
260
+ if (crossed !== undefined) crossed.stopped = 'deadline'
261
+ }
262
+ const record = this.close(running)
263
+ this.records.push(deadline ? { ...record, stopped: 'deadline' } : record)
264
+ this.running = undefined
265
+ }
266
+
267
+ /** Every record, with a stage still running closed as stopped by the
268
+ * deadline (its in-flight part too). Never mutates the tracker. */
269
+ summary(): PassStageRecord[] {
270
+ const running = this.running
271
+ if (running === undefined) return this.records.map((record) => structuredClone(record))
272
+ const parts = running.parts.map((part) =>
273
+ part === running.current ? { ...part, stopped: 'deadline' as const } : { ...part },
274
+ )
275
+ const closed = this.close({ ...running, parts })
276
+ return [
277
+ ...this.records.map((record) => structuredClone(record)),
278
+ { ...closed, stopped: 'deadline' },
279
+ ]
280
+ }
281
+
282
+ private close(running: RunningStage): PassStageRecord {
283
+ return aggregateStage(
284
+ running.stage,
285
+ this.clock() - running.startedAt,
286
+ running.parts.map(({ part, items, total, stopped }) => ({
287
+ part,
288
+ items,
289
+ ...(total !== undefined ? { total } : {}),
290
+ ...(stopped !== undefined ? { stopped } : {}),
291
+ })),
292
+ )
293
+ }
294
+ }
@@ -29,6 +29,7 @@ function reportRequiresPublication(
29
29
  if (report[key] !== (previous.payload.counters[key] ?? 0)) return true
30
30
  // Reported once per occurrence, never standing: any one is activity.
31
31
  if (report.agentContextDiagnostics.length > 0) return true
32
+ if (report.deferredDiagnostics.length > 0) return true
32
33
  for (const key of diagnostics) {
33
34
  const before = previous.payload[key] ?? []
34
35
  if (report[key].length !== before.length || report[key].some((value, i) => value !== before[i]))
@@ -1576,6 +1576,7 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
1576
1576
  creationDiagnostics,
1577
1577
  dependencyDiagnostics,
1578
1578
  agentContextDiagnostics,
1579
+ deferredDiagnostics,
1579
1580
  ...counters
1580
1581
  } = emptyTickReport()
1581
1582
  for (let i = 0; i < 20; i++) {
@@ -2286,6 +2287,12 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
2286
2287
  await complete(store, 'de-late')
2287
2288
  await raise(store, 'de-aborted')
2288
2289
  await store.append('de-aborted', { actor: KERNEL, type: 'build.aborted', payload: {} })
2290
+ // The abort closed its escalation, so cleanup's completion lists nothing.
2291
+ await store.append('de-aborted', {
2292
+ actor: DISPATCHER,
2293
+ type: 'build.completed',
2294
+ payload: { outcome: 'abandoned' },
2295
+ })
2289
2296
  await complete(store, 'de-plain')
2290
2297
  expect((await read(store)).builds).toEqual([])
2291
2298
  await raise(store, 'de-late')