pi-better-server 0.8.0 → 0.8.2
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 +1 -1
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +2 -2
- package/src/runtime/background-tools.ts +1 -1
- package/src/runtime/background.ts +9 -4
- package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +30 -18
- package/src/runtime/domain/background-service/observed-waits.ts +33 -19
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +33 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +75 -6
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +75 -5
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +9 -6
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +14 -8
- package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
- package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
- package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
- package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
- package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
- package/src/runtime/domain/coordinator/src/schema.mjs +75 -6
- package/src/runtime/domain/coordinator/src/store.mjs +9 -6
- package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
- package/src/runtime/domain/subagents/cleanup.ts +6 -8
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +14 -1
- package/src/runtime/domain/subagents/managed-launch-client.ts +15 -1
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry.domain.mjs +34 -27
- package/src/runtime/domain/subagents/registry.ts +36 -24
- package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
- package/src/runtime/domain/subagents/retained-result.ts +2 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +33 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +75 -6
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +75 -5
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +9 -6
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +14 -8
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +6 -20
- package/src/runtime/domain/subagents/worker-waits.ts +6 -17
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
- package/src/runtime/domain/subagents/workspace-files.ts +27 -5
- package/src/runtime/result-supervision.ts +46 -12
- package/src/server.ts +14 -6
- package/src/version.ts +1 -1
package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts
CHANGED
|
@@ -467,23 +467,17 @@ export function listAssignmentCleanupOperations(
|
|
|
467
467
|
ctx: StoreContext,
|
|
468
468
|
limit: number,
|
|
469
469
|
afterOperationId?: string,
|
|
470
|
+
hostId?: string,
|
|
470
471
|
): OperationRecord[] {
|
|
471
472
|
const requested = requireCounter("limit", limit);
|
|
472
473
|
if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
473
474
|
const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
|
|
474
|
-
|
|
475
|
+
const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
|
|
475
476
|
return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
|
|
476
477
|
WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
|
|
477
|
-
FROM operations op
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
|
|
481
|
-
AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
|
|
482
|
-
OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
|
|
483
|
-
AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
|
|
484
|
-
AND e.summary LIKE '%groupCleanup=unproven%'))
|
|
485
|
-
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
|
|
486
|
-
ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
478
|
+
FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
479
|
+
WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
|
|
480
|
+
ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
487
481
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
488
482
|
}
|
|
489
483
|
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
import { isDeepStrictEqual } from "node:util";
|
|
4
4
|
import { getRow, run } from "./sqlite.domain.mjs";
|
|
5
5
|
import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.domain.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { mapOperation } from "./rows.domain.mjs";
|
|
7
|
+
import { requireCounter, requireId, requirePath } from "./validate.domain.mjs";
|
|
7
8
|
const PREFIX = "result-supervision-v1:";
|
|
8
9
|
/** A bounded observation page. A gap requires restoring active authority, not history. */
|
|
9
10
|
export function resultSupervisionChanges(ctx, after) {
|
|
@@ -28,6 +29,24 @@ export function resultSupervision(ctx, operationId) {
|
|
|
28
29
|
const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
|
|
29
30
|
return row ? JSON.parse(String(row.value)) : null;
|
|
30
31
|
}
|
|
32
|
+
/** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
|
|
33
|
+
export function serverAssignmentCleanupRevision(ctx) {
|
|
34
|
+
return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
|
|
35
|
+
}
|
|
36
|
+
/** Pending cleanup under the root daemon's result authority, including past epochs. */
|
|
37
|
+
export function serverAssignmentCleanup(ctx, limit, after) {
|
|
38
|
+
const host = after ? requireId("hostId", after.hostId) : "server:";
|
|
39
|
+
if (!host.startsWith("server:"))
|
|
40
|
+
throw new Error("Expected a server cleanup cursor");
|
|
41
|
+
// 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
|
|
42
|
+
const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
|
|
43
|
+
FROM assignment_cleanup_pending p
|
|
44
|
+
CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
45
|
+
CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
|
|
46
|
+
WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
|
|
47
|
+
ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX, host, after ? requireId("operationId", after.operationId) : "", Math.min(256, requireCounter("limit", limit)));
|
|
48
|
+
return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) }));
|
|
49
|
+
}
|
|
31
50
|
/** The admitting host has stopped its local route before this exact-owner CAS. */
|
|
32
51
|
export function handoffResultSupervision(ctx, input) {
|
|
33
52
|
const operationId = requireId("operationId", input.operationId);
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { isDeepStrictEqual } from "node:util";
|
|
3
3
|
import { getRow, run, type StoreContext } from "./sqlite.ts";
|
|
4
4
|
import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
|
|
5
|
-
import {
|
|
5
|
+
import { mapOperation } from "./rows.ts";
|
|
6
|
+
import { requireCounter, requireId, requirePath } from "./validate.ts";
|
|
6
7
|
import type { RecordTerminalOutcomeInput } from "./types.ts";
|
|
7
8
|
import type { OwnerIdentity } from "./types.ts";
|
|
8
9
|
|
|
@@ -43,6 +44,27 @@ export function resultSupervision(ctx: StoreContext, operationId: string): Resul
|
|
|
43
44
|
return row ? JSON.parse(String(row.value)) : null;
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
/** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
|
|
48
|
+
export function serverAssignmentCleanupRevision(ctx: StoreContext): number {
|
|
49
|
+
return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Pending cleanup under the root daemon's result authority, including past epochs. */
|
|
53
|
+
export function serverAssignmentCleanup(ctx: StoreContext, limit: number, after?: { hostId: string; operationId: string }) {
|
|
54
|
+
const host = after ? requireId("hostId", after.hostId) : "server:";
|
|
55
|
+
if (!host.startsWith("server:")) throw new Error("Expected a server cleanup cursor");
|
|
56
|
+
// 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
|
|
57
|
+
const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
|
|
58
|
+
FROM assignment_cleanup_pending p
|
|
59
|
+
CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
60
|
+
CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
|
|
61
|
+
WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
|
|
62
|
+
ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX,
|
|
63
|
+
host, after ? requireId("operationId", after.operationId) : "",
|
|
64
|
+
Math.min(256, requireCounter("limit", limit)));
|
|
65
|
+
return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) as ResultSupervision | null }));
|
|
66
|
+
}
|
|
67
|
+
|
|
46
68
|
/** The admitting host has stopped its local route before this exact-owner CAS. */
|
|
47
69
|
export function handoffResultSupervision(ctx: StoreContext, input: {
|
|
48
70
|
operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs
CHANGED
|
@@ -68,6 +68,48 @@ const EXPIRY_INDEXES = [
|
|
|
68
68
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
69
69
|
ON operations (operation_id, assignment_attempt_id)
|
|
70
70
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
71
|
+
// Terminal evidence is written before the operation's terminal revision in the same transaction.
|
|
72
|
+
function needsAssignmentCleanup(row) {
|
|
73
|
+
return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
|
|
74
|
+
SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
|
|
75
|
+
AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
|
|
76
|
+
AND e.summary LIKE '%groupCleanup=unproven%'))`;
|
|
77
|
+
}
|
|
78
|
+
const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
|
|
79
|
+
FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
|
|
80
|
+
WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
|
|
81
|
+
// Triggers also cover older processes that still have an open coordinator connection.
|
|
82
|
+
const PENDING_CLEANUP_DDL = [
|
|
83
|
+
`CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
|
|
84
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
85
|
+
supervision_host_id TEXT
|
|
86
|
+
) WITHOUT ROWID`,
|
|
87
|
+
`CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
|
|
88
|
+
`CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
|
|
89
|
+
`CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
|
|
90
|
+
WHERE assignment_attempt_id IS NOT NULL`,
|
|
91
|
+
`CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
|
|
92
|
+
INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
|
|
93
|
+
END`,
|
|
94
|
+
`CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
|
|
95
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
|
|
96
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
|
|
97
|
+
END`,
|
|
98
|
+
`CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
|
|
99
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
|
|
100
|
+
UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
|
|
101
|
+
END`,
|
|
102
|
+
`CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
|
|
103
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
|
|
104
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
105
|
+
END`,
|
|
106
|
+
];
|
|
107
|
+
// Legacy Windows clients can keep writing through an open connection after migration.
|
|
108
|
+
const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
|
|
109
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
|
|
110
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
111
|
+
WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
|
|
112
|
+
BEGIN SELECT RAISE(IGNORE); END`;
|
|
71
113
|
const DDL = [
|
|
72
114
|
`CREATE TABLE task_cancellation_authorities (
|
|
73
115
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -289,6 +331,7 @@ const DDL = [
|
|
|
289
331
|
PRIMARY KEY (wait_id, generation)
|
|
290
332
|
)`,
|
|
291
333
|
RESULT_ADMISSION_FENCE,
|
|
334
|
+
...PENDING_CLEANUP_DDL,
|
|
292
335
|
];
|
|
293
336
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
294
337
|
function existingTables(ctx) {
|
|
@@ -308,6 +351,8 @@ export function ensureSchema(ctx) {
|
|
|
308
351
|
ctx.transaction(() => {
|
|
309
352
|
for (const statement of [...DDL, ...EXPIRY_INDEXES])
|
|
310
353
|
ctx.db.exec(statement);
|
|
354
|
+
if (process.platform === "win32")
|
|
355
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
311
356
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
312
357
|
});
|
|
313
358
|
return;
|
|
@@ -359,14 +404,38 @@ function ensureAssignmentCleanupSchema(ctx) {
|
|
|
359
404
|
for (const statement of EXPIRY_INDEXES)
|
|
360
405
|
ctx.db.exec(statement);
|
|
361
406
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
362
|
-
|
|
407
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
408
|
+
const needsWindowsGuard = () => process.platform === "win32" &&
|
|
409
|
+
!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
|
|
410
|
+
if (hasPending() && !needsWindowsGuard())
|
|
363
411
|
return;
|
|
364
412
|
ctx.transaction(() => {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (!
|
|
368
|
-
|
|
369
|
-
|
|
413
|
+
const createQueue = !hasPending();
|
|
414
|
+
const installGuard = needsWindowsGuard();
|
|
415
|
+
if (!createQueue && !installGuard)
|
|
416
|
+
return;
|
|
417
|
+
if (createQueue) {
|
|
418
|
+
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
419
|
+
// Legacy writers leave the nullable provenance unset.
|
|
420
|
+
if (!hasColumn())
|
|
421
|
+
ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
422
|
+
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
423
|
+
for (const statement of PENDING_CLEANUP_DDL)
|
|
424
|
+
ctx.db.exec(statement);
|
|
425
|
+
}
|
|
426
|
+
if (installGuard) {
|
|
427
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
428
|
+
// Discard marks from writers which treated an unsupported Windows group probe as proof.
|
|
429
|
+
ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
|
|
430
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
431
|
+
WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
|
|
432
|
+
}
|
|
433
|
+
ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
|
|
434
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
435
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
436
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
437
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
438
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
370
439
|
});
|
|
371
440
|
}
|
|
372
441
|
/**
|
|
@@ -72,6 +72,52 @@ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignme
|
|
|
72
72
|
ON operations (operation_id, assignment_attempt_id)
|
|
73
73
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
74
74
|
|
|
75
|
+
// Terminal evidence is written before the operation's terminal revision in the same transaction.
|
|
76
|
+
function needsAssignmentCleanup(row: "op" | "NEW"): string {
|
|
77
|
+
return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
|
|
78
|
+
SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
|
|
79
|
+
AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
|
|
80
|
+
AND e.summary LIKE '%groupCleanup=unproven%'))`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
|
|
84
|
+
FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
|
|
85
|
+
WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
|
|
86
|
+
|
|
87
|
+
// Triggers also cover older processes that still have an open coordinator connection.
|
|
88
|
+
const PENDING_CLEANUP_DDL = [
|
|
89
|
+
`CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
|
|
90
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
91
|
+
supervision_host_id TEXT
|
|
92
|
+
) WITHOUT ROWID`,
|
|
93
|
+
`CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
|
|
94
|
+
`CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
|
|
95
|
+
`CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
|
|
96
|
+
WHERE assignment_attempt_id IS NOT NULL`,
|
|
97
|
+
`CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
|
|
98
|
+
INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
|
|
99
|
+
END`,
|
|
100
|
+
`CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
|
|
101
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
|
|
102
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
|
|
103
|
+
END`,
|
|
104
|
+
`CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
|
|
105
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
|
|
106
|
+
UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
|
|
107
|
+
END`,
|
|
108
|
+
`CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
|
|
109
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
|
|
110
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
111
|
+
END`,
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
// Legacy Windows clients can keep writing through an open connection after migration.
|
|
115
|
+
const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
|
|
116
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
|
|
117
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
118
|
+
WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
|
|
119
|
+
BEGIN SELECT RAISE(IGNORE); END`;
|
|
120
|
+
|
|
75
121
|
const DDL: readonly string[] = [
|
|
76
122
|
`CREATE TABLE task_cancellation_authorities (
|
|
77
123
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -293,6 +339,7 @@ const DDL: readonly string[] = [
|
|
|
293
339
|
PRIMARY KEY (wait_id, generation)
|
|
294
340
|
)`,
|
|
295
341
|
RESULT_ADMISSION_FENCE,
|
|
342
|
+
...PENDING_CLEANUP_DDL,
|
|
296
343
|
];
|
|
297
344
|
|
|
298
345
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
@@ -320,6 +367,7 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
320
367
|
}
|
|
321
368
|
ctx.transaction(() => {
|
|
322
369
|
for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
|
|
370
|
+
if (process.platform === "win32") ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
323
371
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
324
372
|
});
|
|
325
373
|
return;
|
|
@@ -377,12 +425,34 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
377
425
|
function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
|
|
378
426
|
for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
|
|
379
427
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
380
|
-
|
|
428
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
429
|
+
const needsWindowsGuard = () => process.platform === "win32" &&
|
|
430
|
+
!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
|
|
431
|
+
if (hasPending() && !needsWindowsGuard()) return;
|
|
381
432
|
ctx.transaction(() => {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
if (!
|
|
385
|
-
|
|
433
|
+
const createQueue = !hasPending();
|
|
434
|
+
const installGuard = needsWindowsGuard();
|
|
435
|
+
if (!createQueue && !installGuard) return;
|
|
436
|
+
if (createQueue) {
|
|
437
|
+
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
438
|
+
// Legacy writers leave the nullable provenance unset.
|
|
439
|
+
if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
440
|
+
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
441
|
+
for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
|
|
442
|
+
}
|
|
443
|
+
if (installGuard) {
|
|
444
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
445
|
+
// Discard marks from writers which treated an unsupported Windows group probe as proof.
|
|
446
|
+
ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
|
|
447
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
448
|
+
WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
|
|
449
|
+
}
|
|
450
|
+
ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
|
|
451
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
452
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
453
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
454
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
455
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
386
456
|
});
|
|
387
457
|
}
|
|
388
458
|
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs
CHANGED
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { expireWaits, overdueOperations } from "./expiry.domain.mjs";
|
|
12
12
|
import { setUpgradeFence } from "./upgrade.domain.mjs";
|
|
13
|
-
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
|
|
13
|
+
import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
|
|
14
14
|
import { BackgroundRequests } from "./background-requests.domain.mjs";
|
|
15
15
|
import { StoreError } from "./errors.domain.mjs";
|
|
16
16
|
import { SubagentLaunchJournal } from "./subagent-launch.domain.mjs";
|
|
17
|
-
import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
|
|
17
|
+
import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
|
|
18
18
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.domain.mjs";
|
|
19
19
|
import { repairFailedResume } from "./recovery.domain.mjs";
|
|
20
20
|
import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.domain.mjs";
|
|
@@ -59,6 +59,8 @@ export function openStore(options) {
|
|
|
59
59
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
60
60
|
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
61
61
|
hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
|
|
62
|
+
serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
|
|
63
|
+
serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
|
|
62
64
|
resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
|
|
63
65
|
resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
|
|
64
66
|
handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
|
|
@@ -88,6 +90,7 @@ export function openStore(options) {
|
|
|
88
90
|
closed = true;
|
|
89
91
|
db.close();
|
|
90
92
|
},
|
|
93
|
+
parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
|
|
91
94
|
setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
|
|
92
95
|
listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
|
|
93
96
|
listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
|
|
@@ -118,16 +121,16 @@ export function openStore(options) {
|
|
|
118
121
|
alive();
|
|
119
122
|
return readOperationRecords(ctx, filter);
|
|
120
123
|
},
|
|
121
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
124
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
122
125
|
alive();
|
|
123
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
126
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
124
127
|
},
|
|
125
128
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
126
129
|
alive();
|
|
127
130
|
if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1)
|
|
128
131
|
return false;
|
|
129
132
|
return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
|
|
130
|
-
SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
|
|
133
|
+
SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
|
|
131
134
|
FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
132
135
|
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
133
136
|
WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`, operationId, launchToken, terminalRevision) > 0;
|
|
@@ -140,7 +143,7 @@ export function openStore(options) {
|
|
|
140
143
|
alive();
|
|
141
144
|
return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
|
|
142
145
|
},
|
|
143
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
146
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
144
147
|
readDiscoveryClaim(scope) {
|
|
145
148
|
alive();
|
|
146
149
|
return readClaim(ctx, scope);
|
|
@@ -9,11 +9,11 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { expireWaits, overdueOperations } from "./expiry.ts";
|
|
11
11
|
import { setUpgradeFence } from "./upgrade.ts";
|
|
12
|
-
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
|
|
12
|
+
import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
|
|
13
13
|
import { BackgroundRequests } from "./background-requests.ts";
|
|
14
14
|
import { StoreError } from "./errors.ts";
|
|
15
15
|
import { SubagentLaunchJournal } from "./subagent-launch.ts";
|
|
16
|
-
import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
16
|
+
import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
17
17
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
|
|
18
18
|
import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
|
|
19
19
|
import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
|
|
@@ -131,6 +131,8 @@ export interface Store {
|
|
|
131
131
|
overdueOperations(): OperationRecord[];
|
|
132
132
|
expireWaits(): number;
|
|
133
133
|
hasSubagentManagement(): boolean;
|
|
134
|
+
serverAssignmentCleanupRevision(): number;
|
|
135
|
+
serverAssignmentCleanup(limit: number, after?: Parameters<typeof serverAssignmentCleanup>[2]): ReturnType<typeof serverAssignmentCleanup>;
|
|
134
136
|
resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
|
|
135
137
|
subagentLaunchJournal(): SubagentLaunchJournal;
|
|
136
138
|
resultScopeManaged(scope: string): boolean;
|
|
@@ -169,6 +171,7 @@ export interface Store {
|
|
|
169
171
|
// ---- operations ----
|
|
170
172
|
|
|
171
173
|
backgroundRequests(): BackgroundRequests;
|
|
174
|
+
parentRecoveryRevision(scope: ParentCallbackScope): number;
|
|
172
175
|
setParentCallbackPending(taskId: string, pending: boolean): boolean;
|
|
173
176
|
listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
|
|
174
177
|
listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
|
|
@@ -207,7 +210,7 @@ export interface Store {
|
|
|
207
210
|
* Read up to 256 unfinished cleanup obligations in operation id order.
|
|
208
211
|
* The cursor is exclusive. Start each new sweep without a cursor.
|
|
209
212
|
*/
|
|
210
|
-
listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
|
|
213
|
+
listAssignmentCleanupOperations(limit: number, afterOperationId?: string, hostId?: string): OperationRecord[];
|
|
211
214
|
verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
|
|
212
215
|
/** Running operations currently assigned to this supervising host. */
|
|
213
216
|
listRunningSupervisedBy(hostId: string): OperationRecord[];
|
|
@@ -217,7 +220,7 @@ export interface Store {
|
|
|
217
220
|
|
|
218
221
|
/** The shared discovery leader for this store/supervisor scope, if recorded. */
|
|
219
222
|
readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
|
|
220
|
-
readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
|
|
223
|
+
readDiscoveryState(scope: string, hostId?: string): ReturnType<typeof readDiscoveryState>;
|
|
221
224
|
/**
|
|
222
225
|
* Compare-and-swap a discovery claim. The caller must name the exact claim it
|
|
223
226
|
* observed, or null for none; a stale contender receives null and must not
|
|
@@ -369,6 +372,8 @@ export function openStore(options: StoreOptions): Store {
|
|
|
369
372
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
370
373
|
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
371
374
|
hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
|
|
375
|
+
serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
|
|
376
|
+
serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
|
|
372
377
|
resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
|
|
373
378
|
resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
|
|
374
379
|
handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
|
|
@@ -397,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
397
402
|
closed = true;
|
|
398
403
|
db.close();
|
|
399
404
|
},
|
|
405
|
+
parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
|
|
400
406
|
setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
|
|
401
407
|
listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
|
|
402
408
|
listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
|
|
@@ -427,15 +433,15 @@ export function openStore(options: StoreOptions): Store {
|
|
|
427
433
|
alive();
|
|
428
434
|
return readOperationRecords(ctx, filter);
|
|
429
435
|
},
|
|
430
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
436
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
431
437
|
alive();
|
|
432
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
438
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
433
439
|
},
|
|
434
440
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
435
441
|
alive();
|
|
436
442
|
if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
|
|
437
443
|
return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
|
|
438
|
-
SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
|
|
444
|
+
SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
|
|
439
445
|
FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
440
446
|
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
441
447
|
WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
|
|
@@ -453,7 +459,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
453
459
|
terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
|
|
454
460
|
);
|
|
455
461
|
},
|
|
456
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
462
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
457
463
|
readDiscoveryClaim(scope) {
|
|
458
464
|
alive();
|
|
459
465
|
return readClaim(ctx, scope);
|
|
@@ -93,3 +93,8 @@ export function processGroupAlive(pgid) {
|
|
|
93
93
|
return error.code !== "ESRCH";
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
|
+
/** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
|
|
97
|
+
export function processGroupExitVerified(pgid, recordedEmpty = false) {
|
|
98
|
+
return process.platform !== "win32" && (recordedEmpty ||
|
|
99
|
+
(pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
|
|
100
|
+
}
|
|
@@ -91,3 +91,8 @@ export function processGroupAlive(pgid) {
|
|
|
91
91
|
return error.code !== "ESRCH";
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
|
+
/** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
|
|
95
|
+
export function processGroupExitVerified(pgid, recordedEmpty = false) {
|
|
96
|
+
return process.platform !== "win32" && (recordedEmpty ||
|
|
97
|
+
(pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
|
|
98
|
+
}
|
|
@@ -97,3 +97,9 @@ export function processGroupAlive(pgid: number | undefined): boolean {
|
|
|
97
97
|
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
+
|
|
101
|
+
/** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
|
|
102
|
+
export function processGroupExitVerified(pgid: number | undefined, recordedEmpty = false): boolean {
|
|
103
|
+
return process.platform !== "win32" && (recordedEmpty ||
|
|
104
|
+
(pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
|
|
105
|
+
}
|
|
@@ -25,7 +25,7 @@ import { join, resolve } from "node:path";
|
|
|
25
25
|
import { setTimeout as delay } from "node:timers/promises";
|
|
26
26
|
import { validateCondition } from "../conditions.domain.mjs";
|
|
27
27
|
import { stopProcessGroup } from "../process.domain.mjs";
|
|
28
|
-
import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.domain.mjs";
|
|
28
|
+
import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.domain.mjs";
|
|
29
29
|
import { supervisorRunnerInvocation } from "./invocation.domain.mjs";
|
|
30
30
|
import { appendEvent, ensureSupervisorTaskDir, launchRequestHash, readClaimRecord, readCleanupRecord, readCommandRecord, readLaunchRecord, readLostRecord, readStopRequest, readTerminalRecord, resolveSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, SupervisorFenceBusyError, withStateFence, writeCleanupRecord, writeLaunchRecord, writeLostRecord, writeStopRequest, writeTerminalRecord, } from "./store.domain.mjs";
|
|
31
31
|
import { DEFAULT_CLAIM_GRACE_MS, DEFAULT_CLAIM_WAIT_MS, DEFAULT_MAX_LOG_BYTES, DEFAULT_STOP_WAIT_MS, DEFAULT_WATCH_INTERVAL_MS, DEFAULT_WATCH_TIMEOUT_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_INSPECT_FENCE_WAIT_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.domain.mjs";
|
|
@@ -607,8 +607,7 @@ class Supervisor {
|
|
|
607
607
|
// Unknown identity cannot authorize an external signal. A recorded process
|
|
608
608
|
// that is gone is only "already gone" when its group is gone too; survivors
|
|
609
609
|
// in a group whose leader died cannot be verified, so they are refused.
|
|
610
|
-
|
|
611
|
-
outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
|
|
610
|
+
outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
|
|
612
611
|
groupEmpty = outcome === "already-gone" ? true : false;
|
|
613
612
|
}
|
|
614
613
|
else {
|
|
@@ -643,7 +642,7 @@ class Supervisor {
|
|
|
643
642
|
while (Date.now() < killDeadline && processGroupAlive(pgid)) {
|
|
644
643
|
await delay(25);
|
|
645
644
|
}
|
|
646
|
-
groupEmpty =
|
|
645
|
+
groupEmpty = processGroupExitVerified(pgid);
|
|
647
646
|
outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
|
|
648
647
|
}
|
|
649
648
|
const reason = outcome === "killed"
|
|
@@ -25,7 +25,7 @@ import { join, resolve } from "node:path";
|
|
|
25
25
|
import { setTimeout as delay } from "node:timers/promises";
|
|
26
26
|
import { validateCondition } from "../conditions.ts";
|
|
27
27
|
import { stopProcessGroup } from "../process.ts";
|
|
28
|
-
import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.ts";
|
|
28
|
+
import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.ts";
|
|
29
29
|
import type { ProcessIdentityVerdict } from "./identity.ts";
|
|
30
30
|
import { supervisorRunnerInvocation } from "./invocation.ts";
|
|
31
31
|
import {
|
|
@@ -685,8 +685,7 @@ class Supervisor implements LocalSupervisor {
|
|
|
685
685
|
// Unknown identity cannot authorize an external signal. A recorded process
|
|
686
686
|
// that is gone is only "already gone" when its group is gone too; survivors
|
|
687
687
|
// in a group whose leader died cannot be verified, so they are refused.
|
|
688
|
-
|
|
689
|
-
outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
|
|
688
|
+
outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
|
|
690
689
|
groupEmpty = outcome === "already-gone" ? true : false;
|
|
691
690
|
} else {
|
|
692
691
|
/**
|
|
@@ -717,7 +716,7 @@ class Supervisor implements LocalSupervisor {
|
|
|
717
716
|
while (Date.now() < killDeadline && processGroupAlive(pgid)) {
|
|
718
717
|
await delay(25);
|
|
719
718
|
}
|
|
720
|
-
groupEmpty =
|
|
719
|
+
groupEmpty = processGroupExitVerified(pgid);
|
|
721
720
|
outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
|
|
722
721
|
}
|
|
723
722
|
|
|
@@ -34,6 +34,40 @@ export function ensureAssignmentChanges(ctx) {
|
|
|
34
34
|
const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
|
|
35
35
|
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS assignment_change_${table}_${action.toLowerCase()} AFTER ${action} ON ${table} BEGIN ${records.map(r => `INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace) ${select(r)};`).join(" ")} END;`);
|
|
36
36
|
}
|
|
37
|
+
// An idle scan may span several pages. Insertions and authority transfers can
|
|
38
|
+
// put a new candidate behind its cursor; deleting completed work cannot.
|
|
39
|
+
const advanceCleanup = `INSERT INTO coordinator_state VALUES ('server-assignment-cleanup-revision', '1')
|
|
40
|
+
ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1;`;
|
|
41
|
+
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_added AFTER INSERT ON assignment_cleanup_pending
|
|
42
|
+
WHEN NEW.supervision_host_id GLOB 'server:*' BEGIN ${advanceCleanup} END;
|
|
43
|
+
CREATE TRIGGER IF NOT EXISTS server_cleanup_transferred AFTER UPDATE OF supervision_host_id ON assignment_cleanup_pending
|
|
44
|
+
WHEN NEW.supervision_host_id GLOB 'server:*' AND NEW.supervision_host_id IS NOT OLD.supervision_host_id
|
|
45
|
+
BEGIN ${advanceCleanup} END;`);
|
|
46
|
+
// The result grant can arrive after the assignment already ended.
|
|
47
|
+
for (const event of ["INSERT", "UPDATE"])
|
|
48
|
+
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_grant_${event}
|
|
49
|
+
AFTER ${event} ON coordinator_state WHEN NEW.key GLOB 'result-supervision-v1:*' AND EXISTS (
|
|
50
|
+
SELECT 1 FROM assignment_cleanup_pending WHERE operation_id=substr(NEW.key,length('result-supervision-v1:')+1)
|
|
51
|
+
AND supervision_host_id GLOB 'server:*') BEGIN ${advanceCleanup} END`);
|
|
52
|
+
// A foreground polls the branch views of one parent. Keep their durable
|
|
53
|
+
// recovery revision even after older entries roll out of the change journal.
|
|
54
|
+
ctx.db.exec(`CREATE TABLE IF NOT EXISTS background_recovery_scopes (
|
|
55
|
+
workspace TEXT NOT NULL, session_id TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
56
|
+
PRIMARY KEY(workspace,session_id)) WITHOUT ROWID`);
|
|
57
|
+
const recoverySources = [
|
|
58
|
+
["operation_added", "INSERT ON operations", "NEW.owner_kind='parent-session'", "NEW.owner_workspace", "NEW.owner_session_id"],
|
|
59
|
+
["operation_changed", "UPDATE OF terminal_revision, supervision_host_id ON operations",
|
|
60
|
+
"NEW.owner_kind='parent-session' AND (NEW.terminal_revision<>OLD.terminal_revision OR NEW.supervision_host_id IS NOT OLD.supervision_host_id)", "NEW.owner_workspace", "NEW.owner_session_id"],
|
|
61
|
+
["callback_added", "INSERT ON background_parent_callbacks", "1", "NEW.owner_workspace", "NEW.owner_session_id"],
|
|
62
|
+
["callback_removed", "DELETE ON background_parent_callbacks", "1", "OLD.owner_workspace", "OLD.owner_session_id"],
|
|
63
|
+
["delivery_added", "INSERT ON outbox_events", "NEW.event_type='dependency-ready' AND NEW.state='pending' AND NEW.recipient_kind='parent-session'", "NEW.recipient_workspace", "NEW.recipient_session_id"],
|
|
64
|
+
["delivery_released", "UPDATE OF state ON outbox_events", "NEW.event_type='dependency-ready' AND NEW.state='pending' AND OLD.state<>'pending' AND NEW.recipient_kind='parent-session'", "NEW.recipient_workspace", "NEW.recipient_session_id"],
|
|
65
|
+
];
|
|
66
|
+
for (const [name, event, condition, workspace, session] of recoverySources) {
|
|
67
|
+
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_recovery_${name} AFTER ${event} WHEN ${condition}
|
|
68
|
+
BEGIN INSERT INTO background_recovery_scopes VALUES(${workspace},${session},1)
|
|
69
|
+
ON CONFLICT(workspace,session_id) DO UPDATE SET revision=revision+1; END`);
|
|
70
|
+
}
|
|
37
71
|
// These are observation inputs, not execution or delivery authority. Old
|
|
38
72
|
// cooperative SQL writers inherit the same atomic invalidation triggers.
|
|
39
73
|
const backgroundSources = [
|