pi-better-server 0.2.4 → 0.4.0
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 +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import { performance, monitorEventLoopDelay } from "node:perf_hooks";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import type { Duplex } from "node:stream";
|
|
5
|
+
import type { WorkReadModel } from "./read-model.ts";
|
|
6
|
+
import { workScope } from "./queries.ts";
|
|
7
|
+
|
|
8
|
+
export interface EncodedRead { json: string }
|
|
9
|
+
interface Waiter { connection: number; resolve(value: EncodedRead): void; reject(error: Error): void }
|
|
10
|
+
interface Query {
|
|
11
|
+
id: number; key?: string; command: Record<string, unknown>; connection: number;
|
|
12
|
+
enqueued: number; deadline: ReturnType<typeof setTimeout>; waiters: Set<Waiter>;
|
|
13
|
+
}
|
|
14
|
+
export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
|
|
15
|
+
interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
|
|
16
|
+
interface WorkerMetrics { inventories?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
|
|
17
|
+
export interface QueryExecutorOptions {
|
|
18
|
+
capacity?: number; timeoutMs?: number; maxConnections?: number;
|
|
19
|
+
workerUrl?: URL;
|
|
20
|
+
modelOptions?: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** One root, one read worker, one admitted operation at a time. No mutation RPC. */
|
|
24
|
+
export class WorkQueryExecutor {
|
|
25
|
+
private worker: Worker;
|
|
26
|
+
private streams = new Map<number, Stream>();
|
|
27
|
+
private workerConnections = new Set<number>();
|
|
28
|
+
private queue: Query[] = [];
|
|
29
|
+
private active?: Query;
|
|
30
|
+
private flights = new Map<string, Query>();
|
|
31
|
+
private counter = 0;
|
|
32
|
+
private connectionCounter = 0;
|
|
33
|
+
private revision = 0;
|
|
34
|
+
private failure?: Error;
|
|
35
|
+
private termination?: Promise<number>;
|
|
36
|
+
private exited = false;
|
|
37
|
+
private closed = false;
|
|
38
|
+
private workerGeneration = 0;
|
|
39
|
+
private recoveryAttempts: number[] = [];
|
|
40
|
+
private recoveryTimer?: ReturnType<typeof setTimeout>;
|
|
41
|
+
private workerMetrics: WorkerMetrics = {};
|
|
42
|
+
private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
|
|
43
|
+
status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
|
|
44
|
+
};
|
|
45
|
+
private lag = monitorEventLoopDelay({ resolution: 10 });
|
|
46
|
+
private waits: number[] = [];
|
|
47
|
+
private completed = 0;
|
|
48
|
+
private coalesced = 0;
|
|
49
|
+
private rejected = 0;
|
|
50
|
+
private cancelled = 0;
|
|
51
|
+
private timeouts = 0;
|
|
52
|
+
private durations: number[] = [];
|
|
53
|
+
private options: QueryExecutorOptions;
|
|
54
|
+
private agentDir: string;
|
|
55
|
+
readonly instanceId: string;
|
|
56
|
+
|
|
57
|
+
constructor(agentDir: string, instanceId: string, options: QueryExecutorOptions = {}) {
|
|
58
|
+
this.options = options; this.instanceId = instanceId; this.agentDir = agentDir;
|
|
59
|
+
this.lag.enable();
|
|
60
|
+
this.worker = this.startWorker();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private startWorker() {
|
|
64
|
+
const instanceId = this.workerGeneration ? `${this.instanceId}:reads:${this.workerGeneration}` : this.instanceId;
|
|
65
|
+
const worker = new Worker(this.options.workerUrl ?? new URL("./query-worker.mjs", import.meta.url), {
|
|
66
|
+
execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: this.options.modelOptions },
|
|
67
|
+
});
|
|
68
|
+
worker.on("message", message => { if (worker === this.worker) this.receive(message); });
|
|
69
|
+
worker.on("error", error => { if (worker === this.worker) this.fail(new Error(`runtime-unhealthy: read worker failed: ${String(error)}`)); });
|
|
70
|
+
worker.on("exit", code => {
|
|
71
|
+
if (worker !== this.worker) return;
|
|
72
|
+
this.exited = true;
|
|
73
|
+
const sqlite = this.workerMetrics.sqlite;
|
|
74
|
+
if (sqlite) this.workerMetrics = { ...this.workerMetrics, sqlite: { ...sqlite, active: 0 } };
|
|
75
|
+
this.fail(new Error(`runtime-unhealthy: read worker exited (${code}); rebuilding reads after recovery`));
|
|
76
|
+
this.scheduleRecovery();
|
|
77
|
+
});
|
|
78
|
+
return worker;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private scheduleRecovery() {
|
|
82
|
+
if (this.closed || !this.exited || this.recoveryTimer || !this.streams.size) return;
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
this.recoveryAttempts = this.recoveryAttempts.filter(attempt => now - attempt < 60_000);
|
|
85
|
+
if (this.recoveryAttempts.length >= 2) {
|
|
86
|
+
if (!this.failure?.message.includes("recovery budget exhausted")) {
|
|
87
|
+
this.failure = new Error(`${this.failure?.message}; automatic read recovery budget exhausted`);
|
|
88
|
+
}
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this.recoveryTimer = setTimeout(() => {
|
|
92
|
+
this.recoveryTimer = undefined;
|
|
93
|
+
if (this.closed || !this.streams.size) return;
|
|
94
|
+
this.recoveryAttempts.push(Date.now());
|
|
95
|
+
this.workerGeneration++;
|
|
96
|
+
this.exited = false; this.failure = undefined; this.termination = undefined;
|
|
97
|
+
this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
|
|
98
|
+
this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
|
|
99
|
+
this.lag.reset(); this.lag.enable();
|
|
100
|
+
try { this.worker = this.startWorker(); }
|
|
101
|
+
catch (error) {
|
|
102
|
+
this.exited = true; this.lag.disable();
|
|
103
|
+
this.failure = new Error(`runtime-unhealthy: read worker restart failed: ${String(error)}`);
|
|
104
|
+
this.scheduleRecovery();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
|
|
108
|
+
event: { type: "resync_required", reason: "read-worker-recovered", instanceId: this.instanceId } }) + "\n");
|
|
109
|
+
}, 500);
|
|
110
|
+
this.recoveryTimer.unref();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
connect(socket: ReadStream) {
|
|
114
|
+
if (this.streams.size >= (this.options.maxConnections ?? 64)) throw new Error("runtime-overloaded: too many read clients; retry later");
|
|
115
|
+
const connection = ++this.connectionCounter;
|
|
116
|
+
const drain = () => {
|
|
117
|
+
const stream = this.streams.get(connection);
|
|
118
|
+
if (!stream?.paused) return;
|
|
119
|
+
stream.paused = false;
|
|
120
|
+
this.event(connection, JSON.stringify({ type: "event", event: { type: "resync_required", reason: "slow-reader", instanceId: this.instanceId } }) + "\n");
|
|
121
|
+
};
|
|
122
|
+
const close = () => this.detach(connection);
|
|
123
|
+
this.streams.set(connection, { socket, paused: false, generation: 0, drain, close });
|
|
124
|
+
socket.on("drain", drain); socket.once("close", close);
|
|
125
|
+
if (this.failure) this.scheduleRecovery();
|
|
126
|
+
return { handle: (command: Record<string, unknown>) => this.request(connection, command), close };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async livenessReasons(): Promise<any[]> {
|
|
130
|
+
const result = await this.request(0, { type: "runtime_get_liveness" });
|
|
131
|
+
return JSON.parse(result.json);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
observation() {
|
|
135
|
+
return this.failure ? { ...this.lastObservation, status: "degraded" as const, reason: this.failure.message } : this.lastObservation;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
metrics() {
|
|
139
|
+
return { ...this.workerMetrics, executor: { active: this.active ? 1 : 0, queued: this.queue.length,
|
|
140
|
+
clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
|
|
141
|
+
cancelled: this.cancelled, timeouts: this.timeouts,
|
|
142
|
+
capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
|
|
143
|
+
eventLoopLagMs: { p50: this.lag.percentile(50) / 1e6, p95: this.lag.percentile(95) / 1e6, p99: this.lag.percentile(99) / 1e6 },
|
|
144
|
+
worker: this.exited ? "stopped" : this.failure ? "stopping" : "running",
|
|
145
|
+
restarts: this.workerGeneration, recoveryPending: !!this.recoveryTimer,
|
|
146
|
+
status: this.failure ? "degraded" : "ready" } };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private request(connection: number, input: Record<string, unknown>): Promise<EncodedRead> {
|
|
150
|
+
if (connection !== 0 && !this.streams.has(connection)) return Promise.reject(new Error("runtime-unavailable: client disconnected"));
|
|
151
|
+
if (input.type === "runtime_get_metrics") return Promise.resolve({ json: JSON.stringify(this.metrics()) });
|
|
152
|
+
if (this.failure) { this.scheduleRecovery(); return Promise.reject(this.failure); }
|
|
153
|
+
if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
|
|
154
|
+
if (input.sinceSeq !== undefined && !Number.isSafeInteger(input.sinceSeq)) return Promise.reject(new Error("Invalid replay sequence"));
|
|
155
|
+
if (input.instanceId !== undefined && (typeof input.instanceId !== "string" || input.instanceId.length > 256)) return Promise.reject(new Error("Invalid runtime instance"));
|
|
156
|
+
const command: Record<string, unknown> = { type: input.type, sinceSeq: input.sinceSeq, instanceId: input.instanceId };
|
|
157
|
+
if (command.type !== "runtime_unsubscribe" && command.type !== "runtime_get_liveness") {
|
|
158
|
+
const scope = workScope(input.scope);
|
|
159
|
+
if (scope.cwd) scope.cwd = resolve(scope.cwd);
|
|
160
|
+
scope.limit ??= scope.backgroundHistory ? 10 : 50;
|
|
161
|
+
scope.detail ||= undefined;
|
|
162
|
+
scope.statuses = scope.statuses?.length ? [...new Set(scope.statuses)].sort() : undefined;
|
|
163
|
+
command.scope = scope;
|
|
164
|
+
}
|
|
165
|
+
const key = command.type === "runtime_get_snapshot" ? JSON.stringify([this.revision, command.scope]) : undefined;
|
|
166
|
+
let query = key ? this.flights.get(key) : undefined;
|
|
167
|
+
if (query) this.coalesced++;
|
|
168
|
+
else {
|
|
169
|
+
if (this.queue.length + (this.active ? 1 : 0) >= (this.options.capacity ?? 64)) {
|
|
170
|
+
this.rejected++;
|
|
171
|
+
return Promise.reject(new Error("runtime-overloaded: read queue is full; retry later"));
|
|
172
|
+
}
|
|
173
|
+
const id = ++this.counter;
|
|
174
|
+
query = { id, key, command, connection: key ? 0 : connection, enqueued: performance.now(),
|
|
175
|
+
deadline: setTimeout(() => this.expire(id), this.options.timeoutMs ?? 4000), waiters: new Set() };
|
|
176
|
+
this.queue.push(query);
|
|
177
|
+
if (key) this.flights.set(key, query);
|
|
178
|
+
}
|
|
179
|
+
const admitted = query;
|
|
180
|
+
const result = new Promise<EncodedRead>((resolve, reject) => admitted.waiters.add({ connection, resolve, reject }));
|
|
181
|
+
this.pump();
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private pump() {
|
|
186
|
+
if (this.failure || this.active || !this.queue.length) return;
|
|
187
|
+
const query = this.active = this.queue.shift()!;
|
|
188
|
+
this.waits.push(performance.now() - query.enqueued);
|
|
189
|
+
if (this.waits.length > 128) this.waits.shift();
|
|
190
|
+
const stream = this.streams.get(query.connection);
|
|
191
|
+
if (stream) { stream.generation++; this.workerConnections.add(query.connection); }
|
|
192
|
+
this.worker.postMessage({ type: "query", id: query.id, connection: query.connection,
|
|
193
|
+
generation: stream?.generation ?? 0, command: query.command });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private receive(message: any) {
|
|
197
|
+
if (this.failure) return;
|
|
198
|
+
if (message.metrics) this.workerMetrics = message.metrics;
|
|
199
|
+
if (message.observation) this.lastObservation = message.observation;
|
|
200
|
+
if (message.type === "revision") { this.revision++; this.worker.postMessage({ type: "revision-consumed" }); return; }
|
|
201
|
+
if (message.type === "event") {
|
|
202
|
+
if (this.streams.get(message.connection)?.generation === message.generation) this.event(message.connection, message.line);
|
|
203
|
+
this.worker.postMessage({ type: "event-consumed", connection: message.connection, serial: message.serial });
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (message.type !== "reply" || message.id !== this.active?.id) return;
|
|
207
|
+
const query = this.active!;
|
|
208
|
+
this.active = undefined; this.completed++;
|
|
209
|
+
this.durations.push(performance.now() - query.enqueued);
|
|
210
|
+
if (this.durations.length > 128) this.durations.shift();
|
|
211
|
+
this.finish(query, message.error ? new Error(message.error) : undefined, { json: message.json });
|
|
212
|
+
this.pump();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private finish(query: Query, error?: Error, value: EncodedRead = { json: "null" }) {
|
|
216
|
+
clearTimeout(query.deadline);
|
|
217
|
+
if (query.key && this.flights.get(query.key) === query) this.flights.delete(query.key);
|
|
218
|
+
for (const waiter of query.waiters) { if (error) waiter.reject(error); else waiter.resolve(value); }
|
|
219
|
+
query.waiters.clear();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private expire(id: number) {
|
|
223
|
+
this.timeouts++;
|
|
224
|
+
const error = new Error("runtime-unhealthy: read deadline exceeded; retry after recovery");
|
|
225
|
+
if (this.active?.id === id) { this.fail(error); return; }
|
|
226
|
+
const index = this.queue.findIndex(query => query.id === id);
|
|
227
|
+
if (index < 0) return;
|
|
228
|
+
const [query] = this.queue.splice(index, 1);
|
|
229
|
+
this.finish(query!, error);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private event(connection: number, line: string) {
|
|
233
|
+
const stream = this.streams.get(connection);
|
|
234
|
+
if (!stream || stream.socket.destroyed || stream.paused) return;
|
|
235
|
+
if (stream.socket.writableLength > 4 * 1024 * 1024) { stream.paused = true; return; }
|
|
236
|
+
stream.socket.write(line);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private detach(connection: number) {
|
|
240
|
+
const stream = this.streams.get(connection);
|
|
241
|
+
if (!stream) return;
|
|
242
|
+
stream.socket.off("drain", stream.drain); stream.socket.off("close", stream.close);
|
|
243
|
+
this.streams.delete(connection);
|
|
244
|
+
if (this.workerConnections.delete(connection) && !this.failure) this.worker.postMessage({ type: "detach", connection });
|
|
245
|
+
for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) {
|
|
246
|
+
for (const waiter of query.waiters) if (waiter.connection === connection) {
|
|
247
|
+
query.waiters.delete(waiter); this.cancelled++; waiter.reject(new Error("runtime-unavailable: client disconnected"));
|
|
248
|
+
}
|
|
249
|
+
if (!query.waiters.size && query !== this.active) {
|
|
250
|
+
this.queue.splice(this.queue.indexOf(query), 1);
|
|
251
|
+
this.finish(query);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private fail(error: Error) {
|
|
257
|
+
if (this.failure) return;
|
|
258
|
+
this.failure = error; this.lag.disable();
|
|
259
|
+
for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) this.finish(query, error);
|
|
260
|
+
this.queue = []; this.active = undefined;
|
|
261
|
+
for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
|
|
262
|
+
event: { type: "resync_required", reason: error.message, instanceId: this.instanceId } }) + "\n");
|
|
263
|
+
this.termination = this.worker.terminate();
|
|
264
|
+
this.worker.unref();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async close() {
|
|
268
|
+
this.closed = true;
|
|
269
|
+
if (this.recoveryTimer) { clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined; }
|
|
270
|
+
this.fail(new Error("runtime-unavailable: query executor closed"));
|
|
271
|
+
for (const connection of this.streams.keys()) this.detach(connection);
|
|
272
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
273
|
+
// Bound graceful close even while native SQLite is still finishing a call.
|
|
274
|
+
await Promise.race([this.termination, new Promise<void>(resolve => { timeout = setTimeout(resolve, 1000); })]);
|
|
275
|
+
if (timeout) clearTimeout(timeout);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { performance } from "node:perf_hooks";
|
|
5
|
+
|
|
6
|
+
// The fixed Node 24 artifact strips types natively and does not depend on tsx.
|
|
7
|
+
// Development on Node 22 uses the workspace loader without inheriting test preloads.
|
|
8
|
+
if (Number(process.versions.node.split(".")[0]) < 24) {
|
|
9
|
+
const { register } = await import("tsx/esm/api");
|
|
10
|
+
register();
|
|
11
|
+
}
|
|
12
|
+
const sqlite = createRequire(import.meta.url)("node:sqlite");
|
|
13
|
+
const OriginalDatabase = sqlite.DatabaseSync;
|
|
14
|
+
const connections = { opens: 0, active: 0, maximum: 0 };
|
|
15
|
+
sqlite.DatabaseSync = class extends OriginalDatabase {
|
|
16
|
+
counted = true;
|
|
17
|
+
constructor(...args) {
|
|
18
|
+
super(...args);
|
|
19
|
+
connections.opens++; connections.active++;
|
|
20
|
+
connections.maximum = Math.max(connections.maximum, connections.active);
|
|
21
|
+
}
|
|
22
|
+
close() {
|
|
23
|
+
super.close();
|
|
24
|
+
if (this.counted) { this.counted = false; connections.active--; }
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const { WorkReadModel } = await import("./read-model.ts");
|
|
28
|
+
const { WorkQueries } = await import("./queries.ts");
|
|
29
|
+
const model = new WorkReadModel(workerData.agentDir, workerData.instanceId, workerData.modelOptions);
|
|
30
|
+
const sessions = new Map();
|
|
31
|
+
const cache = new Map();
|
|
32
|
+
const encoded = new WeakMap();
|
|
33
|
+
let cacheBytes = 0, cacheHits = 0, queryCount = 0;
|
|
34
|
+
let revisionPending = false, revisionDirty = false;
|
|
35
|
+
const durations = [];
|
|
36
|
+
const metrics = () => ({ ...model.metrics, background: model.backgroundMetrics, sqlite: { ...connections }, cacheHits, queryCount, cacheBytes,
|
|
37
|
+
cacheEntries: cache.size, queryDurationMs: [...durations] });
|
|
38
|
+
const snapshot = model.snapshot.bind(model);
|
|
39
|
+
model.snapshot = scope => {
|
|
40
|
+
const key = JSON.stringify(scope ?? {});
|
|
41
|
+
const cacheable = !scope?.backgroundHistory;
|
|
42
|
+
const previous = cacheable ? cache.get(key) : undefined;
|
|
43
|
+
if (previous) { cacheHits++; cache.delete(key); cache.set(key, previous); return previous.value; }
|
|
44
|
+
const started = performance.now();
|
|
45
|
+
const value = snapshot(scope);
|
|
46
|
+
const json = JSON.stringify(value);
|
|
47
|
+
const bytes = Buffer.byteLength(json);
|
|
48
|
+
encoded.set(value, json);
|
|
49
|
+
queryCount++; durations.push(performance.now() - started);
|
|
50
|
+
if (durations.length > 128) durations.shift();
|
|
51
|
+
if (cacheable && bytes <= 4 * 1024 * 1024) {
|
|
52
|
+
while (cache.size && (cache.size >= 32 || cacheBytes + bytes > 16 * 1024 * 1024)) {
|
|
53
|
+
const oldest = cache.keys().next().value;
|
|
54
|
+
cacheBytes -= cache.get(oldest).bytes; cache.delete(oldest);
|
|
55
|
+
}
|
|
56
|
+
cache.set(key, { value, bytes }); cacheBytes += bytes;
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
};
|
|
60
|
+
function revision() {
|
|
61
|
+
revisionPending = true;
|
|
62
|
+
parentPort.postMessage({ type: "revision", metrics: metrics(), observation: model.observation() });
|
|
63
|
+
}
|
|
64
|
+
model.onChange(() => {
|
|
65
|
+
cache.clear(); cacheBytes = 0;
|
|
66
|
+
if (revisionPending) revisionDirty = true;
|
|
67
|
+
else revision();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
function session(id) {
|
|
71
|
+
if (sessions.has(id)) return sessions.get(id);
|
|
72
|
+
if (sessions.size >= 65) throw new Error("runtime-overloaded: subscription capacity reached; retry later");
|
|
73
|
+
const state = { generation: 0, serial: 0, awaiting: false, pending: undefined, queries: undefined };
|
|
74
|
+
state.flush = () => {
|
|
75
|
+
if (state.awaiting || !state.pending) return;
|
|
76
|
+
state.awaiting = true;
|
|
77
|
+
parentPort.postMessage({ type: "event", connection: id, serial: ++state.serial, ...state.pending });
|
|
78
|
+
state.pending = undefined;
|
|
79
|
+
};
|
|
80
|
+
const stream = Object.assign(new EventEmitter(), { destroyed: false, writableLength: 0,
|
|
81
|
+
write(line) { state.pending = { line, generation: state.generation }; state.flush(); return true; } });
|
|
82
|
+
state.queries = new WorkQueries(model, stream);
|
|
83
|
+
sessions.set(id, state);
|
|
84
|
+
return state;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
parentPort.on("message", async message => {
|
|
88
|
+
if (message.type === "revision-consumed") {
|
|
89
|
+
revisionPending = false;
|
|
90
|
+
if (revisionDirty) { revisionDirty = false; revision(); }
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (message.type === "detach") { sessions.get(message.connection)?.queries.close(); sessions.delete(message.connection); return; }
|
|
94
|
+
if (message.type === "event-consumed") {
|
|
95
|
+
const state = sessions.get(message.connection);
|
|
96
|
+
if (state?.awaiting && state.serial === message.serial) { state.awaiting = false; state.flush(); }
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (message.type !== "query") return;
|
|
100
|
+
try {
|
|
101
|
+
const command = message.command;
|
|
102
|
+
if (command.type === "runtime_get_liveness") {
|
|
103
|
+
await model.reconcile();
|
|
104
|
+
const observation = model.observation(model.livenessReasons());
|
|
105
|
+
parentPort.postMessage({ type: "reply", id: message.id, json: JSON.stringify(observation.reasons), metrics: metrics(), observation });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe"].includes(command.type)) throw new Error("Unsupported read operation");
|
|
109
|
+
const indexed = command.type !== "runtime_get_snapshot" || !command.scope?.id || await model.ensureId(command.scope.id);
|
|
110
|
+
const state = session(message.connection);
|
|
111
|
+
state.generation = message.generation; state.pending = undefined;
|
|
112
|
+
let value = state.queries.handle(command);
|
|
113
|
+
if (!indexed && !value.rows.length) value = { ...value, status: "rebuilding", reason: "The requested run is being indexed; retry after reconciliation." };
|
|
114
|
+
parentPort.postMessage({ type: "reply", id: message.id, json: encoded.get(value) ?? JSON.stringify(value), metrics: metrics() });
|
|
115
|
+
} catch (error) {
|
|
116
|
+
parentPort.postMessage({ type: "reply", id: message.id, error: String(error).slice(0, 512), metrics: metrics() });
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
void model.reconcile();
|