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,6 +1,5 @@
|
|
|
1
1
|
// Generated canonical coordinator. Do not edit directly.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { bumpChangeRevision } from "./discovery.mjs";
|
|
4
3
|
import { StoreError } from "./errors.mjs";
|
|
5
4
|
import { columnText, getRow, getRows, run } from "./sqlite.mjs";
|
|
6
5
|
import { requireWait, readPins } from "./rows.mjs";
|
|
@@ -108,7 +107,6 @@ export function recordAssignmentOutcome(ctx, input) {
|
|
|
108
107
|
for (const e of retained)
|
|
109
108
|
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);
|
|
110
109
|
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);
|
|
111
|
-
bumpChangeRevision(ctx);
|
|
112
110
|
return record;
|
|
113
111
|
});
|
|
114
112
|
}
|
|
@@ -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);
|
|
@@ -33,13 +33,15 @@ export function readDiscoveryClaim(ctx, scope) {
|
|
|
33
33
|
return readClaim(ctx, requireId("scope", scope));
|
|
34
34
|
}
|
|
35
35
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
36
|
-
export function readDiscoveryState(ctx, scope) {
|
|
36
|
+
export function readDiscoveryState(ctx, scope, hostId) {
|
|
37
37
|
scope = requireId("scope", scope);
|
|
38
38
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
39
39
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
40
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
41
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
42
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
|
|
43
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
44
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
43
45
|
}
|
|
44
46
|
export function tryClaimDiscovery(ctx, input) {
|
|
45
47
|
const scope = requireId("scope", input.scope);
|
|
@@ -312,24 +312,17 @@ export function listOperations(ctx, filter = {}) {
|
|
|
312
312
|
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)
|
|
313
313
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
314
314
|
}
|
|
315
|
-
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
|
|
315
|
+
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
|
|
316
316
|
const requested = requireCounter("limit", limit);
|
|
317
317
|
if (requested === 0)
|
|
318
318
|
throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
319
319
|
const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
|
|
320
|
-
|
|
320
|
+
const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
|
|
321
321
|
return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
|
|
322
322
|
WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
|
|
323
|
-
FROM operations op
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
|
|
327
|
-
AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
|
|
328
|
-
OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
|
|
329
|
-
AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
|
|
330
|
-
AND e.summary LIKE '%groupCleanup=unproven%'))
|
|
331
|
-
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
|
|
332
|
-
ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
323
|
+
FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
324
|
+
WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
|
|
325
|
+
ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
333
326
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
334
327
|
}
|
|
335
328
|
/** Running operations assigned to one supervising host, using the phase/host index. */
|
|
@@ -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);
|
|
@@ -67,6 +67,48 @@ const EXPIRY_INDEXES = [
|
|
|
67
67
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
68
68
|
ON operations (operation_id, assignment_attempt_id)
|
|
69
69
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
70
|
+
// Terminal evidence is written before the operation's terminal revision in the same transaction.
|
|
71
|
+
function needsAssignmentCleanup(row) {
|
|
72
|
+
return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
|
|
73
|
+
SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
|
|
74
|
+
AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
|
|
75
|
+
AND e.summary LIKE '%groupCleanup=unproven%'))`;
|
|
76
|
+
}
|
|
77
|
+
const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
|
|
78
|
+
FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
|
|
79
|
+
WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
|
|
80
|
+
// Triggers also cover older processes that still have an open coordinator connection.
|
|
81
|
+
const PENDING_CLEANUP_DDL = [
|
|
82
|
+
`CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
|
|
83
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
84
|
+
supervision_host_id TEXT
|
|
85
|
+
) WITHOUT ROWID`,
|
|
86
|
+
`CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
|
|
87
|
+
`CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
|
|
88
|
+
`CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
|
|
89
|
+
WHERE assignment_attempt_id IS NOT NULL`,
|
|
90
|
+
`CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
|
|
91
|
+
INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
|
|
92
|
+
END`,
|
|
93
|
+
`CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
|
|
94
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
|
|
95
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
|
|
96
|
+
END`,
|
|
97
|
+
`CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
|
|
98
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
|
|
99
|
+
UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
|
|
100
|
+
END`,
|
|
101
|
+
`CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
|
|
102
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
|
|
103
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
104
|
+
END`,
|
|
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`;
|
|
70
112
|
const DDL = [
|
|
71
113
|
`CREATE TABLE task_cancellation_authorities (
|
|
72
114
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -288,6 +330,7 @@ const DDL = [
|
|
|
288
330
|
PRIMARY KEY (wait_id, generation)
|
|
289
331
|
)`,
|
|
290
332
|
RESULT_ADMISSION_FENCE,
|
|
333
|
+
...PENDING_CLEANUP_DDL,
|
|
291
334
|
];
|
|
292
335
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
293
336
|
function existingTables(ctx) {
|
|
@@ -307,6 +350,8 @@ export function ensureSchema(ctx) {
|
|
|
307
350
|
ctx.transaction(() => {
|
|
308
351
|
for (const statement of [...DDL, ...EXPIRY_INDEXES])
|
|
309
352
|
ctx.db.exec(statement);
|
|
353
|
+
if (process.platform === "win32")
|
|
354
|
+
ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
|
|
310
355
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
311
356
|
});
|
|
312
357
|
return;
|
|
@@ -358,14 +403,38 @@ function ensureAssignmentCleanupSchema(ctx) {
|
|
|
358
403
|
for (const statement of EXPIRY_INDEXES)
|
|
359
404
|
ctx.db.exec(statement);
|
|
360
405
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
361
|
-
|
|
406
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
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())
|
|
362
410
|
return;
|
|
363
411
|
ctx.transaction(() => {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
if (!
|
|
367
|
-
|
|
368
|
-
|
|
412
|
+
const createQueue = !hasPending();
|
|
413
|
+
const installGuard = needsWindowsGuard();
|
|
414
|
+
if (!createQueue && !installGuard)
|
|
415
|
+
return;
|
|
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))`);
|
|
431
|
+
}
|
|
432
|
+
ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
|
|
433
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
434
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
435
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
436
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
437
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
369
438
|
});
|
|
370
439
|
}
|
|
371
440
|
/**
|
|
@@ -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); },
|
|
@@ -117,16 +120,16 @@ export function openStore(options) {
|
|
|
117
120
|
alive();
|
|
118
121
|
return readOperationRecords(ctx, filter);
|
|
119
122
|
},
|
|
120
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
123
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
121
124
|
alive();
|
|
122
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
125
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
123
126
|
},
|
|
124
127
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
125
128
|
alive();
|
|
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;
|
|
@@ -139,7 +142,7 @@ export function openStore(options) {
|
|
|
139
142
|
alive();
|
|
140
143
|
return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
|
|
141
144
|
},
|
|
142
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
145
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
143
146
|
readDiscoveryClaim(scope) {
|
|
144
147
|
alive();
|
|
145
148
|
return readClaim(ctx, scope);
|
|
@@ -768,24 +768,21 @@ export function enforceRegistrySizeCapOnce(options = {}) {
|
|
|
768
768
|
};
|
|
769
769
|
const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
|
|
770
770
|
const removed = [];
|
|
771
|
-
let
|
|
771
|
+
let reclaimedBytes = 0;
|
|
772
772
|
for (const id of plan.remove) {
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
retainedBytes += bytesById.get(id) ?? 0;
|
|
773
|
+
if (removeSizeCappedRun(id, scope, errors) !== "removed")
|
|
774
|
+
continue;
|
|
775
|
+
removed.push(id);
|
|
776
|
+
reclaimedBytes += bytesById.get(id) ?? 0;
|
|
778
777
|
}
|
|
779
|
-
|
|
780
|
-
// the shortfall it reports stay honest.
|
|
781
|
-
const keptBytes = plan.keptBytes + retainedBytes;
|
|
778
|
+
const keptBytes = totalBytes - reclaimedBytes;
|
|
782
779
|
try {
|
|
783
780
|
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
784
781
|
}
|
|
785
782
|
catch (err) {
|
|
786
783
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
787
784
|
}
|
|
788
|
-
return {
|
|
785
|
+
return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
|
|
789
786
|
}
|
|
790
787
|
/**
|
|
791
788
|
* Remove one planned size-cap candidate, serialized with its conversation.
|
|
@@ -969,15 +969,13 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
|
|
|
969
969
|
};
|
|
970
970
|
const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
|
|
971
971
|
const removed: string[] = [];
|
|
972
|
-
let
|
|
972
|
+
let reclaimedBytes = 0;
|
|
973
973
|
for (const id of plan.remove) {
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
974
|
+
if (removeSizeCappedRun(id, scope, errors) !== "removed") continue;
|
|
975
|
+
removed.push(id);
|
|
976
|
+
reclaimedBytes += bytesById.get(id) ?? 0;
|
|
977
977
|
}
|
|
978
|
-
|
|
979
|
-
// the shortfall it reports stay honest.
|
|
980
|
-
const keptBytes = plan.keptBytes + retainedBytes;
|
|
978
|
+
const keptBytes = totalBytes - reclaimedBytes;
|
|
981
979
|
|
|
982
980
|
try {
|
|
983
981
|
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
@@ -985,7 +983,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
|
|
|
985
983
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
986
984
|
}
|
|
987
985
|
|
|
988
|
-
return {
|
|
986
|
+
return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
|
|
989
987
|
}
|
|
990
988
|
|
|
991
989
|
/**
|
|
@@ -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,44 +166,51 @@ 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
|
-
export async function* scanParkRecords(metas = listMetas()) {
|
|
196
|
+
export async function* scanParkRecords(metas = listMetas(), include) {
|
|
188
197
|
const runs = join(baseDir(), "runs");
|
|
189
|
-
const volatileIds =
|
|
198
|
+
const volatileIds = await readdir(runs).then(ids => new Set(ids), (error) => error.code === "ENOENT" ? new Set() : undefined);
|
|
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 (error.code === "ENOENT" && meta.park) {
|
|
202
|
-
const record = readMeta(meta.id)?.park;
|
|
203
|
-
if (record)
|
|
204
|
-
return { meta, record };
|
|
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;
|
|
205
210
|
}
|
|
206
211
|
}
|
|
212
|
+
if (record && (!include || include(record)))
|
|
213
|
+
return { meta, record };
|
|
207
214
|
}));
|
|
208
215
|
for (const entry of batch)
|
|
209
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,39 +527,51 @@ 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. */
|
|
547
|
-
export async function* scanParkRecords(
|
|
556
|
+
export async function* scanParkRecords(
|
|
557
|
+
metas: readonly RunMeta[] = listMetas(),
|
|
558
|
+
include?: (record: ParkRecord) => boolean,
|
|
559
|
+
): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
|
|
548
560
|
const runs = join(baseDir(), "runs");
|
|
549
|
-
const volatileIds =
|
|
561
|
+
const volatileIds = await readdir(runs).then(ids => new Set(ids),
|
|
562
|
+
(error: NodeJS.ErrnoException) => error.code === "ENOENT" ? new Set<string>() : undefined);
|
|
550
563
|
const batchSize = 32;
|
|
551
564
|
for (let offset = 0; offset < metas.length; offset += batchSize) {
|
|
552
565
|
const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
const record = readMeta(meta.id)?.park;
|
|
560
|
-
if (record) return { meta, record };
|
|
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;
|
|
561
572
|
}
|
|
562
573
|
}
|
|
574
|
+
if (record && (!include || include(record))) return { meta, record };
|
|
563
575
|
}));
|
|
564
576
|
for (const entry of batch) if (entry) yield entry;
|
|
565
577
|
}
|