pi-better-background-tasks 0.14.4 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/observed-waits.ts +302 -21
- package/src/shared-callback-batcher.ts +8 -3
- package/src/shared-operation-coordinator/assignment-observation.mjs +43 -0
- package/src/shared-operation-coordinator/index.ts +5 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +172 -0
- package/src/shared-operation-coordinator/src/discovery.ts +128 -0
- package/src/shared-operation-coordinator/src/errors.ts +2 -0
- package/src/shared-operation-coordinator/src/operations.ts +88 -6
- package/src/shared-operation-coordinator/src/outbox.ts +11 -2
- package/src/shared-operation-coordinator/src/recovery.ts +55 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -1
- package/src/shared-operation-coordinator/src/schema.ts +114 -2
- package/src/shared-operation-coordinator/src/store.ts +83 -1
- package/src/shared-operation-coordinator/src/types.ts +46 -1
- package/src/shared-operation-coordinator/src/waits.ts +47 -5
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/src/schema.ts. Do not edit directly.
|
|
2
2
|
/**
|
|
3
|
-
* Schema
|
|
3
|
+
* Schema v4 for the durable operation coordinator.
|
|
4
4
|
*
|
|
5
5
|
* The store refuses to open a database whose recorded version it does not
|
|
6
6
|
* understand, and leaves the file untouched. An unreadable or newer database
|
|
@@ -19,6 +19,14 @@ import { StoreError } from "./errors.ts";
|
|
|
19
19
|
import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
20
20
|
|
|
21
21
|
const DDL: readonly string[] = [
|
|
22
|
+
`CREATE TABLE assignment_repairs (
|
|
23
|
+
fault_key TEXT PRIMARY KEY,
|
|
24
|
+
assignment_id TEXT NOT NULL,
|
|
25
|
+
wait_id TEXT NOT NULL,
|
|
26
|
+
generation INTEGER NOT NULL,
|
|
27
|
+
fault_json TEXT NOT NULL,
|
|
28
|
+
claim_id TEXT NOT NULL
|
|
29
|
+
)`,
|
|
22
30
|
`CREATE TABLE schema_meta (
|
|
23
31
|
key TEXT PRIMARY KEY,
|
|
24
32
|
value TEXT NOT NULL
|
|
@@ -35,6 +43,7 @@ const DDL: readonly string[] = [
|
|
|
35
43
|
observer_kind TEXT NOT NULL,
|
|
36
44
|
observer_version TEXT NOT NULL,
|
|
37
45
|
supervision_json TEXT,
|
|
46
|
+
supervision_host_id TEXT,
|
|
38
47
|
authority_ref TEXT,
|
|
39
48
|
intent_ref TEXT,
|
|
40
49
|
phase TEXT NOT NULL,
|
|
@@ -51,6 +60,23 @@ const DDL: readonly string[] = [
|
|
|
51
60
|
)`,
|
|
52
61
|
`CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
|
|
53
62
|
`CREATE INDEX operations_phase ON operations (phase)`,
|
|
63
|
+
`CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
|
|
64
|
+
// Discovery leadership is separate from per-operation supervision. The token
|
|
65
|
+
// fences stale acquisition and release; the host id is checked with process
|
|
66
|
+
// identity before a replacement.
|
|
67
|
+
`CREATE TABLE discovery_claims (
|
|
68
|
+
scope TEXT PRIMARY KEY,
|
|
69
|
+
host_id TEXT NOT NULL,
|
|
70
|
+
token TEXT NOT NULL,
|
|
71
|
+
claimed_at INTEGER NOT NULL,
|
|
72
|
+
updated_at INTEGER NOT NULL
|
|
73
|
+
)`,
|
|
74
|
+
// Small shared state for change notification. The table is additive so an
|
|
75
|
+
// older reader that understands schema version 1 can safely ignore it.
|
|
76
|
+
`CREATE TABLE coordinator_state (
|
|
77
|
+
key TEXT PRIMARY KEY,
|
|
78
|
+
value TEXT NOT NULL
|
|
79
|
+
)`,
|
|
54
80
|
`CREATE TABLE operation_evidence (
|
|
55
81
|
operation_id TEXT NOT NULL REFERENCES operations (operation_id),
|
|
56
82
|
terminal_revision INTEGER NOT NULL,
|
|
@@ -64,6 +90,7 @@ const DDL: readonly string[] = [
|
|
|
64
90
|
PRIMARY KEY (operation_id, terminal_revision, ordinal)
|
|
65
91
|
)`,
|
|
66
92
|
`CREATE TABLE waits (
|
|
93
|
+
dispatch_disarmed INTEGER NOT NULL DEFAULT 0,
|
|
67
94
|
wait_id TEXT NOT NULL,
|
|
68
95
|
generation INTEGER NOT NULL,
|
|
69
96
|
owner_kind TEXT NOT NULL,
|
|
@@ -87,7 +114,7 @@ const DDL: readonly string[] = [
|
|
|
87
114
|
// At most one generation per owner identity (session + branch) may be pending.
|
|
88
115
|
`CREATE UNIQUE INDEX waits_one_pending_per_owner
|
|
89
116
|
ON waits (owner_kind, owner_session_id, coalesce(owner_branch_id, ''))
|
|
90
|
-
WHERE phase NOT IN ('consumed', 'cancelled')`,
|
|
117
|
+
WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0`,
|
|
91
118
|
`CREATE INDEX waits_owner ON waits (owner_kind, owner_session_id)`,
|
|
92
119
|
`CREATE TABLE wait_dependencies (
|
|
93
120
|
wait_id TEXT NOT NULL,
|
|
@@ -153,6 +180,7 @@ const DDL: readonly string[] = [
|
|
|
153
180
|
ON evidence_pins (wait_id, generation, operation_id, terminal_revision, kind, ref)`,
|
|
154
181
|
`CREATE INDEX evidence_pins_operation ON evidence_pins (operation_id, terminal_revision, released_at)`,
|
|
155
182
|
`CREATE TABLE outbox_events (
|
|
183
|
+
event_type TEXT NOT NULL DEFAULT 'dependency-ready',
|
|
156
184
|
event_id TEXT PRIMARY KEY,
|
|
157
185
|
operation_id TEXT NOT NULL,
|
|
158
186
|
terminal_revision INTEGER NOT NULL,
|
|
@@ -176,6 +204,26 @@ const DDL: readonly string[] = [
|
|
|
176
204
|
)`,
|
|
177
205
|
`CREATE INDEX outbox_recipient ON outbox_events (recipient_kind, recipient_session_id, state)`,
|
|
178
206
|
`CREATE INDEX outbox_wait ON outbox_events (wait_id, generation)`,
|
|
207
|
+
`CREATE TABLE assignment_outcomes (
|
|
208
|
+
assignment_id TEXT PRIMARY KEY,
|
|
209
|
+
event_id TEXT NOT NULL UNIQUE,
|
|
210
|
+
record_json TEXT NOT NULL
|
|
211
|
+
)`,
|
|
212
|
+
`CREATE TABLE assignment_bindings (
|
|
213
|
+
assignment_id TEXT PRIMARY KEY,
|
|
214
|
+
owner_json TEXT NOT NULL,
|
|
215
|
+
recipient_json TEXT NOT NULL
|
|
216
|
+
)`,
|
|
217
|
+
`CREATE TABLE assignment_attempts (
|
|
218
|
+
attempt_id TEXT PRIMARY KEY,
|
|
219
|
+
assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
|
|
220
|
+
)`,
|
|
221
|
+
`CREATE TABLE assignment_outcome_waits (
|
|
222
|
+
assignment_id TEXT NOT NULL REFERENCES assignment_outcomes (assignment_id),
|
|
223
|
+
wait_id TEXT NOT NULL,
|
|
224
|
+
generation INTEGER NOT NULL,
|
|
225
|
+
PRIMARY KEY (wait_id, generation)
|
|
226
|
+
)`,
|
|
179
227
|
];
|
|
180
228
|
|
|
181
229
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
@@ -230,11 +278,75 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
230
278
|
);
|
|
231
279
|
}
|
|
232
280
|
if (recorded < SCHEMA_VERSION) {
|
|
281
|
+
if (recorded === 3) {
|
|
282
|
+
ctx.transaction(() => {
|
|
283
|
+
ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
|
|
284
|
+
run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
|
|
285
|
+
});
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (recorded === 1 || recorded === 2) {
|
|
289
|
+
ensureAdditiveSchema(ctx);
|
|
290
|
+
ctx.transaction(() => {
|
|
291
|
+
if (recorded === 1) ctx.db.exec("ALTER TABLE outbox_events ADD COLUMN event_type TEXT NOT NULL DEFAULT 'dependency-ready'");
|
|
292
|
+
for (const statement of DDL.filter((sql) => sql.startsWith("CREATE TABLE assignment_"))) ctx.db.exec(statement.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
|
|
293
|
+
ctx.db.exec("ALTER TABLE waits ADD COLUMN dispatch_disarmed INTEGER NOT NULL DEFAULT 0");
|
|
294
|
+
ctx.db.exec("UPDATE waits SET dispatch_disarmed = 1 WHERE EXISTS (SELECT 1 FROM assignment_outcome_waits aw WHERE aw.wait_id = waits.wait_id AND aw.generation = waits.generation)");
|
|
295
|
+
ctx.db.exec("DROP INDEX waits_one_pending_per_owner");
|
|
296
|
+
ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE UNIQUE INDEX waits_one_pending_per_owner"))!);
|
|
297
|
+
run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
|
|
298
|
+
});
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
233
301
|
throw new StoreError(
|
|
234
302
|
"schema-version",
|
|
235
303
|
`The database is at schema version ${recorded}; this build needs version ${SCHEMA_VERSION}. No migration is provided for this pair; records are left in place.`,
|
|
236
304
|
);
|
|
237
305
|
}
|
|
306
|
+
ensureAdditiveSchema(ctx);
|
|
307
|
+
ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_attempts"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Schema version 1 is extended additively: older readers ignore the new column,
|
|
312
|
+
* index and tables, so a live session on the previous build does not lose its
|
|
313
|
+
* records during a rolling upgrade. Missing additions are created once on open.
|
|
314
|
+
*/
|
|
315
|
+
function ensureAdditiveSchema(ctx: StoreContext): void {
|
|
316
|
+
const hasColumn = (): boolean =>
|
|
317
|
+
getRows(ctx, "PRAGMA table_info(operations)").some((row) => columnText(row, "name") === "supervision_host_id");
|
|
318
|
+
const hasIndex = (): boolean =>
|
|
319
|
+
getRows(ctx, "SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?", "operations_running_supervisor").length > 0;
|
|
320
|
+
const hasTable = (name: string): boolean => existingTables(ctx).includes(name);
|
|
321
|
+
if (
|
|
322
|
+
hasColumn()
|
|
323
|
+
&& hasIndex()
|
|
324
|
+
&& hasTable("discovery_claims")
|
|
325
|
+
&& hasTable("coordinator_state")
|
|
326
|
+
) return;
|
|
327
|
+
|
|
328
|
+
ctx.transaction(() => {
|
|
329
|
+
if (!hasColumn()) {
|
|
330
|
+
ctx.db.exec("ALTER TABLE operations ADD COLUMN supervision_host_id TEXT");
|
|
331
|
+
ctx.db.exec(`UPDATE operations
|
|
332
|
+
SET supervision_host_id = CASE
|
|
333
|
+
WHEN json_valid(supervision_json) THEN json_extract(supervision_json, '$.hostId')
|
|
334
|
+
ELSE NULL
|
|
335
|
+
END`);
|
|
336
|
+
}
|
|
337
|
+
ctx.db.exec("CREATE INDEX IF NOT EXISTS operations_running_supervisor ON operations (phase, supervision_host_id)");
|
|
338
|
+
ctx.db.exec(`CREATE TABLE IF NOT EXISTS discovery_claims (
|
|
339
|
+
scope TEXT PRIMARY KEY,
|
|
340
|
+
host_id TEXT NOT NULL,
|
|
341
|
+
token TEXT NOT NULL,
|
|
342
|
+
claimed_at INTEGER NOT NULL,
|
|
343
|
+
updated_at INTEGER NOT NULL
|
|
344
|
+
)`);
|
|
345
|
+
ctx.db.exec(`CREATE TABLE IF NOT EXISTS coordinator_state (
|
|
346
|
+
key TEXT PRIMARY KEY,
|
|
347
|
+
value TEXT NOT NULL
|
|
348
|
+
)`);
|
|
349
|
+
});
|
|
238
350
|
}
|
|
239
351
|
|
|
240
352
|
/** Test and diagnostic seam: read the recorded schema version without opening a store. */
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
* and leaves no partial record.
|
|
9
9
|
*/
|
|
10
10
|
import { StoreError } from "./errors.ts";
|
|
11
|
+
import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
|
|
12
|
+
import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.ts";
|
|
13
|
+
import type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./assignment-outcomes.ts";
|
|
11
14
|
import {
|
|
12
15
|
describeOwnerDiff,
|
|
13
16
|
normalizeOwner,
|
|
@@ -20,10 +23,18 @@ import { createContext, openDatabase, type StoreContext } from "./sqlite.ts";
|
|
|
20
23
|
import {
|
|
21
24
|
getOperation as readOperationRecord,
|
|
22
25
|
listOperations as readOperationRecords,
|
|
26
|
+
listRunningSupervisedBy as readRunningSupervisedBy,
|
|
27
|
+
releaseSupervision as writeSupervisionRelease,
|
|
23
28
|
recordSupervision as writeSupervision,
|
|
24
29
|
recordTerminalOutcome as writeTerminalOutcome,
|
|
25
30
|
registerOperation as writeOperation,
|
|
26
31
|
} from "./operations.ts";
|
|
32
|
+
import {
|
|
33
|
+
getChangeRevision as readChangeRevision,
|
|
34
|
+
readDiscoveryClaim as readClaim,
|
|
35
|
+
releaseDiscoveryClaim as deleteDiscoveryClaim,
|
|
36
|
+
tryClaimDiscovery as writeDiscoveryClaim,
|
|
37
|
+
} from "./discovery.ts";
|
|
27
38
|
import {
|
|
28
39
|
acknowledgeResult as writeAcknowledgement,
|
|
29
40
|
cancelWait as writeCancellation,
|
|
@@ -60,6 +71,7 @@ import {
|
|
|
60
71
|
type CancelWaitResult,
|
|
61
72
|
type ClaimOutboxInput,
|
|
62
73
|
type ClaimResumeInput,
|
|
74
|
+
type DiscoveryClaimRecord,
|
|
63
75
|
type EvidencePinRecord,
|
|
64
76
|
type EvidenceReadRecord,
|
|
65
77
|
type HoldFailedResumeInput,
|
|
@@ -77,6 +89,7 @@ import {
|
|
|
77
89
|
type RecordEvidencePinResult,
|
|
78
90
|
type RecordEvidenceReadInput,
|
|
79
91
|
type RecordEvidenceReadResult,
|
|
92
|
+
type ReleaseSupervisionInput,
|
|
80
93
|
type RecordSupervisionInput,
|
|
81
94
|
type RecordTerminalOutcomeInput,
|
|
82
95
|
type RecordTerminalOutcomeResult,
|
|
@@ -84,6 +97,7 @@ import {
|
|
|
84
97
|
type RegisterOperationResult,
|
|
85
98
|
type RegisterWaitInput,
|
|
86
99
|
type RegisterWaitResult,
|
|
100
|
+
type ReleaseDiscoveryClaimInput,
|
|
87
101
|
type ReleaseOutboxInput,
|
|
88
102
|
type ReleaseResumeClaimInput,
|
|
89
103
|
type ReleaseResumeClaimResult,
|
|
@@ -93,6 +107,7 @@ import {
|
|
|
93
107
|
type StoreOptions,
|
|
94
108
|
type TransitionWaitPhaseInput,
|
|
95
109
|
type TransitionWaitPhaseResult,
|
|
110
|
+
type TryClaimDiscoveryInput,
|
|
96
111
|
type WaitDependencyRecord,
|
|
97
112
|
type WaitFilter,
|
|
98
113
|
type WaitRecord,
|
|
@@ -100,6 +115,12 @@ import {
|
|
|
100
115
|
} from "./types.ts";
|
|
101
116
|
|
|
102
117
|
export interface Store {
|
|
118
|
+
registerAssignment(input: Parameters<typeof registerAssignment>[1]): void;
|
|
119
|
+
receiptAssignmentOutcome(input: Parameters<typeof receiptAssignmentOutcome>[1]): AssignmentOutcomeRecord;
|
|
120
|
+
recordAssignmentOutcome(input: AssignmentOutcomeInput): AssignmentOutcomeRecord;
|
|
121
|
+
getAssignmentOutcome(assignmentId: string): AssignmentOutcomeRecord | null;
|
|
122
|
+
inspectAssignmentOutcome(input: Parameters<typeof inspectAssignmentOutcome>[1]): AssignmentOutcomeRecord;
|
|
123
|
+
consumeAssignmentOutcome(input: Parameters<typeof consumeAssignmentOutcome>[1]): AssignmentOutcomeRecord;
|
|
103
124
|
/** Schema version this handle verified on open. */
|
|
104
125
|
readonly schemaVersion: number;
|
|
105
126
|
/** Database path this handle opened. */
|
|
@@ -118,9 +139,18 @@ export interface Store {
|
|
|
118
139
|
registerOperation(input: RegisterOperationInput): RegisterOperationResult;
|
|
119
140
|
/**
|
|
120
141
|
* Replace supervision identity and/or report observer health
|
|
121
|
-
* (`active`/`unmonitored`/`lost`). Ownership stays untouched.
|
|
142
|
+
* (`active`/`unmonitored`/`lost`). Ownership stays untouched. A supervision
|
|
143
|
+
* replacement requires `expectedHostId` and is refused with
|
|
144
|
+
* `supervision-conflict` when another host took over first.
|
|
122
145
|
*/
|
|
123
146
|
recordSupervision(input: RecordSupervisionInput): OperationRecord;
|
|
147
|
+
/**
|
|
148
|
+
* Clear a closed host's supervision authority when the recorded host still
|
|
149
|
+
* matches. A newer holder is left untouched, and a terminal operation keeps
|
|
150
|
+
* its final supervision record. Returns `null` when another host already took
|
|
151
|
+
* over.
|
|
152
|
+
*/
|
|
153
|
+
releaseSupervision(input: ReleaseSupervisionInput): OperationRecord | null;
|
|
124
154
|
/**
|
|
125
155
|
* Record the single terminal revision of an operation and settle every wait
|
|
126
156
|
* that depends on it. Replaying the same event id is idempotent; a different
|
|
@@ -130,8 +160,25 @@ export interface Store {
|
|
|
130
160
|
recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
|
|
131
161
|
getOperation(operationId: string): OperationRecord | null;
|
|
132
162
|
listOperations(filter?: OperationFilter): OperationRecord[];
|
|
163
|
+
/** Running operations currently assigned to this supervising host. */
|
|
164
|
+
listRunningSupervisedBy(hostId: string): OperationRecord[];
|
|
133
165
|
listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
|
|
134
166
|
|
|
167
|
+
// ---- discovery coordination ----
|
|
168
|
+
|
|
169
|
+
/** The shared discovery leader for this store/supervisor scope, if recorded. */
|
|
170
|
+
readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
|
|
171
|
+
/**
|
|
172
|
+
* Compare-and-swap a discovery claim. The caller must name the exact claim it
|
|
173
|
+
* observed, or null for none; a stale contender receives null and must not
|
|
174
|
+
* start a global scan.
|
|
175
|
+
*/
|
|
176
|
+
tryClaimDiscovery(input: TryClaimDiscoveryInput): DiscoveryClaimRecord | null;
|
|
177
|
+
/** Delete only this exact host/token claim; a successor is never released. */
|
|
178
|
+
releaseDiscoveryClaim(input: ReleaseDiscoveryClaimInput): boolean;
|
|
179
|
+
/** Monotonic revision for registration, authority changes and terminal publication. */
|
|
180
|
+
getChangeRevision(): number;
|
|
181
|
+
|
|
135
182
|
// ---- waits ----
|
|
136
183
|
|
|
137
184
|
/**
|
|
@@ -189,6 +236,7 @@ export interface Store {
|
|
|
189
236
|
* refused untouched.
|
|
190
237
|
*/
|
|
191
238
|
holdFailedResume(input: HoldFailedResumeInput): HoldFailedResumeResult;
|
|
239
|
+
repairFailedResume(input: RepairResumeInput): { phase: string; repaired: boolean };
|
|
192
240
|
listResumeClaims(filter?: ResumeClaimFilter): ResumeClaimRecord[];
|
|
193
241
|
/** Active claims a replacement host must reconcile before admitting resumes. */
|
|
194
242
|
listUnreconciledClaims(): ResumeClaimRecord[];
|
|
@@ -260,6 +308,12 @@ export function openStore(options: StoreOptions): Store {
|
|
|
260
308
|
};
|
|
261
309
|
|
|
262
310
|
const store: Store = {
|
|
311
|
+
registerAssignment(input) { alive(); registerAssignment(ctx, input); },
|
|
312
|
+
receiptAssignmentOutcome(input) { alive(); return receiptAssignmentOutcome(ctx, input); },
|
|
313
|
+
recordAssignmentOutcome(input) { alive(); return recordAssignmentOutcome(ctx, input); },
|
|
314
|
+
getAssignmentOutcome(assignmentId) { alive(); return getAssignmentOutcome(ctx, assignmentId); },
|
|
315
|
+
inspectAssignmentOutcome(input) { alive(); return inspectAssignmentOutcome(ctx, input); },
|
|
316
|
+
consumeAssignmentOutcome(input) { alive(); return consumeAssignmentOutcome(ctx, input); },
|
|
263
317
|
schemaVersion: SCHEMA_VERSION,
|
|
264
318
|
path,
|
|
265
319
|
close() {
|
|
@@ -275,6 +329,10 @@ export function openStore(options: StoreOptions): Store {
|
|
|
275
329
|
alive();
|
|
276
330
|
return writeSupervision(ctx, input);
|
|
277
331
|
},
|
|
332
|
+
releaseSupervision(input) {
|
|
333
|
+
alive();
|
|
334
|
+
return writeSupervisionRelease(ctx, input);
|
|
335
|
+
},
|
|
278
336
|
recordTerminalOutcome(input) {
|
|
279
337
|
alive();
|
|
280
338
|
return writeTerminalOutcome(ctx, input);
|
|
@@ -287,6 +345,10 @@ export function openStore(options: StoreOptions): Store {
|
|
|
287
345
|
alive();
|
|
288
346
|
return readOperationRecords(ctx, filter);
|
|
289
347
|
},
|
|
348
|
+
listRunningSupervisedBy(hostId) {
|
|
349
|
+
alive();
|
|
350
|
+
return readRunningSupervisedBy(ctx, hostId);
|
|
351
|
+
},
|
|
290
352
|
listOperationEvidence(operationId, terminalRevision) {
|
|
291
353
|
alive();
|
|
292
354
|
return readOperationEvidence(
|
|
@@ -295,6 +357,22 @@ export function openStore(options: StoreOptions): Store {
|
|
|
295
357
|
terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
|
|
296
358
|
);
|
|
297
359
|
},
|
|
360
|
+
readDiscoveryClaim(scope) {
|
|
361
|
+
alive();
|
|
362
|
+
return readClaim(ctx, scope);
|
|
363
|
+
},
|
|
364
|
+
tryClaimDiscovery(input) {
|
|
365
|
+
alive();
|
|
366
|
+
return writeDiscoveryClaim(ctx, input);
|
|
367
|
+
},
|
|
368
|
+
releaseDiscoveryClaim(input) {
|
|
369
|
+
alive();
|
|
370
|
+
return deleteDiscoveryClaim(ctx, input);
|
|
371
|
+
},
|
|
372
|
+
getChangeRevision() {
|
|
373
|
+
alive();
|
|
374
|
+
return readChangeRevision(ctx);
|
|
375
|
+
},
|
|
298
376
|
registerWait(input) {
|
|
299
377
|
alive();
|
|
300
378
|
return writeWait(ctx, input);
|
|
@@ -339,6 +417,10 @@ export function openStore(options: StoreOptions): Store {
|
|
|
339
417
|
alive();
|
|
340
418
|
return writeHoldFailedResume(ctx, input);
|
|
341
419
|
},
|
|
420
|
+
repairFailedResume(input) {
|
|
421
|
+
alive();
|
|
422
|
+
return repairFailedResume(ctx, input);
|
|
423
|
+
},
|
|
342
424
|
listResumeClaims(filter = {}) {
|
|
343
425
|
alive();
|
|
344
426
|
return readClaims(ctx, filter);
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
/** Schema version this build writes and accepts. Any other version is refused. */
|
|
23
|
-
export const SCHEMA_VERSION =
|
|
23
|
+
export const SCHEMA_VERSION = 4;
|
|
24
24
|
|
|
25
25
|
/** Who receives an operation's result and decides what happens next. */
|
|
26
26
|
export type OwnerKind = "parent-session" | "worker-conversation";
|
|
@@ -151,6 +151,48 @@ export interface RecordSupervisionInput {
|
|
|
151
151
|
supervision?: SupervisionIdentity | null;
|
|
152
152
|
health?: ObserverHealth;
|
|
153
153
|
reason?: string | null;
|
|
154
|
+
/**
|
|
155
|
+
* The host id the caller observed as current, or null when no supervisor was
|
|
156
|
+
* recorded. Required when supplying `supervision`. The write is refused with
|
|
157
|
+
* `supervision-conflict` if another host took over after the caller read the
|
|
158
|
+
* operation, so a stale contender cannot replace a newly live holder.
|
|
159
|
+
*/
|
|
160
|
+
expectedHostId?: string | null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export interface ReleaseSupervisionInput {
|
|
164
|
+
operationId: string;
|
|
165
|
+
/** Must be the recorded owner; a replacement host acts for the same owner. */
|
|
166
|
+
owner: OwnerIdentity;
|
|
167
|
+
/** The exact host whose authority is being released. A newer holder is untouched. */
|
|
168
|
+
hostId: string;
|
|
169
|
+
/** Why the host stopped supervising, retained on the unmonitored record. */
|
|
170
|
+
reason?: string | null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** One shared discovery leader for a coordinator database and supervisor scope. */
|
|
174
|
+
export interface DiscoveryClaimRecord {
|
|
175
|
+
/** Opaque canonical scope computed from the store path and supervisor directory. */
|
|
176
|
+
scope: string;
|
|
177
|
+
hostId: string;
|
|
178
|
+
/** Fences acquisition and release against a stale or ABA competitor. */
|
|
179
|
+
token: string;
|
|
180
|
+
claimedAt: number;
|
|
181
|
+
updatedAt: number;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface TryClaimDiscoveryInput {
|
|
185
|
+
scope: string;
|
|
186
|
+
/** The exact claim the caller observed, or null when it observed no claim. */
|
|
187
|
+
expected: Pick<DiscoveryClaimRecord, "hostId" | "token"> | null;
|
|
188
|
+
hostId: string;
|
|
189
|
+
token: string;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface ReleaseDiscoveryClaimInput {
|
|
193
|
+
scope: string;
|
|
194
|
+
hostId: string;
|
|
195
|
+
token: string;
|
|
154
196
|
}
|
|
155
197
|
|
|
156
198
|
// ---- terminal outcome ---------------------------------------------------
|
|
@@ -579,6 +621,7 @@ export interface OutboxDispatchClaim {
|
|
|
579
621
|
}
|
|
580
622
|
|
|
581
623
|
export interface OutboxEventRecord {
|
|
624
|
+
type: "dependency-ready" | "assignment-outcome";
|
|
582
625
|
eventId: string;
|
|
583
626
|
operationId: string;
|
|
584
627
|
/** Terminal revision this event delivers. Unique per wait generation. */
|
|
@@ -610,6 +653,8 @@ export interface OutboxFilter {
|
|
|
610
653
|
}
|
|
611
654
|
|
|
612
655
|
export interface ClaimOutboxInput {
|
|
656
|
+
eventId?: string;
|
|
657
|
+
type?: OutboxEventRecord["type"];
|
|
613
658
|
/** Restrict to one wait generation. Omit to claim across a recipient. */
|
|
614
659
|
waitId?: string;
|
|
615
660
|
generation?: number;
|
|
@@ -143,6 +143,9 @@ function assertWaitOwner(wait: WaitRecord, owner: OwnerIdentity, action: string)
|
|
|
143
143
|
|
|
144
144
|
/** Reject a caller that addresses a superseded generation. */
|
|
145
145
|
function assertCurrentGeneration(ctx: StoreContext, waitId: string, generation: number): void {
|
|
146
|
+
if (getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation)) {
|
|
147
|
+
throw new StoreError("wait-phase", "The assignment has a terminal outcome; automatic dispatch is disarmed.");
|
|
148
|
+
}
|
|
146
149
|
const latest = latestWaitGeneration(ctx, waitId);
|
|
147
150
|
if (latest !== null && generation < latest) {
|
|
148
151
|
throw new StoreError(
|
|
@@ -289,6 +292,22 @@ export function settleWaitsForOperation(
|
|
|
289
292
|
);
|
|
290
293
|
}
|
|
291
294
|
const phase = columnText(waitRow, "phase") as WaitPhase;
|
|
295
|
+
const terminalAssignment = getRow(ctx, `SELECT a.event_id, a.record_json FROM assignment_outcomes a
|
|
296
|
+
JOIN assignment_outcome_waits aw ON aw.assignment_id = a.assignment_id
|
|
297
|
+
WHERE aw.wait_id = ? AND aw.generation = ?`, waitId, generation);
|
|
298
|
+
if (terminalAssignment) {
|
|
299
|
+
const outcome = JSON.parse(columnText(terminalAssignment, "record_json"));
|
|
300
|
+
if (!outcome.disposition) {
|
|
301
|
+
outcome.inspectedAt = null;
|
|
302
|
+
run(ctx, "UPDATE assignment_outcomes SET record_json = ? WHERE assignment_id = ?", JSON.stringify(outcome), outcome.assignmentId);
|
|
303
|
+
for (const evidence of getRows(ctx, "SELECT * FROM operation_evidence WHERE operation_id = ? AND terminal_revision = ?", operation.operationId, operation.terminalRevision)) {
|
|
304
|
+
run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at)
|
|
305
|
+
VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, columnText(terminalAssignment, "event_id"), operation.operationId, operation.terminalRevision,
|
|
306
|
+
columnText(evidence, "kind"), columnText(evidence, "ref"), columnNullableText(evidence, "summary"), columnNumber(evidence, "detail_lost"), evidence.bytes as number | null, at);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
292
311
|
if (phase !== "waiting" || !state.settled) continue;
|
|
293
312
|
run(
|
|
294
313
|
ctx,
|
|
@@ -311,11 +330,21 @@ export function registerWait(ctx: StoreContext, input: RegisterWaitInput): Regis
|
|
|
311
330
|
const dependencies = normalizeDependencies(input.dependencies);
|
|
312
331
|
const continuationNote = requireText("continuationNote", input.continuationNote, 8192);
|
|
313
332
|
const park = normalizePark(input.park);
|
|
314
|
-
|
|
333
|
+
let origin = normalizeOrigin(input.origin);
|
|
315
334
|
const requestedWaitId = input.waitId === undefined ? null : requireId("waitId", input.waitId);
|
|
316
335
|
|
|
317
336
|
return ctx.transaction(() => {
|
|
318
337
|
const at = ctx.now();
|
|
338
|
+
if (park) {
|
|
339
|
+
const binding = getRow(ctx, "SELECT assignment_id FROM assignment_attempts WHERE attempt_id = ?", park.attemptId);
|
|
340
|
+
if (binding) {
|
|
341
|
+
if (origin?.assignmentRef && origin.assignmentRef !== binding.assignment_id) throw new StoreError("foreign-owner", "Wait assignment does not match its attempt.");
|
|
342
|
+
origin = { ...origin, assignmentRef: columnText(binding, "assignment_id") };
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (origin?.assignmentRef && getRow(ctx, "SELECT assignment_id FROM assignment_outcomes WHERE assignment_id = ?", origin.assignmentRef)) {
|
|
346
|
+
throw new StoreError("wait-phase", "A terminal assignment cannot register another wait; delegate a new assignment.");
|
|
347
|
+
}
|
|
319
348
|
const resolved: Array<{
|
|
320
349
|
dependency: WaitDependencyInput;
|
|
321
350
|
terminalRevision: number;
|
|
@@ -364,7 +393,7 @@ export function registerWait(ctx: StoreContext, input: RegisterWaitInput): Regis
|
|
|
364
393
|
}
|
|
365
394
|
}
|
|
366
395
|
const pending = existing.find(
|
|
367
|
-
(row) => !TERMINAL_PHASES.includes(columnText(row, "phase") as WaitPhase),
|
|
396
|
+
(row) => !TERMINAL_PHASES.includes(columnText(row, "phase") as WaitPhase) && columnNumber(row, "dispatch_disarmed") === 0,
|
|
368
397
|
);
|
|
369
398
|
if (pending) {
|
|
370
399
|
throw new StoreError(
|
|
@@ -379,7 +408,7 @@ export function registerWait(ctx: StoreContext, input: RegisterWaitInput): Regis
|
|
|
379
408
|
`SELECT * FROM waits
|
|
380
409
|
WHERE owner_kind = ? AND owner_session_id = ?
|
|
381
410
|
AND coalesce(owner_branch_id, '') = ?
|
|
382
|
-
AND phase NOT IN ('consumed', 'cancelled')`,
|
|
411
|
+
AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0`,
|
|
383
412
|
owner.kind,
|
|
384
413
|
owner.sessionId,
|
|
385
414
|
owner.branchId ?? "",
|
|
@@ -636,6 +665,9 @@ export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeC
|
|
|
636
665
|
`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
666
|
);
|
|
638
667
|
}
|
|
668
|
+
const priorWriter = getRow(ctx, `SELECT c.claim_id FROM resume_claims c JOIN waits w ON w.wait_id = c.wait_id AND w.generation = c.generation
|
|
669
|
+
WHERE w.owner_kind = ? AND w.owner_session_id = ? AND w.owner_workspace = ? AND c.state = 'published' LIMIT 1`, wait.owner.kind, wait.owner.sessionId, wait.owner.workspace);
|
|
670
|
+
if (priorWriter) throw new StoreError("concurrent-claim", "A prior published conversation writer still needs independent exit proof.");
|
|
639
671
|
if (wait.phase !== "ready") {
|
|
640
672
|
throw new StoreError(
|
|
641
673
|
"wait-phase",
|
|
@@ -880,6 +912,15 @@ export function holdFailedResume(
|
|
|
880
912
|
}
|
|
881
913
|
|
|
882
914
|
return ctx.transaction(() => {
|
|
915
|
+
const terminal = getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation);
|
|
916
|
+
if (terminal) {
|
|
917
|
+
const claim = requireClaim(ctx, claimId);
|
|
918
|
+
if (claim.waitId !== waitId || claim.generation !== generation || claim.claimToken !== claimToken
|
|
919
|
+
|| claim.attemptId !== attemptId || claim.launchToken !== launchToken) throw new StoreError("claim-state", "Terminal writer exit proof does not match the published attempt.");
|
|
920
|
+
const applied = claim.state === "published";
|
|
921
|
+
if (applied) run(ctx, "UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ? WHERE claim_id = ?", ctx.now(), reason, claimId);
|
|
922
|
+
return { wait: requireWait(ctx, waitId, generation), claim: requireClaim(ctx, claimId), applied };
|
|
923
|
+
}
|
|
883
924
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
884
925
|
const wait = requireWait(ctx, waitId, generation);
|
|
885
926
|
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
@@ -1084,6 +1125,7 @@ export function recordEvidencePin(
|
|
|
1084
1125
|
|
|
1085
1126
|
return ctx.transaction(() => {
|
|
1086
1127
|
const wait = requireWait(ctx, waitId, generation);
|
|
1128
|
+
if (getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation)) throw new StoreError("wait-phase", "Evidence obligations belong to the terminal outcome, not the old wait.");
|
|
1087
1129
|
if (TERMINAL_PHASES.includes(wait.phase)) {
|
|
1088
1130
|
throw new StoreError(
|
|
1089
1131
|
"wait-phase",
|
|
@@ -1330,7 +1372,7 @@ export function listWaits(ctx: StoreContext, filter: WaitFilter = {}): WaitRecor
|
|
|
1330
1372
|
params.push(...phases);
|
|
1331
1373
|
}
|
|
1332
1374
|
if (filter.pendingOnly) {
|
|
1333
|
-
clauses.push("phase NOT IN ('consumed', 'cancelled')");
|
|
1375
|
+
clauses.push("phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0");
|
|
1334
1376
|
}
|
|
1335
1377
|
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
1336
1378
|
return getRows(
|
|
@@ -1361,7 +1403,7 @@ export function findPendingWaitForOwner(
|
|
|
1361
1403
|
ctx,
|
|
1362
1404
|
`SELECT * FROM waits
|
|
1363
1405
|
WHERE owner_kind = ? AND owner_session_id = ? AND coalesce(owner_branch_id, '') = ?
|
|
1364
|
-
AND phase NOT IN ('consumed', 'cancelled')`,
|
|
1406
|
+
AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0`,
|
|
1365
1407
|
owner.kind,
|
|
1366
1408
|
owner.sessionId,
|
|
1367
1409
|
owner.branchId ?? "",
|