pi-better-background-tasks 0.21.4 → 0.21.5
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/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/work-client.mjs +43 -14
- package/src/observed-waits.ts +3 -2
- package/src/registry.ts +65 -5
- package/src/shared-navigator.ts +2 -2
- package/src/shared-work-client.mjs +43 -14
package/package.json
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"f7fc76580596e35cfcba5dd98d62c81d4b29ae92eb247d1a54c56ee76e745397"},"sha256":"27de1234e8628fc61063f6fc160befadb0d157f18cb0d182ce6c06f0155825be"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"30608dc6d48179221e6d725228ef015d4ba9f57ba2d0ba949bd16f451157ae4b"},"sha256":"87f4407983446fae701ad4fef1ecd95597ba1950b114b2bc1ce45e6c0c616216"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"76f10f923bfe26156b39585bec8a4826ae62dc793bd16fee6322584ab9eb72e3"},"sha256":"b772d4fca8849e79eaea41868ad602b36daa6087ce1a9bb30d036bb44c276129"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"e0f9da740f48ea7459380f1979f318ae4748479fec3315b2bdb41dc31e4e65ef"},"sha256":"2f15804cf057b6ce3644689c2e884ded6245dd15fd413fc79af92eebb930aa27"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { connect } from "node:net";
|
|
3
4
|
import { performance } from "node:perf_hooks";
|
|
4
5
|
import { setTimeout as delay } from "node:timers/promises";
|
|
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
|
|
|
13
14
|
return file ? existsSync(file) : Boolean(session.getLeafId?.());
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
function unknownLaunchReceipt(cause) {
|
|
18
|
+
return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
|
|
19
|
+
}
|
|
20
|
+
|
|
16
21
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
17
22
|
export class WorkClient {
|
|
23
|
+
lastSubscriptionTrace;
|
|
18
24
|
socket;
|
|
19
25
|
snapshot;
|
|
20
26
|
pending = new Map();
|
|
@@ -29,6 +35,7 @@ export class WorkClient {
|
|
|
29
35
|
recoveryAgain = false;
|
|
30
36
|
recoveryDelay = 100;
|
|
31
37
|
scopeGeneration = 0;
|
|
38
|
+
snapshotGeneration = 0;
|
|
32
39
|
|
|
33
40
|
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
34
41
|
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
@@ -44,7 +51,10 @@ export class WorkClient {
|
|
|
44
51
|
if (message.type === "event") {
|
|
45
52
|
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
46
53
|
if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
|
|
47
|
-
else if (message.event.type === "runtime_snapshot")
|
|
54
|
+
else if (message.event.type === "runtime_snapshot") {
|
|
55
|
+
const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
|
|
56
|
+
this.accept(message.event.snapshot, message.event.previousSeq, generation);
|
|
57
|
+
}
|
|
48
58
|
} else {
|
|
49
59
|
const request = this.pending.get(message.id);
|
|
50
60
|
if (!request) continue;
|
|
@@ -64,10 +74,28 @@ export class WorkClient {
|
|
|
64
74
|
request(type, params = {}) {
|
|
65
75
|
if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
|
|
66
76
|
if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
|
|
67
|
-
const
|
|
77
|
+
const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
|
|
78
|
+
if (trace) this.lastSubscriptionTrace = trace;
|
|
79
|
+
const id = trace?.id ?? `work-${++this.sequence}`;
|
|
68
80
|
return new Promise((resolve, reject) => {
|
|
69
|
-
const
|
|
70
|
-
|
|
81
|
+
const rejectPending = type === "runtime_launch_subagent" ? error => reject(unknownLaunchReceipt(error)) : reject;
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
this.pending.delete(id);
|
|
84
|
+
if (trace) trace.timedOutAt = Date.now();
|
|
85
|
+
rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
|
|
86
|
+
}, 5000);
|
|
87
|
+
this.pending.set(id, { resolve: value => {
|
|
88
|
+
if (trace) trace.receivedAt = Date.now();
|
|
89
|
+
// Apply subscription receipts in wire order, including events in the same socket chunk.
|
|
90
|
+
try {
|
|
91
|
+
if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
|
|
92
|
+
this.accept(value, undefined, params.subscriptionGeneration);
|
|
93
|
+
resolve(value);
|
|
94
|
+
} catch (error) { reject(error); }
|
|
95
|
+
}, reject: error => {
|
|
96
|
+
if (trace) trace.receivedAt = Date.now();
|
|
97
|
+
reject(error);
|
|
98
|
+
}, rejectPending, timer });
|
|
71
99
|
this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
|
|
72
100
|
});
|
|
73
101
|
}
|
|
@@ -78,17 +106,20 @@ export class WorkClient {
|
|
|
78
106
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
79
107
|
this.notify();
|
|
80
108
|
}
|
|
81
|
-
accept(snapshot, previousSeq) {
|
|
82
|
-
if (this.
|
|
109
|
+
accept(snapshot, previousSeq, generation = this.scopeGeneration) {
|
|
110
|
+
if (this.closed || generation !== this.scopeGeneration) return;
|
|
111
|
+
const sameSubscription = this.snapshotGeneration === generation;
|
|
112
|
+
if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
83
113
|
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
84
114
|
this.degrade("instance-changed: resync required");
|
|
85
115
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
86
|
-
} else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
116
|
+
} else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
87
117
|
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
88
118
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
89
119
|
}
|
|
90
120
|
// Global seq may skip unrelated changes; only a missing subscription
|
|
91
121
|
// predecessor indicates loss. The received snapshot is still complete.
|
|
122
|
+
this.snapshotGeneration = generation;
|
|
92
123
|
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
93
124
|
}
|
|
94
125
|
scheduleRecovery(delay = 0) {
|
|
@@ -123,18 +154,16 @@ export class WorkClient {
|
|
|
123
154
|
}
|
|
124
155
|
async subscribe(scope) {
|
|
125
156
|
await this.ready;
|
|
126
|
-
this.scopeGeneration
|
|
157
|
+
const generation = ++this.scopeGeneration;
|
|
127
158
|
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
128
159
|
this.recoveryAgain = false; this.recoveryDelay = 100;
|
|
129
160
|
this.scope = scope;
|
|
130
|
-
|
|
131
|
-
this.accept(snapshot); return snapshot;
|
|
161
|
+
return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
|
|
132
162
|
}
|
|
133
163
|
async resync() {
|
|
134
164
|
const generation = this.scopeGeneration;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
return snapshot;
|
|
165
|
+
return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
|
|
166
|
+
sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
|
|
138
167
|
}
|
|
139
168
|
async get(scope) {
|
|
140
169
|
await this.ready;
|
|
@@ -151,7 +180,7 @@ export class WorkClient {
|
|
|
151
180
|
this.closed = true;
|
|
152
181
|
this.scopeGeneration++;
|
|
153
182
|
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
154
|
-
for (const request of this.pending.values()) { clearTimeout(request.timer); request.
|
|
183
|
+
for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
|
|
155
184
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
156
185
|
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
157
186
|
}
|
package/src/observed-waits.ts
CHANGED
|
@@ -77,7 +77,7 @@ import {
|
|
|
77
77
|
type SupervisorStartOptions,
|
|
78
78
|
type SupervisorTaskStatus,
|
|
79
79
|
} from "./supervisor/index.js";
|
|
80
|
-
import { processGroupExitVerified } from "./supervisor/identity.js";
|
|
80
|
+
import { processGroupExitVerified, verifyProcessIdentity } from "./supervisor/identity.js";
|
|
81
81
|
import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
|
|
82
82
|
import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
|
|
83
83
|
import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
|
|
@@ -1355,7 +1355,8 @@ export class ObservedWaitHost {
|
|
|
1355
1355
|
store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
|
|
1356
1356
|
return;
|
|
1357
1357
|
}
|
|
1358
|
-
if (!pgid
|
|
1358
|
+
if (!pgid || (process.platform === "win32" &&
|
|
1359
|
+
verifyProcessIdentity(inspection.command?.pid, inspection.command?.pidStartTime) !== "verified")) return;
|
|
1359
1360
|
}
|
|
1360
1361
|
if (!this.localCancels.has(taskId)) {
|
|
1361
1362
|
this.localCancels.add(taskId);
|
package/src/registry.ts
CHANGED
|
@@ -286,9 +286,68 @@ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number
|
|
|
286
286
|
return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
|
|
287
287
|
}
|
|
288
288
|
|
|
289
|
+
/** Read each task once, even when its active and recent pointers overlap. */
|
|
290
|
+
export function observeOriginActivity(origin: BackgroundTaskCallbackOrigin, retained: string[] = [], exactId?: string) {
|
|
291
|
+
let active: string[];
|
|
292
|
+
let recent: Array<{ id: string; observedAt: number }>;
|
|
293
|
+
if (exactId !== undefined) {
|
|
294
|
+
if (!/^[A-Za-z0-9_-]+$/.test(exactId)) throw new Error("Invalid Background task ID");
|
|
295
|
+
registryIo.indexRevisionChecks += 2;
|
|
296
|
+
const marker = statSync(join(recentPath(origin), exactId), { throwIfNoEntry: false });
|
|
297
|
+
recent = marker && marker.mtimeMs + RECENT_MS > Date.now() ? [{ id: exactId, observedAt: marker.mtimeMs }] : [];
|
|
298
|
+
active = statSync(join(originActiveIndexDir(origin), exactId), { throwIfNoEntry: false }) ? [exactId] : [];
|
|
299
|
+
} else {
|
|
300
|
+
registryIo.indexDirectoryReads++;
|
|
301
|
+
try { active = readdirSync(originActiveIndexDir(origin)).filter(id => id !== ".initialized"); }
|
|
302
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; active = []; }
|
|
303
|
+
recent = recentEntries(origin);
|
|
304
|
+
}
|
|
305
|
+
const deadlines = recent.map(entry => entry.observedAt + RECENT_MS);
|
|
306
|
+
const recentIds = new Set(recent.map(entry => entry.id));
|
|
307
|
+
const activeIds = new Set(active);
|
|
308
|
+
const retainedIds = new Set(retained);
|
|
309
|
+
const rows: BackgroundTaskMeta[] = [];
|
|
310
|
+
for (const id of new Set([...active, ...recentIds, ...retained])) {
|
|
311
|
+
const record = inspectMeta(id);
|
|
312
|
+
if (record.found && !record.meta) throw new Error(`Unverified background task ${id}: ${record.error}`);
|
|
313
|
+
const meta = record.meta;
|
|
314
|
+
if (!meta || !belongsToOrigin(meta, origin) || meta.dismissedAt !== undefined) continue;
|
|
315
|
+
const wasRetained = retainedIds.has(id) && meta.status !== "running" && (!meta.endedAt || meta.endedAt + RECENT_MS > Date.now());
|
|
316
|
+
if (wasRetained && meta.endedAt) deadlines.push(meta.endedAt + RECENT_MS);
|
|
317
|
+
if (wasRetained || recentIds.has(id) || (activeIds.has(id) && meta.callbackOrigin && meta.status === "running")) rows.push(meta);
|
|
318
|
+
}
|
|
319
|
+
return { rows, deadline: deadlines.length ? Math.min(...deadlines) : null };
|
|
320
|
+
}
|
|
321
|
+
|
|
289
322
|
/** Exact cooperative source identity; no metadata or historical enumeration. */
|
|
290
323
|
export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
|
|
291
|
-
return
|
|
324
|
+
return observedIndexRevision(originKey(origin));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const absentOrigin = "missing;missing";
|
|
328
|
+
function observedIndexRevision(key: string): string {
|
|
329
|
+
const root = baseDir();
|
|
330
|
+
return [join(root, "by-origin-active", key), join(root, "by-origin-recent", key)]
|
|
331
|
+
.map(path => indexDirectorySignature(path, true)).join(";");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** A missing origin directory cannot appear without changing its parent. Existing directories
|
|
335
|
+
* still need exact checks because writes to their children do not change the parent's stamp. */
|
|
336
|
+
export function beginOriginIndexScan(previous?: { roots: string; missing: Set<string> }) {
|
|
337
|
+
const roots = observedIndexRevision("");
|
|
338
|
+
const missing = new Set<string>();
|
|
339
|
+
const revisions = new Map<string, string>();
|
|
340
|
+
function revision(origin: BackgroundTaskCallbackOrigin): string {
|
|
341
|
+
if (roots === absentOrigin) return absentOrigin;
|
|
342
|
+
const key = originKey(origin);
|
|
343
|
+
const cached = revisions.get(key);
|
|
344
|
+
if (cached !== undefined) return cached;
|
|
345
|
+
const stamp = previous?.roots === roots && previous.missing.has(key) ? absentOrigin : observedIndexRevision(key);
|
|
346
|
+
if (stamp === absentOrigin) missing.add(key);
|
|
347
|
+
revisions.set(key, stamp);
|
|
348
|
+
return stamp;
|
|
349
|
+
}
|
|
350
|
+
return { state: { roots, missing }, revision };
|
|
292
351
|
}
|
|
293
352
|
|
|
294
353
|
/** Bounded cooperative writes, including results written before the first reader. */
|
|
@@ -441,12 +500,13 @@ function removeIndexEntry(directory: string, id: string): void {
|
|
|
441
500
|
}
|
|
442
501
|
}
|
|
443
502
|
|
|
444
|
-
function indexDirectorySignature(directory: string): string {
|
|
503
|
+
function indexDirectorySignature(directory: string, verifyAbsence = false): string {
|
|
445
504
|
registryIo.indexRevisionChecks += 1;
|
|
446
505
|
try {
|
|
447
|
-
const stat = statSync(directory);
|
|
448
|
-
return
|
|
449
|
-
} catch {
|
|
506
|
+
const stat = statSync(directory, { bigint: true });
|
|
507
|
+
return [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(":");
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (verifyAbsence && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
450
510
|
return "missing";
|
|
451
511
|
}
|
|
452
512
|
}
|
package/src/shared-navigator.ts
CHANGED
|
@@ -1539,7 +1539,7 @@ function neighbourCloseTarget(
|
|
|
1539
1539
|
|
|
1540
1540
|
function buildTranscriptDetailLines(
|
|
1541
1541
|
detail: BackgroundWorkDetail,
|
|
1542
|
-
transcriptLines: string[],
|
|
1542
|
+
transcriptLines: readonly string[],
|
|
1543
1543
|
width: number,
|
|
1544
1544
|
truncate: (s: string, width: number) => string,
|
|
1545
1545
|
fg: (color: string, value: string) => string,
|
|
@@ -1599,7 +1599,7 @@ function detailOverlayOptions() {
|
|
|
1599
1599
|
};
|
|
1600
1600
|
}
|
|
1601
1601
|
|
|
1602
|
-
function renderEditorLines(width: number): string[] {
|
|
1602
|
+
function renderEditorLines(width: number): readonly string[] {
|
|
1603
1603
|
try {
|
|
1604
1604
|
const lines = state().editorComponent?.render(width);
|
|
1605
1605
|
if (lines?.length) return lines;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { connect } from "node:net";
|
|
3
4
|
import { performance } from "node:perf_hooks";
|
|
4
5
|
import { setTimeout as delay } from "node:timers/promises";
|
|
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
|
|
|
13
14
|
return file ? existsSync(file) : Boolean(session.getLeafId?.());
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
function unknownLaunchReceipt(cause) {
|
|
18
|
+
return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
|
|
19
|
+
}
|
|
20
|
+
|
|
16
21
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
17
22
|
export class WorkClient {
|
|
23
|
+
lastSubscriptionTrace;
|
|
18
24
|
socket;
|
|
19
25
|
snapshot;
|
|
20
26
|
pending = new Map();
|
|
@@ -29,6 +35,7 @@ export class WorkClient {
|
|
|
29
35
|
recoveryAgain = false;
|
|
30
36
|
recoveryDelay = 100;
|
|
31
37
|
scopeGeneration = 0;
|
|
38
|
+
snapshotGeneration = 0;
|
|
32
39
|
|
|
33
40
|
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
34
41
|
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
@@ -44,7 +51,10 @@ export class WorkClient {
|
|
|
44
51
|
if (message.type === "event") {
|
|
45
52
|
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
46
53
|
if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
|
|
47
|
-
else if (message.event.type === "runtime_snapshot")
|
|
54
|
+
else if (message.event.type === "runtime_snapshot") {
|
|
55
|
+
const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
|
|
56
|
+
this.accept(message.event.snapshot, message.event.previousSeq, generation);
|
|
57
|
+
}
|
|
48
58
|
} else {
|
|
49
59
|
const request = this.pending.get(message.id);
|
|
50
60
|
if (!request) continue;
|
|
@@ -64,10 +74,28 @@ export class WorkClient {
|
|
|
64
74
|
request(type, params = {}) {
|
|
65
75
|
if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
|
|
66
76
|
if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
|
|
67
|
-
const
|
|
77
|
+
const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
|
|
78
|
+
if (trace) this.lastSubscriptionTrace = trace;
|
|
79
|
+
const id = trace?.id ?? `work-${++this.sequence}`;
|
|
68
80
|
return new Promise((resolve, reject) => {
|
|
69
|
-
const
|
|
70
|
-
|
|
81
|
+
const rejectPending = type === "runtime_launch_subagent" ? error => reject(unknownLaunchReceipt(error)) : reject;
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
this.pending.delete(id);
|
|
84
|
+
if (trace) trace.timedOutAt = Date.now();
|
|
85
|
+
rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
|
|
86
|
+
}, 5000);
|
|
87
|
+
this.pending.set(id, { resolve: value => {
|
|
88
|
+
if (trace) trace.receivedAt = Date.now();
|
|
89
|
+
// Apply subscription receipts in wire order, including events in the same socket chunk.
|
|
90
|
+
try {
|
|
91
|
+
if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
|
|
92
|
+
this.accept(value, undefined, params.subscriptionGeneration);
|
|
93
|
+
resolve(value);
|
|
94
|
+
} catch (error) { reject(error); }
|
|
95
|
+
}, reject: error => {
|
|
96
|
+
if (trace) trace.receivedAt = Date.now();
|
|
97
|
+
reject(error);
|
|
98
|
+
}, rejectPending, timer });
|
|
71
99
|
this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
|
|
72
100
|
});
|
|
73
101
|
}
|
|
@@ -78,17 +106,20 @@ export class WorkClient {
|
|
|
78
106
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
79
107
|
this.notify();
|
|
80
108
|
}
|
|
81
|
-
accept(snapshot, previousSeq) {
|
|
82
|
-
if (this.
|
|
109
|
+
accept(snapshot, previousSeq, generation = this.scopeGeneration) {
|
|
110
|
+
if (this.closed || generation !== this.scopeGeneration) return;
|
|
111
|
+
const sameSubscription = this.snapshotGeneration === generation;
|
|
112
|
+
if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
83
113
|
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
84
114
|
this.degrade("instance-changed: resync required");
|
|
85
115
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
86
|
-
} else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
116
|
+
} else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
87
117
|
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
88
118
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
89
119
|
}
|
|
90
120
|
// Global seq may skip unrelated changes; only a missing subscription
|
|
91
121
|
// predecessor indicates loss. The received snapshot is still complete.
|
|
122
|
+
this.snapshotGeneration = generation;
|
|
92
123
|
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
93
124
|
}
|
|
94
125
|
scheduleRecovery(delay = 0) {
|
|
@@ -123,18 +154,16 @@ export class WorkClient {
|
|
|
123
154
|
}
|
|
124
155
|
async subscribe(scope) {
|
|
125
156
|
await this.ready;
|
|
126
|
-
this.scopeGeneration
|
|
157
|
+
const generation = ++this.scopeGeneration;
|
|
127
158
|
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
128
159
|
this.recoveryAgain = false; this.recoveryDelay = 100;
|
|
129
160
|
this.scope = scope;
|
|
130
|
-
|
|
131
|
-
this.accept(snapshot); return snapshot;
|
|
161
|
+
return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
|
|
132
162
|
}
|
|
133
163
|
async resync() {
|
|
134
164
|
const generation = this.scopeGeneration;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
return snapshot;
|
|
165
|
+
return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
|
|
166
|
+
sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
|
|
138
167
|
}
|
|
139
168
|
async get(scope) {
|
|
140
169
|
await this.ready;
|
|
@@ -151,7 +180,7 @@ export class WorkClient {
|
|
|
151
180
|
this.closed = true;
|
|
152
181
|
this.scopeGeneration++;
|
|
153
182
|
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
154
|
-
for (const request of this.pending.values()) { clearTimeout(request.timer); request.
|
|
183
|
+
for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
|
|
155
184
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
156
185
|
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
157
186
|
}
|