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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/retained-result.ts. Do not edit directly.
|
|
2
|
-
import { copyFileSync,
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import { snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
|
|
4
|
+
import { copyTree, snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
|
|
5
5
|
import { resultDir } from "./session-store.domain.mjs";
|
|
6
6
|
// Published only while retiring a quiescent attempt. A result record can answer reads,
|
|
7
7
|
// but cannot authorize admission, revive a writer or make a failed attempt resumable.
|
|
@@ -26,7 +26,7 @@ export function retainResult(meta, logPath, scratch) {
|
|
|
26
26
|
if (scratch && existsSync(scratch)) {
|
|
27
27
|
const files = snapshotTree(scratch);
|
|
28
28
|
if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
|
|
29
|
-
|
|
29
|
+
copyTree(scratch, join(temp, "scratch"), files);
|
|
30
30
|
verifyTree(join(temp, "scratch"), files);
|
|
31
31
|
verifyTree(scratch, files);
|
|
32
32
|
savedScratch = join(dir, "scratch");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
2
|
copyFileSync,
|
|
3
|
-
cpSync,
|
|
4
3
|
existsSync,
|
|
5
4
|
mkdirSync,
|
|
6
5
|
mkdtempSync,
|
|
@@ -10,7 +9,7 @@ import {
|
|
|
10
9
|
writeFileSync,
|
|
11
10
|
} from "node:fs";
|
|
12
11
|
import { dirname, join } from "node:path";
|
|
13
|
-
import { snapshotTree, verifyTree } from "./workspace-files.ts";
|
|
12
|
+
import { copyTree, snapshotTree, verifyTree } from "./workspace-files.ts";
|
|
14
13
|
import type { RunMeta } from "./registry.ts";
|
|
15
14
|
import { resultDir } from "./session-store.ts";
|
|
16
15
|
|
|
@@ -35,7 +34,7 @@ export function retainResult(meta: RunMeta, logPath: string, scratch?: string):
|
|
|
35
34
|
if (scratch && existsSync(scratch)) {
|
|
36
35
|
const files = snapshotTree(scratch);
|
|
37
36
|
if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
|
|
38
|
-
|
|
37
|
+
copyTree(scratch, join(temp, "scratch"), files);
|
|
39
38
|
verifyTree(join(temp, "scratch"), files);
|
|
40
39
|
verifyTree(scratch, files);
|
|
41
40
|
savedScratch = join(dir, "scratch");
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs
CHANGED
|
@@ -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 = [
|
|
@@ -35,6 +35,39 @@ export function ensureAssignmentChanges(ctx: StoreContext): void {
|
|
|
35
35
|
const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
|
|
36
36
|
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;`);
|
|
37
37
|
}
|
|
38
|
+
// An idle scan may span several pages. Insertions and authority transfers can
|
|
39
|
+
// put a new candidate behind its cursor; deleting completed work cannot.
|
|
40
|
+
const advanceCleanup = `INSERT INTO coordinator_state VALUES ('server-assignment-cleanup-revision', '1')
|
|
41
|
+
ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1;`;
|
|
42
|
+
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_added AFTER INSERT ON assignment_cleanup_pending
|
|
43
|
+
WHEN NEW.supervision_host_id GLOB 'server:*' BEGIN ${advanceCleanup} END;
|
|
44
|
+
CREATE TRIGGER IF NOT EXISTS server_cleanup_transferred AFTER UPDATE OF supervision_host_id ON assignment_cleanup_pending
|
|
45
|
+
WHEN NEW.supervision_host_id GLOB 'server:*' AND NEW.supervision_host_id IS NOT OLD.supervision_host_id
|
|
46
|
+
BEGIN ${advanceCleanup} END;`);
|
|
47
|
+
// The result grant can arrive after the assignment already ended.
|
|
48
|
+
for (const event of ["INSERT", "UPDATE"]) 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
|
+
}
|
|
38
71
|
// These are observation inputs, not execution or delivery authority. Old
|
|
39
72
|
// cooperative SQL writers inherit the same atomic invalidation triggers.
|
|
40
73
|
const backgroundSources = [
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
2
2
|
// Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
-
import { bumpChangeRevision } from "./discovery.domain.mjs";
|
|
5
4
|
import { StoreError } from "./errors.domain.mjs";
|
|
6
5
|
import { columnText, getRow, getRows, run } from "./sqlite.domain.mjs";
|
|
7
6
|
import { requireWait, readPins } from "./rows.domain.mjs";
|
|
@@ -109,7 +108,6 @@ export function recordAssignmentOutcome(ctx, input) {
|
|
|
109
108
|
for (const e of retained)
|
|
110
109
|
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) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
111
110
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
112
|
-
bumpChangeRevision(ctx);
|
|
113
111
|
return record;
|
|
114
112
|
});
|
|
115
113
|
}
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { bumpChangeRevision } from "./discovery.ts";
|
|
4
3
|
import { StoreError } from "./errors.ts";
|
|
5
4
|
import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
6
5
|
import { requireWait, readPins } from "./rows.ts";
|
|
@@ -121,7 +120,6 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
|
|
|
121
120
|
}
|
|
122
121
|
for (const e of retained) 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) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
123
122
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
124
|
-
bumpChangeRevision(ctx);
|
|
125
123
|
return record;
|
|
126
124
|
});
|
|
127
125
|
}
|
|
@@ -7,6 +7,10 @@ import { getRow, getRows, run } from "./sqlite.domain.mjs";
|
|
|
7
7
|
import { requireBoolean, requireCounter, requireId, requirePath } from "./validate.domain.mjs";
|
|
8
8
|
const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
|
|
9
9
|
const scopeValues = (scope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)];
|
|
10
|
+
export function parentRecoveryRevision(ctx, scope) {
|
|
11
|
+
const row = getRow(ctx, 'SELECT revision FROM background_recovery_scopes WHERE workspace=? AND session_id=?', ...scopeValues(scope));
|
|
12
|
+
return Number(row?.revision ?? 0);
|
|
13
|
+
}
|
|
10
14
|
export function setParentCallbackPending(ctx, taskId, pending) {
|
|
11
15
|
taskId = requireId('taskId', taskId);
|
|
12
16
|
pending = requireBoolean('pending', pending);
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts
CHANGED
|
@@ -17,6 +17,11 @@ export interface RecentBackgroundTerminalPage {
|
|
|
17
17
|
const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
|
|
18
18
|
const scopeValues = (scope: ParentCallbackScope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)] as const;
|
|
19
19
|
|
|
20
|
+
export function parentRecoveryRevision(ctx: StoreContext, scope: ParentCallbackScope): number {
|
|
21
|
+
const row = getRow(ctx, 'SELECT revision FROM background_recovery_scopes WHERE workspace=? AND session_id=?', ...scopeValues(scope));
|
|
22
|
+
return Number(row?.revision ?? 0);
|
|
23
|
+
}
|
|
24
|
+
|
|
20
25
|
export function setParentCallbackPending(ctx: StoreContext, taskId: string, pending: boolean): boolean {
|
|
21
26
|
taskId = requireId('taskId', taskId);
|
|
22
27
|
pending = requireBoolean('pending', pending);
|
|
@@ -34,13 +34,15 @@ export function readDiscoveryClaim(ctx, scope) {
|
|
|
34
34
|
return readClaim(ctx, requireId("scope", scope));
|
|
35
35
|
}
|
|
36
36
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
37
|
-
export function readDiscoveryState(ctx, scope) {
|
|
37
|
+
export function readDiscoveryState(ctx, scope, hostId) {
|
|
38
38
|
scope = requireId("scope", scope);
|
|
39
39
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
40
40
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
41
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
42
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
43
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
|
|
44
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
45
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
44
46
|
}
|
|
45
47
|
export function tryClaimDiscovery(ctx, input) {
|
|
46
48
|
const scope = requireId("scope", input.scope);
|
|
@@ -49,13 +49,16 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
52
|
-
export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
|
|
52
|
+
export function readDiscoveryState(ctx: StoreContext, scope: string, hostId?: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean; cleanupPending?: boolean } {
|
|
53
53
|
scope = requireId("scope", scope);
|
|
54
54
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
55
55
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
56
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
57
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
58
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope,
|
|
59
|
+
hostId === undefined ? null : requireId("hostId", hostId), scope)!;
|
|
60
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
61
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
59
62
|
}
|
|
60
63
|
|
|
61
64
|
export function tryClaimDiscovery(
|
|
@@ -313,24 +313,17 @@ export function listOperations(ctx, filter = {}) {
|
|
|
313
313
|
return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
|
|
314
314
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
315
315
|
}
|
|
316
|
-
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
|
|
316
|
+
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
|
|
317
317
|
const requested = requireCounter("limit", limit);
|
|
318
318
|
if (requested === 0)
|
|
319
319
|
throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
320
320
|
const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
|
|
321
|
-
|
|
321
|
+
const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
|
|
322
322
|
return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
|
|
323
323
|
WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
|
|
324
|
-
FROM operations op
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
|
|
328
|
-
AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
|
|
329
|
-
OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
|
|
330
|
-
AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
|
|
331
|
-
AND e.summary LIKE '%groupCleanup=unproven%'))
|
|
332
|
-
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
|
|
333
|
-
ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
324
|
+
FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
325
|
+
WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
|
|
326
|
+
ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
334
327
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
335
328
|
}
|
|
336
329
|
/** Running operations assigned to one supervising host, using the phase/host index. */
|
|
@@ -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
|
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs
CHANGED
|
@@ -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);
|
|
@@ -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;
|
|
@@ -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
|
|