my-durable 0.0.60 → 0.0.61
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.
|
@@ -77,11 +77,17 @@ export function serviceEnv(env: Record<string, string | undefined>): Record<stri
|
|
|
77
77
|
return out;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
/** The env the detached child inherits: drop the Electron-node hazards (paseo lesson)
|
|
80
|
+
/** The env the detached child inherits: drop the Electron-node hazards (paseo lesson)
|
|
81
|
+
* and the R6 relaunch marker. DPI_WRAPPER_PID is the launcher wrapper's pid for the
|
|
82
|
+
* 2s orphan-watch in bin/dpi.mjs — a DETACHED daemon outlives that wrapper by days
|
|
83
|
+
* (the wrapper exits as soon as `device start` returns), so inheriting the marker
|
|
84
|
+
* made every started daemon kill itself the moment its start shell's wrapper went
|
|
85
|
+
* away. The daemon is its own supervisor; it must never watch a short-lived pid. */
|
|
81
86
|
export function cleanChildEnv(env: Record<string, string | undefined>): NodeJS.ProcessEnv {
|
|
82
87
|
const out: NodeJS.ProcessEnv = { ...env };
|
|
83
88
|
delete out.ELECTRON_RUN_AS_NODE;
|
|
84
89
|
delete out.ELECTRON_NO_ATTACH_CONSOLE;
|
|
90
|
+
delete out.DPI_WRAPPER_PID;
|
|
85
91
|
return out;
|
|
86
92
|
}
|
|
87
93
|
|
|
@@ -15,6 +15,7 @@ import { DevicePairing } from "./pairing.js";
|
|
|
15
15
|
import { DeviceConnector, readCaPem } from "./tunnel.js";
|
|
16
16
|
import { PAIR_PAGE_HTML } from "./pair-page.js";
|
|
17
17
|
import { parseDeviceSub, runDeviceCommand, daemonPaths, boundedStep } from "./daemon.js";
|
|
18
|
+
import { startEventLoopMonitor } from "./vitals.js";
|
|
18
19
|
|
|
19
20
|
// `dpi device start|stop|status|install|uninstall` manage a background daemon
|
|
20
21
|
// and exit; everything else (bare `dpi device` or flags) runs the daemon here.
|
|
@@ -25,6 +26,11 @@ import { parseDeviceSub, runDeviceCommand, daemonPaths, boundedStep } from "./da
|
|
|
25
26
|
|
|
26
27
|
assertLimitsConfig();
|
|
27
28
|
|
|
29
|
+
// Event-loop lag sampling starts before anything else can block: if boot
|
|
30
|
+
// itself stalls (sync SQLite migrations, registry writes), the first vitals
|
|
31
|
+
// window records it. Idempotent; vitals() also starts it lazily.
|
|
32
|
+
startEventLoopMonitor();
|
|
33
|
+
|
|
28
34
|
// Crash reports (policy gate #1) are installed FIRST, before anything below can
|
|
29
35
|
// throw: a config or store failure still leaves a redacted local report (nothing
|
|
30
36
|
// is ever uploaded). The state getter reads the store lazily — before it opens,
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded, single-attempt salvage of an unreadable session database (R7).
|
|
3
|
+
*
|
|
4
|
+
* R5 store audit finding: garbage in the SQLite header (the audit recipe wrote
|
|
5
|
+
* 0x41 over bytes 32-64) hides intact data forever — the close-path WAL
|
|
6
|
+
* checkpoint folds the WAL into the corrupt main file without ever fixing
|
|
7
|
+
* page 1, and the only recovery was a manual header patch. The auditor proved
|
|
8
|
+
* the patch on a copy: fix the first 100 header bytes, integrity_check passes,
|
|
9
|
+
* every entry reads back.
|
|
10
|
+
*
|
|
11
|
+
* `salvageSessionDb` automates exactly that, conservatively:
|
|
12
|
+
*
|
|
13
|
+
* 1. COPY the db aside (`<db>.salvage`, plus its `-wal`/`-shm` sidecars when
|
|
14
|
+
* present, so an unclean shutdown's frames replay onto the copy). The
|
|
15
|
+
* original file is NEVER opened for write and never modified.
|
|
16
|
+
* 2. Patch the copy's first 100 header bytes: restore the magic string, a
|
|
17
|
+
* legal page size and versions when they are garbage, zero the freelist
|
|
18
|
+
* and the auto-vacuum root page (garbage there turns ptrmap validation
|
|
19
|
+
* on), and re-seat the schema-format and text-encoding fields. Every
|
|
20
|
+
* write targets header fields sqlite validates at open; page data is
|
|
21
|
+
* untouched, so a wrong guess can only fail integrity_check, never
|
|
22
|
+
* "recover" to something wrong.
|
|
23
|
+
* 3. `PRAGMA integrity_check` on the copy. Only "ok" counts.
|
|
24
|
+
* 4. Promote on the caller's thread: the original is renamed aside
|
|
25
|
+
* (`<db>.corrupt-<ts>` — the house quarantine rule: it is the only copy
|
|
26
|
+
* of that data, so it is kept, never deleted) and the copy is atomically
|
|
27
|
+
* renamed into place.
|
|
28
|
+
*
|
|
29
|
+
* The whole attempt runs in a worker thread under a hard time ceiling
|
|
30
|
+
* (`SALVAGE_CEILING_MS`): `PRAGMA integrity_check` is synchronous, so on a
|
|
31
|
+
* pathological multi-gigabyte database the only honest bound is terminating
|
|
32
|
+
* the worker — the device's event loop never stalls, and the open path fails
|
|
33
|
+
* on schedule instead of hanging. On timeout or any failure the copy files
|
|
34
|
+
* are removed and the original is left byte-identical.
|
|
35
|
+
*/
|
|
36
|
+
import { Worker } from "node:worker_threads";
|
|
37
|
+
import { existsSync, renameSync, rmSync } from "node:fs";
|
|
38
|
+
|
|
39
|
+
/** The open path must never hang on salvage: everything above this ceiling is abandoned. */
|
|
40
|
+
export const SALVAGE_CEILING_MS = 5_000;
|
|
41
|
+
|
|
42
|
+
/** What happened to ONE salvage attempt. Bounded and secret-free — it reaches operator surfaces. */
|
|
43
|
+
export interface SalvageOutcome {
|
|
44
|
+
/** Always true when salvageSessionDb returned: the attempt was made. */
|
|
45
|
+
attempted: boolean;
|
|
46
|
+
/** The patched copy passed integrity_check and was promoted into place. */
|
|
47
|
+
recovered: boolean;
|
|
48
|
+
/** Why the salvage did not recover, when it did not. */
|
|
49
|
+
reason?: string;
|
|
50
|
+
/** Where the original (still corrupt) file was kept when promotion happened. */
|
|
51
|
+
keptAs?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The copy/patch/integrity_check work, as plain CommonJS so it can run in a
|
|
56
|
+
* `new Worker(src, { eval: true })` thread. No imports of project code: the
|
|
57
|
+
* worker is self-contained and terminable at any instruction.
|
|
58
|
+
*/
|
|
59
|
+
const WORKER_SRC = `
|
|
60
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
61
|
+
const { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
|
|
62
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
63
|
+
const main = workerData.dbPath;
|
|
64
|
+
const copy = main + ".salvage";
|
|
65
|
+
const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
|
|
66
|
+
function run() {
|
|
67
|
+
try {
|
|
68
|
+
// 1. Copy main + sidecars aside. The original is only ever read.
|
|
69
|
+
rmSync(copy, { force: true });
|
|
70
|
+
copyFileSync(main, copy);
|
|
71
|
+
for (const suffix of ["-wal", "-shm"]) {
|
|
72
|
+
if (existsSync(main + suffix)) copyFileSync(main + suffix, copy + suffix);
|
|
73
|
+
else rmSync(copy + suffix, { force: true });
|
|
74
|
+
}
|
|
75
|
+
// 2. Patch the copy's header: only fields sqlite validates at open (see module doc).
|
|
76
|
+
const b = readFileSync(copy);
|
|
77
|
+
const MAGIC = "SQLite format 3\\0";
|
|
78
|
+
if (b.slice(0, 16).toString("latin1") !== MAGIC) b.write(MAGIC, 0, 16, "latin1");
|
|
79
|
+
const pageSize = b.readUInt16BE(16);
|
|
80
|
+
const legalPageSize = pageSize === 1 || (pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0);
|
|
81
|
+
if (!legalPageSize) b.writeUInt16BE(4096, 16); // sqlite's default; a wrong guess fails integrity, never lies
|
|
82
|
+
if (b[18] !== 1 && b[18] !== 2) b[18] = 2; // write version: WAL (pi-durable's journal mode)
|
|
83
|
+
if (b[19] !== 1 && b[19] !== 2) b[19] = 2; // read version
|
|
84
|
+
if (b[20] > 32) b[20] = 0; // reserved bytes per page: node:sqlite uses 0
|
|
85
|
+
b.writeUInt32BE(0, 32); // first freelist trunk page (garbage here = freelist corruption)
|
|
86
|
+
b.writeUInt32BE(0, 36); // freelist page count
|
|
87
|
+
const schemaFormat = b.readUInt32BE(44);
|
|
88
|
+
if (!(schemaFormat >= 1 && schemaFormat <= 4)) b.writeUInt32BE(4, 44); // "unsupported file format" otherwise
|
|
89
|
+
b.writeUInt32BE(0, 52); // largest root b-tree page: nonzero garbage turns ptrmap validation on
|
|
90
|
+
const encoding = b.readUInt32BE(56);
|
|
91
|
+
if (!(encoding >= 1 && encoding <= 3)) b.writeUInt32BE(1, 56); // UTF-8
|
|
92
|
+
writeFileSync(copy, b);
|
|
93
|
+
// 3. Integrity is the ONLY gate for promotion.
|
|
94
|
+
let db;
|
|
95
|
+
try {
|
|
96
|
+
db = new DatabaseSync(copy); // read-write: a copied -wal may need recovery replay
|
|
97
|
+
const rows = db.prepare("PRAGMA integrity_check").all();
|
|
98
|
+
const ok = rows.length === 1 && rows[0].integrity_check === "ok";
|
|
99
|
+
if (!ok) {
|
|
100
|
+
db.close();
|
|
101
|
+
db = undefined;
|
|
102
|
+
parentPort.postMessage({ ok: false, reason: "integrity check failed" });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
// Fold any replayed WAL into the copy so the promoted file is self-contained
|
|
106
|
+
// (the same checkpoint pi-durable's own close runs).
|
|
107
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
108
|
+
db.close();
|
|
109
|
+
db = undefined;
|
|
110
|
+
parentPort.postMessage({ ok: true });
|
|
111
|
+
} finally {
|
|
112
|
+
try { db && db.close(); } catch (e) {}
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
fail((error && error.message) || error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
run();
|
|
119
|
+
`;
|
|
120
|
+
|
|
121
|
+
const rmCopyFiles = (dbPath: string) => {
|
|
122
|
+
for (const suffix of [".salvage", ".salvage-wal", ".salvage-shm"]) rmSync(dbPath + suffix, { force: true });
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** Promote the verified copy: original aside (kept), copy atomically into place. */
|
|
126
|
+
const promote = (dbPath: string): string => {
|
|
127
|
+
const aside = `${dbPath}.corrupt-${Date.now()}`;
|
|
128
|
+
renameSync(dbPath, aside);
|
|
129
|
+
for (const suffix of ["-wal", "-shm"]) if (existsSync(dbPath + suffix)) renameSync(dbPath + suffix, `${aside}${suffix}`);
|
|
130
|
+
renameSync(`${dbPath}.salvage`, dbPath);
|
|
131
|
+
rmCopyFiles(dbPath); // the copy's own sidecars were checkpointed away; drop leftovers
|
|
132
|
+
return aside;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* ONE bounded salvage attempt for the session db at `dbPath`. Resolves — never
|
|
137
|
+
* rejects: a salvage that cannot run is a failed salvage, and the caller's
|
|
138
|
+
* failure surface (not this module) owns what the client sees.
|
|
139
|
+
*/
|
|
140
|
+
export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEILING_MS): Promise<SalvageOutcome> {
|
|
141
|
+
return new Promise((resolve) => {
|
|
142
|
+
let worker: Worker;
|
|
143
|
+
try {
|
|
144
|
+
worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath } });
|
|
145
|
+
} catch {
|
|
146
|
+
resolve({ attempted: false, recovered: false, reason: "salvage worker unavailable" });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
let settled = false;
|
|
150
|
+
const finish = (result: SalvageOutcome) => {
|
|
151
|
+
if (settled) return;
|
|
152
|
+
settled = true;
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
void worker.terminate().catch(() => {});
|
|
155
|
+
let outcome = result;
|
|
156
|
+
if (outcome.recovered) {
|
|
157
|
+
try {
|
|
158
|
+
outcome = { ...outcome, keptAs: promote(dbPath) };
|
|
159
|
+
} catch {
|
|
160
|
+
outcome = { attempted: true, recovered: false, reason: "promotion failed" };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!outcome.recovered) rmCopyFiles(dbPath);
|
|
164
|
+
resolve(outcome);
|
|
165
|
+
};
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
finish({ attempted: true, recovered: false, reason: `timed out after ${ceilingMs}ms` });
|
|
168
|
+
}, Math.max(0, ceilingMs));
|
|
169
|
+
worker.once("message", (message: { ok?: boolean; reason?: string }) => {
|
|
170
|
+
if (message?.ok) finish({ attempted: true, recovered: true });
|
|
171
|
+
else finish({ attempted: true, recovered: false, reason: message?.reason ?? "salvage failed" });
|
|
172
|
+
});
|
|
173
|
+
worker.once("error", (error: Error) => finish({ attempted: true, recovered: false, reason: error.name }));
|
|
174
|
+
worker.once("exit", () => finish({ attempted: true, recovered: false, reason: "salvage worker exited" }));
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The operator-facing note when a salvage was attempted and did not recover.
|
|
180
|
+
* House pattern of `sessionFailureMessage`, extended so the session list says
|
|
181
|
+
* a salvage WAS attempted (and that the original file is untouched — the one
|
|
182
|
+
* fact an operator needs before reaching for a backup).
|
|
183
|
+
*/
|
|
184
|
+
export const salvageFailureNote = (outcome: SalvageOutcome): string =>
|
|
185
|
+
`Session failed and is unavailable (UnreadableStorage); a salvage copy was attempted but ${
|
|
186
|
+
outcome.reason ? `failed (${outcome.reason}); ` : "did not pass integrity checks; "
|
|
187
|
+
}the original file is untouched`;
|
|
@@ -77,7 +77,8 @@ import {
|
|
|
77
77
|
type ArchivedView,
|
|
78
78
|
} from "./archived.js";
|
|
79
79
|
import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
|
|
80
|
-
import { zipSync, type ZipEntry } from "./zip.js";
|
|
80
|
+
import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
|
|
81
|
+
import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
|
|
81
82
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
82
83
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
83
84
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
@@ -1516,8 +1517,43 @@ export class Store {
|
|
|
1516
1517
|
// Custom extensions are installed but not selected: an agent turns them on in its own selection.
|
|
1517
1518
|
const addons = createAddons({ offline: this.options.provider === "faux" });
|
|
1518
1519
|
for (const extension of addons.list) registry.install(extension);
|
|
1520
|
+
// R7: an unreadable db (a corrupt header, per the R5 audit recipe — garbage
|
|
1521
|
+
// bytes 32-64) used to hide intact data forever: the close-path checkpoint
|
|
1522
|
+
// folds the WAL into the corrupt main file without fixing page 1, and the
|
|
1523
|
+
// only recovery was a manual header patch. Before failing the open, ONE
|
|
1524
|
+
// bounded salvage on a COPY (header patch + integrity_check + atomic
|
|
1525
|
+
// promote; see salvage.ts). The original file is never modified — a failed
|
|
1526
|
+
// salvage leaves it byte-identical and the failure surface says so. Any other
|
|
1527
|
+
// open error (a held lock, a schema mismatch) keeps its existing behavior.
|
|
1528
|
+
let storage: Awaited<ReturnType<typeof openNodeSqliteStorage>>;
|
|
1529
|
+
try {
|
|
1530
|
+
storage = await openNodeSqliteStorage(row.dbPath);
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
if (create || !isUnreadableStorage(error)) throw error;
|
|
1533
|
+
const outcome = await salvageSessionDb(row.dbPath);
|
|
1534
|
+
if (!outcome.recovered) {
|
|
1535
|
+
const note = salvageFailureNote(outcome);
|
|
1536
|
+
const previous = this.errors.get(row.id);
|
|
1537
|
+
this.errors.set(row.id, note); // rides the session summary and every later fault
|
|
1538
|
+
this.notify();
|
|
1539
|
+
// Same operator visibility failSession gives a mid-run failure — once per
|
|
1540
|
+
// distinct note, so repeated failed opens do not spam the sinks.
|
|
1541
|
+
if (previous !== note)
|
|
1542
|
+
void this.notifyEvent({
|
|
1543
|
+
kind: "session.failed",
|
|
1544
|
+
title: `Session failed on ${this.name}`,
|
|
1545
|
+
body: `${this.sessionName(row.id)}: ${note}`,
|
|
1546
|
+
data: { sessionId: row.id, device: this.name },
|
|
1547
|
+
});
|
|
1548
|
+
throw new ApiFault("unavailable", note);
|
|
1549
|
+
}
|
|
1550
|
+
process.emitWarning(
|
|
1551
|
+
`[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs})`,
|
|
1552
|
+
);
|
|
1553
|
+
storage = await openNodeSqliteStorage(row.dbPath); // the ONE retry, on the promoted copy
|
|
1554
|
+
}
|
|
1519
1555
|
const harness = await Harness.open(
|
|
1520
|
-
|
|
1556
|
+
storage,
|
|
1521
1557
|
{
|
|
1522
1558
|
models: this.models,
|
|
1523
1559
|
registry,
|
|
@@ -1895,6 +1931,10 @@ export class Store {
|
|
|
1895
1931
|
h = await this.reopenOnce(row);
|
|
1896
1932
|
} catch (retryError) {
|
|
1897
1933
|
if (isStorageBusy(retryError)) throw storageBusyFault();
|
|
1934
|
+
// R7: a reopen that failed with its own typed fault (a salvage that was
|
|
1935
|
+
// attempted and did not recover) is MORE specific than the recorded
|
|
1936
|
+
// "Session X is unavailable" this path used to re-throw — surface it.
|
|
1937
|
+
if (retryError instanceof ApiFault) throw retryError;
|
|
1898
1938
|
throw e; // the recorded, bounded reason — never the raw storage error
|
|
1899
1939
|
}
|
|
1900
1940
|
}
|
|
@@ -2404,19 +2444,35 @@ export class Store {
|
|
|
2404
2444
|
session: { id: row.id, name: row.name, cwd: row.cwd, model: row.model, createdAt: row.createdAt },
|
|
2405
2445
|
agents: agents.map((a) => ({ id: a.id, name: a.name, kind: a.kind })),
|
|
2406
2446
|
};
|
|
2407
|
-
files.push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
|
|
2408
|
-
files.push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
|
|
2409
2447
|
const opened = this.opened.get(row.id);
|
|
2448
|
+
// R7 memory guard: every entry text is held in RAM at zip time, and the zip
|
|
2449
|
+
// writer adds deflate + base64 copies (≈2-3× raw). Refuse over the raw limit
|
|
2450
|
+
// BEFORE the second copy exists — checked as files accumulate so a huge
|
|
2451
|
+
// transcript also skips the per-agent extras that would follow it.
|
|
2452
|
+
let rawBytes = 0;
|
|
2453
|
+
const push = (entry: ZipEntry) => {
|
|
2454
|
+
rawBytes += Buffer.byteLength(entry.text, "utf8");
|
|
2455
|
+
if (rawBytes > EXPORT_RAW_LIMIT_BYTES) {
|
|
2456
|
+
const mb = (n: number) => `${(n / (1024 * 1024)).toFixed(1)} MiB`;
|
|
2457
|
+
throw invalid(
|
|
2458
|
+
`Export refused: transcripts are ${mb(rawBytes)} of text, over the ${mb(EXPORT_RAW_LIMIT_BYTES)} in-memory limit. ` +
|
|
2459
|
+
`Compact the session first, then export again`,
|
|
2460
|
+
);
|
|
2461
|
+
}
|
|
2462
|
+
files.push(entry);
|
|
2463
|
+
};
|
|
2464
|
+
push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
|
|
2465
|
+
push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
|
|
2410
2466
|
for (const agent of agents) {
|
|
2411
2467
|
const c = opened ? await opened.harness.conversation(agent.id as ConversationId, ctx) : undefined;
|
|
2412
2468
|
if (!c) continue;
|
|
2413
2469
|
const dir = `agents/${agent.id}`;
|
|
2414
|
-
|
|
2470
|
+
push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
|
|
2415
2471
|
const md = await this.transcript(c, "markdown");
|
|
2416
|
-
if (typeof md.text === "string")
|
|
2417
|
-
|
|
2472
|
+
if (typeof md.text === "string") push({ path: `${dir}/transcript.md`, text: md.text });
|
|
2473
|
+
push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
|
|
2418
2474
|
}
|
|
2419
|
-
if (!agents.length)
|
|
2475
|
+
if (!agents.length) push({ path: "README.txt", text: NOT_OPENED_README });
|
|
2420
2476
|
const zip = zipSync(files);
|
|
2421
2477
|
return {
|
|
2422
2478
|
filename: `${slugName(row.name || row.id)}.bundle.zip`,
|
|
@@ -9,6 +9,75 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { statfsSync } from "node:fs";
|
|
11
11
|
import { cpus, loadavg, uptime as osUptime, freemem, totalmem } from "node:os";
|
|
12
|
+
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
13
|
+
|
|
14
|
+
// --- Event-loop lag (R7 perf lane) -----------------------------------------
|
|
15
|
+
//
|
|
16
|
+
// The R6 soak caught the device event loop stalling up to 1.44 s while the
|
|
17
|
+
// paired hub stayed ≤9 ms on the same machine — load-average says "healthy",
|
|
18
|
+
// RTT spikes say "blocked". host loadavg cannot see that (it is host-wide),
|
|
19
|
+
// so vitals carries its own lag numbers. `monitorEventLoopDelay` is a native
|
|
20
|
+
// histogram (one C++ sampler, no JS churn), measurably lighter than a JS
|
|
21
|
+
// setInterval-drift probe and immune to the very stalls it measures.
|
|
22
|
+
|
|
23
|
+
/** One window of lag samples (a 1 s "window" is the worst delay in that second). */
|
|
24
|
+
const LAG_WINDOW = 60;
|
|
25
|
+
const LAG_SAMPLE_MS = 1_000;
|
|
26
|
+
/** Histogram resolution in ms; 20 (the Node default) is plenty — we hunt ≥500 ms stalls. */
|
|
27
|
+
const LAG_RESOLUTION_MS = 20;
|
|
28
|
+
|
|
29
|
+
let lagHistogram: ReturnType<typeof monitorEventLoopDelay> | null = null;
|
|
30
|
+
let lagRing: number[] = [];
|
|
31
|
+
|
|
32
|
+
export interface EventLoopLagVitals {
|
|
33
|
+
/** Worst event-loop delay in the most recent 1 s window, ms (0 before the first window completes). */
|
|
34
|
+
lagMsLast: number;
|
|
35
|
+
/** Worst delay across the last 60 windows (a rolling minute), ms. */
|
|
36
|
+
lagMsMax1m: number;
|
|
37
|
+
/** Windows sampled so far — grows to 60 as the process ages; <60 right after boot. */
|
|
38
|
+
samples: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Start (once; idempotent) the event-loop lag monitor. Called at daemon boot
|
|
43
|
+
* (`main.ts`) so the minute-window has history from the start, and lazily from
|
|
44
|
+
* `deviceVitals()` so any context that only reads vitals still gets numbers.
|
|
45
|
+
*/
|
|
46
|
+
export function startEventLoopMonitor(): void {
|
|
47
|
+
if (lagHistogram) return;
|
|
48
|
+
lagHistogram = monitorEventLoopDelay({ resolution: LAG_RESOLUTION_MS });
|
|
49
|
+
lagHistogram.enable();
|
|
50
|
+
const tick = setInterval(() => {
|
|
51
|
+
const h = lagHistogram;
|
|
52
|
+
if (!h) return;
|
|
53
|
+
// Node's histogram records NANOseconds even though `resolution` is in ms
|
|
54
|
+
// (verified by tests/vitals-lag.test.ts's ms-not-ns bound — 160 ms block
|
|
55
|
+
// read as 168_689_663 before the /1e6).
|
|
56
|
+
lagRing.push(h.max / 1e6); // worst delay since the previous tick, in ms
|
|
57
|
+
h.reset();
|
|
58
|
+
if (lagRing.length > LAG_WINDOW) lagRing.shift();
|
|
59
|
+
}, LAG_SAMPLE_MS);
|
|
60
|
+
tick.unref?.(); // never hold the process open just to keep counting
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The rolling lag window. Starts the monitor on first use. */
|
|
64
|
+
export function eventLoopLag(): EventLoopLagVitals {
|
|
65
|
+
startEventLoopMonitor();
|
|
66
|
+
let max = 0;
|
|
67
|
+
let last = 0;
|
|
68
|
+
for (const v of lagRing) {
|
|
69
|
+
if (v > max) max = v;
|
|
70
|
+
last = v;
|
|
71
|
+
}
|
|
72
|
+
return { lagMsLast: Math.round(last), lagMsMax1m: Math.round(max), samples: lagRing.length };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Stop and forget the monitor (tests; daemon teardown). */
|
|
76
|
+
export function stopEventLoopMonitor(): void {
|
|
77
|
+
lagHistogram?.disable();
|
|
78
|
+
lagHistogram = null;
|
|
79
|
+
lagRing = [];
|
|
80
|
+
}
|
|
12
81
|
|
|
13
82
|
export interface DiskVitals {
|
|
14
83
|
path: string;
|
|
@@ -28,6 +97,8 @@ export interface DeviceVitals {
|
|
|
28
97
|
cpuCount: number;
|
|
29
98
|
memory: { totalBytes: number; freeBytes: number; usedBytes: number; processRssBytes: number; heapUsedBytes: number };
|
|
30
99
|
disk: DiskVitals;
|
|
100
|
+
/** Event-loop lag — the number `loadavg` cannot express: how long ready JS waited to run. */
|
|
101
|
+
eventLoop: EventLoopLagVitals;
|
|
31
102
|
pid: number;
|
|
32
103
|
at: number;
|
|
33
104
|
}
|
|
@@ -65,6 +136,7 @@ export function deviceVitals(diskPath: string, startedAt: number, now = Date.now
|
|
|
65
136
|
heapUsedBytes: memory.heapUsed,
|
|
66
137
|
},
|
|
67
138
|
disk: diskVitals(diskPath),
|
|
139
|
+
eventLoop: eventLoopLag(),
|
|
68
140
|
pid: process.pid,
|
|
69
141
|
at: now,
|
|
70
142
|
};
|
|
@@ -18,6 +18,23 @@ export interface ZipEntry {
|
|
|
18
18
|
text: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* R7 export memory guard. A bundle is built entirely in RAM — raw entry texts,
|
|
23
|
+
* then deflate, then base64 — which the R5 audit measured at ≈2-3× the transcript
|
|
24
|
+
* size held at once (a 13 MB probe already pushed RSS to ~150 MB). Until export
|
|
25
|
+
* streams (R8+), refuse above this ceiling instead of hitting the scale cliff:
|
|
26
|
+
* 32 MiB of raw serialized entries is a transcript nobody has compacted, and the
|
|
27
|
+
* refusal names the size and tells the operator to compact first.
|
|
28
|
+
*/
|
|
29
|
+
export const EXPORT_RAW_LIMIT_BYTES = 32 * 1024 * 1024;
|
|
30
|
+
|
|
31
|
+
/** Total UTF-8 bytes an archive would hold — the "raw" side of the guard (pre-deflate). */
|
|
32
|
+
export function zipRawBytes(entries: readonly ZipEntry[]): number {
|
|
33
|
+
let bytes = 0;
|
|
34
|
+
for (const entry of entries) bytes += Buffer.byteLength(entry.text, "utf8");
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
|
|
21
38
|
const LOCAL_SIG = 0x04034b50;
|
|
22
39
|
const CENTRAL_SIG = 0x02014b50;
|
|
23
40
|
const EOCD_SIG = 0x06054b50;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.61",
|
|
4
4
|
"description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|