Skip to content

statechart: a stop signal that arrives as the worker finishes publishes the output and exits 0 #1353

Backlog

Description

@Absorber97

Since #1292 (0b46ec3), on macOS and Linux killGroup in pstack/skills/statechart/scripts/kill.ts calls process.kill and resolves in the same tick. In statechart.ts, after the worker's exit event, the awaits at lines 130-134 all settle as microtasks, so if (stop) at line 135 runs before Node dispatches a SIGTERM the OS has already queued. The command renames the draft into place and exits 0.

Before #1292, killGroup waited on a /bin/sh child's exit, which gave the event loop a turn. The same signal then exited 143 with "SIGTERM stopped the check, so the command wrote nothing."

Reproduction

Reproduced at ca782ed (0.15.48) on macOS with Node 26.7.0, using the repo's own test/corpus/Login replay fixture. No Java or TLC is needed. The preload sends SIGTERM to the CLI inside the worker's exit event and blocks 50 ms so the signal is queued.

Checkout SIGTERM queued at worker exit Exit Output folder
e1cc031 (0.15.43) no 0 chart.mmd, report.md, tlc.out
e1cc031 (0.15.43) yes 143, "SIGTERM stopped the check, so the command wrote nothing." none
ca782ed (0.15.48) no 0 chart.mmd, report.md, tlc.out
ca782ed (0.15.48) yes 0, empty stderr chart.mmd, report.md, tlc.out

The timing is forced, so this shows the window exists, not how often a real stop lands in it. SIGINT goes through the same handler and flag; I did not run it. Linux, Bun and Deno were not run.

Save the two files below side by side and run:

python3 probe-exit-signal.py head=/path/to/pstack/skills/statechart/scripts
exit-signal-preload.cjs
// Signal only this CLI after the fixture worker has completed, before the CLI
// observes completion. A synchronous pause lets the OS enqueue SIGTERM while
// keeping JS signal handlers from dispatching until control returns.
const childProcess = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const { syncBuiltinESMExports } = require("node:module");

if (path.basename(process.argv[1] || "") === "statechart.ts" && process.env.FIXTURE_EXIT_SIGNAL) {
  const spawn = childProcess.spawn;
  childProcess.spawn = function (file, args, ...rest) {
    const child = spawn.call(this, file, args, ...rest);
    const entry = args.findIndex((arg) => path.basename(arg) === "worker.ts");
    if (entry !== -1) {
      const done = path.join(args[entry + 1], "done");
      child.prependOnceListener("exit", (code, signal) => {
        const ready = fs.existsSync(done);
        if (!ready || code !== 0 || signal) return;
        const sent = process.kill(process.pid, "SIGTERM");
        fs.writeFileSync(process.env.FIXTURE_EXIT_SIGNAL, JSON.stringify({ ready, code, sent }));
        Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
      });
    }
    return child;
  };
  syncBuiltinESMExports();
}
probe-exit-signal.py
"""Usage: probe-exit-signal.py LABEL=SCRIPTS_DIR [LABEL=SCRIPTS_DIR ...]

SCRIPTS_DIR is a `skills/statechart/scripts` folder. Needs only node and
python3: the fixture replays TLC through the checkout's own test/java.ts.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile

PRELOAD = Path(__file__).resolve().parent / "exit-signal-preload.cjs"

for arg in sys.argv[1:]:
    label, _, folder = arg.partition("=")
    scripts = Path(folder).resolve()
    hashes = {
        item: hashlib.sha256((scripts / item).read_bytes()).hexdigest()
        for item in ("statechart.ts", "run.ts", "worker.ts", "kill.ts")
        if (scripts / item).exists()
    }
    fixture = scripts / "test/corpus/Login"
    for send_signal in (False, True):
        with tempfile.TemporaryDirectory(prefix="probe-exit-signal-") as root:
            root = Path(root).resolve()
            out = root / "out"
            scratch = root / "scratch"
            scratch.mkdir()
            marker = root / "signal.json"
            env = {
                "PATH": os.environ["PATH"],
                "TMPDIR": str(scratch),
                "TLA2TOOLS": "unused.jar",
                "JAVA": str(scripts / "test/java.ts"),
                "STATECHART_REPLAY": str(fixture),
                "FIXTURE_EXIT_SIGNAL": str(marker) if send_signal else "",
            }
            result = subprocess.run(
                ["node", "--require", str(PRELOAD),
                    str(scripts / "statechart.ts"), str(fixture / "Login.tla"), "--out", str(out)],
                env=env, text=True, capture_output=True, timeout=30,
            )
            print(json.dumps({
                "version": label,
                "signalTest": send_signal,
                "signalReceipt": json.loads(marker.read_bytes()) if marker.exists() else None,
                "status": result.returncode,
                "stderr": result.stderr,
                "published": sorted(p.name for p in out.iterdir()) if out.exists() else None,
                "scratchEmpty": not any(scratch.iterdir()),
                "sha256": hashes,
            }))

Why the tests stay green

test/cli.test.ts covers a signal while TLC runs and a signal while the command reads TLC's last output. Nothing covers a signal queued at the worker's exit.

Possible fix

Give the event loop one turn after await exited and before reading stop, so a queued signal is dispatched before the publish step. That should restore the earlier behavior on macOS and Linux without bringing /bin/sh back.

Activity

  1. hoangtuan2k5 commented on Nov 27, 2026

    @hoangtuan2k5

    Thanks for the clear reproduction! I reproduced the issue on Linux with Node 22: a signal queued at worker exit still published the output and returned 0.

    I've opened #1354 to let the queued signal be handled before publishing. It adds regression coverage for both SIGINT and SIGTERM, and I also checked SIGTERM against a real TLC run: it exited with 143 and wrote no output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions