@andares/pi-toolkits 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,215 +0,0 @@
1
- /**
2
- * quit-guard feature — independent-thread hard kill.
3
- *
4
- * Why this exists (2026-11-13, real hang, pid 398960): the guard fired,
5
- * wrote its report, printed "forcing exit" and called `process.exit(0)` —
6
- * and the process stayed alive for 18+ minutes (`futex_wait`, PPID=1, its
7
- * pty already deleted by the user closing the terminal window). The exit
8
- * path runs host code (`process.on("exit")` listeners, graceful-fs patches,
9
- * stdio flush) and can deadlock synchronously. Any fallback scheduled on
10
- * the event loop (`setTimeout`) is dead the moment the main thread blocks:
11
- * a timer cannot fire inside a dead loop.
12
- *
13
- * Two watchdogs, both on `worker_threads` (an independent OS thread that
14
- * keeps running while the main thread is blocked):
15
- *
16
- * 1. `armThreadHardKill(delayMs)` — the last-resort layer of fire(): after
17
- * the report is on disk and "forcing exit" has been printed, kill the
18
- * process `delayMs` later no matter what `process.exit(0)` did.
19
- *
20
- * 2. `armThreadWatchdog({ deadlineMs, ... })` — armed when the guard arms
21
- * (teardown marker / shutdown event), covering the blind spot the
22
- * main-loop timer has: a main thread that deadlocks BEFORE the fire
23
- * deadline (e.g. synchronously inside `process.exit` right after a fast
24
- * dispose) never runs the fire timer at all. The main loop must prove
25
- * liveness with a heartbeat (a 1 Hz counter in shared memory). The
26
- * worker waits out `deadlineMs` (+ a head start for the main-loop fire
27
- * timer, which handles the common hangs with full context: raw-mode
28
- * probe, report, restore), then samples the heartbeat twice. Still
29
- * beating → the event loop is alive → step aside (the fire timer owns
30
- * the outcome, including its stray-marker protection). Stopped → the
31
- * main loop can never fire → the worker restores the terminal, writes a
32
- * minimal report and SIGKILLs. This kills exactly-and-only a main
33
- * thread that is alive as a process but dead as an event loop.
34
- *
35
- * Failure policy: if a Worker cannot even be constructed, degrade to a
36
- * no-op — the fire path still has its `setTimeout` fallback, and a killer
37
- * that breaks the arm/fire sequence is worse than no extra killer.
38
- */
39
- import { Worker } from "node:worker_threads";
40
-
41
- /**
42
- * Start a watchdog thread that SIGKILLs this process after `delayMs`.
43
- *
44
- * Returns a `cancel()` that terminates the worker. Cancelling only matters
45
- * on the "process.exit threw synchronously" path, where fire() recovers and
46
- * performs its own synchronous kill; on every healthy path the process dies
47
- * with the main thread and the worker is never heard from again.
48
- */
49
- export function armThreadHardKill(delayMs: number): () => void {
50
- let worker: Worker;
51
- try {
52
- worker = new Worker(
53
- `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${Math.max(
54
- 0,
55
- delayMs,
56
- )});
57
- process.kill(process.pid, "SIGKILL");`,
58
- { eval: true },
59
- );
60
- } catch {
61
- // Could not start the watchdog thread (resource exhaustion, ...):
62
- // degrade to the setTimeout fallback instead of breaking the fire path.
63
- return () => {};
64
- }
65
- // The worker must never keep the process alive on its own: its only job
66
- // is to end it.
67
- worker.unref();
68
- return () => {
69
- try {
70
- void worker.terminate();
71
- } catch {
72
- // terminate() returns a promise that can only reject if the worker
73
- // is already gone; either way this process is about to exit.
74
- }
75
- };
76
- }
77
-
78
- /** Handle returned by {@link armThreadWatchdog}. */
79
- export interface ThreadWatchdog {
80
- /** Record one main-loop heartbeat tick (idempotent per tick). */
81
- heartbeat(): void;
82
- /** Disarm: the main loop owns the outcome from here on. */
83
- cancel(): void;
84
- }
85
-
86
- export interface ThreadWatchdogOptions {
87
- /** Guard deadline (ms) the main-loop fire timer is armed with. */
88
- readonly deadlineMs: number;
89
- /**
90
- * Grace after the deadline before the first heartbeat sample (ms), so
91
- * the main-loop fire timer — which handles hangs with full context —
92
- * always gets the first shot.
93
- */
94
- readonly headStartMs?: number;
95
- /** Gap between the two heartbeat samples (ms). Default 1500. */
96
- readonly sampleMs?: number;
97
- /** Terminal restore written before the watchdog's kill. */
98
- readonly restore?: string;
99
- /** Directory for the minimal deadlock report; omit to skip the report. */
100
- readonly reportDir?: string;
101
- /** PI_QUIT_GUARD_DEBUG path, appended to from the worker on a kill. */
102
- readonly debugPath?: string;
103
- }
104
-
105
- /**
106
- * Cells of the shared heartbeat buffer: [0] = heartbeat ticks (written by
107
- * the main loop, never waited on), [1] = signal (0 = armed, 1 = cancelled;
108
- * the only cell the worker waits on — Atomics.wait's third argument is the
109
- * EXPECTED value, so waiting on the heartbeat cell, which changes on every
110
- * tick, would return "not-equal" immediately and fake a deadlock).
111
- */
112
- const CELL_HEARTBEAT = 0;
113
- const CELL_SIGNAL = 1;
114
-
115
- const WATCHDOG_SOURCE = `
116
- (function () {
117
- const { workerData } = require("node:worker_threads");
118
- const { writeSync, writeFileSync, mkdirSync, appendFileSync } = require("node:fs");
119
- const cells = workerData.cells;
120
- const cancelFlag = () => Atomics.load(cells, ${CELL_SIGNAL}) === 1;
121
- // Phase 1: wait out the deadline plus the main-loop timer's head start.
122
- Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.deadlineMs + workerData.headStartMs);
123
- if (cancelFlag()) return;
124
- // Phase 2: sample the heartbeat twice. A loop that is merely slow still
125
- // ticks; a loop that is blocked cannot.
126
- const first = Atomics.load(cells, ${CELL_HEARTBEAT});
127
- Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.sampleMs);
128
- if (cancelFlag()) return;
129
- if (Atomics.load(cells, ${CELL_HEARTBEAT}) !== first) return;
130
- // Phase 3: deadlocked. Restore the terminal, leave a minimal trace, kill.
131
- try { writeSync(1, workerData.restore); } catch {}
132
- try {
133
- mkdirSync(workerData.reportDir, { recursive: true });
134
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
135
- writeFileSync(
136
- workerData.reportDir + "/quit-hang-" + ts + "-" + process.pid + "-thread.json",
137
- JSON.stringify(
138
- {
139
- version: 1,
140
- kind: "quit-guard",
141
- source: "thread-watchdog",
142
- timestamp: new Date().toISOString(),
143
- pid: process.pid,
144
- timeoutMs: workerData.deadlineMs,
145
- elapsedMs: workerData.deadlineMs + workerData.headStartMs + workerData.sampleMs,
146
- marker: "heartbeat-stopped",
147
- note: "main event loop stopped beating during shutdown; killed from the watchdog thread (main-loop fire timer could never run)",
148
- },
149
- null,
150
- "\\t",
151
- ) + "\\n",
152
- );
153
- } catch {}
154
- try {
155
- writeSync(2, "[pi-toolkits/quit-guard] main loop stopped during shutdown (no heartbeat for " + workerData.sampleMs + "ms after the " + (workerData.deadlineMs + workerData.headStartMs) + "ms deadline); killing from the watchdog thread.\\n");
156
- } catch {}
157
- try {
158
- if (workerData.debugPath) appendFileSync(workerData.debugPath, new Date().toISOString() + " thread-kill heartbeat-stopped deadline=" + workerData.deadlineMs + "\\n");
159
- } catch {}
160
- process.kill(process.pid, "SIGKILL");
161
- })();
162
- `;
163
-
164
- /**
165
- * Arm the arm-time watchdog. See the module comment for the protocol.
166
- *
167
- * The returned handle is deliberately passive: an owner that forgets to
168
- * cancel merely keeps one unref'd worker alive for the rest of the process
169
- * — which the deadline then ends (heartbeat still beating → the worker
170
- * steps aside; heartbeat stopped → the process was dead anyway).
171
- */
172
- export function armThreadWatchdog(
173
- options: ThreadWatchdogOptions,
174
- ): ThreadWatchdog {
175
- const cells = new Int32Array(new SharedArrayBuffer(8));
176
- let worker: Worker;
177
- try {
178
- worker = new Worker(WATCHDOG_SOURCE, {
179
- eval: true,
180
- workerData: {
181
- cells,
182
- deadlineMs: Math.max(0, options.deadlineMs),
183
- headStartMs: Math.max(0, options.headStartMs ?? 500),
184
- sampleMs: Math.max(0, options.sampleMs ?? 1_500),
185
- restore: options.restore ?? "",
186
- reportDir: options.reportDir ?? "",
187
- debugPath: options.debugPath ?? "",
188
- },
189
- });
190
- } catch {
191
- // No watchdog thread: the guard degrades to its main-loop timer,
192
- // exactly the behavior that existed before this layer.
193
- return { heartbeat: () => {}, cancel: () => {} };
194
- }
195
- worker.unref();
196
- let beats = 0;
197
- return {
198
- heartbeat: () => {
199
- Atomics.store(cells, CELL_HEARTBEAT, ++beats);
200
- },
201
- cancel: () => {
202
- // Flag first so a worker whose terminate() has not landed yet
203
- // stops at its next check; notify so it wakes now (the signal cell
204
- // is the only one the worker waits on); terminate so the thread
205
- // goes away even mid-phase-1.
206
- Atomics.store(cells, CELL_SIGNAL, 1);
207
- Atomics.notify(cells, CELL_SIGNAL);
208
- try {
209
- void worker.terminate();
210
- } catch {
211
- // Already gone.
212
- }
213
- },
214
- };
215
- }