pi-better-server 0.8.1 → 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-service/observed-waits.domain.mjs +20 -11
- package/src/runtime/domain/background-service/observed-waits.ts +24 -13
- 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/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/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 +30 -13
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +28 -11
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +6 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +9 -3
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
- package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
- package/src/runtime/domain/coordinator/src/schema.mjs +30 -13
- package/src/runtime/domain/coordinator/src/store.mjs +6 -3
- 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 +32 -27
- package/src/runtime/domain/subagents/registry.ts +30 -23
- 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/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/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 +30 -13
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +28 -11
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +6 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +9 -3
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -16
- package/src/runtime/domain/subagents/worker-waits.ts +3 -14
- package/src/runtime/result-supervision.ts +33 -10
- package/src/server.ts +8 -1
- package/src/version.ts +1 -1
|
@@ -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[];
|
|
@@ -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); },
|
|
@@ -435,7 +441,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
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 = ?`,
|
|
@@ -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 = [
|
|
@@ -6,6 +6,10 @@ import { getRow, getRows, run } from './sqlite.mjs';
|
|
|
6
6
|
import { requireBoolean, requireCounter, requireId, requirePath } from './validate.mjs';
|
|
7
7
|
const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
|
|
8
8
|
const scopeValues = (scope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)];
|
|
9
|
+
export function parentRecoveryRevision(ctx, scope) {
|
|
10
|
+
const row = getRow(ctx, 'SELECT revision FROM background_recovery_scopes WHERE workspace=? AND session_id=?', ...scopeValues(scope));
|
|
11
|
+
return Number(row?.revision ?? 0);
|
|
12
|
+
}
|
|
9
13
|
export function setParentCallbackPending(ctx, taskId, pending) {
|
|
10
14
|
taskId = requireId('taskId', taskId);
|
|
11
15
|
pending = requireBoolean('pending', pending);
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { isDeepStrictEqual } from "node:util";
|
|
3
3
|
import { getRow, run } from "./sqlite.mjs";
|
|
4
4
|
import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { mapOperation } from "./rows.mjs";
|
|
6
|
+
import { requireCounter, requireId, requirePath } from "./validate.mjs";
|
|
6
7
|
const PREFIX = "result-supervision-v1:";
|
|
7
8
|
/** A bounded observation page. A gap requires restoring active authority, not history. */
|
|
8
9
|
export function resultSupervisionChanges(ctx, after) {
|
|
@@ -27,6 +28,24 @@ export function resultSupervision(ctx, operationId) {
|
|
|
27
28
|
const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
|
|
28
29
|
return row ? JSON.parse(String(row.value)) : null;
|
|
29
30
|
}
|
|
31
|
+
/** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
|
|
32
|
+
export function serverAssignmentCleanupRevision(ctx) {
|
|
33
|
+
return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
|
|
34
|
+
}
|
|
35
|
+
/** Pending cleanup under the root daemon's result authority, including past epochs. */
|
|
36
|
+
export function serverAssignmentCleanup(ctx, limit, after) {
|
|
37
|
+
const host = after ? requireId("hostId", after.hostId) : "server:";
|
|
38
|
+
if (!host.startsWith("server:"))
|
|
39
|
+
throw new Error("Expected a server cleanup cursor");
|
|
40
|
+
// 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
|
|
41
|
+
const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
|
|
42
|
+
FROM assignment_cleanup_pending p
|
|
43
|
+
CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
44
|
+
CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
|
|
45
|
+
WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
|
|
46
|
+
ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX, host, after ? requireId("operationId", after.operationId) : "", Math.min(256, requireCounter("limit", limit)));
|
|
47
|
+
return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) }));
|
|
48
|
+
}
|
|
30
49
|
/** The admitting host has stopped its local route before this exact-owner CAS. */
|
|
31
50
|
export function handoffResultSupervision(ctx, input) {
|
|
32
51
|
const operationId = requireId("operationId", input.operationId);
|
|
@@ -103,6 +103,12 @@ const PENDING_CLEANUP_DDL = [
|
|
|
103
103
|
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
104
104
|
END`,
|
|
105
105
|
];
|
|
106
|
+
// Legacy Windows clients can keep writing through an open connection after migration.
|
|
107
|
+
const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
|
|
108
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
|
|
109
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
110
|
+
WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
|
|
111
|
+
BEGIN SELECT RAISE(IGNORE); END`;
|
|
106
112
|
const DDL = [
|
|
107
113
|
`CREATE TABLE task_cancellation_authorities (
|
|
108
114
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -344,6 +350,8 @@ export function ensureSchema(ctx) {
|
|
|
344
350
|
ctx.transaction(() => {
|
|
345
351
|
for (const statement of [...DDL, ...EXPIRY_INDEXES])
|
|
346
352
|
ctx.db.exec(statement);
|
|
353
|
+
if (process.platform === "win32")
|
|
354
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
347
355
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
348
356
|
});
|
|
349
357
|
return;
|
|
@@ -396,23 +404,32 @@ function ensureAssignmentCleanupSchema(ctx) {
|
|
|
396
404
|
ctx.db.exec(statement);
|
|
397
405
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
398
406
|
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
399
|
-
|
|
407
|
+
const needsWindowsGuard = () => process.platform === "win32" &&
|
|
408
|
+
!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
|
|
409
|
+
if (hasPending() && !needsWindowsGuard())
|
|
400
410
|
return;
|
|
401
411
|
ctx.transaction(() => {
|
|
402
|
-
|
|
412
|
+
const createQueue = !hasPending();
|
|
413
|
+
const installGuard = needsWindowsGuard();
|
|
414
|
+
if (!createQueue && !installGuard)
|
|
403
415
|
return;
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
416
|
+
if (createQueue) {
|
|
417
|
+
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
418
|
+
// Legacy writers leave the nullable provenance unset.
|
|
419
|
+
if (!hasColumn())
|
|
420
|
+
ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
421
|
+
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
422
|
+
for (const statement of PENDING_CLEANUP_DDL)
|
|
423
|
+
ctx.db.exec(statement);
|
|
424
|
+
}
|
|
425
|
+
if (installGuard) {
|
|
426
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
427
|
+
// Discard marks from writers which treated an unsupported Windows group probe as proof.
|
|
428
|
+
ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
|
|
429
|
+
SELECT 'v2:' || launch_token FROM operations
|
|
430
|
+
WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
|
|
414
431
|
}
|
|
415
|
-
ctx.db.exec(`INSERT INTO assignment_cleanup_pending
|
|
432
|
+
ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
|
|
416
433
|
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
417
434
|
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
418
435
|
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
@@ -9,11 +9,11 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { expireWaits, overdueOperations } from "./expiry.mjs";
|
|
11
11
|
import { setUpgradeFence } from "./upgrade.mjs";
|
|
12
|
-
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from './background-parent-callbacks.mjs';
|
|
12
|
+
import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from './background-parent-callbacks.mjs';
|
|
13
13
|
import { BackgroundRequests } from "./background-requests.mjs";
|
|
14
14
|
import { StoreError } from "./errors.mjs";
|
|
15
15
|
import { SubagentLaunchJournal } from "./subagent-launch.mjs";
|
|
16
|
-
import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.mjs";
|
|
16
|
+
import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.mjs";
|
|
17
17
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.mjs";
|
|
18
18
|
import { repairFailedResume } from "./recovery.mjs";
|
|
19
19
|
import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.mjs";
|
|
@@ -58,6 +58,8 @@ export function openStore(options) {
|
|
|
58
58
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
59
59
|
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
60
60
|
hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
|
|
61
|
+
serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
|
|
62
|
+
serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
|
|
61
63
|
resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
|
|
62
64
|
resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
|
|
63
65
|
handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
|
|
@@ -87,6 +89,7 @@ export function openStore(options) {
|
|
|
87
89
|
closed = true;
|
|
88
90
|
db.close();
|
|
89
91
|
},
|
|
92
|
+
parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
|
|
90
93
|
setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
|
|
91
94
|
listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
|
|
92
95
|
listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
|
|
@@ -126,7 +129,7 @@ export function openStore(options) {
|
|
|
126
129
|
if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1)
|
|
127
130
|
return false;
|
|
128
131
|
return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
|
|
129
|
-
SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
|
|
132
|
+
SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
|
|
130
133
|
FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
131
134
|
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
132
135
|
WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`, operationId, launchToken, terminalRevision) > 0;
|
|
@@ -34,6 +34,7 @@ export async function submitManagedLaunch(pi, ctx, key, tool, params, signal) {
|
|
|
34
34
|
const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"], { signal });
|
|
35
35
|
const id = randomUUID(), secret = randomBytes(32).toString("hex"), path = join(directory, `${id}.json`);
|
|
36
36
|
let unsubscribe;
|
|
37
|
+
let dispatched = false;
|
|
37
38
|
const cancel = () => {
|
|
38
39
|
try {
|
|
39
40
|
rmSync(path, { force: true });
|
|
@@ -76,10 +77,22 @@ export async function submitManagedLaunch(pi, ctx, key, tool, params, signal) {
|
|
|
76
77
|
checking = false;
|
|
77
78
|
}
|
|
78
79
|
});
|
|
80
|
+
signal?.throwIfAborted();
|
|
81
|
+
dispatched = true;
|
|
79
82
|
return await client.request("runtime_launch_subagent", { authority: { id, secret } });
|
|
80
83
|
}
|
|
81
84
|
catch (error) {
|
|
82
|
-
|
|
85
|
+
if (!dispatched)
|
|
86
|
+
signal?.throwIfAborted();
|
|
87
|
+
// Revoking the grant can stop later batch admissions after a worker has already started.
|
|
88
|
+
if (dispatched && error instanceof Error && ((signal?.aborted && error.message === "runtime-unavailable: client closed")
|
|
89
|
+
|| error.message === "runtime-unhealthy: runtime_launch_subagent timed out")) {
|
|
90
|
+
return {
|
|
91
|
+
isError: true,
|
|
92
|
+
details: { status: "outcome_unknown" },
|
|
93
|
+
content: [{ type: "text", text: "The launch receipt is unknown. Check subagent_list in this session before retrying. A worker may already be running." }],
|
|
94
|
+
};
|
|
95
|
+
}
|
|
83
96
|
throw error;
|
|
84
97
|
}
|
|
85
98
|
finally {
|
|
@@ -32,6 +32,7 @@ export async function submitManagedLaunch(pi: ExtensionAPI, ctx: ExtensionContex
|
|
|
32
32
|
const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"], { signal });
|
|
33
33
|
const id = randomUUID(), secret = randomBytes(32).toString("hex"), path = join(directory, `${id}.json`);
|
|
34
34
|
let unsubscribe: unknown;
|
|
35
|
+
let dispatched = false;
|
|
35
36
|
const cancel = () => {
|
|
36
37
|
try { rmSync(path, { force: true }); } catch { /* Finally retries cleanup. */ }
|
|
37
38
|
client.close();
|
|
@@ -63,9 +64,22 @@ export async function submitManagedLaunch(pi: ExtensionAPI, ctx: ExtensionContex
|
|
|
63
64
|
} catch { rmSync(path, { force: true }); }
|
|
64
65
|
finally { checking = false; }
|
|
65
66
|
});
|
|
67
|
+
signal?.throwIfAborted();
|
|
68
|
+
dispatched = true;
|
|
66
69
|
return await client.request("runtime_launch_subagent", { authority: { id, secret } });
|
|
67
70
|
} catch (error) {
|
|
68
|
-
signal?.throwIfAborted();
|
|
71
|
+
if (!dispatched) signal?.throwIfAborted();
|
|
72
|
+
// Revoking the grant can stop later batch admissions after a worker has already started.
|
|
73
|
+
if (dispatched && error instanceof Error && (
|
|
74
|
+
(signal?.aborted && error.message === "runtime-unavailable: client closed")
|
|
75
|
+
|| error.message === "runtime-unhealthy: runtime_launch_subagent timed out"
|
|
76
|
+
)) {
|
|
77
|
+
return {
|
|
78
|
+
isError: true,
|
|
79
|
+
details: { status: "outcome_unknown" },
|
|
80
|
+
content: [{ type: "text", text: "The launch receipt is unknown. Check subagent_list in this session before retrying. A worker may already be running." }],
|
|
81
|
+
};
|
|
82
|
+
}
|
|
69
83
|
throw error;
|
|
70
84
|
} finally {
|
|
71
85
|
signal?.removeEventListener("abort", cancel);
|
|
@@ -136,7 +136,7 @@ export function writeParkRecord(id, record, options = {}) {
|
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
138
|
/** Read the attempt's park disposition; absent for an ordinary run. */
|
|
139
|
-
export function readParkRecord(id) {
|
|
139
|
+
export function readParkRecord(id, listedMeta) {
|
|
140
140
|
try {
|
|
141
141
|
return parseParkRecord(JSON.parse(readFileSync(parkRecordPath(id), "utf-8")));
|
|
142
142
|
}
|
|
@@ -145,7 +145,7 @@ export function readParkRecord(id) {
|
|
|
145
145
|
return undefined;
|
|
146
146
|
// The volatile run directory may already be reclaimed; the durable
|
|
147
147
|
// completed-attempt record carries the park snapshot taken at finalization.
|
|
148
|
-
return readMeta(id)?.park;
|
|
148
|
+
return (listedMeta ?? readMeta(id))?.park;
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
151
|
/** Merge one phase/reason change into the park disposition. */
|
|
@@ -166,22 +166,31 @@ export function isPendingPark(record) {
|
|
|
166
166
|
* by resume reconciliation; a consumed or cancelled park is not included.
|
|
167
167
|
*/
|
|
168
168
|
export function listPendingParkedRuns(metas = listMetas()) {
|
|
169
|
-
return listParkRecordCandidates(metas)
|
|
170
|
-
const record = meta.park ?? readParkRecord(meta.id);
|
|
171
|
-
return record !== undefined && isPendingPark(record);
|
|
172
|
-
});
|
|
169
|
+
return listParkRecordCandidates(metas, isPendingPark);
|
|
173
170
|
}
|
|
174
|
-
/**
|
|
175
|
-
export function listParkRecordCandidates(metas = listMetas()) {
|
|
171
|
+
/** Read live sidecars before consulting the listed disposition of a reclaimed run. */
|
|
172
|
+
export function listParkRecordCandidates(metas = listMetas(), include) {
|
|
173
|
+
const runs = join(baseDir(), "runs");
|
|
176
174
|
let volatileIds;
|
|
177
175
|
try {
|
|
178
|
-
volatileIds = new Set(readdirSync(
|
|
176
|
+
volatileIds = new Set(readdirSync(runs));
|
|
179
177
|
}
|
|
180
|
-
catch {
|
|
181
|
-
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error.code === "ENOENT")
|
|
180
|
+
volatileIds = new Set();
|
|
181
|
+
}
|
|
182
|
+
const parked = [];
|
|
183
|
+
for (const meta of metas) {
|
|
184
|
+
let record = meta.park;
|
|
185
|
+
if (!volatileIds || volatileIds.has(meta.id)) {
|
|
186
|
+
if (!record && !existsSync(join(runs, meta.id, "park.json")))
|
|
187
|
+
continue;
|
|
188
|
+
record = readParkRecord(meta.id, meta);
|
|
189
|
+
}
|
|
190
|
+
if (record && (!include || include(record)))
|
|
191
|
+
parked.push({ ...meta, park: record });
|
|
182
192
|
}
|
|
183
|
-
return
|
|
184
|
-
|| (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
|
|
193
|
+
return parked;
|
|
185
194
|
}
|
|
186
195
|
/** Read recovery sidecars in batches so a large registry does not block socket replies. */
|
|
187
196
|
export async function* scanParkRecords(metas = listMetas(), include) {
|
|
@@ -190,22 +199,18 @@ export async function* scanParkRecords(metas = listMetas(), include) {
|
|
|
190
199
|
const batchSize = 32;
|
|
191
200
|
for (let offset = 0; offset < metas.length; offset += batchSize) {
|
|
192
201
|
const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
if (record && (!include || include(record)))
|
|
202
|
-
return { meta, record };
|
|
203
|
-
}
|
|
204
|
-
catch (error) {
|
|
205
|
-
if (error.code === "ENOENT" && meta.park) {
|
|
206
|
-
return { meta, record: meta.park };
|
|
202
|
+
let record = meta.park;
|
|
203
|
+
if (!volatileIds || volatileIds.has(meta.id)) {
|
|
204
|
+
try {
|
|
205
|
+
record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (error.code !== "ENOENT")
|
|
209
|
+
return;
|
|
207
210
|
}
|
|
208
211
|
}
|
|
212
|
+
if (record && (!include || include(record)))
|
|
213
|
+
return { meta, record };
|
|
209
214
|
}));
|
|
210
215
|
for (const entry of batch)
|
|
211
216
|
if (entry)
|
|
@@ -495,14 +495,14 @@ export function writeParkRecord(id: string, record: ParkRecord, options: { ifAbs
|
|
|
495
495
|
}
|
|
496
496
|
|
|
497
497
|
/** Read the attempt's park disposition; absent for an ordinary run. */
|
|
498
|
-
export function readParkRecord(id: string): ParkRecord | undefined {
|
|
498
|
+
export function readParkRecord(id: string, listedMeta?: RunMeta): ParkRecord | undefined {
|
|
499
499
|
try {
|
|
500
500
|
return parseParkRecord(JSON.parse(readFileSync(parkRecordPath(id), "utf-8")));
|
|
501
501
|
} catch (error) {
|
|
502
502
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
|
|
503
503
|
// The volatile run directory may already be reclaimed; the durable
|
|
504
504
|
// completed-attempt record carries the park snapshot taken at finalization.
|
|
505
|
-
return readMeta(id)?.park;
|
|
505
|
+
return (listedMeta ?? readMeta(id))?.park;
|
|
506
506
|
}
|
|
507
507
|
}
|
|
508
508
|
|
|
@@ -527,20 +527,29 @@ export function isPendingPark(record: Pick<ParkRecord, "phase">): boolean {
|
|
|
527
527
|
* Runs whose park disposition can still resume. Used by cleanup protection and
|
|
528
528
|
* by resume reconciliation; a consumed or cancelled park is not included.
|
|
529
529
|
*/
|
|
530
|
-
export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas())
|
|
531
|
-
return listParkRecordCandidates(metas)
|
|
532
|
-
const record = meta.park ?? readParkRecord(meta.id);
|
|
533
|
-
return record !== undefined && isPendingPark(record);
|
|
534
|
-
});
|
|
530
|
+
export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas()) {
|
|
531
|
+
return listParkRecordCandidates(metas, isPendingPark);
|
|
535
532
|
}
|
|
536
533
|
|
|
537
|
-
/**
|
|
538
|
-
export function listParkRecordCandidates(
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
534
|
+
/** Read live sidecars before consulting the listed disposition of a reclaimed run. */
|
|
535
|
+
export function listParkRecordCandidates(
|
|
536
|
+
metas: readonly RunMeta[] = listMetas(),
|
|
537
|
+
include?: (record: ParkRecord) => boolean,
|
|
538
|
+
): Array<RunMeta & { park: ParkRecord }> {
|
|
539
|
+
const runs = join(baseDir(), "runs");
|
|
540
|
+
let volatileIds: Set<string> | undefined;
|
|
541
|
+
try { volatileIds = new Set(readdirSync(runs)); }
|
|
542
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") volatileIds = new Set(); }
|
|
543
|
+
const parked: Array<RunMeta & { park: ParkRecord }> = [];
|
|
544
|
+
for (const meta of metas) {
|
|
545
|
+
let record = meta.park;
|
|
546
|
+
if (!volatileIds || volatileIds.has(meta.id)) {
|
|
547
|
+
if (!record && !existsSync(join(runs, meta.id, "park.json"))) continue;
|
|
548
|
+
record = readParkRecord(meta.id, meta);
|
|
549
|
+
}
|
|
550
|
+
if (record && (!include || include(record))) parked.push({ ...meta, park: record });
|
|
551
|
+
}
|
|
552
|
+
return parked;
|
|
544
553
|
}
|
|
545
554
|
|
|
546
555
|
/** Read recovery sidecars in batches so a large registry does not block socket replies. */
|
|
@@ -554,17 +563,15 @@ export async function* scanParkRecords(
|
|
|
554
563
|
const batchSize = 32;
|
|
555
564
|
for (let offset = 0; offset < metas.length; offset += batchSize) {
|
|
556
565
|
const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
|
|
557
|
-
|
|
558
|
-
if (volatileIds
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
} catch (error) {
|
|
564
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT" && meta.park) {
|
|
565
|
-
return { meta, record: meta.park };
|
|
566
|
+
let record = meta.park;
|
|
567
|
+
if (!volatileIds || volatileIds.has(meta.id)) {
|
|
568
|
+
try {
|
|
569
|
+
record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
|
|
570
|
+
} catch (error) {
|
|
571
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
|
|
566
572
|
}
|
|
567
573
|
}
|
|
574
|
+
if (record && (!include || include(record))) return { meta, record };
|
|
568
575
|
}));
|
|
569
576
|
for (const entry of batch) if (entry) yield entry;
|
|
570
577
|
}
|
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 = [
|
|
@@ -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);
|