pi-better-server 0.2.4 → 0.3.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/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// Generated canonical coordinator. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Operation registration, supervision updates and terminal outcomes.
|
|
4
|
+
*
|
|
5
|
+
* Launch identity is immutable. Registering the same launch twice is an
|
|
6
|
+
* idempotent replay; changing any of it is refused, because a store that
|
|
7
|
+
* rewrites an owner or a task binding cannot be used to prove who owns a wait.
|
|
8
|
+
*
|
|
9
|
+
* A terminal outcome is recorded once per operation (`terminalRevision` 1) with
|
|
10
|
+
* the supervisor's event id. A replay with the same event id returns the
|
|
11
|
+
* recorded revision without side effects; a different terminal event for the
|
|
12
|
+
* same operation is refused instead of overwriting the first evidence.
|
|
13
|
+
*/
|
|
14
|
+
import { StoreError } from "./errors.mjs";
|
|
15
|
+
import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.mjs";
|
|
16
|
+
import { columnText, getRows, isUniqueViolation, run, } from "./sqlite.mjs";
|
|
17
|
+
import { describeOwnerDiff, normalizeOwner, optionalText, requireBoolean, requireEnum, requireEvidenceKind, requireId, requireObserver, requireOptionalCounter, requireText, sameOwner, } from "./validate.mjs";
|
|
18
|
+
import { mapOutbox } from "./rows.mjs";
|
|
19
|
+
import { settleWaitsForOperation } from "./waits.mjs";
|
|
20
|
+
import { bumpChangeRevision } from "./discovery.mjs";
|
|
21
|
+
const HEALTH_VALUES = ["active", "unmonitored", "lost"];
|
|
22
|
+
const OUTCOME_VALUES = ["succeeded", "failed", "cancelled", "lost"];
|
|
23
|
+
function normalizeSupervision(value) {
|
|
24
|
+
if (value === undefined || value === null)
|
|
25
|
+
return null;
|
|
26
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
27
|
+
throw new StoreError("validation", "Invalid supervision: must be an object");
|
|
28
|
+
}
|
|
29
|
+
const supervision = value;
|
|
30
|
+
return {
|
|
31
|
+
hostId: requireId("supervision.hostId", supervision.hostId),
|
|
32
|
+
runnerId: supervision.runnerId === undefined || supervision.runnerId === null
|
|
33
|
+
? null
|
|
34
|
+
: requireId("supervision.runnerId", supervision.runnerId),
|
|
35
|
+
processStartToken: supervision.processStartToken === undefined || supervision.processStartToken === null
|
|
36
|
+
? null
|
|
37
|
+
: requireId("supervision.processStartToken", supervision.processStartToken),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function normalizeEvidence(value) {
|
|
41
|
+
if (value === undefined || value === null)
|
|
42
|
+
return [];
|
|
43
|
+
if (!Array.isArray(value)) {
|
|
44
|
+
throw new StoreError("validation", "Invalid evidence: must be an array");
|
|
45
|
+
}
|
|
46
|
+
return value.map((entry, index) => {
|
|
47
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
48
|
+
throw new StoreError("validation", `Invalid evidence[${index}]: must be an object`);
|
|
49
|
+
}
|
|
50
|
+
const item = entry;
|
|
51
|
+
const normalized = {
|
|
52
|
+
kind: requireEvidenceKind(`evidence[${index}].kind`, item.kind),
|
|
53
|
+
ref: requireText(`evidence[${index}].ref`, item.ref, 1024),
|
|
54
|
+
detailLost: item.detailLost === undefined ? false : requireBoolean(`evidence[${index}].detailLost`, item.detailLost),
|
|
55
|
+
};
|
|
56
|
+
const summary = optionalText(`evidence[${index}].summary`, item.summary, 2048);
|
|
57
|
+
if (summary !== null)
|
|
58
|
+
normalized.summary = summary;
|
|
59
|
+
const bytes = requireOptionalCounter(`evidence[${index}].bytes`, item.bytes);
|
|
60
|
+
if (bytes !== null)
|
|
61
|
+
normalized.bytes = bytes;
|
|
62
|
+
return normalized;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export function registerOperation(ctx, input) {
|
|
66
|
+
const operationId = requireId("operationId", input.operationId);
|
|
67
|
+
const taskId = requireId("taskId", input.taskId);
|
|
68
|
+
const launchToken = requireId("launchToken", input.launchToken);
|
|
69
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
70
|
+
const observer = requireObserver("observer", input.observer);
|
|
71
|
+
const supervision = normalizeSupervision(input.supervision);
|
|
72
|
+
const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
|
|
73
|
+
const intentRef = optionalText("intentRef", input.intentRef, 200);
|
|
74
|
+
const assertTaskAvailable = () => {
|
|
75
|
+
const byTask = getRows(ctx, "SELECT * FROM operations WHERE task_id = ?", taskId)[0];
|
|
76
|
+
if (!byTask)
|
|
77
|
+
return;
|
|
78
|
+
const existingOwner = ownerFromRow(byTask);
|
|
79
|
+
if (!sameOwner(existingOwner, owner)) {
|
|
80
|
+
throw new StoreError("task-ownership", `Background task ${taskId} is owned by another execution owner. A task id belongs to the launch that registered it; a different owner must not attach to it.`);
|
|
81
|
+
}
|
|
82
|
+
throw new StoreError("operation-conflict", `Background task ${taskId} is already bound to operation ${columnText(byTask, "operation_id")}. One durable operation exists per task launch; reconcile the recorded one instead of registering a second.`);
|
|
83
|
+
};
|
|
84
|
+
const assertLaunchIdentity = (existing) => {
|
|
85
|
+
const differences = [];
|
|
86
|
+
if (existing.taskId !== taskId)
|
|
87
|
+
differences.push("taskId");
|
|
88
|
+
if (existing.launchToken !== launchToken)
|
|
89
|
+
differences.push("launchToken");
|
|
90
|
+
if (!sameOwner(existing.owner, owner)) {
|
|
91
|
+
differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
|
|
92
|
+
}
|
|
93
|
+
if (existing.observer.kind !== observer.kind || existing.observer.version !== observer.version) {
|
|
94
|
+
differences.push("observer");
|
|
95
|
+
}
|
|
96
|
+
if (differences.length > 0) {
|
|
97
|
+
throw new StoreError("operation-conflict", `Operation ${operationId} is already registered with a different launch identity: ${differences.join(", ")}. Launch identity and ownership are immutable; register a new operation id for a new launch.`);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
return ctx.transaction(() => {
|
|
101
|
+
const existing = readOperation(ctx, operationId);
|
|
102
|
+
if (existing) {
|
|
103
|
+
assertLaunchIdentity(existing);
|
|
104
|
+
return { operation: existing, created: false };
|
|
105
|
+
}
|
|
106
|
+
assertTaskAvailable();
|
|
107
|
+
const at = ctx.now();
|
|
108
|
+
try {
|
|
109
|
+
run(ctx, `INSERT INTO operations (
|
|
110
|
+
operation_id, task_id, launch_token,
|
|
111
|
+
owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
|
|
112
|
+
observer_kind, observer_version, supervision_json, supervision_host_id, authority_ref, intent_ref,
|
|
113
|
+
phase, health, health_reason, terminal_revision, created_at, updated_at
|
|
114
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`, operationId, taskId, launchToken, owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? null, owner.goalId ?? null, observer.kind, observer.version, supervision ? JSON.stringify(supervision) : null, supervision?.hostId ?? null, authorityRef, intentRef, at, at);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// Another process may have registered the same launch (or the same task)
|
|
118
|
+
// between the check above and this insert. Re-read and report the same
|
|
119
|
+
// typed outcome instead of leaking a raw constraint error.
|
|
120
|
+
if (!isUniqueViolation(error, "operations.task_id", "operations.operation_id"))
|
|
121
|
+
throw error;
|
|
122
|
+
const raced = readOperation(ctx, operationId);
|
|
123
|
+
if (raced) {
|
|
124
|
+
assertLaunchIdentity(raced);
|
|
125
|
+
return { operation: raced, created: false };
|
|
126
|
+
}
|
|
127
|
+
assertTaskAvailable();
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
bumpChangeRevision(ctx);
|
|
131
|
+
return { operation: requireOperation(ctx, operationId), created: true };
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Replace the supervision identity and/or observer health. A replacement host
|
|
136
|
+
* may take over observation; ownership and launch identity stay untouched.
|
|
137
|
+
*/
|
|
138
|
+
export function recordSupervision(ctx, input) {
|
|
139
|
+
const operationId = requireId("operationId", input.operationId);
|
|
140
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
141
|
+
const supervision = normalizeSupervision(input.supervision);
|
|
142
|
+
const expectedHostId = input.expectedHostId === undefined
|
|
143
|
+
? undefined
|
|
144
|
+
: input.expectedHostId === null
|
|
145
|
+
? null
|
|
146
|
+
: requireId("expectedHostId", input.expectedHostId);
|
|
147
|
+
const health = input.health === undefined
|
|
148
|
+
? null
|
|
149
|
+
: requireEnum("health", input.health, HEALTH_VALUES);
|
|
150
|
+
const reason = optionalText("reason", input.reason, 1024);
|
|
151
|
+
if (health === null && supervision === null) {
|
|
152
|
+
throw new StoreError("validation", "Invalid supervision update: nothing to record");
|
|
153
|
+
}
|
|
154
|
+
if (supervision !== null && expectedHostId === undefined) {
|
|
155
|
+
throw new StoreError("validation", "Invalid expectedHostId: replacing supervision requires the observed current host id, or null when no supervisor was recorded.");
|
|
156
|
+
}
|
|
157
|
+
return ctx.transaction(() => {
|
|
158
|
+
const operation = requireOperation(ctx, operationId);
|
|
159
|
+
if (!sameOwner(operation.owner, owner)) {
|
|
160
|
+
throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}).`);
|
|
161
|
+
}
|
|
162
|
+
if (expectedHostId !== undefined) {
|
|
163
|
+
const currentHostId = operation.supervision?.hostId ?? null;
|
|
164
|
+
if (currentHostId !== expectedHostId) {
|
|
165
|
+
throw new StoreError("supervision-conflict", `Operation ${operationId} is now supervised by ${currentHostId ?? "no host"}, not the observed ${expectedHostId ?? "no host"}; the stale replacement was refused.`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const nextHealth = health ?? operation.health;
|
|
169
|
+
const nextReason = nextHealth === "active" ? null : (reason ?? operation.healthReason);
|
|
170
|
+
if (nextHealth !== "active" && nextReason === null) {
|
|
171
|
+
throw new StoreError("validation", "Invalid reason: observer health other than active requires a recorded reason");
|
|
172
|
+
}
|
|
173
|
+
const nextSupervision = supervision ?? operation.supervision;
|
|
174
|
+
const nextHostId = nextSupervision?.hostId ?? null;
|
|
175
|
+
const authorityChanged = (operation.supervision?.hostId ?? null) !== nextHostId;
|
|
176
|
+
run(ctx, "UPDATE operations SET supervision_json = ?, supervision_host_id = ?, health = ?, health_reason = ?, updated_at = ? WHERE operation_id = ?", nextSupervision ? JSON.stringify(nextSupervision) : null, nextHostId, nextHealth, nextReason, ctx.now(), operationId);
|
|
177
|
+
if (authorityChanged)
|
|
178
|
+
bumpChangeRevision(ctx);
|
|
179
|
+
return requireOperation(ctx, operationId);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Release a closed host's supervision authority without clearing a newer
|
|
184
|
+
* holder. The update is conditional on the exact recorded host, so a host that
|
|
185
|
+
* shut down while another process already took over cannot erase the takeover.
|
|
186
|
+
* A terminal operation keeps its final supervision record; only running work
|
|
187
|
+
* becomes explicitly unmonitored for the next host.
|
|
188
|
+
*/
|
|
189
|
+
export function releaseSupervision(ctx, input) {
|
|
190
|
+
const operationId = requireId("operationId", input.operationId);
|
|
191
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
192
|
+
const hostId = requireId("hostId", input.hostId);
|
|
193
|
+
const reason = optionalText("reason", input.reason, 1024)
|
|
194
|
+
?? "the supervising host closed; another host may take over";
|
|
195
|
+
return ctx.transaction(() => {
|
|
196
|
+
const operation = requireOperation(ctx, operationId);
|
|
197
|
+
if (!sameOwner(operation.owner, owner)) {
|
|
198
|
+
throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}).`);
|
|
199
|
+
}
|
|
200
|
+
if (operation.supervision?.hostId !== hostId)
|
|
201
|
+
return null;
|
|
202
|
+
if (operation.phase === "terminal")
|
|
203
|
+
return operation;
|
|
204
|
+
run(ctx, `UPDATE operations
|
|
205
|
+
SET supervision_json = NULL, supervision_host_id = NULL,
|
|
206
|
+
health = 'unmonitored', health_reason = ?, updated_at = ?
|
|
207
|
+
WHERE operation_id = ?`, reason, ctx.now(), operationId);
|
|
208
|
+
bumpChangeRevision(ctx);
|
|
209
|
+
return requireOperation(ctx, operationId);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
export function recordTerminalOutcome(ctx, input) {
|
|
213
|
+
const operationId = requireId("operationId", input.operationId);
|
|
214
|
+
const eventId = requireId("eventId", input.eventId);
|
|
215
|
+
const outcome = requireEnum("outcome", input.outcome, OUTCOME_VALUES);
|
|
216
|
+
const owner = normalizeOwner("owner", input.owner);
|
|
217
|
+
const evidence = normalizeEvidence(input.evidence);
|
|
218
|
+
const reason = optionalText("reason", input.reason, 1024);
|
|
219
|
+
const detailLost = input.detailLost === undefined
|
|
220
|
+
? outcome === "lost"
|
|
221
|
+
: requireBoolean("detailLost", input.detailLost);
|
|
222
|
+
return ctx.transaction(() => {
|
|
223
|
+
const operation = requireOperation(ctx, operationId);
|
|
224
|
+
if (!sameOwner(operation.owner, owner)) {
|
|
225
|
+
throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}); a terminal outcome must be reported by or for its registered owner.`);
|
|
226
|
+
}
|
|
227
|
+
if (operation.phase === "terminal") {
|
|
228
|
+
if (operation.terminalEventId === eventId) {
|
|
229
|
+
return {
|
|
230
|
+
operation,
|
|
231
|
+
recorded: false,
|
|
232
|
+
outbox: listOutboxForRevision(ctx, operationId, operation.terminalRevision),
|
|
233
|
+
ready: [],
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
throw new StoreError("terminal-conflict", `Operation ${operationId} already recorded terminal event ${operation.terminalEventId} (${operation.terminalOutcome}). Event ${eventId} is a different terminal event and cannot replace it; a replayed event must reuse its original event id.`);
|
|
237
|
+
}
|
|
238
|
+
// A replay may omit evidence: the recorded revision already holds it. Only a
|
|
239
|
+
// new terminal revision must be interpretable on its own.
|
|
240
|
+
if (evidence.length === 0 && reason === null) {
|
|
241
|
+
throw new StoreError("validation", "Invalid reason: a terminal outcome without evidence must record why (for example lost supervision), so the result is interpretable.");
|
|
242
|
+
}
|
|
243
|
+
const at = ctx.now();
|
|
244
|
+
evidence.forEach((item, ordinal) => {
|
|
245
|
+
run(ctx, `INSERT INTO operation_evidence (
|
|
246
|
+
operation_id, terminal_revision, ordinal, kind, ref, summary, detail_lost, bytes, captured_at
|
|
247
|
+
) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?)`, operationId, ordinal, item.kind, item.ref, item.summary ?? null, item.detailLost ? 1 : 0, item.bytes ?? null, at);
|
|
248
|
+
});
|
|
249
|
+
run(ctx, `UPDATE operations
|
|
250
|
+
SET phase = 'terminal', terminal_revision = 1, terminal_outcome = ?, terminal_event_id = ?,
|
|
251
|
+
terminal_detail_lost = ?, terminal_reason = ?, terminal_at = ?, updated_at = ?
|
|
252
|
+
WHERE operation_id = ?`, outcome, eventId, detailLost ? 1 : 0, reason, at, at, operationId);
|
|
253
|
+
bumpChangeRevision(ctx);
|
|
254
|
+
const settledOperation = requireOperation(ctx, operationId);
|
|
255
|
+
const settled = settleWaitsForOperation(ctx, settledOperation, at);
|
|
256
|
+
const outbox = listOutboxForRevision(ctx, operationId, 1);
|
|
257
|
+
return {
|
|
258
|
+
operation: settledOperation,
|
|
259
|
+
recorded: true,
|
|
260
|
+
outbox,
|
|
261
|
+
ready: settled.ready,
|
|
262
|
+
};
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
export function getOperation(ctx, operationId) {
|
|
266
|
+
return readOperation(ctx, operationId);
|
|
267
|
+
}
|
|
268
|
+
export function listOperations(ctx, filter = {}) {
|
|
269
|
+
const clauses = [];
|
|
270
|
+
const params = [];
|
|
271
|
+
if (filter.ownerScope) {
|
|
272
|
+
const owner = normalizeOwner("ownerScope", filter.ownerScope);
|
|
273
|
+
clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
|
|
274
|
+
params.push(owner.kind, owner.sessionId, owner.workspace);
|
|
275
|
+
}
|
|
276
|
+
if (filter.owner) {
|
|
277
|
+
const owner = normalizeOwner("owner", filter.owner);
|
|
278
|
+
clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ? AND coalesce(owner_branch_id, '') = ? AND coalesce(owner_goal_id, '') = ?");
|
|
279
|
+
params.push(owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? "");
|
|
280
|
+
}
|
|
281
|
+
if (filter.phase !== undefined) {
|
|
282
|
+
clauses.push("phase = ?");
|
|
283
|
+
params.push(requireEnum("phase", filter.phase, ["running", "terminal"]));
|
|
284
|
+
}
|
|
285
|
+
if (filter.taskId !== undefined) {
|
|
286
|
+
clauses.push("task_id = ?");
|
|
287
|
+
params.push(requireId("taskId", filter.taskId));
|
|
288
|
+
}
|
|
289
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
290
|
+
return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
|
|
291
|
+
.map(mapOperation);
|
|
292
|
+
}
|
|
293
|
+
/** Running operations assigned to one supervising host, using the phase/host index. */
|
|
294
|
+
export function listRunningSupervisedBy(ctx, hostId) {
|
|
295
|
+
return getRows(ctx, "SELECT * FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id", requireId("hostId", hostId)).map(mapOperation);
|
|
296
|
+
}
|
|
297
|
+
function listOutboxForRevision(ctx, operationId, terminalRevision) {
|
|
298
|
+
return getRows(ctx, "SELECT * FROM outbox_events WHERE operation_id = ? AND terminal_revision = ? ORDER BY created_at, event_id", operationId, terminalRevision).map((row) => mapOutbox(ctx, row));
|
|
299
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Generated canonical coordinator. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Durable result delivery.
|
|
4
|
+
*
|
|
5
|
+
* The outbox is addressed to the wait's owner identity, not to a process. One
|
|
6
|
+
* event exists per terminal revision per wait generation, so duplicate terminal
|
|
7
|
+
* events, reload replay and repeated reconciliation cannot enqueue a second
|
|
8
|
+
* event for the same result.
|
|
9
|
+
*
|
|
10
|
+
* Delivery itself is at-least-once, not exactly-once. The unique event and its
|
|
11
|
+
* unique index make enqueue idempotent, but `markOutboxDelivered` commits after
|
|
12
|
+
* the caller emitted the result: a crash between emission and that write leaves
|
|
13
|
+
* the event claimed, and a reconciled host may emit it again. Recipients must
|
|
14
|
+
* key on the event id (or operation, revision, wait and generation) instead of
|
|
15
|
+
* assuming a result is emitted once.
|
|
16
|
+
*
|
|
17
|
+
* Delivery and interpretation are separate: a dispatched or delivered event is
|
|
18
|
+
* not a consumed result. Only `acknowledgeResult` marks the generation consumed,
|
|
19
|
+
* and only an acknowledgement releases the evidence pins that kept the terminal
|
|
20
|
+
* evidence alive.
|
|
21
|
+
*/
|
|
22
|
+
import { randomUUID } from "node:crypto";
|
|
23
|
+
import { StoreError } from "./errors.mjs";
|
|
24
|
+
import { dependencyState, mapOutbox, ownerFromRow, readOperationEvidence, readOutboxRow, requireWaitRow, } from "./rows.mjs";
|
|
25
|
+
import { columnJson, columnNullableText, columnNumber, columnText, getRows, run } from "./sqlite.mjs";
|
|
26
|
+
import { requireCounter, requireId, requireText } from "./validate.mjs";
|
|
27
|
+
const OUTBOX_STATES = [
|
|
28
|
+
"pending",
|
|
29
|
+
"claimed",
|
|
30
|
+
"delivered",
|
|
31
|
+
"acknowledged",
|
|
32
|
+
"voided",
|
|
33
|
+
];
|
|
34
|
+
/** Delivery is only meaningful once the generation can act on the evidence. */
|
|
35
|
+
const DELIVERABLE_WAIT_PHASES = ["ready", "resuming"];
|
|
36
|
+
const UNCONSUMED_OUTBOX_STATES = ["pending", "claimed", "delivered"];
|
|
37
|
+
function placeholders(count) {
|
|
38
|
+
return new Array(count).fill("?").join(", ");
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Enqueue one event per settled dependency at its terminal revision, and pin the
|
|
42
|
+
* evidence that event refers to. Idempotent: the unique
|
|
43
|
+
* (operation, revision, wait, generation) index decides whether anything is new.
|
|
44
|
+
*/
|
|
45
|
+
export function enqueueGenerationOutbox(ctx, waitId, generation, recipient, dependencies, at) {
|
|
46
|
+
const inserted = [];
|
|
47
|
+
for (const dependency of dependencies) {
|
|
48
|
+
if (dependency.terminalRevision <= 0)
|
|
49
|
+
continue;
|
|
50
|
+
const eventId = `evt_${randomUUID()}`;
|
|
51
|
+
const changes = run(ctx, `INSERT OR IGNORE INTO outbox_events (
|
|
52
|
+
event_id, operation_id, terminal_revision, wait_id, generation,
|
|
53
|
+
recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
|
|
54
|
+
state, attempts, created_at
|
|
55
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)`, eventId, dependency.operationId, dependency.terminalRevision, waitId, generation, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
56
|
+
if (changes === 0)
|
|
57
|
+
continue;
|
|
58
|
+
for (const evidence of readOperationEvidence(ctx, dependency.operationId, dependency.terminalRevision)) {
|
|
59
|
+
run(ctx, `INSERT OR IGNORE INTO evidence_pins (
|
|
60
|
+
pin_id, wait_id, generation, operation_id, terminal_revision,
|
|
61
|
+
kind, ref, summary, detail_lost, bytes, pinned_at
|
|
62
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, waitId, generation, evidence.operationId, evidence.terminalRevision, evidence.kind, evidence.ref, evidence.summary ?? null, evidence.detailLost ? 1 : 0, evidence.bytes ?? null, at);
|
|
63
|
+
}
|
|
64
|
+
const row = readOutboxRow(ctx, eventId);
|
|
65
|
+
if (row)
|
|
66
|
+
inserted.push(mapOutbox(ctx, row));
|
|
67
|
+
}
|
|
68
|
+
return inserted;
|
|
69
|
+
}
|
|
70
|
+
/** Enqueue for a generation that just became ready, reading its dependencies. */
|
|
71
|
+
export function enqueueReadyGeneration(ctx, waitId, generation, at) {
|
|
72
|
+
const row = requireWaitRow(ctx, waitId, generation);
|
|
73
|
+
const recipient = {
|
|
74
|
+
kind: columnText(row, "owner_kind"),
|
|
75
|
+
sessionId: columnText(row, "owner_session_id"),
|
|
76
|
+
workspace: columnText(row, "owner_workspace"),
|
|
77
|
+
branchId: columnNullableText(row, "owner_branch_id"),
|
|
78
|
+
goalId: columnNullableText(row, "owner_goal_id"),
|
|
79
|
+
};
|
|
80
|
+
const state = dependencyState(ctx, waitId, generation);
|
|
81
|
+
if (!state.settled) {
|
|
82
|
+
throw new StoreError("dependencies-unsettled", `Wait ${waitId} generation ${generation} still has unfinished dependencies; result delivery is enqueued only when every dependency has a terminal outcome.`);
|
|
83
|
+
}
|
|
84
|
+
return enqueueGenerationOutbox(ctx, waitId, generation, recipient, state.dependencies, at);
|
|
85
|
+
}
|
|
86
|
+
/** Release the pins of a generation; used by acknowledgement and cancellation. */
|
|
87
|
+
export function releaseGenerationPins(ctx, waitId, generation, reason, at) {
|
|
88
|
+
const rows = getRows(ctx, "SELECT pin_id FROM evidence_pins WHERE wait_id = ? AND generation = ? AND released_at IS NULL", waitId, generation);
|
|
89
|
+
const ids = rows.map((row) => columnText(row, "pin_id"));
|
|
90
|
+
if (ids.length === 0)
|
|
91
|
+
return [];
|
|
92
|
+
run(ctx, `UPDATE evidence_pins SET released_at = ?, release_reason = ?
|
|
93
|
+
WHERE wait_id = ? AND generation = ? AND released_at IS NULL`, at, reason, waitId, generation);
|
|
94
|
+
return ids;
|
|
95
|
+
}
|
|
96
|
+
/** Void unconsumed deliveries of a generation; cancellation resolves the wait, not the result. */
|
|
97
|
+
export function voidGenerationOutbox(ctx, waitId, generation, reason, at) {
|
|
98
|
+
const rows = getRows(ctx, `SELECT event_id FROM outbox_events
|
|
99
|
+
WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
|
|
100
|
+
const ids = rows.map((row) => columnText(row, "event_id"));
|
|
101
|
+
if (ids.length === 0)
|
|
102
|
+
return [];
|
|
103
|
+
run(ctx, `UPDATE outbox_events SET state = 'voided', voided_at = ?, reason = ?, dispatch_claim_json = NULL
|
|
104
|
+
WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, at, reason, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
|
|
105
|
+
return ids;
|
|
106
|
+
}
|
|
107
|
+
/** Mark the generation's deliveries consumed by interpretation. */
|
|
108
|
+
export function acknowledgeGenerationOutbox(ctx, waitId, generation, at) {
|
|
109
|
+
const rows = getRows(ctx, `SELECT event_id FROM outbox_events
|
|
110
|
+
WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
|
|
111
|
+
const ids = rows.map((row) => columnText(row, "event_id"));
|
|
112
|
+
if (ids.length === 0)
|
|
113
|
+
return [];
|
|
114
|
+
run(ctx, `UPDATE outbox_events SET state = 'acknowledged', acknowledged_at = ?, dispatch_claim_json = NULL
|
|
115
|
+
WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, at, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
|
|
116
|
+
return ids;
|
|
117
|
+
}
|
|
118
|
+
function ownerClause(prefix, owner) {
|
|
119
|
+
return {
|
|
120
|
+
sql: `${prefix}_kind = ? AND ${prefix}_session_id = ? AND ${prefix}_workspace = ?
|
|
121
|
+
AND coalesce(${prefix}_branch_id, '') = ? AND coalesce(${prefix}_goal_id, '') = ?`,
|
|
122
|
+
params: [owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? ""],
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export function listOutbox(ctx, filter = {}) {
|
|
126
|
+
const clauses = [];
|
|
127
|
+
const params = [];
|
|
128
|
+
if (filter.recipient) {
|
|
129
|
+
const clause = ownerClause("recipient", filter.recipient);
|
|
130
|
+
clauses.push(clause.sql);
|
|
131
|
+
params.push(...clause.params);
|
|
132
|
+
}
|
|
133
|
+
if (filter.state !== undefined) {
|
|
134
|
+
const states = Array.isArray(filter.state) ? filter.state : [filter.state];
|
|
135
|
+
for (const state of states) {
|
|
136
|
+
if (!OUTBOX_STATES.includes(state)) {
|
|
137
|
+
throw new StoreError("validation", `Invalid state: must be one of ${OUTBOX_STATES.join(", ")}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
clauses.push(`state IN (${placeholders(states.length)})`);
|
|
141
|
+
params.push(...states);
|
|
142
|
+
}
|
|
143
|
+
if (filter.waitId !== undefined) {
|
|
144
|
+
clauses.push("wait_id = ?");
|
|
145
|
+
params.push(requireId("waitId", filter.waitId));
|
|
146
|
+
}
|
|
147
|
+
if (filter.generation !== undefined) {
|
|
148
|
+
clauses.push("generation = ?");
|
|
149
|
+
params.push(requireCounter("generation", filter.generation));
|
|
150
|
+
}
|
|
151
|
+
if (filter.operationId !== undefined) {
|
|
152
|
+
clauses.push("operation_id = ?");
|
|
153
|
+
params.push(requireId("operationId", filter.operationId));
|
|
154
|
+
}
|
|
155
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
156
|
+
return getRows(ctx, `SELECT * FROM outbox_events ${where} ORDER BY created_at, event_id`, ...params).map((row) => mapOutbox(ctx, row));
|
|
157
|
+
}
|
|
158
|
+
/** Find recipients with deliverable dependencies without loading each event's evidence. */
|
|
159
|
+
export function listDispatchableOutboxRecipients(ctx) {
|
|
160
|
+
return getRows(ctx, `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
|
|
161
|
+
count(*) AS pending_count
|
|
162
|
+
FROM outbox_events
|
|
163
|
+
WHERE state = 'pending' AND event_type = 'dependency-ready'
|
|
164
|
+
AND EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
|
|
165
|
+
AND w.generation = outbox_events.generation
|
|
166
|
+
AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)}))
|
|
167
|
+
GROUP BY recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id
|
|
168
|
+
ORDER BY min(created_at), min(event_id)`, ...DELIVERABLE_WAIT_PHASES).map((row) => ({ recipient: ownerFromRow(row, "recipient"), count: columnNumber(row, "pending_count") }));
|
|
169
|
+
}
|
|
170
|
+
function readDispatchClaim(row) {
|
|
171
|
+
return columnJson(row, "dispatch_claim_json");
|
|
172
|
+
}
|
|
173
|
+
function assertDispatchTokenUnused(ctx, claimToken) {
|
|
174
|
+
const rows = getRows(ctx, "SELECT event_id, dispatch_claim_json FROM outbox_events WHERE state = 'claimed'");
|
|
175
|
+
for (const row of rows) {
|
|
176
|
+
const claim = readDispatchClaim(row);
|
|
177
|
+
if (claim === null)
|
|
178
|
+
continue;
|
|
179
|
+
if (claim.token === claimToken) {
|
|
180
|
+
throw new StoreError("outbox-state", `Dispatch token ${claimToken} is already held by event ${columnText(row, "event_id")}. Use a fresh token for a new dispatch attempt.`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Claim pending deliveries for dispatch. Claiming records an attempt but does not
|
|
186
|
+
* consume the result: an event that is never acknowledged stays visible.
|
|
187
|
+
*/
|
|
188
|
+
export function claimOutbox(ctx, input) {
|
|
189
|
+
const claimToken = requireId("claimToken", input.claimToken);
|
|
190
|
+
const claimedBy = requireText("claimedBy", input.claimedBy, 200);
|
|
191
|
+
const limit = input.limit === undefined ? 10 : requireCounter("limit", input.limit);
|
|
192
|
+
if (limit < 1) {
|
|
193
|
+
throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
194
|
+
}
|
|
195
|
+
const recipient = input.recipient;
|
|
196
|
+
return ctx.transaction(() => {
|
|
197
|
+
assertDispatchTokenUnused(ctx, claimToken);
|
|
198
|
+
const clauses = [
|
|
199
|
+
"state = 'pending'",
|
|
200
|
+
`(event_type = 'assignment-outcome' OR EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
|
|
201
|
+
AND w.generation = outbox_events.generation
|
|
202
|
+
AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)})))`,
|
|
203
|
+
];
|
|
204
|
+
const params = [...DELIVERABLE_WAIT_PHASES];
|
|
205
|
+
if (input.eventId !== undefined) {
|
|
206
|
+
clauses.push("event_id = ?");
|
|
207
|
+
params.push(requireId("eventId", input.eventId));
|
|
208
|
+
}
|
|
209
|
+
if (input.type !== undefined) {
|
|
210
|
+
if (!["dependency-ready", "assignment-outcome"].includes(input.type))
|
|
211
|
+
throw new StoreError("validation", "Unknown outbox event type.");
|
|
212
|
+
clauses.push("event_type = ?");
|
|
213
|
+
params.push(input.type);
|
|
214
|
+
}
|
|
215
|
+
if (input.waitId !== undefined) {
|
|
216
|
+
clauses.push("wait_id = ?");
|
|
217
|
+
params.push(requireId("waitId", input.waitId));
|
|
218
|
+
}
|
|
219
|
+
if (input.generation !== undefined) {
|
|
220
|
+
clauses.push("generation = ?");
|
|
221
|
+
params.push(requireCounter("generation", input.generation));
|
|
222
|
+
}
|
|
223
|
+
if (recipient) {
|
|
224
|
+
const clause = ownerClause("recipient", recipient);
|
|
225
|
+
clauses.push(clause.sql);
|
|
226
|
+
params.push(...clause.params);
|
|
227
|
+
}
|
|
228
|
+
const rows = getRows(ctx, `SELECT * FROM outbox_events WHERE ${clauses.join(" AND ")} ORDER BY created_at, event_id LIMIT ?`, ...params, limit);
|
|
229
|
+
const at = ctx.now();
|
|
230
|
+
const claimed = [];
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
const eventId = columnText(row, "event_id");
|
|
233
|
+
run(ctx, `UPDATE outbox_events
|
|
234
|
+
SET state = 'claimed', attempts = attempts + 1, claimed_at = ?, dispatch_claim_json = ?
|
|
235
|
+
WHERE event_id = ? AND state = 'pending'`, at, JSON.stringify({ token: claimToken, claimedBy, claimedAt: at }), eventId);
|
|
236
|
+
const updated = readOutboxRow(ctx, eventId);
|
|
237
|
+
if (updated)
|
|
238
|
+
claimed.push(mapOutbox(ctx, updated));
|
|
239
|
+
}
|
|
240
|
+
return claimed;
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function requireClaimedEvent(ctx, input) {
|
|
244
|
+
const eventId = requireId("eventId", input.eventId);
|
|
245
|
+
const claimToken = requireId("claimToken", input.claimToken);
|
|
246
|
+
const row = readOutboxRow(ctx, eventId);
|
|
247
|
+
if (!row) {
|
|
248
|
+
throw new StoreError("outbox-state", `No outbox event ${eventId} is recorded.`);
|
|
249
|
+
}
|
|
250
|
+
const state = columnText(row, "state");
|
|
251
|
+
if (state !== "claimed") {
|
|
252
|
+
throw new StoreError("outbox-state", `Outbox event ${eventId} is ${state}; only a claimed delivery can be completed or released.`);
|
|
253
|
+
}
|
|
254
|
+
const claim = readDispatchClaim(row);
|
|
255
|
+
if (claim === null || claim.token !== claimToken) {
|
|
256
|
+
throw new StoreError("outbox-state", `Outbox event ${eventId} is claimed by a different dispatch token; the caller does not hold this delivery.`);
|
|
257
|
+
}
|
|
258
|
+
return row;
|
|
259
|
+
}
|
|
260
|
+
export function markOutboxDelivered(ctx, input) {
|
|
261
|
+
return ctx.transaction(() => {
|
|
262
|
+
const row = requireClaimedEvent(ctx, input);
|
|
263
|
+
const eventId = columnText(row, "event_id");
|
|
264
|
+
run(ctx, "UPDATE outbox_events SET state = 'delivered', delivered_at = ?, dispatch_claim_json = NULL WHERE event_id = ?", ctx.now(), eventId);
|
|
265
|
+
const updated = readOutboxRow(ctx, eventId);
|
|
266
|
+
return mapOutbox(ctx, updated);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Return a claimed delivery to the queue with a recorded reason. Attempts and the
|
|
271
|
+
* recovery reason are retained, and the result stays unconsumed.
|
|
272
|
+
*/
|
|
273
|
+
export function releaseOutbox(ctx, input) {
|
|
274
|
+
const reason = requireText("reason", input.reason, 1024);
|
|
275
|
+
return ctx.transaction(() => {
|
|
276
|
+
const row = requireClaimedEvent(ctx, input);
|
|
277
|
+
const eventId = columnText(row, "event_id");
|
|
278
|
+
run(ctx, "UPDATE outbox_events SET state = 'pending', reason = ?, dispatch_claim_json = NULL WHERE event_id = ?", reason, eventId);
|
|
279
|
+
const updated = readOutboxRow(ctx, eventId);
|
|
280
|
+
return mapOutbox(ctx, updated);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Generated canonical coordinator. Do not edit directly.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { StoreError } from "./errors.mjs";
|
|
4
|
+
import { getRow, getRows, columnText, run } from "./sqlite.mjs";
|
|
5
|
+
import { requireWait } from "./rows.mjs";
|
|
6
|
+
import { holdFailedResume } from "./waits.mjs";
|
|
7
|
+
import { getAssignmentOutcome, recordAssignmentOutcome } from "./assignment-outcomes.mjs";
|
|
8
|
+
/** The exact exit is fenced and the allowance committed in the same transaction. */
|
|
9
|
+
export function repairFailedResume(ctx, input) {
|
|
10
|
+
return ctx.transaction(() => {
|
|
11
|
+
const wait = requireWait(ctx, input.waitId, input.generation);
|
|
12
|
+
const assignmentId = wait.origin?.assignmentRef;
|
|
13
|
+
if (!assignmentId || !wait.park || input.checkpointId !== wait.park.checkpointId) {
|
|
14
|
+
throw new StoreError("resume-proof", "Repair requires the assignment's original checkpoint identity.");
|
|
15
|
+
}
|
|
16
|
+
if (wait.cancelEpoch !== input.expectedCancelEpoch)
|
|
17
|
+
throw new StoreError("stale-cancel-epoch", "Repair cancellation epoch changed.");
|
|
18
|
+
const publication = getRow(ctx, "SELECT claim_id FROM resume_claims WHERE claim_id = ? AND claim_token = ? AND attempt_id = ? AND launch_token = ? AND wait_id = ? AND generation = ? AND cancel_epoch = ?", input.claimId, input.claimToken, input.attemptId, input.launchToken, wait.waitId, wait.generation, wait.cancelEpoch);
|
|
19
|
+
if (!publication)
|
|
20
|
+
throw new StoreError("claim-state", "Repair does not match the exact published writer.");
|
|
21
|
+
const fault = JSON.stringify({ category: "unacknowledged-exit", checkpointId: input.checkpointId,
|
|
22
|
+
dependencies: wait.dependencies.map((d) => [d.operationId, d.terminalRevision]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))) });
|
|
23
|
+
const key = createHash("sha256").update(JSON.stringify([assignmentId, wait.waitId, wait.generation, fault])).digest("hex");
|
|
24
|
+
const prior = getRow(ctx, "SELECT claim_id FROM assignment_repairs WHERE fault_key = ?", key);
|
|
25
|
+
const terminal = getAssignmentOutcome(ctx, assignmentId);
|
|
26
|
+
if (terminal) {
|
|
27
|
+
holdFailedResume(ctx, input);
|
|
28
|
+
return { phase: "held", repaired: false };
|
|
29
|
+
}
|
|
30
|
+
// Duplicate exit notifications cannot exhaust a repair that has not run.
|
|
31
|
+
if (prior && columnText(prior, "claim_id") === input.claimId)
|
|
32
|
+
return { phase: wait.phase, repaired: false };
|
|
33
|
+
holdFailedResume(ctx, input);
|
|
34
|
+
if (prior) {
|
|
35
|
+
const binding = getRow(ctx, "SELECT recipient_json FROM assignment_bindings WHERE assignment_id = ?", assignmentId);
|
|
36
|
+
if (!binding)
|
|
37
|
+
throw new StoreError("foreign-owner", "Repair has no captured parent recipient.");
|
|
38
|
+
recordAssignmentOutcome(ctx, { assignmentId, owner: wait.owner, recipient: JSON.parse(columnText(binding, "recipient_json")),
|
|
39
|
+
revision: 1, outcome: "failed", reason: "Automatic repair repeated the same unacknowledged-exit fault; the one-repair allowance is exhausted.",
|
|
40
|
+
processUncertain: false, evidence: [{ kind: "summary", ref: `repair:${key}`, summary: input.reason }],
|
|
41
|
+
waits: getRows(ctx, "SELECT wait_id, generation FROM waits WHERE json_extract(origin_json, '$.assignmentRef') = ?", assignmentId).map((row) => {
|
|
42
|
+
const linked = requireWait(ctx, columnText(row, "wait_id"), Number(row.generation));
|
|
43
|
+
return { waitId: linked.waitId, generation: linked.generation, cancelEpoch: linked.cancelEpoch };
|
|
44
|
+
}) });
|
|
45
|
+
return { phase: "held", repaired: false };
|
|
46
|
+
}
|
|
47
|
+
run(ctx, "INSERT INTO assignment_repairs VALUES (?, ?, ?, ?, ?, ?)", key, assignmentId, wait.waitId, wait.generation, fault, input.claimId);
|
|
48
|
+
run(ctx, "UPDATE waits SET phase = 'ready', phase_reason = 'bounded-repair', updated_at = ? WHERE wait_id = ? AND generation = ?", ctx.now(), wait.waitId, wait.generation);
|
|
49
|
+
return { phase: "ready", repaired: true };
|
|
50
|
+
});
|
|
51
|
+
}
|