pi-better-server 0.7.3 → 0.8.1
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/src/runtime/background-tools.ts +146 -6
- package/src/runtime/background.ts +2 -2
- package/src/runtime/catalog.ts +30 -1
- package/src/runtime/ci-recovery.ts +172 -0
- package/src/runtime/domain/assignment-inbox.mjs +4 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +1 -0
- 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/ci-observation.domain.mjs +134 -0
- package/src/runtime/domain/background-service/ci-observation.ts +118 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
- package/src/runtime/domain/background-service/managed-client.ts +6 -2
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
- package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +36 -7
- package/src/runtime/domain/background-service/observed-waits.ts +33 -6
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -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/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/schema.domain.mjs +53 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
- 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/catalog/catalog-schema.d.mts +6 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
- package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
- 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/schema.mjs +53 -1
- package/src/runtime/domain/coordinator/src/store.mjs +3 -3
- package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
- package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
- package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
- package/src/runtime/domain/subagents/cleanup.ts +6 -8
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
- package/src/runtime/domain/subagents/registry.ts +11 -6
- 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/roles/role.supervisor.md +16 -0
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
- package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -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/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/schema.domain.mjs +53 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
- package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
- package/src/runtime/domain/subagents/worker-waits.ts +3 -3
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
- package/src/runtime/domain/subagents/workspace-files.ts +27 -5
- package/src/runtime/queries.ts +17 -3
- package/src/runtime/query-executor.ts +46 -3
- package/src/runtime/query-worker.mjs +6 -1
- package/src/runtime/read-model.ts +14 -5
- package/src/runtime/result-supervision.ts +16 -5
- package/src/runtime/shared-read-diagnosis.ts +29 -0
- package/src/runtime/supervisor-admission.ts +42 -0
- package/src/runtime/supervisor-decisions.ts +60 -0
- package/src/server.ts +9 -8
- package/src/version.ts +1 -1
|
@@ -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
|
|
|
@@ -68,6 +68,42 @@ 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
|
+
];
|
|
71
107
|
const DDL = [
|
|
72
108
|
`CREATE TABLE task_cancellation_authorities (
|
|
73
109
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -289,6 +325,7 @@ const DDL = [
|
|
|
289
325
|
PRIMARY KEY (wait_id, generation)
|
|
290
326
|
)`,
|
|
291
327
|
RESULT_ADMISSION_FENCE,
|
|
328
|
+
...PENDING_CLEANUP_DDL,
|
|
292
329
|
];
|
|
293
330
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
294
331
|
function existingTables(ctx) {
|
|
@@ -359,14 +396,29 @@ function ensureAssignmentCleanupSchema(ctx) {
|
|
|
359
396
|
for (const statement of EXPIRY_INDEXES)
|
|
360
397
|
ctx.db.exec(statement);
|
|
361
398
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
362
|
-
|
|
399
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
400
|
+
if (hasPending())
|
|
363
401
|
return;
|
|
364
402
|
ctx.transaction(() => {
|
|
403
|
+
if (hasPending())
|
|
404
|
+
return;
|
|
365
405
|
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
366
406
|
// Legacy writers leave the nullable provenance unset.
|
|
367
407
|
if (!hasColumn())
|
|
368
408
|
ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
369
409
|
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
410
|
+
for (const statement of PENDING_CLEANUP_DDL)
|
|
411
|
+
ctx.db.exec(statement);
|
|
412
|
+
if (process.platform === "win32") {
|
|
413
|
+
// Earlier Windows writers mistook an unsupported group probe for proof of exit.
|
|
414
|
+
ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
|
|
415
|
+
}
|
|
416
|
+
ctx.db.exec(`INSERT INTO assignment_cleanup_pending
|
|
417
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
418
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
419
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
420
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
421
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
370
422
|
});
|
|
371
423
|
}
|
|
372
424
|
/**
|
|
@@ -72,6 +72,45 @@ 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
|
+
|
|
75
114
|
const DDL: readonly string[] = [
|
|
76
115
|
`CREATE TABLE task_cancellation_authorities (
|
|
77
116
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -293,6 +332,7 @@ const DDL: readonly string[] = [
|
|
|
293
332
|
PRIMARY KEY (wait_id, generation)
|
|
294
333
|
)`,
|
|
295
334
|
RESULT_ADMISSION_FENCE,
|
|
335
|
+
...PENDING_CLEANUP_DDL,
|
|
296
336
|
];
|
|
297
337
|
|
|
298
338
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
@@ -377,12 +417,25 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
377
417
|
function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
|
|
378
418
|
for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
|
|
379
419
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
380
|
-
|
|
420
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
421
|
+
if (hasPending()) return;
|
|
381
422
|
ctx.transaction(() => {
|
|
423
|
+
if (hasPending()) return;
|
|
382
424
|
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
383
425
|
// Legacy writers leave the nullable provenance unset.
|
|
384
426
|
if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
385
427
|
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
428
|
+
for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
|
|
429
|
+
if (process.platform === "win32") {
|
|
430
|
+
// Earlier Windows writers mistook an unsupported group probe for proof of exit.
|
|
431
|
+
ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
|
|
432
|
+
}
|
|
433
|
+
ctx.db.exec(`INSERT 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)`);
|
|
386
439
|
});
|
|
387
440
|
}
|
|
388
441
|
|
|
@@ -118,9 +118,9 @@ export function openStore(options) {
|
|
|
118
118
|
alive();
|
|
119
119
|
return readOperationRecords(ctx, filter);
|
|
120
120
|
},
|
|
121
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
121
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
122
122
|
alive();
|
|
123
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
123
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
124
124
|
},
|
|
125
125
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
126
126
|
alive();
|
|
@@ -140,7 +140,7 @@ export function openStore(options) {
|
|
|
140
140
|
alive();
|
|
141
141
|
return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
|
|
142
142
|
},
|
|
143
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
143
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
144
144
|
readDiscoveryClaim(scope) {
|
|
145
145
|
alive();
|
|
146
146
|
return readClaim(ctx, scope);
|
|
@@ -207,7 +207,7 @@ export interface Store {
|
|
|
207
207
|
* Read up to 256 unfinished cleanup obligations in operation id order.
|
|
208
208
|
* The cursor is exclusive. Start each new sweep without a cursor.
|
|
209
209
|
*/
|
|
210
|
-
listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
|
|
210
|
+
listAssignmentCleanupOperations(limit: number, afterOperationId?: string, hostId?: string): OperationRecord[];
|
|
211
211
|
verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
|
|
212
212
|
/** Running operations currently assigned to this supervising host. */
|
|
213
213
|
listRunningSupervisedBy(hostId: string): OperationRecord[];
|
|
@@ -217,7 +217,7 @@ export interface Store {
|
|
|
217
217
|
|
|
218
218
|
/** The shared discovery leader for this store/supervisor scope, if recorded. */
|
|
219
219
|
readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
|
|
220
|
-
readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
|
|
220
|
+
readDiscoveryState(scope: string, hostId?: string): ReturnType<typeof readDiscoveryState>;
|
|
221
221
|
/**
|
|
222
222
|
* Compare-and-swap a discovery claim. The caller must name the exact claim it
|
|
223
223
|
* observed, or null for none; a stale contender receives null and must not
|
|
@@ -427,9 +427,9 @@ export function openStore(options: StoreOptions): Store {
|
|
|
427
427
|
alive();
|
|
428
428
|
return readOperationRecords(ctx, filter);
|
|
429
429
|
},
|
|
430
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
430
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
431
431
|
alive();
|
|
432
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
432
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
433
433
|
},
|
|
434
434
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
435
435
|
alive();
|
|
@@ -453,7 +453,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
453
453
|
terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
|
|
454
454
|
);
|
|
455
455
|
},
|
|
456
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
456
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
457
457
|
readDiscoveryClaim(scope) {
|
|
458
458
|
alive();
|
|
459
459
|
return readClaim(ctx, scope);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/supervisor-client.mjs. Do not edit directly.
|
|
2
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { createCatalogHostAdapter } from "./catalog-host-admission.domain.mjs";
|
|
4
|
+
import { createAgentSessionSettings } from "./agent-session-settings.domain.mjs";
|
|
5
|
+
import { openSharedCatalog } from "./shared-catalog.domain.mjs";
|
|
6
|
+
import { resolveSelection } from "./catalog-resolver.domain.mjs";
|
|
7
|
+
export async function openSupervisorClient(pi, ctx, signal) {
|
|
8
|
+
const settings = createAgentSessionSettings(pi);
|
|
9
|
+
settings.restore(ctx);
|
|
10
|
+
// Pi loads extensions independently. Bind this request to its own live host context.
|
|
11
|
+
const host = createCatalogHostAdapter();
|
|
12
|
+
host.noteCatalogHostContext(ctx, () => settings.snapshot());
|
|
13
|
+
let catalog;
|
|
14
|
+
try {
|
|
15
|
+
catalog = await openSharedCatalog(ctx.cwd, getAgentDir(), ctx.sessionManager.getSessionId(), undefined, signal, host.catalogHostAuthority);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
host.closeCatalogHost();
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
close() { catalog.close(); host.closeCatalogHost(); },
|
|
23
|
+
review: catalog.review,
|
|
24
|
+
decision: catalog.decision,
|
|
25
|
+
sharedReadDiagnosis: catalog.sharedReadDiagnosis,
|
|
26
|
+
async role() {
|
|
27
|
+
settings.restore(ctx);
|
|
28
|
+
const snapshot = await catalog.get(settings.snapshot());
|
|
29
|
+
const selected = resolveSelection(snapshot, { roleId: "role.supervisor" });
|
|
30
|
+
if (!selected.launchable || !selected.effective)
|
|
31
|
+
return;
|
|
32
|
+
const { instructions, model, effort } = selected.effective;
|
|
33
|
+
return { revision: snapshot.revision, instructions, model: model.value, effort: effort.value };
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -2157,10 +2157,9 @@ export async function reconcileParkedWaits(service, outerOptions) {
|
|
|
2157
2157
|
// Consumed waits cannot resume, but a missed exit observer may have left
|
|
2158
2158
|
// their published writer claim behind. Reconcile that exact claim once.
|
|
2159
2159
|
const candidates = [];
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
continue;
|
|
2160
|
+
const needsReconciliation = (record) => isPendingPark(record) || (record.phase === "consumed"
|
|
2161
|
+
&& !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
|
|
2162
|
+
for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
|
|
2164
2163
|
candidates.push(parkedEntry(meta, record));
|
|
2165
2164
|
}
|
|
2166
2165
|
// Release earlier writers before admitting later waits in the conversation.
|
|
@@ -2719,9 +2719,9 @@ export async function reconcileParkedWaits(
|
|
|
2719
2719
|
// Consumed waits cannot resume, but a missed exit observer may have left
|
|
2720
2720
|
// their published writer claim behind. Reconcile that exact claim once.
|
|
2721
2721
|
const candidates: ParkedWait[] = [];
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2722
|
+
const needsReconciliation = (record: ParkRecord) => isPendingPark(record) || (record.phase === "consumed"
|
|
2723
|
+
&& !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
|
|
2724
|
+
for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
|
|
2725
2725
|
candidates.push(parkedEntry(meta, record));
|
|
2726
2726
|
}
|
|
2727
2727
|
// Release earlier writers before admitting later waits in the conversation.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// A private content store lets retained checkouts share identical Git objects and files.
|
|
3
3
|
// Source files are never hardlinked into storage. Restoring a file makes an independent copy.
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
-
import { chmodSync, closeSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
|
|
5
|
+
import { chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, lchmodSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
7
|
function fileHash(path, buffer) {
|
|
8
8
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
@@ -71,7 +71,7 @@ export function snapshotTree(root, store, omit = new Set()) {
|
|
|
71
71
|
walk("");
|
|
72
72
|
return entries;
|
|
73
73
|
}
|
|
74
|
-
|
|
74
|
+
function materializeTree(root, entries, copyRegularFile) {
|
|
75
75
|
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
76
76
|
const directories = new Set(["."]);
|
|
77
77
|
for (const entry of entries) {
|
|
@@ -84,11 +84,12 @@ export function restoreTree(root, store, entries) {
|
|
|
84
84
|
mkdirSync(dest);
|
|
85
85
|
directories.add(entry.name);
|
|
86
86
|
}
|
|
87
|
-
else if (entry.type === "symlink")
|
|
87
|
+
else if (entry.type === "symlink") {
|
|
88
88
|
symlinkSync(entry.target, dest);
|
|
89
|
+
lchmodSync?.(dest, entry.mode);
|
|
90
|
+
}
|
|
89
91
|
else {
|
|
90
|
-
|
|
91
|
-
chmodSync(dest, entry.mode);
|
|
92
|
+
copyRegularFile(entry, dest);
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
for (const entry of entries.slice().reverse()) {
|
|
@@ -96,6 +97,19 @@ export function restoreTree(root, store, entries) {
|
|
|
96
97
|
chmodSync(join(root, entry.name), entry.mode);
|
|
97
98
|
}
|
|
98
99
|
}
|
|
100
|
+
export function restoreTree(root, store, entries) {
|
|
101
|
+
materializeTree(root, entries, (entry, dest) => {
|
|
102
|
+
copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
|
|
103
|
+
chmodSync(dest, entry.mode);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
export function copyTree(source, dest, entries) {
|
|
107
|
+
const rootMode = lstatSync(source).mode & 0o7777;
|
|
108
|
+
materializeTree(dest, entries, (entry, target) => {
|
|
109
|
+
cpSync(join(source, entry.name), target, { verbatimSymlinks: true, force: false, errorOnExist: true });
|
|
110
|
+
});
|
|
111
|
+
chmodSync(dest, rootMode);
|
|
112
|
+
}
|
|
99
113
|
export function verifyTree(root, entries, omit) {
|
|
100
114
|
if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
|
|
101
115
|
throw new Error("Workspace contents changed or could not be recovered at " + root);
|
|
@@ -6,7 +6,9 @@ import {
|
|
|
6
6
|
closeSync,
|
|
7
7
|
constants,
|
|
8
8
|
copyFileSync,
|
|
9
|
+
cpSync,
|
|
9
10
|
existsSync,
|
|
11
|
+
lchmodSync,
|
|
10
12
|
lstatSync,
|
|
11
13
|
mkdirSync,
|
|
12
14
|
openSync,
|
|
@@ -84,7 +86,11 @@ export function snapshotTree(root: string, store?: string, omit: ReadonlySet<str
|
|
|
84
86
|
return entries;
|
|
85
87
|
}
|
|
86
88
|
|
|
87
|
-
|
|
89
|
+
function materializeTree(
|
|
90
|
+
root: string,
|
|
91
|
+
entries: SavedEntry[],
|
|
92
|
+
copyRegularFile: (entry: Extract<SavedEntry, { type: "file" }>, dest: string) => void,
|
|
93
|
+
): void {
|
|
88
94
|
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
89
95
|
const directories = new Set(["."]);
|
|
90
96
|
for (const entry of entries) {
|
|
@@ -96,10 +102,11 @@ export function restoreTree(root: string, store: string, entries: SavedEntry[]):
|
|
|
96
102
|
if (entry.type === "directory") {
|
|
97
103
|
mkdirSync(dest);
|
|
98
104
|
directories.add(entry.name);
|
|
99
|
-
} else if (entry.type === "symlink")
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
105
|
+
} else if (entry.type === "symlink") {
|
|
106
|
+
symlinkSync(entry.target, dest);
|
|
107
|
+
lchmodSync?.(dest, entry.mode);
|
|
108
|
+
} else {
|
|
109
|
+
copyRegularFile(entry, dest);
|
|
103
110
|
}
|
|
104
111
|
}
|
|
105
112
|
for (const entry of entries.slice().reverse()) {
|
|
@@ -107,6 +114,21 @@ export function restoreTree(root: string, store: string, entries: SavedEntry[]):
|
|
|
107
114
|
}
|
|
108
115
|
}
|
|
109
116
|
|
|
117
|
+
export function restoreTree(root: string, store: string, entries: SavedEntry[]): void {
|
|
118
|
+
materializeTree(root, entries, (entry, dest) => {
|
|
119
|
+
copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
|
|
120
|
+
chmodSync(dest, entry.mode);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function copyTree(source: string, dest: string, entries: SavedEntry[]): void {
|
|
125
|
+
const rootMode = lstatSync(source).mode & 0o7777;
|
|
126
|
+
materializeTree(dest, entries, (entry, target) => {
|
|
127
|
+
cpSync(join(source, entry.name), target, { verbatimSymlinks: true, force: false, errorOnExist: true });
|
|
128
|
+
});
|
|
129
|
+
chmodSync(dest, rootMode);
|
|
130
|
+
}
|
|
131
|
+
|
|
110
132
|
export function verifyTree(root: string, entries: SavedEntry[], omit?: ReadonlySet<string>): void {
|
|
111
133
|
if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
|
|
112
134
|
throw new Error("Workspace contents changed or could not be recovered at " + root);
|
package/src/runtime/queries.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Socket } from "node:net";
|
|
2
|
-
import type { WorkReadModel, WorkScope } from "./read-model.ts";
|
|
2
|
+
import type { WorkReadModel, WorkScope, WorkSnapshot } from "./read-model.ts";
|
|
3
3
|
|
|
4
4
|
const eventEncodings = new WeakMap<object, string>();
|
|
5
5
|
const snapshotEncodings = new WeakMap<object, string>();
|
|
@@ -8,6 +8,10 @@ export function snapshotJSON(snapshot: object): string {
|
|
|
8
8
|
if (json === undefined) { json = JSON.stringify(snapshot); snapshotEncodings.set(snapshot, json); }
|
|
9
9
|
return json;
|
|
10
10
|
}
|
|
11
|
+
// The global sequence may advance while a session's Background rows and deadlines stay unchanged.
|
|
12
|
+
function backgroundNotificationKey(snapshot: WorkSnapshot) {
|
|
13
|
+
return JSON.stringify([snapshot.scopeRevision, snapshot.status, snapshot.reason, snapshot.nextDeadline]);
|
|
14
|
+
}
|
|
11
15
|
export const queryEncodingMetrics = { serializations: 0, frames: 0, bytes: 0 };
|
|
12
16
|
|
|
13
17
|
export function workScope(input: unknown): WorkScope {
|
|
@@ -35,6 +39,7 @@ export class WorkQueries {
|
|
|
35
39
|
private dispose?: () => void;
|
|
36
40
|
private paused = false;
|
|
37
41
|
private lastSnapshotSeq?: number;
|
|
42
|
+
private lastBackgroundKey?: string;
|
|
38
43
|
private model: WorkReadModel;
|
|
39
44
|
private socket: Socket;
|
|
40
45
|
private maxQueuedBytes: number;
|
|
@@ -51,8 +56,10 @@ export class WorkQueries {
|
|
|
51
56
|
}
|
|
52
57
|
private event(event: unknown) {
|
|
53
58
|
if (this.socket.destroyed || this.paused) return;
|
|
54
|
-
if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
|
|
55
59
|
const snapshot = (event as any)?.type === "runtime_snapshot" ? (event as any).snapshot : undefined;
|
|
60
|
+
const key = snapshot && this.lastBackgroundKey !== undefined ? backgroundNotificationKey(snapshot) : undefined;
|
|
61
|
+
if (key !== undefined && key === this.lastBackgroundKey) return;
|
|
62
|
+
if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
|
|
56
63
|
let line: string;
|
|
57
64
|
if (snapshot) {
|
|
58
65
|
let prefix = eventEncodings.get(snapshot);
|
|
@@ -68,7 +75,10 @@ export class WorkQueries {
|
|
|
68
75
|
this.socket.write(JSON.stringify({ type: "event", event: { type: "resync_required", reason: "snapshot-too-large: narrow the scope or limit" } }) + "\n");
|
|
69
76
|
return;
|
|
70
77
|
}
|
|
71
|
-
if (snapshot)
|
|
78
|
+
if (snapshot) {
|
|
79
|
+
this.lastSnapshotSeq = snapshot.seq;
|
|
80
|
+
this.lastBackgroundKey = key;
|
|
81
|
+
}
|
|
72
82
|
this.socket.write(line);
|
|
73
83
|
queryEncodingMetrics.frames++; queryEncodingMetrics.bytes += Buffer.byteLength(line);
|
|
74
84
|
}
|
|
@@ -76,11 +86,15 @@ export class WorkQueries {
|
|
|
76
86
|
if (command.type === "runtime_unsubscribe") { this.close(); return { unsubscribed: true }; }
|
|
77
87
|
if (command.type === "runtime_get_metrics") return { ...this.model.metrics };
|
|
78
88
|
const scope = workScope(command.scope);
|
|
89
|
+
// An explicit read must see new commits. Publication callbacks already observe
|
|
90
|
+
// the reconciled state and must not poll the inbox again for every subscriber.
|
|
91
|
+
if (scope.background && !scope.backgroundHistory) this.model.prepareBackgroundQuery();
|
|
79
92
|
const snapshot = this.model.snapshot(scope);
|
|
80
93
|
if (Buffer.byteLength(snapshotJSON(snapshot)) > 4 * 1024 * 1024 - 1024) throw new Error("state-degraded: snapshot exceeds the 4 MiB frame allowance; narrow the scope or limit");
|
|
81
94
|
if (command.type === "runtime_subscribe") {
|
|
82
95
|
this.close();
|
|
83
96
|
this.lastSnapshotSeq = snapshot.seq;
|
|
97
|
+
this.lastBackgroundKey = scope.background && !scope.backgroundHistory ? backgroundNotificationKey(snapshot) : undefined;
|
|
84
98
|
this.dispose = this.model.onChange(() => {
|
|
85
99
|
try {
|
|
86
100
|
this.event({ type: "runtime_snapshot", snapshot: this.model.snapshot({ ...scope, cursor: undefined }) });
|
|
@@ -8,6 +8,8 @@ import { executionPhases, inventoryPhases } from "./read-watchdog-probe.ts";
|
|
|
8
8
|
import { notifyWorkBudget } from "./work-budget.ts";
|
|
9
9
|
import { HostSourceWatches } from "./source-watch.ts";
|
|
10
10
|
|
|
11
|
+
const INBOX_DIAGNOSTICS_WAIT_MS = 100;
|
|
12
|
+
|
|
11
13
|
export interface EncodedRead { json: string }
|
|
12
14
|
interface Waiter { connection: number; expiresAt: number; deadline: ReturnType<typeof setTimeout>; resolve(value: EncodedRead): void; reject(error: Error): void }
|
|
13
15
|
interface Query {
|
|
@@ -16,7 +18,7 @@ interface Query {
|
|
|
16
18
|
}
|
|
17
19
|
export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
|
|
18
20
|
interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
|
|
19
|
-
interface WorkerMetrics { sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
|
|
21
|
+
interface WorkerMetrics { background?: Record<string, unknown>; sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
|
|
20
22
|
export interface QueryExecutorOptions {
|
|
21
23
|
queryCacheDiagnostics?: boolean;
|
|
22
24
|
capacity?: number; timeoutMs?: number; maxConnections?: number; watchdogMs?: number;
|
|
@@ -54,6 +56,8 @@ export class WorkQueryExecutor {
|
|
|
54
56
|
private heartbeat!: BigInt64Array;
|
|
55
57
|
private probe?: Int32Array;
|
|
56
58
|
private workerMetrics: WorkerMetrics = {};
|
|
59
|
+
private inboxSample?: WorkReadModel["inboxDiagnostics"];
|
|
60
|
+
private inboxRequest?: { ready: Promise<boolean>; finish(fresh: boolean, error?: string): void };
|
|
57
61
|
private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
|
|
58
62
|
status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
|
|
59
63
|
};
|
|
@@ -189,6 +193,7 @@ export class WorkQueryExecutor {
|
|
|
189
193
|
this.workerGeneration++;
|
|
190
194
|
this.internalRecoveryDemand = false;
|
|
191
195
|
this.exited = false; this.failure = undefined; this.termination = undefined;
|
|
196
|
+
this.inboxSample = undefined;
|
|
192
197
|
this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
|
|
193
198
|
this.lastResponse = performance.now();
|
|
194
199
|
this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
|
|
@@ -232,12 +237,21 @@ export class WorkQueryExecutor {
|
|
|
232
237
|
return JSON.parse(result.json);
|
|
233
238
|
}
|
|
234
239
|
|
|
240
|
+
sharedReadHealth() {
|
|
241
|
+
return { state: this.observation().status, generation: this.workerGeneration };
|
|
242
|
+
}
|
|
243
|
+
|
|
235
244
|
observation() {
|
|
236
245
|
return this.failure ? { ...this.lastObservation, status: "degraded" as const, reason: this.failure.message } : this.lastObservation;
|
|
237
246
|
}
|
|
238
247
|
|
|
239
248
|
metrics() {
|
|
240
|
-
|
|
249
|
+
const unavailable = { available: false, received: null, applied: null, pending: null };
|
|
250
|
+
return { ...this.workerMetrics,
|
|
251
|
+
assignments: this.inboxSample?.assignments ?? unavailable,
|
|
252
|
+
background: { ...this.workerMetrics.background, changes: this.inboxSample?.backgroundChanges ?? unavailable },
|
|
253
|
+
inboxDiagnosticsObservedAt: this.inboxSample?.observedAt ?? null,
|
|
254
|
+
sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
|
|
241
255
|
clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
|
|
242
256
|
cancelled: this.cancelled, timeouts: this.timeouts, queueTimeouts: this.queueTimeouts, callerTimeouts: this.callerTimeouts,
|
|
243
257
|
capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
|
|
@@ -247,9 +261,30 @@ export class WorkQueryExecutor {
|
|
|
247
261
|
status: this.failure ? "degraded" : "ready" } };
|
|
248
262
|
}
|
|
249
263
|
|
|
264
|
+
private sampleInbox(): Promise<boolean> {
|
|
265
|
+
if (this.failure || this.closed) return Promise.resolve(false);
|
|
266
|
+
if (this.inboxRequest) return this.inboxRequest.ready;
|
|
267
|
+
|
|
268
|
+
let finish!: (fresh: boolean, error?: string) => void;
|
|
269
|
+
const ready = new Promise<boolean>((resolve, reject) => {
|
|
270
|
+
// Return cached diagnostics on timeout, but keep the worker request single-flight until its reply.
|
|
271
|
+
const timer = setTimeout(() => resolve(false), INBOX_DIAGNOSTICS_WAIT_MS);
|
|
272
|
+
finish = (fresh, error) => {
|
|
273
|
+
clearTimeout(timer);
|
|
274
|
+
if (error) reject(new Error(error));
|
|
275
|
+
else resolve(fresh);
|
|
276
|
+
};
|
|
277
|
+
});
|
|
278
|
+
this.inboxRequest = { ready, finish };
|
|
279
|
+
this.worker.postMessage({ type: "inbox-diagnostics" });
|
|
280
|
+
return ready;
|
|
281
|
+
}
|
|
282
|
+
|
|
250
283
|
private request(connection: number, input: Record<string, unknown>): Promise<EncodedRead> {
|
|
251
284
|
if (connection !== 0 && !this.streams.has(connection)) return Promise.reject(new Error("runtime-unavailable: client disconnected"));
|
|
252
|
-
if (input.type === "runtime_get_metrics")
|
|
285
|
+
if (input.type === "runtime_get_metrics") {
|
|
286
|
+
return this.sampleInbox().then(fresh => ({ json: JSON.stringify({ ...this.metrics(), inboxDiagnosticsFresh: fresh }) }));
|
|
287
|
+
}
|
|
253
288
|
if (this.failure) {
|
|
254
289
|
if (connection === 0) this.internalRecoveryDemand = true;
|
|
255
290
|
this.scheduleRecovery(); return Promise.reject(this.failure);
|
|
@@ -324,6 +359,12 @@ export class WorkQueryExecutor {
|
|
|
324
359
|
if (message.id === this.active?.id) { this.active = undefined; this.pump(); }
|
|
325
360
|
return;
|
|
326
361
|
}
|
|
362
|
+
if (message.type === "inbox-diagnostics") {
|
|
363
|
+
if (message.sample) this.inboxSample = message.sample;
|
|
364
|
+
this.inboxRequest?.finish(Boolean(message.sample), message.error);
|
|
365
|
+
this.inboxRequest = undefined;
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
327
368
|
if (message.metrics) this.workerMetrics = message.metrics;
|
|
328
369
|
if (message.observation) this.lastObservation = message.observation;
|
|
329
370
|
if (message.type === "terminal-logs") {
|
|
@@ -406,6 +447,8 @@ export class WorkQueryExecutor {
|
|
|
406
447
|
if ([...this.queue, ...(this.active ? [this.active] : [])].some(query =>
|
|
407
448
|
[...query.waiters].some(waiter => waiter.connection === 0))) this.internalRecoveryDemand = true;
|
|
408
449
|
this.failure = error; this.lag.disable();
|
|
450
|
+
this.inboxRequest?.finish(false);
|
|
451
|
+
this.inboxRequest = undefined;
|
|
409
452
|
for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) this.finish(query, error);
|
|
410
453
|
this.queue = []; this.active = undefined;
|
|
411
454
|
for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
|