pi-better-subagents 0.26.2 → 0.27.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.
- package/README.md +23 -6
- package/child-operations.ts +1109 -0
- package/child-ownership.ts +12 -1
- package/cleanup.ts +11 -2
- package/docs/usage.md +44 -3
- package/finalization.ts +53 -8
- package/goal-provider.ts +42 -4
- package/index.ts +549 -14
- package/lifecycle.ts +26 -0
- package/navigator.mjs +13 -2
- package/navigator.ts +1 -0
- package/operation-bridge-types.ts +1109 -0
- package/package.json +2 -1
- package/park-checkpoint.ts +61 -0
- package/parse.ts +19 -1
- package/registry.ts +192 -6
- package/session-store.ts +3 -0
- package/shared-execution-policy.ts +2 -0
- package/shared-operation-coordinator/index.ts +113 -0
- package/shared-operation-coordinator/src/errors.ts +75 -0
- package/shared-operation-coordinator/src/operations.ts +376 -0
- package/shared-operation-coordinator/src/outbox.ts +431 -0
- package/shared-operation-coordinator/src/rows.ts +439 -0
- package/shared-operation-coordinator/src/schema.ts +244 -0
- package/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/shared-operation-coordinator/src/store.ts +397 -0
- package/shared-operation-coordinator/src/types.ts +648 -0
- package/shared-operation-coordinator/src/validate.ts +239 -0
- package/shared-operation-coordinator/src/waits.ts +1378 -0
- package/shared-task-exec.ts +9 -0
- package/stop.ts +7 -3
- package/task-guard.ts +22 -3
- package/task-policy.ts +7 -0
- package/worker-operations-host.ts +1226 -0
- package/worker-waits.ts +2549 -0
|
@@ -0,0 +1,1378 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/waits.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* All-settled waits, their phase machine, resume claims, evidence pins and
|
|
4
|
+
* interpretation acknowledgement.
|
|
5
|
+
*
|
|
6
|
+
* The phase machine is deliberately small and every transition names the phase
|
|
7
|
+
* it acts on, so an out-of-order or duplicated call is refused instead of
|
|
8
|
+
* replaying a step. A parked worker cannot reach `waiting`/`ready` without
|
|
9
|
+
* proving its checkpoint was committed and its writer exited; a dependency that
|
|
10
|
+
* settled earlier is not missed, because registration reads the terminal
|
|
11
|
+
* revisions inside its own transaction and resolves straight to `ready`.
|
|
12
|
+
*
|
|
13
|
+
* Fencing: every mutation names the generation and, where cancellation can race,
|
|
14
|
+
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
15
|
+
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { StoreError } from "./errors.ts";
|
|
19
|
+
import {
|
|
20
|
+
acknowledgeGenerationOutbox,
|
|
21
|
+
enqueueReadyGeneration,
|
|
22
|
+
releaseGenerationPins,
|
|
23
|
+
voidGenerationOutbox,
|
|
24
|
+
} from "./outbox.ts";
|
|
25
|
+
import {
|
|
26
|
+
dependencyState,
|
|
27
|
+
getOperationRow,
|
|
28
|
+
latestWaitGeneration,
|
|
29
|
+
mapClaim,
|
|
30
|
+
mapEvidencePin,
|
|
31
|
+
mapEvidenceRead,
|
|
32
|
+
mapWait,
|
|
33
|
+
ownerFromRow,
|
|
34
|
+
readPins,
|
|
35
|
+
readWait,
|
|
36
|
+
readWaitRow,
|
|
37
|
+
requireClaim,
|
|
38
|
+
requireWait,
|
|
39
|
+
requireWaitRow,
|
|
40
|
+
} from "./rows.ts";
|
|
41
|
+
import {
|
|
42
|
+
columnNullableText,
|
|
43
|
+
columnNumber,
|
|
44
|
+
columnText,
|
|
45
|
+
getRow,
|
|
46
|
+
getRows,
|
|
47
|
+
isUniqueViolation,
|
|
48
|
+
run,
|
|
49
|
+
type StoreContext,
|
|
50
|
+
} from "./sqlite.ts";
|
|
51
|
+
import type {
|
|
52
|
+
AcknowledgeDisposition,
|
|
53
|
+
AcknowledgeResultInput,
|
|
54
|
+
AcknowledgeResultOutput,
|
|
55
|
+
CancelWaitInput,
|
|
56
|
+
CancelWaitResult,
|
|
57
|
+
ClaimResumeInput,
|
|
58
|
+
EvidencePinRecord,
|
|
59
|
+
EvidenceReadRecord,
|
|
60
|
+
HoldFailedResumeInput,
|
|
61
|
+
HoldFailedResumeResult,
|
|
62
|
+
OperationRecord,
|
|
63
|
+
OwnerIdentity,
|
|
64
|
+
PublishResumeAttemptInput,
|
|
65
|
+
PublishResumeAttemptResult,
|
|
66
|
+
RecordEvidencePinInput,
|
|
67
|
+
RecordEvidencePinResult,
|
|
68
|
+
RecordEvidenceReadInput,
|
|
69
|
+
RecordEvidenceReadResult,
|
|
70
|
+
RegisterWaitInput,
|
|
71
|
+
RegisterWaitResult,
|
|
72
|
+
ReleaseResumeClaimInput,
|
|
73
|
+
ReleaseResumeClaimResult,
|
|
74
|
+
ResumeClaimFilter,
|
|
75
|
+
ResumeClaimRecord,
|
|
76
|
+
ResumeClaimResult,
|
|
77
|
+
ResumeClaimState,
|
|
78
|
+
ResumeLeaseIdentity,
|
|
79
|
+
TerminalOutcome,
|
|
80
|
+
TransitionWaitPhaseInput,
|
|
81
|
+
TransitionWaitPhaseResult,
|
|
82
|
+
WaitDependencyInput,
|
|
83
|
+
WaitDependencyRecord,
|
|
84
|
+
WaitFilter,
|
|
85
|
+
WaitParkIntent,
|
|
86
|
+
WaitPhase,
|
|
87
|
+
WaitRecord,
|
|
88
|
+
WaitRef,
|
|
89
|
+
} from "./types.ts";
|
|
90
|
+
import {
|
|
91
|
+
describeOwnerDiff,
|
|
92
|
+
normalizeOwner,
|
|
93
|
+
optionalText,
|
|
94
|
+
requireBoolean,
|
|
95
|
+
requireCounter,
|
|
96
|
+
requireEnum,
|
|
97
|
+
requireId,
|
|
98
|
+
requireText,
|
|
99
|
+
sameOwner,
|
|
100
|
+
} from "./validate.ts";
|
|
101
|
+
|
|
102
|
+
const PHASES: readonly WaitPhase[] = [
|
|
103
|
+
"registering",
|
|
104
|
+
"parking",
|
|
105
|
+
"waiting",
|
|
106
|
+
"ready",
|
|
107
|
+
"resuming",
|
|
108
|
+
"consumed",
|
|
109
|
+
"held",
|
|
110
|
+
"cancelled",
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
const TERMINAL_PHASES: readonly WaitPhase[] = ["consumed", "cancelled"];
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Direct transitions. `consumed`/`cancelled` have dedicated calls, and leaving
|
|
117
|
+
* `resuming` goes through `releaseResumeClaim` so the claim record stays truthful.
|
|
118
|
+
*/
|
|
119
|
+
const ALLOWED_TRANSITIONS: Readonly<Record<WaitPhase, readonly WaitPhase[]>> = {
|
|
120
|
+
registering: ["parking", "waiting", "ready", "held"],
|
|
121
|
+
parking: ["waiting", "ready", "held"],
|
|
122
|
+
waiting: ["ready", "held"],
|
|
123
|
+
ready: ["held"],
|
|
124
|
+
resuming: [],
|
|
125
|
+
held: ["waiting", "ready"],
|
|
126
|
+
consumed: [],
|
|
127
|
+
cancelled: [],
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const DIRECT_TARGETS = ["parking", "waiting", "ready", "held"] as const;
|
|
131
|
+
|
|
132
|
+
const DISPOSITIONS: readonly AcknowledgeDisposition[] = ["continue", "blocked", "assignment-complete"];
|
|
133
|
+
const CLAIM_STATES: readonly ResumeClaimState[] = ["claimed", "published", "released", "invalidated"];
|
|
134
|
+
|
|
135
|
+
function assertWaitOwner(wait: WaitRecord, owner: OwnerIdentity, action: string): void {
|
|
136
|
+
if (!sameOwner(wait.owner, owner)) {
|
|
137
|
+
throw new StoreError(
|
|
138
|
+
"foreign-owner",
|
|
139
|
+
`Wait ${wait.waitId} generation ${wait.generation} belongs to another execution owner (differs in ${describeOwnerDiff(wait.owner, owner)}); ${action} must come from the owner.`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Reject a caller that addresses a superseded generation. */
|
|
145
|
+
function assertCurrentGeneration(ctx: StoreContext, waitId: string, generation: number): void {
|
|
146
|
+
const latest = latestWaitGeneration(ctx, waitId);
|
|
147
|
+
if (latest !== null && generation < latest) {
|
|
148
|
+
throw new StoreError(
|
|
149
|
+
"stale-generation",
|
|
150
|
+
`Wait ${waitId} has moved on to generation ${latest}; generation ${generation} is superseded. Read the current generation before acting.`,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function assertExpectedEpoch(wait: WaitRecord, expected: number): void {
|
|
156
|
+
if (expected !== wait.cancelEpoch) {
|
|
157
|
+
throw new StoreError(
|
|
158
|
+
"stale-cancel-epoch",
|
|
159
|
+
`Wait ${wait.waitId} generation ${wait.generation} is at cancellation epoch ${wait.cancelEpoch}; the caller observed ${expected}. A cancellation or replacement happened in between, so this action is stale.`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function normalizeDependencies(value: unknown): WaitDependencyInput[] {
|
|
165
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
166
|
+
throw new StoreError(
|
|
167
|
+
"validation",
|
|
168
|
+
"Invalid dependencies: a wait needs at least one operation dependency",
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
if (value.length > 100) {
|
|
172
|
+
throw new StoreError("validation", "Invalid dependencies: at most 100 operations per wait");
|
|
173
|
+
}
|
|
174
|
+
const seen = new Set<string>();
|
|
175
|
+
return value.map((entry, index) => {
|
|
176
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
177
|
+
throw new StoreError("validation", `Invalid dependencies[${index}]: must be an object`);
|
|
178
|
+
}
|
|
179
|
+
const item = entry as WaitDependencyInput;
|
|
180
|
+
const operationId = requireId(`dependencies[${index}].operationId`, item.operationId);
|
|
181
|
+
if (seen.has(operationId)) {
|
|
182
|
+
throw new StoreError(
|
|
183
|
+
"validation",
|
|
184
|
+
`Invalid dependencies: operation ${operationId} is listed twice`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
seen.add(operationId);
|
|
188
|
+
const link = item.link === undefined
|
|
189
|
+
? "owner" as const
|
|
190
|
+
: requireEnum(`dependencies[${index}].link`, item.link, ["owner", "explicit"] as const);
|
|
191
|
+
return { operationId, link };
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function normalizePark(value: unknown): WaitParkIntent | null {
|
|
196
|
+
if (value === undefined || value === null) return null;
|
|
197
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
198
|
+
throw new StoreError("validation", "Invalid park: must be an object");
|
|
199
|
+
}
|
|
200
|
+
const park = value as WaitParkIntent;
|
|
201
|
+
return {
|
|
202
|
+
attemptId: requireId("park.attemptId", park.attemptId),
|
|
203
|
+
checkpointId: requireId("park.checkpointId", park.checkpointId),
|
|
204
|
+
writerLeaseId: park.writerLeaseId === undefined || park.writerLeaseId === null
|
|
205
|
+
? null
|
|
206
|
+
: requireId("park.writerLeaseId", park.writerLeaseId),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function normalizeOrigin(value: unknown): RegisterWaitInput["origin"] | null {
|
|
211
|
+
if (value === undefined || value === null) return null;
|
|
212
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
213
|
+
throw new StoreError("validation", "Invalid origin: must be an object");
|
|
214
|
+
}
|
|
215
|
+
const origin = value as NonNullable<RegisterWaitInput["origin"]>;
|
|
216
|
+
if (origin.taskIds !== undefined && !Array.isArray(origin.taskIds)) {
|
|
217
|
+
throw new StoreError("validation", "Invalid origin.taskIds: must be an array");
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
taskIds: (origin.taskIds ?? []).map((taskId, index) => requireId(`origin.taskIds[${index}]`, taskId)),
|
|
221
|
+
assignmentRef: optionalText("origin.assignmentRef", origin.assignmentRef, 200),
|
|
222
|
+
attemptId: origin.attemptId === undefined || origin.attemptId === null
|
|
223
|
+
? null
|
|
224
|
+
: requireId("origin.attemptId", origin.attemptId),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function normalizeLease(value: unknown): ResumeLeaseIdentity {
|
|
229
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
230
|
+
throw new StoreError("validation", "Invalid lease: must be an object");
|
|
231
|
+
}
|
|
232
|
+
const lease = value as ResumeLeaseIdentity;
|
|
233
|
+
return {
|
|
234
|
+
ownerId: requireId("lease.ownerId", lease.ownerId),
|
|
235
|
+
pid: lease.pid === undefined || lease.pid === null ? null : requireCounter("lease.pid", lease.pid),
|
|
236
|
+
processStartToken: lease.processStartToken === undefined || lease.processStartToken === null
|
|
237
|
+
? null
|
|
238
|
+
: requireId("lease.processStartToken", lease.processStartToken),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---- settlement ---------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Apply a terminal revision to every wait generation that depends on it.
|
|
246
|
+
*
|
|
247
|
+
* Waits in `waiting` move to `ready` and get their delivery enqueued in the same
|
|
248
|
+
* transaction. Waits in `registering`/`parking` stay put — their checkpoint gate
|
|
249
|
+
* is still open — but their dependency rows are already settled, so their next
|
|
250
|
+
* transition resolves straight to `ready`.
|
|
251
|
+
*/
|
|
252
|
+
export function settleWaitsForOperation(
|
|
253
|
+
ctx: StoreContext,
|
|
254
|
+
operation: OperationRecord,
|
|
255
|
+
at: number,
|
|
256
|
+
): { ready: WaitRecord[] } {
|
|
257
|
+
if (operation.terminalRevision <= 0) return { ready: [] };
|
|
258
|
+
const affected = getRows(
|
|
259
|
+
ctx,
|
|
260
|
+
"SELECT DISTINCT wait_id, generation FROM wait_dependencies WHERE operation_id = ? AND terminal_revision = 0",
|
|
261
|
+
operation.operationId,
|
|
262
|
+
);
|
|
263
|
+
if (affected.length === 0) return { ready: [] };
|
|
264
|
+
run(
|
|
265
|
+
ctx,
|
|
266
|
+
`UPDATE wait_dependencies SET terminal_revision = ?, terminal_outcome = ?, settled_at = ?
|
|
267
|
+
WHERE operation_id = ? AND terminal_revision = 0`,
|
|
268
|
+
operation.terminalRevision,
|
|
269
|
+
operation.terminalOutcome,
|
|
270
|
+
at,
|
|
271
|
+
operation.operationId,
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
const ready: WaitRecord[] = [];
|
|
275
|
+
for (const row of affected) {
|
|
276
|
+
const waitId = columnText(row, "wait_id");
|
|
277
|
+
const generation = columnNumber(row, "generation");
|
|
278
|
+
const waitRow = readWaitRow(ctx, waitId, generation);
|
|
279
|
+
if (!waitRow) continue;
|
|
280
|
+
const state = dependencyState(ctx, waitId, generation);
|
|
281
|
+
if (state.settled) {
|
|
282
|
+
run(
|
|
283
|
+
ctx,
|
|
284
|
+
"UPDATE waits SET settled_at = coalesce(settled_at, ?), updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
285
|
+
state.settledAt ?? at,
|
|
286
|
+
at,
|
|
287
|
+
waitId,
|
|
288
|
+
generation,
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
const phase = columnText(waitRow, "phase") as WaitPhase;
|
|
292
|
+
if (phase !== "waiting" || !state.settled) continue;
|
|
293
|
+
run(
|
|
294
|
+
ctx,
|
|
295
|
+
"UPDATE waits SET phase = 'ready', phase_reason = ?, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
296
|
+
"dependencies-settled",
|
|
297
|
+
at,
|
|
298
|
+
waitId,
|
|
299
|
+
generation,
|
|
300
|
+
);
|
|
301
|
+
enqueueReadyGeneration(ctx, waitId, generation, at);
|
|
302
|
+
ready.push(requireWait(ctx, waitId, generation));
|
|
303
|
+
}
|
|
304
|
+
return { ready };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ---- registration -------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
export function registerWait(ctx: StoreContext, input: RegisterWaitInput): RegisterWaitResult {
|
|
310
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
311
|
+
const dependencies = normalizeDependencies(input.dependencies);
|
|
312
|
+
const continuationNote = requireText("continuationNote", input.continuationNote, 8192);
|
|
313
|
+
const park = normalizePark(input.park);
|
|
314
|
+
const origin = normalizeOrigin(input.origin);
|
|
315
|
+
const requestedWaitId = input.waitId === undefined ? null : requireId("waitId", input.waitId);
|
|
316
|
+
|
|
317
|
+
return ctx.transaction(() => {
|
|
318
|
+
const at = ctx.now();
|
|
319
|
+
const resolved: Array<{
|
|
320
|
+
dependency: WaitDependencyInput;
|
|
321
|
+
terminalRevision: number;
|
|
322
|
+
terminalOutcome: TerminalOutcome | null;
|
|
323
|
+
}> = [];
|
|
324
|
+
for (const dependency of dependencies) {
|
|
325
|
+
const row = getOperationRow(ctx, dependency.operationId);
|
|
326
|
+
if (!row) {
|
|
327
|
+
throw new StoreError(
|
|
328
|
+
"unknown-operation",
|
|
329
|
+
`Unknown operation ${dependency.operationId}. A wait may only depend on a registered operation; an unregistered id is refused rather than watched.`,
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
const operationOwner = ownerFromRow(row);
|
|
333
|
+
if (dependency.link === "owner" && !sameOwner(operationOwner, owner)) {
|
|
334
|
+
throw new StoreError(
|
|
335
|
+
"foreign-owner",
|
|
336
|
+
`Operation ${dependency.operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operationOwner, owner)}). Only an owned or explicitly linked operation may be waited on.`,
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
const terminalRevision = columnNumber(row, "terminal_revision");
|
|
340
|
+
resolved.push({
|
|
341
|
+
dependency,
|
|
342
|
+
terminalRevision,
|
|
343
|
+
terminalOutcome: terminalRevision > 0
|
|
344
|
+
? columnNullableText(row, "terminal_outcome") as TerminalOutcome | null
|
|
345
|
+
: null,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
let waitId = requestedWaitId ?? `wait_${randomUUID()}`;
|
|
350
|
+
let generation = 1;
|
|
351
|
+
if (requestedWaitId !== null) {
|
|
352
|
+
const existing = getRows(
|
|
353
|
+
ctx,
|
|
354
|
+
"SELECT * FROM waits WHERE wait_id = ? ORDER BY generation DESC",
|
|
355
|
+
requestedWaitId,
|
|
356
|
+
);
|
|
357
|
+
for (const row of existing) {
|
|
358
|
+
const existingOwner = ownerFromRow(row);
|
|
359
|
+
if (!sameOwner(existingOwner, owner)) {
|
|
360
|
+
throw new StoreError(
|
|
361
|
+
"foreign-owner",
|
|
362
|
+
`Wait ${requestedWaitId} is owned by another execution owner (differs in ${describeOwnerDiff(existingOwner, owner)}).`,
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const pending = existing.find(
|
|
367
|
+
(row) => !TERMINAL_PHASES.includes(columnText(row, "phase") as WaitPhase),
|
|
368
|
+
);
|
|
369
|
+
if (pending) {
|
|
370
|
+
throw new StoreError(
|
|
371
|
+
"pending-wait-generation",
|
|
372
|
+
`Wait ${requestedWaitId} generation ${Number(pending.generation)} is still ${columnText(pending, "phase")}. A second pending generation is refused; consume, cancel or take over the existing one first.`,
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
generation = existing.length === 0 ? 1 : Number(existing[0].generation) + 1;
|
|
376
|
+
} else {
|
|
377
|
+
const otherPending = getRow(
|
|
378
|
+
ctx,
|
|
379
|
+
`SELECT * FROM waits
|
|
380
|
+
WHERE owner_kind = ? AND owner_session_id = ?
|
|
381
|
+
AND coalesce(owner_branch_id, '') = ?
|
|
382
|
+
AND phase NOT IN ('consumed', 'cancelled')`,
|
|
383
|
+
owner.kind,
|
|
384
|
+
owner.sessionId,
|
|
385
|
+
owner.branchId ?? "",
|
|
386
|
+
);
|
|
387
|
+
if (otherPending) {
|
|
388
|
+
waitId = columnText(otherPending, "wait_id");
|
|
389
|
+
throw new StoreError(
|
|
390
|
+
"pending-wait-generation",
|
|
391
|
+
`This execution owner already has a pending wait (${waitId} generation ${Number(otherPending.generation)}, ${columnText(otherPending, "phase")}). A second pending generation would compete for the same continuation; reuse that wait id after consuming or cancelling it.`,
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const settled = resolved.every((entry) => entry.terminalRevision > 0);
|
|
397
|
+
const phase: WaitPhase = park !== null ? "registering" : settled ? "ready" : "waiting";
|
|
398
|
+
const settledAt = settled ? at : null;
|
|
399
|
+
try {
|
|
400
|
+
run(
|
|
401
|
+
ctx,
|
|
402
|
+
`INSERT INTO waits (
|
|
403
|
+
wait_id, generation,
|
|
404
|
+
owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
|
|
405
|
+
phase, phase_reason, cancel_epoch, continuation_note, park_json, origin_json,
|
|
406
|
+
settled_at, created_at, updated_at
|
|
407
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`,
|
|
408
|
+
waitId,
|
|
409
|
+
generation,
|
|
410
|
+
owner.kind,
|
|
411
|
+
owner.sessionId,
|
|
412
|
+
owner.workspace,
|
|
413
|
+
owner.branchId ?? null,
|
|
414
|
+
owner.goalId ?? null,
|
|
415
|
+
phase,
|
|
416
|
+
settled ? "dependencies-settled-at-registration" : null,
|
|
417
|
+
continuationNote,
|
|
418
|
+
park ? JSON.stringify(park) : null,
|
|
419
|
+
origin ? JSON.stringify(origin) : null,
|
|
420
|
+
settledAt,
|
|
421
|
+
at,
|
|
422
|
+
at,
|
|
423
|
+
);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
// A concurrent process registered a generation for this owner identity
|
|
426
|
+
// between the check above and this insert.
|
|
427
|
+
if (isUniqueViolation(error, "waits_one_pending_per_owner", "waits")) {
|
|
428
|
+
throw new StoreError(
|
|
429
|
+
"pending-wait-generation",
|
|
430
|
+
`This execution owner already has a pending wait generation; a concurrent registration won. Re-read the pending generation before registering again.`,
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
435
|
+
resolved.forEach((entry, ordinal) => {
|
|
436
|
+
run(
|
|
437
|
+
ctx,
|
|
438
|
+
`INSERT INTO wait_dependencies (
|
|
439
|
+
wait_id, generation, ordinal, operation_id, link,
|
|
440
|
+
terminal_revision, terminal_outcome, settled_at
|
|
441
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
442
|
+
waitId,
|
|
443
|
+
generation,
|
|
444
|
+
ordinal,
|
|
445
|
+
entry.dependency.operationId,
|
|
446
|
+
entry.dependency.link ?? "owner",
|
|
447
|
+
entry.terminalRevision,
|
|
448
|
+
entry.terminalOutcome,
|
|
449
|
+
entry.terminalRevision > 0 ? at : null,
|
|
450
|
+
);
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
const outbox = settled ? enqueueReadyGeneration(ctx, waitId, generation, at) : [];
|
|
454
|
+
return {
|
|
455
|
+
wait: requireWait(ctx, waitId, generation),
|
|
456
|
+
settledAtRegistration: settled,
|
|
457
|
+
outbox,
|
|
458
|
+
};
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// ---- phase transitions --------------------------------------------------
|
|
463
|
+
|
|
464
|
+
export function transitionWaitPhase(
|
|
465
|
+
ctx: StoreContext,
|
|
466
|
+
input: TransitionWaitPhaseInput,
|
|
467
|
+
): TransitionWaitPhaseResult {
|
|
468
|
+
const waitId = requireId("waitId", input.waitId);
|
|
469
|
+
const generation = requireCounter("generation", input.generation);
|
|
470
|
+
const from = requireEnum("from", input.from, PHASES);
|
|
471
|
+
const to = requireEnum("to", input.to, DIRECT_TARGETS);
|
|
472
|
+
const reason = optionalText("reason", input.reason, 1024);
|
|
473
|
+
const proof = input.proof === undefined || input.proof === null
|
|
474
|
+
? null
|
|
475
|
+
: {
|
|
476
|
+
checkpointRecorded: requireBoolean("proof.checkpointRecorded", input.proof.checkpointRecorded),
|
|
477
|
+
writerLeaseReleased: requireBoolean("proof.writerLeaseReleased", input.proof.writerLeaseReleased),
|
|
478
|
+
writerPidGone: input.proof.writerPidGone === undefined
|
|
479
|
+
? false
|
|
480
|
+
: requireBoolean("proof.writerPidGone", input.proof.writerPidGone),
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
return ctx.transaction(() => {
|
|
484
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
485
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
486
|
+
if (wait.phase !== from) {
|
|
487
|
+
throw new StoreError(
|
|
488
|
+
"stale-phase",
|
|
489
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}, but the caller acted on ${from}. Re-read the wait before transitioning it.`,
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
if (to === "parking" && wait.park === null) {
|
|
493
|
+
throw new StoreError(
|
|
494
|
+
"wait-phase",
|
|
495
|
+
`Wait ${waitId} generation ${generation} has no park intent; a responsive parent stays in waiting/ready and does not park an attempt.`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
if (!ALLOWED_TRANSITIONS[wait.phase].includes(to)) {
|
|
499
|
+
const allowed = ALLOWED_TRANSITIONS[wait.phase];
|
|
500
|
+
const detail = wait.phase === "resuming"
|
|
501
|
+
? "a resuming wait is completed with releaseResumeClaim, not a direct transition"
|
|
502
|
+
: `allowed from ${wait.phase}: ${allowed.length === 0 ? "none" : allowed.join(", ")}`;
|
|
503
|
+
throw new StoreError(
|
|
504
|
+
"wait-phase",
|
|
505
|
+
`Wait ${waitId} generation ${generation} cannot move ${wait.phase} → ${to} (${detail}).`,
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
// The checkpoint gate belongs to the parking boundary only. Once a parked
|
|
509
|
+
// worker has left `parking` with proof, later holds and recoveries act on
|
|
510
|
+
// the same generation and must not be asked to re-prove the checkpoint.
|
|
511
|
+
const atParkingBoundary = wait.park !== null
|
|
512
|
+
&& to !== "parking"
|
|
513
|
+
&& (wait.phase === "registering" || wait.phase === "parking");
|
|
514
|
+
if (atParkingBoundary) {
|
|
515
|
+
const proven = proof !== null
|
|
516
|
+
&& proof.checkpointRecorded
|
|
517
|
+
&& proof.writerLeaseReleased
|
|
518
|
+
&& proof.writerPidGone;
|
|
519
|
+
if (wait.phase !== "parking" || !proven) {
|
|
520
|
+
throw new StoreError(
|
|
521
|
+
"checkpoint-proof",
|
|
522
|
+
`Wait ${waitId} generation ${generation} belongs to a parked worker. It can reach ${to} only from parking with proven checkpoint commit, writer lease release and writer process exit (got phase ${wait.phase}${proof ? "" : ", no proof"}). A partially recorded checkpoint must never become the continuation point.`,
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (to === "held" && reason === null) {
|
|
527
|
+
throw new StoreError(
|
|
528
|
+
"validation",
|
|
529
|
+
"Invalid reason: a held wait must record why it is held",
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
const state = dependencyState(ctx, waitId, generation);
|
|
533
|
+
if (to === "ready" && !state.settled) {
|
|
534
|
+
throw new StoreError(
|
|
535
|
+
"dependencies-unsettled",
|
|
536
|
+
`Wait ${waitId} generation ${generation} cannot be ready: ${state.dependencies.filter((dep) => dep.terminalRevision === 0).map((dep) => dep.operationId).join(", ")} has no terminal outcome yet.`,
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
// A dependency that settled during parking resolves straight to ready.
|
|
540
|
+
const resulting: WaitPhase = to === "waiting" && state.settled ? "ready" : to;
|
|
541
|
+
const phaseReason = to === "waiting" && state.settled
|
|
542
|
+
? "settled-while-parking"
|
|
543
|
+
: reason;
|
|
544
|
+
const at = ctx.now();
|
|
545
|
+
run(
|
|
546
|
+
ctx,
|
|
547
|
+
"UPDATE waits SET phase = ?, phase_reason = ?, settled_at = coalesce(settled_at, ?), updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
548
|
+
resulting,
|
|
549
|
+
phaseReason,
|
|
550
|
+
state.settled ? state.settledAt ?? at : null,
|
|
551
|
+
at,
|
|
552
|
+
waitId,
|
|
553
|
+
generation,
|
|
554
|
+
);
|
|
555
|
+
const outbox = resulting === "ready" ? enqueueReadyGeneration(ctx, waitId, generation, at) : [];
|
|
556
|
+
return { wait: requireWait(ctx, waitId, generation), outbox };
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// ---- cancellation -------------------------------------------------------
|
|
561
|
+
|
|
562
|
+
export function cancelWait(ctx: StoreContext, input: CancelWaitInput): CancelWaitResult {
|
|
563
|
+
const waitId = requireId("waitId", input.waitId);
|
|
564
|
+
const generation = requireCounter("generation", input.generation);
|
|
565
|
+
const expectedCancelEpoch = requireCounter("expectedCancelEpoch", input.expectedCancelEpoch);
|
|
566
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
567
|
+
const reason = requireText("reason", input.reason, 1024);
|
|
568
|
+
|
|
569
|
+
return ctx.transaction(() => {
|
|
570
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
571
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
572
|
+
assertWaitOwner(wait, owner, "cancellation");
|
|
573
|
+
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
574
|
+
throw new StoreError(
|
|
575
|
+
"wait-phase",
|
|
576
|
+
`Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`,
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
580
|
+
const at = ctx.now();
|
|
581
|
+
run(
|
|
582
|
+
ctx,
|
|
583
|
+
"UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
584
|
+
reason,
|
|
585
|
+
at,
|
|
586
|
+
waitId,
|
|
587
|
+
generation,
|
|
588
|
+
);
|
|
589
|
+
const activeClaimRows = getRows(
|
|
590
|
+
ctx,
|
|
591
|
+
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
592
|
+
waitId,
|
|
593
|
+
generation,
|
|
594
|
+
);
|
|
595
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
596
|
+
run(
|
|
597
|
+
ctx,
|
|
598
|
+
`UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
599
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
|
|
600
|
+
at,
|
|
601
|
+
reason,
|
|
602
|
+
waitId,
|
|
603
|
+
generation,
|
|
604
|
+
);
|
|
605
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
606
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
607
|
+
return {
|
|
608
|
+
wait: requireWait(ctx, waitId, generation),
|
|
609
|
+
invalidatedClaimIds,
|
|
610
|
+
voidedOutboxIds,
|
|
611
|
+
};
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// ---- resume claims ------------------------------------------------------
|
|
616
|
+
|
|
617
|
+
export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeClaimResult {
|
|
618
|
+
const waitId = requireId("waitId", input.waitId);
|
|
619
|
+
const generation = requireCounter("generation", input.generation);
|
|
620
|
+
const expectedCancelEpoch = requireCounter("expectedCancelEpoch", input.expectedCancelEpoch);
|
|
621
|
+
const lease = normalizeLease(input.lease);
|
|
622
|
+
const reservedCheckpointId = requireId("reservedCheckpointId", input.reservedCheckpointId);
|
|
623
|
+
|
|
624
|
+
return ctx.transaction(() => {
|
|
625
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
626
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
627
|
+
const active = getRows(
|
|
628
|
+
ctx,
|
|
629
|
+
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
630
|
+
waitId,
|
|
631
|
+
generation,
|
|
632
|
+
)[0];
|
|
633
|
+
if (active) {
|
|
634
|
+
throw new StoreError(
|
|
635
|
+
"concurrent-claim",
|
|
636
|
+
`Wait ${waitId} generation ${generation} already has an active resume claim (${columnText(active, "claim_id")}). One conversation admits one writer; release or invalidate that claim instead of claiming again.`,
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
if (wait.phase !== "ready") {
|
|
640
|
+
throw new StoreError(
|
|
641
|
+
"wait-phase",
|
|
642
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}; only a ready generation can be claimed for continuation.`,
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
646
|
+
if (!wait.settled) {
|
|
647
|
+
throw new StoreError(
|
|
648
|
+
"dependencies-unsettled",
|
|
649
|
+
`Wait ${waitId} generation ${generation} has unfinished dependencies; a continuation is claimed only after every dependency is terminal.`,
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
const at = ctx.now();
|
|
653
|
+
const claimId = `claim_${randomUUID()}`;
|
|
654
|
+
try {
|
|
655
|
+
run(
|
|
656
|
+
ctx,
|
|
657
|
+
`INSERT INTO resume_claims (
|
|
658
|
+
claim_id, wait_id, generation, cancel_epoch, claim_token, state,
|
|
659
|
+
lease_json, reserved_checkpoint_id, claimed_at
|
|
660
|
+
) VALUES (?, ?, ?, ?, ?, 'claimed', ?, ?, ?)`,
|
|
661
|
+
claimId,
|
|
662
|
+
waitId,
|
|
663
|
+
generation,
|
|
664
|
+
wait.cancelEpoch,
|
|
665
|
+
`claimtok_${randomUUID()}`,
|
|
666
|
+
JSON.stringify(lease),
|
|
667
|
+
reservedCheckpointId,
|
|
668
|
+
at,
|
|
669
|
+
);
|
|
670
|
+
} catch (error) {
|
|
671
|
+
// Another supervisor claimed this generation concurrently.
|
|
672
|
+
if (isUniqueViolation(error, "resume_claims_one_active", "resume_claims")) {
|
|
673
|
+
throw new StoreError(
|
|
674
|
+
"concurrent-claim",
|
|
675
|
+
`Wait ${waitId} generation ${generation} was claimed concurrently by another supervisor. One conversation admits one writer; reconcile that claim instead of claiming again.`,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
throw error;
|
|
679
|
+
}
|
|
680
|
+
run(
|
|
681
|
+
ctx,
|
|
682
|
+
"UPDATE waits SET phase = 'resuming', phase_reason = ?, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
683
|
+
"resume-claimed",
|
|
684
|
+
at,
|
|
685
|
+
waitId,
|
|
686
|
+
generation,
|
|
687
|
+
);
|
|
688
|
+
return { claim: requireClaim(ctx, claimId), wait: requireWait(ctx, waitId, generation) };
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
export function publishResumeAttempt(
|
|
693
|
+
ctx: StoreContext,
|
|
694
|
+
input: PublishResumeAttemptInput,
|
|
695
|
+
): PublishResumeAttemptResult {
|
|
696
|
+
const waitId = requireId("waitId", input.waitId);
|
|
697
|
+
const generation = requireCounter("generation", input.generation);
|
|
698
|
+
const claimId = requireId("claimId", input.claimId);
|
|
699
|
+
const claimToken = requireId("claimToken", input.claimToken);
|
|
700
|
+
const attemptId = requireId("attemptId", input.attemptId);
|
|
701
|
+
const launchToken = requireId("launchToken", input.launchToken);
|
|
702
|
+
|
|
703
|
+
return ctx.transaction(() => {
|
|
704
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
705
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
706
|
+
const claim = requireClaim(ctx, claimId);
|
|
707
|
+
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
708
|
+
throw new StoreError(
|
|
709
|
+
"claim-state",
|
|
710
|
+
`Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`,
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
if (claim.claimToken !== claimToken) {
|
|
714
|
+
throw new StoreError(
|
|
715
|
+
"claim-state",
|
|
716
|
+
`Resume claim ${claimId} was not issued with this token; the caller does not hold the claim.`,
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
if (claim.state === "invalidated") {
|
|
720
|
+
throw new StoreError(
|
|
721
|
+
"claim-state",
|
|
722
|
+
`Resume claim ${claimId} was invalidated (${claim.reason ?? "no reason recorded"}); it can never publish an attempt.`,
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
if (wait.phase === "cancelled" || wait.cancelEpoch !== claim.cancelEpoch) {
|
|
726
|
+
// Cancellation already invalidates the claim in its own transaction; this
|
|
727
|
+
// refusal must not write anything (a throw rolls the transaction back).
|
|
728
|
+
throw new StoreError(
|
|
729
|
+
"stale-cancel-epoch",
|
|
730
|
+
`Wait ${waitId} generation ${generation} was cancelled after the claim (epoch ${wait.cancelEpoch} vs claimed ${claim.cancelEpoch}). The attempt must not start.`,
|
|
731
|
+
);
|
|
732
|
+
}
|
|
733
|
+
if (wait.phase !== "resuming") {
|
|
734
|
+
throw new StoreError(
|
|
735
|
+
"claim-state",
|
|
736
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}; a resume attempt may only be published while the generation is resuming.`,
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
if (claim.state === "published") {
|
|
740
|
+
if (claim.attemptId === attemptId && claim.launchToken === launchToken) {
|
|
741
|
+
return { claim, wait, published: false };
|
|
742
|
+
}
|
|
743
|
+
throw new StoreError(
|
|
744
|
+
"claim-state",
|
|
745
|
+
`Resume claim ${claimId} already published attempt ${claim.attemptId}. One claim launches one attempt; reconcile that attempt instead of publishing another.`,
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
if (claim.state !== "claimed") {
|
|
749
|
+
throw new StoreError(
|
|
750
|
+
"claim-state",
|
|
751
|
+
`Resume claim ${claimId} is ${claim.state}; only a claimed reservation can publish an attempt.`,
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
const clash = getRow(
|
|
755
|
+
ctx,
|
|
756
|
+
"SELECT claim_id FROM resume_claims WHERE attempt_id = ? AND claim_id <> ?",
|
|
757
|
+
attemptId,
|
|
758
|
+
claimId,
|
|
759
|
+
);
|
|
760
|
+
if (clash) {
|
|
761
|
+
throw new StoreError(
|
|
762
|
+
"attempt-conflict",
|
|
763
|
+
`Attempt ${attemptId} is already published by resume claim ${columnText(clash, "claim_id")}. Attempt ids identify one execution and cannot be reused.`,
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
const at = ctx.now();
|
|
767
|
+
run(
|
|
768
|
+
ctx,
|
|
769
|
+
"UPDATE resume_claims SET state = 'published', attempt_id = ?, launch_token = ?, published_at = ? WHERE claim_id = ?",
|
|
770
|
+
attemptId,
|
|
771
|
+
launchToken,
|
|
772
|
+
at,
|
|
773
|
+
claimId,
|
|
774
|
+
);
|
|
775
|
+
return { claim: requireClaim(ctx, claimId), wait, published: true };
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
export function releaseResumeClaim(
|
|
780
|
+
ctx: StoreContext,
|
|
781
|
+
input: ReleaseResumeClaimInput,
|
|
782
|
+
): ReleaseResumeClaimResult {
|
|
783
|
+
const waitId = requireId("waitId", input.waitId);
|
|
784
|
+
const generation = requireCounter("generation", input.generation);
|
|
785
|
+
const claimId = requireId("claimId", input.claimId);
|
|
786
|
+
const claimToken = requireId("claimToken", input.claimToken);
|
|
787
|
+
const outcome = requireEnum("outcome", input.outcome, ["ready", "held"] as const);
|
|
788
|
+
const reason = requireText("reason", input.reason, 1024);
|
|
789
|
+
|
|
790
|
+
return ctx.transaction(() => {
|
|
791
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
792
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
793
|
+
const claim = requireClaim(ctx, claimId);
|
|
794
|
+
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
795
|
+
throw new StoreError(
|
|
796
|
+
"claim-state",
|
|
797
|
+
`Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`,
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
if (claim.claimToken !== claimToken) {
|
|
801
|
+
throw new StoreError(
|
|
802
|
+
"claim-state",
|
|
803
|
+
`Resume claim ${claimId} was not issued with this token; the caller does not hold the claim.`,
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
if (claim.state === "published") {
|
|
807
|
+
throw new StoreError(
|
|
808
|
+
"claim-state",
|
|
809
|
+
`Resume claim ${claimId} already published attempt ${claim.attemptId}. A published attempt is reconciled, not released; releasing it could start a second execution.`,
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
if (claim.state !== "claimed") {
|
|
813
|
+
throw new StoreError(
|
|
814
|
+
"claim-state",
|
|
815
|
+
`Resume claim ${claimId} is ${claim.state}; only a claimed reservation can be released.`,
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
if (outcome === "ready" && !wait.settled) {
|
|
819
|
+
throw new StoreError(
|
|
820
|
+
"dependencies-unsettled",
|
|
821
|
+
`Wait ${waitId} generation ${generation} cannot return to ready with unfinished dependencies.`,
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
const at = ctx.now();
|
|
825
|
+
run(
|
|
826
|
+
ctx,
|
|
827
|
+
"UPDATE resume_claims SET state = 'released', released_at = ?, reason = ? WHERE claim_id = ?",
|
|
828
|
+
at,
|
|
829
|
+
reason,
|
|
830
|
+
claimId,
|
|
831
|
+
);
|
|
832
|
+
run(
|
|
833
|
+
ctx,
|
|
834
|
+
"UPDATE waits SET phase = ?, phase_reason = ?, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
835
|
+
outcome,
|
|
836
|
+
reason,
|
|
837
|
+
at,
|
|
838
|
+
waitId,
|
|
839
|
+
generation,
|
|
840
|
+
);
|
|
841
|
+
return { claim: requireClaim(ctx, claimId), wait: requireWait(ctx, waitId, generation) };
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* Hold a published generation whose attempt exited without interpreting it.
|
|
847
|
+
*
|
|
848
|
+
* This is the proven-exit counterpart of `releaseResumeClaim`: the general release
|
|
849
|
+
* refuses a published claim because releasing it could start a second execution.
|
|
850
|
+
* Here the attempt is proven gone, so the generation leaves `resuming` for `held`
|
|
851
|
+
* with a reason, its cancellation epoch is unchanged (a failure is not a user
|
|
852
|
+
* cancellation), its evidence pins are retained, and the claim is invalidated so it
|
|
853
|
+
* can never publish another attempt.
|
|
854
|
+
*
|
|
855
|
+
* Identity is exact: generation, claim id, claim token, attempt id and launch
|
|
856
|
+
* token must all name this publication. The proof must state a gone writer and a
|
|
857
|
+
* released writer lease. Replaying the same call is idempotent. A generation that
|
|
858
|
+
* is already `consumed` or `cancelled` is never altered.
|
|
859
|
+
*/
|
|
860
|
+
export function holdFailedResume(
|
|
861
|
+
ctx: StoreContext,
|
|
862
|
+
input: HoldFailedResumeInput,
|
|
863
|
+
): HoldFailedResumeResult {
|
|
864
|
+
const waitId = requireId("waitId", input.waitId);
|
|
865
|
+
const generation = requireCounter("generation", input.generation);
|
|
866
|
+
const claimId = requireId("claimId", input.claimId);
|
|
867
|
+
const claimToken = requireId("claimToken", input.claimToken);
|
|
868
|
+
const attemptId = requireId("attemptId", input.attemptId);
|
|
869
|
+
const launchToken = requireId("launchToken", input.launchToken);
|
|
870
|
+
const reason = requireText("reason", input.reason, 1024);
|
|
871
|
+
const proof = input.proof;
|
|
872
|
+
if (!proof || typeof proof !== "object") {
|
|
873
|
+
throw new StoreError("validation", "Invalid proof: a held resume needs the writer exit proof");
|
|
874
|
+
}
|
|
875
|
+
if (proof.writerPidGone !== true || proof.writerLeaseReleased !== true) {
|
|
876
|
+
throw new StoreError(
|
|
877
|
+
"resume-proof",
|
|
878
|
+
"Holding a published resume needs proven writer exit and a released writer lease; an ambiguous identity stays with its live writer and is not held here.",
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
return ctx.transaction(() => {
|
|
883
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
884
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
885
|
+
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
886
|
+
throw new StoreError(
|
|
887
|
+
"wait-phase",
|
|
888
|
+
`Wait ${waitId} generation ${generation} is already ${wait.phase}; a failed resume never rewrites a consumed or cancelled generation.`,
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
const claim = requireClaim(ctx, claimId);
|
|
892
|
+
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
893
|
+
throw new StoreError(
|
|
894
|
+
"claim-state",
|
|
895
|
+
`Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`,
|
|
896
|
+
);
|
|
897
|
+
}
|
|
898
|
+
if (claim.claimToken !== claimToken) {
|
|
899
|
+
throw new StoreError(
|
|
900
|
+
"claim-state",
|
|
901
|
+
`Resume claim ${claimId} was not issued with this token; the caller does not hold the claim.`,
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
if (claim.attemptId !== attemptId || claim.launchToken !== launchToken) {
|
|
905
|
+
throw new StoreError(
|
|
906
|
+
"claim-state",
|
|
907
|
+
`Resume claim ${claimId} published attempt ${claim.attemptId ?? "(none)"} with a different launch token; this is not the attempt that failed.`,
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
if (claim.cancelEpoch !== wait.cancelEpoch) {
|
|
911
|
+
throw new StoreError(
|
|
912
|
+
"stale-cancel-epoch",
|
|
913
|
+
`Resume claim ${claimId} was taken at cancellation epoch ${claim.cancelEpoch}, but the wait is at ${wait.cancelEpoch}.`,
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
if (claim.state === "invalidated" && wait.phase === "held") {
|
|
917
|
+
// Idempotent replay: the same failed attempt already held this generation.
|
|
918
|
+
return { wait, claim, applied: false };
|
|
919
|
+
}
|
|
920
|
+
if (claim.state !== "published") {
|
|
921
|
+
throw new StoreError(
|
|
922
|
+
"claim-state",
|
|
923
|
+
`Resume claim ${claimId} is ${claim.state}; only a published attempt can be held after a proven exit.`,
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
if (wait.phase !== "resuming") {
|
|
927
|
+
throw new StoreError(
|
|
928
|
+
"wait-phase",
|
|
929
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}, not resuming; it cannot be held as a failed resume.`,
|
|
930
|
+
);
|
|
931
|
+
}
|
|
932
|
+
const at = ctx.now();
|
|
933
|
+
run(
|
|
934
|
+
ctx,
|
|
935
|
+
"UPDATE waits SET phase = 'held', phase_reason = ?, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
936
|
+
reason,
|
|
937
|
+
at,
|
|
938
|
+
waitId,
|
|
939
|
+
generation,
|
|
940
|
+
);
|
|
941
|
+
run(
|
|
942
|
+
ctx,
|
|
943
|
+
"UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ? WHERE claim_id = ? AND state = 'published'",
|
|
944
|
+
at,
|
|
945
|
+
reason,
|
|
946
|
+
claimId,
|
|
947
|
+
);
|
|
948
|
+
return { wait: requireWait(ctx, waitId, generation), claim: requireClaim(ctx, claimId), applied: true };
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
export function listResumeClaims(
|
|
953
|
+
ctx: StoreContext,
|
|
954
|
+
filter: ResumeClaimFilter = {},
|
|
955
|
+
): ResumeClaimRecord[] {
|
|
956
|
+
const clauses: string[] = [];
|
|
957
|
+
const params: Array<string | number> = [];
|
|
958
|
+
if (filter.waitId !== undefined) {
|
|
959
|
+
clauses.push("wait_id = ?");
|
|
960
|
+
params.push(requireId("waitId", filter.waitId));
|
|
961
|
+
}
|
|
962
|
+
if (filter.generation !== undefined) {
|
|
963
|
+
clauses.push("generation = ?");
|
|
964
|
+
params.push(requireCounter("generation", filter.generation));
|
|
965
|
+
}
|
|
966
|
+
if (filter.state !== undefined) {
|
|
967
|
+
const states = Array.isArray(filter.state) ? filter.state : [filter.state as ResumeClaimState];
|
|
968
|
+
for (const state of states) {
|
|
969
|
+
if (!CLAIM_STATES.includes(state)) {
|
|
970
|
+
throw new StoreError("validation", `Invalid state: must be one of ${CLAIM_STATES.join(", ")}`);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
clauses.push(`state IN (${states.map(() => "?").join(", ")})`);
|
|
974
|
+
params.push(...states);
|
|
975
|
+
}
|
|
976
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
977
|
+
return getRows(ctx, `SELECT * FROM resume_claims ${where} ORDER BY claimed_at, claim_id`, ...params)
|
|
978
|
+
.map(mapClaim);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// ---- evidence reads and pins -------------------------------------------
|
|
982
|
+
|
|
983
|
+
export function recordEvidenceRead(
|
|
984
|
+
ctx: StoreContext,
|
|
985
|
+
input: RecordEvidenceReadInput,
|
|
986
|
+
): RecordEvidenceReadResult {
|
|
987
|
+
const waitId = requireId("waitId", input.waitId);
|
|
988
|
+
const generation = requireCounter("generation", input.generation);
|
|
989
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
990
|
+
const operationId = requireId("operationId", input.operationId);
|
|
991
|
+
const terminalRevision = requireCounter("terminalRevision", input.terminalRevision);
|
|
992
|
+
|
|
993
|
+
return ctx.transaction(() => {
|
|
994
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
995
|
+
assertWaitOwner(wait, owner, "an evidence read");
|
|
996
|
+
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
997
|
+
throw new StoreError(
|
|
998
|
+
"wait-phase",
|
|
999
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}; its evidence is no longer interpreted.`,
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
const dependency = wait.dependencies.find((dep) => dep.operationId === operationId);
|
|
1003
|
+
if (!dependency) {
|
|
1004
|
+
throw new StoreError(
|
|
1005
|
+
"stale-evidence",
|
|
1006
|
+
`Operation ${operationId} is not a dependency of wait ${waitId} generation ${generation}.`,
|
|
1007
|
+
);
|
|
1008
|
+
}
|
|
1009
|
+
if (dependency.terminalRevision === 0) {
|
|
1010
|
+
throw new StoreError(
|
|
1011
|
+
"dependencies-unsettled",
|
|
1012
|
+
`Operation ${operationId} has no terminal outcome yet, so there is no evidence to read for wait ${waitId}.`,
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
if (dependency.terminalRevision !== terminalRevision) {
|
|
1016
|
+
throw new StoreError(
|
|
1017
|
+
"stale-evidence",
|
|
1018
|
+
`Operation ${operationId} is at terminal revision ${dependency.terminalRevision}, not ${terminalRevision}. A read must name the revision it actually inspected.`,
|
|
1019
|
+
);
|
|
1020
|
+
}
|
|
1021
|
+
const at = ctx.now();
|
|
1022
|
+
const changes = run(
|
|
1023
|
+
ctx,
|
|
1024
|
+
`INSERT OR IGNORE INTO evidence_reads (
|
|
1025
|
+
wait_id, generation, operation_id, terminal_revision,
|
|
1026
|
+
reader_kind, reader_session_id, reader_workspace, reader_branch_id, reader_goal_id, read_at
|
|
1027
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1028
|
+
waitId,
|
|
1029
|
+
generation,
|
|
1030
|
+
operationId,
|
|
1031
|
+
terminalRevision,
|
|
1032
|
+
owner.kind,
|
|
1033
|
+
owner.sessionId,
|
|
1034
|
+
owner.workspace,
|
|
1035
|
+
owner.branchId ?? null,
|
|
1036
|
+
owner.goalId ?? null,
|
|
1037
|
+
at,
|
|
1038
|
+
);
|
|
1039
|
+
const row = getRow(
|
|
1040
|
+
ctx,
|
|
1041
|
+
`SELECT * FROM evidence_reads
|
|
1042
|
+
WHERE wait_id = ? AND generation = ? AND operation_id = ? AND terminal_revision = ?`,
|
|
1043
|
+
waitId,
|
|
1044
|
+
generation,
|
|
1045
|
+
operationId,
|
|
1046
|
+
terminalRevision,
|
|
1047
|
+
);
|
|
1048
|
+
return { read: mapEvidenceRead(row as Record<string, unknown>), recorded: changes > 0 };
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
export function listEvidenceReads(ctx: StoreContext, ref: WaitRef): EvidenceReadRecord[] {
|
|
1053
|
+
const waitId = requireId("waitId", ref.waitId);
|
|
1054
|
+
const generation = ref.generation === undefined
|
|
1055
|
+
? latestWaitGeneration(ctx, waitId)
|
|
1056
|
+
: requireCounter("generation", ref.generation);
|
|
1057
|
+
if (generation === null) return [];
|
|
1058
|
+
return getRows(
|
|
1059
|
+
ctx,
|
|
1060
|
+
"SELECT * FROM evidence_reads WHERE wait_id = ? AND generation = ? ORDER BY read_at, operation_id",
|
|
1061
|
+
waitId,
|
|
1062
|
+
generation,
|
|
1063
|
+
).map(mapEvidenceRead);
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
export function recordEvidencePin(
|
|
1067
|
+
ctx: StoreContext,
|
|
1068
|
+
input: RecordEvidencePinInput,
|
|
1069
|
+
): RecordEvidencePinResult {
|
|
1070
|
+
const waitId = requireId("waitId", input.waitId);
|
|
1071
|
+
const generation = requireCounter("generation", input.generation);
|
|
1072
|
+
const operationId = requireId("operationId", input.operationId);
|
|
1073
|
+
const terminalRevision = requireCounter("terminalRevision", input.terminalRevision);
|
|
1074
|
+
const kind = requireEnum("kind", input.kind, [
|
|
1075
|
+
"terminal-record",
|
|
1076
|
+
"log",
|
|
1077
|
+
"summary",
|
|
1078
|
+
"artifact",
|
|
1079
|
+
] as const);
|
|
1080
|
+
const ref = requireText("ref", input.ref, 1024);
|
|
1081
|
+
const summary = optionalText("summary", input.summary, 2048);
|
|
1082
|
+
const detailLost = input.detailLost === undefined ? false : requireBoolean("detailLost", input.detailLost);
|
|
1083
|
+
const bytes = input.bytes === undefined ? null : requireCounter("bytes", input.bytes);
|
|
1084
|
+
|
|
1085
|
+
return ctx.transaction(() => {
|
|
1086
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
1087
|
+
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
1088
|
+
throw new StoreError(
|
|
1089
|
+
"wait-phase",
|
|
1090
|
+
`Wait ${waitId} generation ${generation} is ${wait.phase}; its evidence pins were released.`,
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
const dependency = wait.dependencies.find((dep) => dep.operationId === operationId);
|
|
1094
|
+
if (!dependency) {
|
|
1095
|
+
throw new StoreError(
|
|
1096
|
+
"stale-evidence",
|
|
1097
|
+
`Operation ${operationId} is not a dependency of wait ${waitId} generation ${generation}.`,
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
if (dependency.terminalRevision === 0) {
|
|
1101
|
+
throw new StoreError(
|
|
1102
|
+
"dependencies-unsettled",
|
|
1103
|
+
`Operation ${operationId} has no terminal outcome yet; only terminal evidence can be pinned.`,
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
if (dependency.terminalRevision !== terminalRevision) {
|
|
1107
|
+
throw new StoreError(
|
|
1108
|
+
"stale-evidence",
|
|
1109
|
+
`Operation ${operationId} is at terminal revision ${dependency.terminalRevision}, not ${terminalRevision}.`,
|
|
1110
|
+
);
|
|
1111
|
+
}
|
|
1112
|
+
const at = ctx.now();
|
|
1113
|
+
const pinId = `pin_${randomUUID()}`;
|
|
1114
|
+
const changes = run(
|
|
1115
|
+
ctx,
|
|
1116
|
+
`INSERT OR IGNORE INTO evidence_pins (
|
|
1117
|
+
pin_id, wait_id, generation, operation_id, terminal_revision,
|
|
1118
|
+
kind, ref, summary, detail_lost, bytes, pinned_at
|
|
1119
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1120
|
+
pinId,
|
|
1121
|
+
waitId,
|
|
1122
|
+
generation,
|
|
1123
|
+
operationId,
|
|
1124
|
+
terminalRevision,
|
|
1125
|
+
kind,
|
|
1126
|
+
ref,
|
|
1127
|
+
summary,
|
|
1128
|
+
detailLost ? 1 : 0,
|
|
1129
|
+
bytes,
|
|
1130
|
+
at,
|
|
1131
|
+
);
|
|
1132
|
+
const row = changes > 0
|
|
1133
|
+
? getRow(ctx, "SELECT * FROM evidence_pins WHERE pin_id = ?", pinId)
|
|
1134
|
+
: getRow(
|
|
1135
|
+
ctx,
|
|
1136
|
+
`SELECT * FROM evidence_pins
|
|
1137
|
+
WHERE wait_id = ? AND generation = ? AND operation_id = ? AND terminal_revision = ?
|
|
1138
|
+
AND kind = ? AND ref = ?`,
|
|
1139
|
+
waitId,
|
|
1140
|
+
generation,
|
|
1141
|
+
operationId,
|
|
1142
|
+
terminalRevision,
|
|
1143
|
+
kind,
|
|
1144
|
+
ref,
|
|
1145
|
+
);
|
|
1146
|
+
return { pin: mapEvidencePin(row as Record<string, unknown>), recorded: changes > 0 };
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
export function listEvidencePins(
|
|
1151
|
+
ctx: StoreContext,
|
|
1152
|
+
ref: WaitRef,
|
|
1153
|
+
options: { includeReleased?: boolean } = {},
|
|
1154
|
+
): EvidencePinRecord[] {
|
|
1155
|
+
const waitId = requireId("waitId", ref.waitId);
|
|
1156
|
+
const generation = ref.generation === undefined
|
|
1157
|
+
? latestWaitGeneration(ctx, waitId)
|
|
1158
|
+
: requireCounter("generation", ref.generation);
|
|
1159
|
+
if (generation === null) return [];
|
|
1160
|
+
return readPins(ctx, waitId, generation, options.includeReleased === true);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/**
|
|
1164
|
+
* Explicit dismissal: release pins without consuming the result. Called by the
|
|
1165
|
+
* owner or by the supervising host during cleanup; it changes retention only.
|
|
1166
|
+
*/
|
|
1167
|
+
export function releaseEvidencePins(
|
|
1168
|
+
ctx: StoreContext,
|
|
1169
|
+
ref: WaitRef & { generation: number },
|
|
1170
|
+
reason: string,
|
|
1171
|
+
): string[] {
|
|
1172
|
+
const waitId = requireId("waitId", ref.waitId);
|
|
1173
|
+
const generation = requireCounter("generation", ref.generation);
|
|
1174
|
+
const text = requireText("reason", reason, 1024);
|
|
1175
|
+
return ctx.transaction(() => {
|
|
1176
|
+
requireWaitRow(ctx, waitId, generation);
|
|
1177
|
+
return releaseGenerationPins(ctx, waitId, generation, text, ctx.now());
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// ---- interpretation acknowledgement ------------------------------------
|
|
1182
|
+
|
|
1183
|
+
/**
|
|
1184
|
+
* Record the owner's interpretation of the exact terminal revisions and consume
|
|
1185
|
+
* the wait generation. A read of the current revision by the same owner and a
|
|
1186
|
+
* persisted note are required; delivery or a status read alone is not consumption.
|
|
1187
|
+
*/
|
|
1188
|
+
export function acknowledgeResult(
|
|
1189
|
+
ctx: StoreContext,
|
|
1190
|
+
input: AcknowledgeResultInput,
|
|
1191
|
+
): AcknowledgeResultOutput {
|
|
1192
|
+
const waitId = requireId("waitId", input.waitId);
|
|
1193
|
+
const generation = requireCounter("generation", input.generation);
|
|
1194
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
1195
|
+
const disposition = requireEnum("disposition", input.disposition, DISPOSITIONS);
|
|
1196
|
+
const note = requireText("note", input.note, 8192);
|
|
1197
|
+
if (!Array.isArray(input.terminalRevisions) || input.terminalRevisions.length === 0) {
|
|
1198
|
+
throw new StoreError(
|
|
1199
|
+
"validation",
|
|
1200
|
+
"Invalid terminalRevisions: acknowledgement names the exact revisions it interpreted",
|
|
1201
|
+
);
|
|
1202
|
+
}
|
|
1203
|
+
const revisions = input.terminalRevisions.map((entry, index) => {
|
|
1204
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
1205
|
+
throw new StoreError("validation", `Invalid terminalRevisions[${index}]: must be an object`);
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
operationId: requireId(`terminalRevisions[${index}].operationId`, entry.operationId),
|
|
1209
|
+
revision: requireCounter(`terminalRevisions[${index}].revision`, entry.revision),
|
|
1210
|
+
};
|
|
1211
|
+
});
|
|
1212
|
+
|
|
1213
|
+
return ctx.transaction(() => {
|
|
1214
|
+
assertCurrentGeneration(ctx, waitId, generation);
|
|
1215
|
+
const wait = requireWait(ctx, waitId, generation);
|
|
1216
|
+
assertWaitOwner(wait, owner, "acknowledgement");
|
|
1217
|
+
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
1218
|
+
throw new StoreError(
|
|
1219
|
+
"wait-phase",
|
|
1220
|
+
`Wait ${waitId} generation ${generation} is already ${wait.phase}; an interpretation is recorded once per generation.`,
|
|
1221
|
+
);
|
|
1222
|
+
}
|
|
1223
|
+
if (wait.phase === "registering" || wait.phase === "parking") {
|
|
1224
|
+
throw new StoreError(
|
|
1225
|
+
"wait-phase",
|
|
1226
|
+
`Wait ${waitId} generation ${generation} is still ${wait.phase}; the attempt that owns this checkpoint has not parked, so the result cannot be interpreted yet.`,
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
if (!wait.settled) {
|
|
1230
|
+
throw new StoreError(
|
|
1231
|
+
"dependencies-unsettled",
|
|
1232
|
+
`Wait ${waitId} generation ${generation} still has unfinished dependencies; acknowledgement requires a terminal outcome for every one.`,
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
const byOperation = new Map(revisions.map((entry) => [entry.operationId, entry.revision]));
|
|
1236
|
+
if (byOperation.size !== revisions.length) {
|
|
1237
|
+
throw new StoreError(
|
|
1238
|
+
"validation",
|
|
1239
|
+
"Invalid terminalRevisions: an operation is listed twice",
|
|
1240
|
+
);
|
|
1241
|
+
}
|
|
1242
|
+
for (const dependency of wait.dependencies) {
|
|
1243
|
+
const claimed = byOperation.get(dependency.operationId);
|
|
1244
|
+
if (claimed === undefined) {
|
|
1245
|
+
throw new StoreError(
|
|
1246
|
+
"stale-evidence",
|
|
1247
|
+
`Acknowledgement omits operation ${dependency.operationId}; every settled dependency must be interpreted.`,
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
if (claimed !== dependency.terminalRevision) {
|
|
1251
|
+
throw new StoreError(
|
|
1252
|
+
"stale-evidence",
|
|
1253
|
+
`Operation ${dependency.operationId} is at terminal revision ${dependency.terminalRevision}, but the acknowledgement names ${claimed}.`,
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
if (byOperation.size !== wait.dependencies.length) {
|
|
1258
|
+
throw new StoreError(
|
|
1259
|
+
"stale-evidence",
|
|
1260
|
+
"Acknowledgement names an operation that is not a dependency of this wait generation.",
|
|
1261
|
+
);
|
|
1262
|
+
}
|
|
1263
|
+
for (const dependency of wait.dependencies) {
|
|
1264
|
+
const read = getRow(
|
|
1265
|
+
ctx,
|
|
1266
|
+
`SELECT 1 AS present FROM evidence_reads
|
|
1267
|
+
WHERE wait_id = ? AND generation = ? AND operation_id = ? AND terminal_revision = ?`,
|
|
1268
|
+
waitId,
|
|
1269
|
+
generation,
|
|
1270
|
+
dependency.operationId,
|
|
1271
|
+
dependency.terminalRevision,
|
|
1272
|
+
);
|
|
1273
|
+
if (!read) {
|
|
1274
|
+
throw new StoreError(
|
|
1275
|
+
"evidence-read-required",
|
|
1276
|
+
`Operation ${dependency.operationId} revision ${dependency.terminalRevision} has not been read by this owner. Record the evidence read before acknowledging; a delivery or status read is not an interpretation.`,
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
const at = ctx.now();
|
|
1281
|
+
run(
|
|
1282
|
+
ctx,
|
|
1283
|
+
"UPDATE waits SET phase = 'consumed', phase_reason = ?, acknowledged_at = ?, acknowledgement_json = ?, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
1284
|
+
disposition,
|
|
1285
|
+
at,
|
|
1286
|
+
JSON.stringify({ disposition, note, revisions, acknowledgedAt: at }),
|
|
1287
|
+
at,
|
|
1288
|
+
waitId,
|
|
1289
|
+
generation,
|
|
1290
|
+
);
|
|
1291
|
+
const acknowledgedOutboxIds = acknowledgeGenerationOutbox(ctx, waitId, generation, at);
|
|
1292
|
+
const releasedPinIds = releaseGenerationPins(ctx, waitId, generation, "wait-consumed", at);
|
|
1293
|
+
return {
|
|
1294
|
+
wait: requireWait(ctx, waitId, generation),
|
|
1295
|
+
acknowledgedOutboxIds,
|
|
1296
|
+
releasedPinIds,
|
|
1297
|
+
};
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// ---- reads --------------------------------------------------------------
|
|
1302
|
+
|
|
1303
|
+
export function getWait(ctx: StoreContext, ref: WaitRef): WaitRecord | null {
|
|
1304
|
+
const waitId = requireId("waitId", ref.waitId);
|
|
1305
|
+
const generation = ref.generation === undefined
|
|
1306
|
+
? undefined
|
|
1307
|
+
: requireCounter("generation", ref.generation);
|
|
1308
|
+
return readWait(ctx, waitId, generation);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
export function listWaits(ctx: StoreContext, filter: WaitFilter = {}): WaitRecord[] {
|
|
1312
|
+
const clauses: string[] = [];
|
|
1313
|
+
const params: Array<string | number> = [];
|
|
1314
|
+
if (filter.owner) {
|
|
1315
|
+
clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
|
|
1316
|
+
params.push(filter.owner.kind, filter.owner.sessionId, filter.owner.workspace);
|
|
1317
|
+
if (filter.owner.branchId !== undefined) {
|
|
1318
|
+
clauses.push("coalesce(owner_branch_id, '') = ?");
|
|
1319
|
+
params.push(filter.owner.branchId ?? "");
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
if (filter.phase !== undefined) {
|
|
1323
|
+
const phases = Array.isArray(filter.phase) ? filter.phase : [filter.phase as WaitPhase];
|
|
1324
|
+
for (const phase of phases) {
|
|
1325
|
+
if (!PHASES.includes(phase)) {
|
|
1326
|
+
throw new StoreError("validation", `Invalid phase: must be one of ${PHASES.join(", ")}`);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
clauses.push(`phase IN (${phases.map(() => "?").join(", ")})`);
|
|
1330
|
+
params.push(...phases);
|
|
1331
|
+
}
|
|
1332
|
+
if (filter.pendingOnly) {
|
|
1333
|
+
clauses.push("phase NOT IN ('consumed', 'cancelled')");
|
|
1334
|
+
}
|
|
1335
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
1336
|
+
return getRows(
|
|
1337
|
+
ctx,
|
|
1338
|
+
`SELECT * FROM waits ${where} ORDER BY created_at, wait_id, generation`,
|
|
1339
|
+
...params,
|
|
1340
|
+
).map((row) => mapWait(ctx, row));
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
export function listDependencies(
|
|
1344
|
+
ctx: StoreContext,
|
|
1345
|
+
ref: WaitRef,
|
|
1346
|
+
): WaitDependencyRecord[] {
|
|
1347
|
+
const waitId = requireId("waitId", ref.waitId);
|
|
1348
|
+
const generation = ref.generation === undefined
|
|
1349
|
+
? latestWaitGeneration(ctx, waitId)
|
|
1350
|
+
: requireCounter("generation", ref.generation);
|
|
1351
|
+
if (generation === null) return [];
|
|
1352
|
+
return dependencyState(ctx, waitId, generation).dependencies;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/** Latest-generation helper for callers that only know an owner. */
|
|
1356
|
+
export function findPendingWaitForOwner(
|
|
1357
|
+
ctx: StoreContext,
|
|
1358
|
+
owner: OwnerIdentity,
|
|
1359
|
+
): WaitRecord | null {
|
|
1360
|
+
const row = getRow(
|
|
1361
|
+
ctx,
|
|
1362
|
+
`SELECT * FROM waits
|
|
1363
|
+
WHERE owner_kind = ? AND owner_session_id = ? AND coalesce(owner_branch_id, '') = ?
|
|
1364
|
+
AND phase NOT IN ('consumed', 'cancelled')`,
|
|
1365
|
+
owner.kind,
|
|
1366
|
+
owner.sessionId,
|
|
1367
|
+
owner.branchId ?? "",
|
|
1368
|
+
);
|
|
1369
|
+
return row ? requireWait(ctx, columnText(row, "wait_id"), columnNumber(row, "generation")) : null;
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** Diagnostic: unresolved resume claims a replacement host must reconcile first. */
|
|
1373
|
+
export function listUnreconciledClaims(ctx: StoreContext): ResumeClaimRecord[] {
|
|
1374
|
+
return getRows(
|
|
1375
|
+
ctx,
|
|
1376
|
+
"SELECT * FROM resume_claims WHERE state IN ('claimed', 'published') ORDER BY claimed_at, claim_id",
|
|
1377
|
+
).map(mapClaim);
|
|
1378
|
+
}
|