Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 103 additions & 26 deletions tests/python-bench-stop.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@
// never reported. The kill printed nothing (`console.error` does not reach a piped stderr before the SIGKILL),
// so the log named no stage. The boot and every `cell()` now carry their own 180 s guard — the row's own
// `timeout` is a timer on the frozen thread and cannot fire — and helpers-fileguard writes its line synchronously.
//
// FOURTH sighting, and the instrument (2026-12-01): #2216's `test (node 26)` hung the same row at the same place —
// "handler=1 beacon=1 stop=1 left2ms=22 answer=0" — and that line's reading was wrong. CPython's emscripten helper
// READS the interrupt slot, stores 0 back, and only then calls `PyErr_SetInterruptEx`, which trips nothing while the
// Python SIGINT handler is ignore/default or does not raise (Modules/signalmodule.c:1898): the probe made the loss
// deterministic with `signal.signal(SIGINT, SIG_IGN)` and with a handler that returns, both RAN-TO-END with the
// slot read. So `left2ms` names a read, never a delivery. The loop row's script now reports, through the chunk
// hook, the SIGINT handler it saw before the beacon, that the beacon print returned, that the loop was reached,
// and any unraisable the interpreter dropped; `wipes` counts run()'s own zeros. The writer's success is the CELL's
// answer, so a stop consumed and not raised fails at its own 15 s line, slots included, instead of reading as a
// landing. The CI state itself (default handler seen locally, hang in CI) is still unexplained; the slots name it
// when it recurs.
import { test, before, after } from "node:test";
import assert from "node:assert";
import path from "node:path";
Expand All @@ -45,11 +57,20 @@ import { armFileGuard } from "./helpers-fileguard.mjs";

/** The guards' account of where a frozen cell had got to, printed in the kill line — three sightings of "cell 2 did
* not finish within 180s" (2026-11-28/29) could not say whether the writer had written at all, never reached its
* beacon, or left the slot and BELIEVED the stop landed. Written by this thread (`handler`, `beacon`, `answer`) and
* by the writer (`stop`, `left2ms`), so the guard reads it with the main thread frozen. */
const PROGRESS = new Int32Array(new SharedArrayBuffer(4 * 5));
const P = { handler: 0, beacon: 1, stop: 2, left2ms: 3, answer: 4 };
const progress = { slots: PROGRESS, names: ["handler", "beacon", "stop", "left2ms", "answer"] };
* beacon, or left the slot and BELIEVED the stop landed. Written by this thread (`handler`, `beacon`, the marker
* prints, `answer`, `wipes`) and by the writer (`stop`, `left2ms`), so the guard reads it with the main thread frozen.
*
* `left2ms` does NOT mean the stop landed (2026-12-01, the CI hang's reading): CPython's emscripten helper reads the
* interrupt buffer, stores 0 back, and only THEN calls `PyErr_SetInterruptEx`, which trips a Python signal only when
* `get_handler(SIGINT)` is neither ignore nor default (signalmodule.c:1898). So the slot leaves 2 whenever the
* interpreter LOOKS at it. The loop row's script therefore records, through the chunk hook, what the kill line needs
* to tell the cases apart: the SIGINT handler it saw before the beacon (`getsig`), that the beacon print returned
* (`prep`), that control reached the loop (`loop`), and whether its own unraisablehook saw a dropped signal
* (`unraisable`). `wipes` counts the runtime's own store of 0 (`python-worker.ts` `clearInterrupt`, run()'s start and
* finally — the only writer of 0 in the product): a hang with `wipes=1` is a hang with no wipe of its own. */
const PROGRESS = new Int32Array(new SharedArrayBuffer(4 * 10));
const P = { handler: 0, beacon: 1, getsig: 2, prep: 3, loop: 4, unraisable: 5, stop: 6, left2ms: 7, answer: 8, wipes: 9 };
const progress = { slots: PROGRESS, names: ["handler", "beacon", "getsig", "prep", "loop", "unraisable", "stop", "left2ms", "answer", "wipes"] };

// Armed at module load, before `before()` — the boot is the gap the per-test writers cannot see (header, 2026-11-14).
// The last resort; the per-phase guards below fire first and name their phase.
Expand Down Expand Up @@ -101,6 +122,15 @@ const flag = new Int32Array(new SharedArrayBuffer(4));
// thread. The writer thread polls it; `cell`'s own poll cannot, a WASM loop freezes it for the whole script.
const beaconFlag = new Int32Array(new SharedArrayBuffer(4));

// Every zero the runtime itself writes into the stop slot, counted where it happens: `clearInterrupt` is the only
// writer of 0 in the product (`python-worker.ts`: `Atomics.store(interruptFlag, 0, 0)`), so this counts run()'s start
// and finally wipes and nothing else. Patched in this realm only — the writer thread has its own `Atomics`.
const realAtomicsStore = Atomics.store;
Atomics.store = (arr, idx, val) => {
if (arr === flag && idx === 0 && val === 0) PROGRESS[P.wipes] += 1;
return realAtomicsStore(arr, idx, val);
};

/**
* The writer thread's source — `stopOnBeacon` runs it, and the backstop row runs the SAME string under a
* `spawnSync` child, so the kill it asserts is the kill the rows rely on.
Expand All @@ -109,14 +139,17 @@ const WRITER_SRC = `
const { workerData } = require('node:worker_threads');
const a = new Int32Array(workerData.sab);
const beacon = new Int32Array(workerData.beacon);
// The caller's progress slots, when it keeps any: whether this thread wrote at all (stop), and how long after it
// started it left the loop (left2ms, 0 while still spinning). A guard that freezes the main thread reads these.
// The caller's progress slots, when it keeps any: whether this thread wrote at all (stop), how long after it
// started the slot was READ (left2ms, 0 while never read), and whether the CELL answered (answer). A guard that
// freezes the main thread reads these.
const st = workerData.progress ? new Int32Array(workerData.progress) : null;
const at = workerData.at;
const names = workerData.names ?? [];
const t0 = Date.now();
const deadline = t0 + workerData.failAfterMs;
let written = false;
let success = false;
let left2ms = 0;
while (Date.now() < deadline) {
if (!written) {
if (Atomics.load(beacon, 0)) { // the script's beacon printed: its blocking section is running
Expand All @@ -128,15 +161,31 @@ const WRITER_SRC = `
}
continue;
}
if (Atomics.load(a, 0) !== 2) { success = true; if (st) Atomics.store(st, at.left2ms, Date.now() - t0); break; } // the end wipe cleared it: the stop landed
Atomics.wait(a, 0, 2, 5); // sleep while the slot still holds 2: the end wipe wakes us
if (Atomics.load(a, 0) !== 2) {
// The slot was READ. NOT proof the stop landed (2026-12-01): CPython's emscripten helper zeroes the slot
// when it looks at it and only then asks PyErr_SetInterruptEx, which trips nothing while the script owns
// SIGINT — the CI hang's left2ms=22 was a read with no delivery. Success is the CELL answering.
if (!left2ms) { left2ms = Date.now() - t0; if (st) Atomics.store(st, at.left2ms, left2ms); }
if (!st) break; // no slots (the backstop child): a read is all it can judge
Atomics.wait(st, at.answer, 0, 5); // sleep until the cell answers, or 5 ms — the deadline still turns
if (Atomics.load(st, at.answer)) { success = true; break; }
continue;
}
Atomics.wait(a, 0, 2, 5); // sleep while the slot still holds 2: the reader wakes us
}
if (!success) {
// The line names WHICH case: never reached the beacon, the slot was read and the script did not end (a stop
// consumed and lost, or a loop that cannot end), or the slot was never read (inside C, or the script ended
// without its reader running). The slots after it are the frozen thread's account (the file guard's account).
const slots = st ? names.map((n, i) => ' ' + n + '=' + Atomics.load(st, i)).join('') : '';
const why = !written
? 'python-bench-stop: the script never reached its beacon within ' + workerData.failAfterMs + 'ms'
: 'python-bench-stop: the stop never ended the script within ' + workerData.failAfterMs + 'ms';
require('node:fs').writeSync(2, why + '\\n'); // synchronous: the SIGKILL below ends the process in this
// turn, and a piped stderr written on the event loop loses the line
? 'the script never reached its beacon within ' + workerData.failAfterMs + 'ms'
: left2ms
? 'the slot was READ at ' + left2ms + 'ms and the script never ended within ' + workerData.failAfterMs + 'ms'
: 'the slot still held 2 at ' + workerData.failAfterMs + 'ms: the interpreter never looked at it';
require('node:fs').writeSync(2, 'python-bench-stop: ' + why + slots + '\\n'); // synchronous: the SIGKILL
// below ends the process in this turn, and a piped stderr written
// on the event loop loses the line
process.kill(process.pid, 'SIGKILL'); // process.exit() on a worker thread ends only the THREAD —
// measured 2026-11-09: a blocked main thread outlives it and
// the process exits 0. SIGKILL takes the process down loud.
Expand All @@ -158,10 +207,15 @@ before(async () => {
location: { href: pathToFileURL(shim + "/").href },
postMessage: (m) => {
posted.push(m);
if (m.partial && typeof m.chunk === "string" && m.chunk.includes(BEACON)) {
Atomics.store(beaconFlag, 0, 1);
Atomics.store(PROGRESS, P.beacon, 1);
}
if (!m.partial || typeof m.chunk !== "string") return;
// The markers the loop row's script prints, each recorded while the main thread is still inside the
// print that wrote it — the only place a frozen thread's account can be taken (see `P`).
const c = m.chunk;
if (c.includes(BEACON)) { Atomics.store(beaconFlag, 0, 1); Atomics.store(PROGRESS, P.beacon, 1); }
if (c.includes("WML-GETSIG")) Atomics.store(PROGRESS, P.getsig, c.includes("default_int_handler") ? 1 : 2);
if (c.includes("WML-PRE-LOOP")) Atomics.store(PROGRESS, P.prep, 1);
if (c.includes("WML-IN-LOOP")) Atomics.store(PROGRESS, P.loop, 1);
if (c.includes("WML-UNRAISABLE")) Atomics.store(PROGRESS, P.unraisable, 1);
},
addEventListener: (type, fn) => { if (type === "message") handler = fn; },
});
Expand All @@ -182,11 +236,11 @@ async function cell(code) {
const id = nextId++;
// The handler runs the script on THIS thread: a cell that freezes it cannot be ended by the row's timer, so
// the guard names the cell and SIGKILLs 180 s in (2026-11-19, run 44519875129: the one gap with no writer).
// ALL five slots are cleared: a cell that arms no writer must not print the previous writer's `stop=1 left2ms=N`
// ALL slots are cleared: a cell that arms no writer must not print the previous writer's `stop=1 left2ms=N`
// in its kill line, which is the "wrote and believed it landed" reading this exists to rule in or out (janitor-2,
// comment 7261548549). Safe for a writer's own cell: it writes only after the beacon, inside the script below.
Atomics.store(PROGRESS, P.handler, 0); Atomics.store(PROGRESS, P.beacon, 0); Atomics.store(PROGRESS, P.answer, 0);
Atomics.store(PROGRESS, P.stop, 0); Atomics.store(PROGRESS, P.left2ms, 0);
// comment 7261548549). `wipes` restarts from this cell's posting, so its kill line counts only this cell's own
// zeros. Safe for a writer's own cell: it writes only after the beacon, inside the script below.
for (const k of Object.values(P)) Atomics.store(PROGRESS, k, 0);
const disarm = armFileGuard({ budgetMs: CELL_GUARD_MS, label: "python-bench-stop: cell " + id, state: progress });
try {
Atomics.store(PROGRESS, P.handler, 1); // this call does not return until the script has ended
Expand All @@ -212,16 +266,18 @@ async function cell(code) {
*
* The same thread WATCHES: if the script never reached its beacon, or the stop never ended it, `failAfterMs` later
* it `SIGKILL`s the PROCESS — its deadline is `Date.now()` checked inside an `Atomics.wait` sleep, not a `setTimeout`,
* so a main thread spinning in WASM cannot starve the clock (2026-11-12). The product's own bound is
* `BENCH_STOP_KILL_MS` in offscreen.ts — this test drives the worker's handler directly and so does not get that
* kill — and `process.exit(1)` on a worker thread is inert (janitor-3's measurement, 2026-11-09).
* so a main thread spinning in WASM cannot starve the clock (2026-11-12). "Ended" is the CELL's answer (`P.answer`),
* never the slot leaving 2: the slot leaves 2 when the interpreter merely READS it (see `P`), so a stop consumed and
* never raised still fails loud here, with the slots in the line, instead of being read as a landing. The product's
* own bound is `BENCH_STOP_KILL_MS` in offscreen.ts — this test drives the worker's handler directly and so does not
* get that kill — and `process.exit(1)` on a worker thread is inert (janitor-3's measurement, 2026-11-09).
*/
function stopOnBeacon({ failAfterMs = 15_000 } = {}) {
Atomics.store(beaconFlag, 0, 0);
Atomics.store(PROGRESS, P.stop, 0);
Atomics.store(PROGRESS, P.left2ms, 0);
const w = new Worker(WRITER_SRC,
{ eval: true, workerData: { sab: flag.buffer, beacon: beaconFlag.buffer, failAfterMs, progress: PROGRESS.buffer, at: P } });
{ eval: true, workerData: { sab: flag.buffer, beacon: beaconFlag.buffer, failAfterMs, progress: PROGRESS.buffer, at: P, names: progress.names } });
return () => w.terminate();
}

Expand Down Expand Up @@ -322,12 +378,33 @@ test("a stop written while a Python loop runs ends it with KeyboardInterrupt, an
let r, t0;
try {
t0 = Date.now();
r = await cell(`print('${BEACON}')\nwhile True:\n pass`);
// The CI shape (`while True: pass`) plus what the kill line needs to tell its cases apart, all through the
// chunk hook: the SIGINT handler the script sees, the beacon, the print that follows it, and the loop's
// first iteration. The unraisablehook is the only way to SEE the interpreter drop a tripped signal (the
// default hook would write into the cell's captured stderr, which a hang never returns).
r = await cell([
"import signal, sys",
"sys.unraisablehook = lambda u: print('WML-UNRAISABLE', repr(u.exc_value), flush=True)",
"print('WML-GETSIG', repr(signal.getsignal(signal.SIGINT)), flush=True)",
`print('${BEACON}', flush=True)`,
"print('WML-PRE-LOOP', flush=True)",
"_i = 0",
"while True:",
" _i += 1",
" if _i == 1:",
" print('WML-IN-LOOP', flush=True)",
].join("\n"));
} finally {
done(); // the writer is spent (one write), and its backstop must not outlive the row
}
assert.match(text(r), /KeyboardInterrupt/, JSON.stringify(r).slice(0, 400));
assert.ok(Date.now() - t0 < 10000, "the loop ended on the stop, not on anything slower");
// The instrument, on the row that hangs in CI: any of these failing names the state a recurrence is in.
assert.equal(Atomics.load(PROGRESS, P.getsig), 1, "the SIGINT handler at the beacon was default_int_handler, the one PyErr_SetInterruptEx can trip");
assert.equal(Atomics.load(PROGRESS, P.prep), 1, "the beacon print returned: the pre-loop print ran");
assert.equal(Atomics.load(PROGRESS, P.loop), 1, "control reached the loop's first iteration");
assert.equal(Atomics.load(PROGRESS, P.unraisable), 0, "no signal was dropped as unraisable during the spin");
assert.equal(Atomics.load(PROGRESS, P.wipes), 2, "run()'s start and end wipes are the only zeros the slot saw");
assert.ok(vars(r).includes("kept_before"), `the kept namespace is listed: ${vars(r)}`);
assert.match(text(await cell("print(kept_before + 1)")), /42/, "and the next script reads it");
// And that next cell, which arms no writer, did not inherit the spent writer's slots in its kill line.
Expand Down
14 changes: 14 additions & 0 deletions tests/python-lease-offscreen.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ test("PY_CANCEL kills the sandbox when the interrupt does not land in time, and
assert.equal(a.stopped, "restarted");
});

test("a cell whose script swallowed the stop still ends at the backstop, and the message does not blame a C function", { todo: "open (2026-12-01): CPython's emscripten helper zeroes the interrupt slot when it READS it, and PyErr_SetInterruptEx trips nothing while the Python SIGINT handler is ignore/default or does not raise (signalmodule.c:1898; the python-bench-stop probe made both shapes deterministic), so a script's own `signal.signal(SIGINT, SIG_IGN)` makes every Stop cost the namespace — and CELL_STOP_KILLED tells the person and the model it was 'most likely inside a C function'. The offscreen document owns the flag and can tell the two apart at kill time (still 2: the interpreter never looked, a C call; read to 0: consumed and not raised, the script's handler); the message must say which. Owner: flaky-ci" }, async () => {
const { cell, w, answer } = await leased();
const cancel = send({ type: "PY_CANCEL", cell });
await tick();
assert.equal(Atomics.load(w.flag, 0), 2, "SIGINT written into the cell's worker");
Atomics.store(w.flag, 0, 0); // the interpreter read it at its next periodic check: the helper zeroes before it decides
assert.deepEqual(await cancel, { how: "killed" }, "the cell still ends, at the backstop");
assert.equal(w.terminated, true);
const a = await answer;
assert.equal(a.stopped, "restarted");
assert.match(a.error, /names are lost/, "the cost stays stated");
assert.doesNotMatch(a.error, /inside a C function/, `the message names no cause it does not know: ${a.error}`);
});

test("PY_CANCEL before the cell started interrupts it as it starts", async () => {
const { cell, post, w } = await leased({ started: false });
const cancel = send({ type: "PY_CANCEL", cell });
Expand Down
6 changes: 6 additions & 0 deletions tests/python-lease.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,12 @@ test("task cancel answered 'killed' says the names are lost and names the interr
await done(c);
});

test("a cancel answered 'killed' names no cause the sandbox did not report: a stop the script swallowed is not 'inside a C function'", { todo: "open (2026-12-01): PY_CANCEL's answer is `how` alone, so pyCancelText('killed') asserts 'most likely inside a C function' for every kill — including one the interpreter READ and the script's own SIGINT handler swallowed (signalmodule.c:1898; the python-bench-stop probe made both shapes deterministic). The offscreen document owns the interrupt flag and can tell the cases apart at kill time; the answer must carry that reason and this text use it. Owner: flaky-ci" }, () => {
const text = pyCancelText("killed");
assert.match(text, /names are lost/, "the cost stays stated");
assert.doesNotMatch(text, /inside a C function/, `the model's sentence names no cause the sandbox did not report: ${text}`);
});

test("task cancel answered 'ended' does not mark the task cancelled: a result that follows is a done task", T, async () => {
const c = await detached();
cancelHow = "ended";
Expand Down
Loading