From 72fe49f5cb3e79c443a8a0f8b40f73035faecdd7 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Sat, 3 Oct 2026 17:39:58 +0200 Subject: [PATCH] ci: the offline suite is judged by what its own processes leave running The step compared every listener of the machine before and after the suite, and failed twice on the reference box on 2026-10-03 for ports opened or closed while the suite ran: VS Code's own log named one of the first two, and a per-second log of every listener and its owner named VS Code for both of the second, a run in which the suite left nothing. The suite now runs under tests/suite_reaper.py, a child subreaper (prctl PR_SET_CHILD_SUBREAPER): every process it starts stays its descendant whatever session or environment it gives itself, so what is still running once the suite is over (after a 5 s grace) is the suite's own: named with its listening sockets, stopped, and fatal to the step, a process left running without a socket included. Other programs' listeners are shown with their owner, and fail the step on a GitHub runner only, where nothing else runs. tests/test_suite_reaper.py: 8 tests, an orphaned listener, one under setsid with an empty environment, a process without a socket, one on its way out, another program's listener; they fail with the subreaper bit or the grace taken out. The step passed on the reference box with VS Code connected. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 34 +++++--- CHANGELOG.md | 11 +++ TESTING.md | 18 +++-- tests/suite_reaper.py | 160 +++++++++++++++++++++++++++++++++++++ tests/test_suite_reaper.py | 119 +++++++++++++++++++++++++++ 5 files changed, 324 insertions(+), 18 deletions(-) create mode 100644 tests/suite_reaper.py create mode 100644 tests/test_suite_reaper.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aaed9939..153f0fc7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -250,14 +250,22 @@ jobs: export PYTHONPATH="$probe" QWEN38_CONTACT_LOG="$probe/contacts" QWEN38_SERVING_PORTS=30000,30001,30020,30090,30091,4096 before="$(find "$witness" -type f -exec sha256sum {} + | sort)" ports_before="$(ss -Htln 2>/dev/null | awk '{print $4}' | sort || true)" + # The suite runs under tests/suite_reaper.py, a child subreaper: every process it + # starts stays its descendant, so what still runs once the suite is over is the + # suite's own, named with the sockets it listens on, then stopped. Comparing every + # listener of the machine instead failed twice on the reference box on 2026-10-03, + # for ports VS Code opened while the suite ran. + cat > "$probe/suite.sh" <<'SH' (cd dashboard && python3 -m unittest \ $(cd tests && ls test_*.py | sed 's/\.py$//' | sed 's/^/tests./' | tr '\n' ' ') \ 2>&1 | tail -3) # a file that fails says how: a red run of 2026-10-03 said only # "tests/test_proxy_hold.py failed", and left nothing to read - (for f in tests/test_*.py; do - out="$(python3 "$f" 2>&1)" || { echo "$f failed, the end of its output:"; printf '%s\n' "$out" | tail -60; exit 1; } - done) + for f in tests/test_*.py; do + out="$(python3 "$f" 2>&1)" || { echo "$f failed, the end of its output:"; printf '%s\n' "$out" | tail -60; exit 1; } + done + SH + python3 tests/suite_reaper.py bash -e "$probe/suite.sh" after="$(find "$witness" -type f -exec sha256sum {} + | sort)" if [ "$before" != "$after" ]; then echo "the offline suite wrote into HOME:" @@ -265,20 +273,24 @@ jobs: exit 1 fi ports_after="$(ss -Htln 2>/dev/null | awk '{print $4}' | sort || true)" - [ "$ports_before" = "$ports_after" ] || { - echo "the offline suite left a listening socket behind:" - diff <(echo "$ports_before") <(echo "$ports_after") || true - echo "(on the CI runner this is the suite. Running ci-local.sh ON a serving box," - echo " an engine or cockpit finishing its boot mid-suite shows up here too: check" - echo " whether the port that appeared is one of this repo's own before digging.)" - exit 1; } + if [ "$ports_before" != "$ports_after" ]; then + # Not the suite's: the reaper above names and stops those. Another program + # opened or closed a port meanwhile; shown, and fatal on a runner only, where + # nothing else runs. + echo "listeners other programs opened (>) or closed (<) while the suite ran:" + diff <(echo "$ports_before") <(echo "$ports_after") | grep '^[<>]' || true + for addr in $(comm -13 <(echo "$ports_before") <(echo "$ports_after")); do + ss -Htlnp "sport = :${addr##*:}" 2>/dev/null | awk '{print " held by:", $4, $6}' + done + [ "${GITHUB_ACTIONS:-}" != "true" ] || { echo "(nothing else runs on a runner)"; exit 1; } + fi if [ -s "$probe/contacts" ]; then echo "the offline suite contacted a serving port:" sort "$probe/contacts" | uniq -c | sort -rn | head -20 exit 1 fi rm -rf "$witness" "$probe" - echo " ok: HOME untouched, no socket left listening, no serving port contacted" + echo " ok: HOME untouched, nothing left running or listening, no serving port contacted" - name: Coverage floors (measured, per module) run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 86a4be4c..9890025b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,17 @@ local run and written over by any second run beside it: they now go under `${TMP and a new step fails the workflow on a fixed path in /tmp. A full local run now leaves /tmp as it found it. Nothing changes on GitHub's runners, which set no TMPDIR and start empty. +The step that checks the offline suite leaves nothing behind compared every listener of the +machine before and after the suite, and failed twice on the reference box on 2026-10-03 for +ports opened or closed while the suite ran: VS Code's own log named one of the first two, and +a log of every listener and its owner, kept each second, named VS Code for both of the +second, a run in which the suite itself left nothing. The suite now runs under +`tests/suite_reaper.py`, a child subreaper: every process it starts stays its descendant, +whatever session or environment that process gives itself, so what still runs once the suite +is over is the suite's own. It is named with the sockets it listens on, stopped, and fails +the step, a process left running without a socket included. Other programs' listeners are +shown, and fail the step on a GitHub runner only, where nothing else runs. + TESTING.md said what `ci-local.sh` did two versions ago: it now says where the test venv is looked for (`QWEN38_TEST_PYTHON` first, which a fresh clone needs, or the four steps that use `coverage` or `hypothesis` are skipped), how a step is skipped (a missing tool it calls, a diff --git a/TESTING.md b/TESTING.md index 222e5e20..0d54d72f 100644 --- a/TESTING.md +++ b/TESTING.md @@ -465,10 +465,14 @@ the hole, a conditional is both branches. systemctl, no real API key. That is a **checked property**, not an intention, because these tests are run on the machine that serves production: the CI step "The offline suite touches nothing outside itself" gives the suite a witness - `HOME`, hashes every file in it before and after, and compares the listening - sockets on both sides. It earned its place immediately by catching - `test_cockpit_code.py` writing `cockpit-secret` into the developer's own - `~/.config/qwen38`, because importing `cockpit.py` persists an HMAC secret (so - a service restart does not log every browser out) and that suite had not - redirected `COCKPIT_CONFIG_DIR`. `test_cockpit_collectors.py` adds the other - half by recording every argv its stub was asked for. + `HOME`, hashes every file in it before and after, and runs the suite under + `tests/suite_reaper.py`, a child subreaper: whatever the suite's processes + leave running, listening or not, is theirs to answer for, while an editor that + opens a port meanwhile is not (comparing every listener of the machine failed + twice on 2026-10-03 while VS Code opened and closed ports). It earned its + place immediately by catching `test_cockpit_code.py` writing `cockpit-secret` + into the developer's own `~/.config/qwen38`, because importing `cockpit.py` + persists an HMAC secret (so a service restart does not log every browser out) + and that suite had not redirected `COCKPIT_CONFIG_DIR`. + `test_cockpit_collectors.py` adds the other half by recording every argv its + stub was asked for. diff --git a/tests/suite_reaper.py b/tests/suite_reaper.py new file mode 100644 index 00000000..eb460596 --- /dev/null +++ b/tests/suite_reaper.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Run a command as a child subreaper, and report what it leaves running. + +Usage: tests/suite_reaper.py COMMAND [ARG...] + +The offline suite is run on the box that serves production, so "it leaves no +listening socket behind" was checked by comparing every listener on the machine +before and after it. On 2026-10-03 that failed twice on the reference box for +ports VS Code opened and closed while the suite ran, the second time while the +suite itself left nothing: a comparison of the whole machine cannot tell the +suite from an editor. + +This process makes itself a child subreaper (prctl PR_SET_CHILD_SUBREAPER), so +every process the command starts, and every orphan of those, stays one of its +descendants, whatever session or environment it gave itself. What is still +running once the command is over (after a short grace for processes on their +way out) is therefore the command's own: each such process is reported, with +the sockets it listens on, then stopped. + +Exit status: the command's own when it failed, 3 when it left a process +running, 2 on a usage or setup error, 0 otherwise. +""" +import ctypes +import os +import re +import signal +import subprocess +import sys +import time + +PR_SET_CHILD_SUBREAPER = 36 +# How long a process the command started may take to exit once it is over. Read +# here so the tests can shorten it. +GRACE_S = float(os.environ.get("SUITE_REAPER_GRACE_S", "5")) + + +def reap(): + """Collect every child that has exited, orphans handed to us included.""" + while True: + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + return + if pid == 0: + return + + +def descendants(root): + """The live processes under root, from /proc (a zombie holds nothing).""" + parent = {} + for name in os.listdir("/proc"): + if not name.isdigit(): + continue + try: + with open(f"/proc/{name}/stat") as f: + stat = f.read() + except OSError: + continue # gone between the listing and the read + # The command name may hold spaces and parentheses: fields start after the last ")". + fields = stat[stat.rindex(")") + 2:].split() + if fields[0] != "Z": + parent[int(name)] = int(fields[1]) + found = [] + for pid in parent: + up = parent[pid] + while up in parent and up != root: + up = parent[up] + if up == root: + found.append(pid) + return sorted(found) + + +def listening(pids): + """{pid: [local address, ...]} for the TCP listeners these processes hold.""" + out = subprocess.run(["ss", "-Htlnp"], capture_output=True, text=True).stdout + held = {} + for line in out.splitlines(): + cols = line.split() + if len(cols) < 4: + continue + for pid in {int(p) for p in re.findall(r"pid=(\d+)", line)} & set(pids): + held.setdefault(pid, []).append(cols[3]) + return held + + +def command_line(pid): + try: + with open(f"/proc/{pid}/cmdline", "rb") as f: + text = f.read().replace(b"\0", b" ").decode(errors="replace").strip() + except OSError: + return "(exited)" + return text[:160] or "(no command line)" + + +def stop(pids): + """SIGTERM, a moment to exit, then SIGKILL for what is left.""" + for sig, wait in ((signal.SIGTERM, 3.0), (signal.SIGKILL, 1.0)): + for pid in pids: + try: + os.kill(pid, sig) + except ProcessLookupError: + pass + deadline = time.monotonic() + wait + while time.monotonic() < deadline: + reap() + pids = [p for p in pids if p in descendants(os.getpid())] + if not pids: + return + time.sleep(0.1) + + +def main(argv): + if not argv: + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0: + print(f"suite_reaper: prctl(PR_SET_CHILD_SUBREAPER) failed, errno {ctypes.get_errno()}", + file=sys.stderr) + return 2 + child = os.fork() + if child == 0: + try: + os.execvp(argv[0], argv) + except OSError as e: + print(f"suite_reaper: cannot run {argv[0]}: {e}", file=sys.stderr) + os._exit(127) + code = None + while code is None: + pid, status = os.waitpid(-1, 0) # orphans that exit meanwhile are collected here too + if pid == child: + code = os.waitstatus_to_exitcode(status) + me = os.getpid() + deadline = time.monotonic() + GRACE_S + while True: + reap() + left = descendants(me) + if not left or time.monotonic() >= deadline: + break + time.sleep(0.1) + if left: + held = listening(left) + if held: + print("the offline suite left a listening socket behind:") + for pid, addrs in sorted(held.items()): + print(f" {', '.join(sorted(addrs))} held by pid {pid}: {command_line(pid)}") + others = [p for p in left if p not in held] + if others: + print("the offline suite left a process running:") + for pid in others: + print(f" pid {pid}: {command_line(pid)}") + stop(left) + print("(stopped now)") + if code != 0: + return code + return 3 if left else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/test_suite_reaper.py b/tests/test_suite_reaper.py new file mode 100644 index 00000000..ff1123cb --- /dev/null +++ b/tests/test_suite_reaper.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""tests/suite_reaper.py tells what a command leaves running from what others do. + +The offline suite's "no listening socket left behind" compared every listener of +the machine before and after the suite, and failed twice on the reference box on +2026-10-03 for ports VS Code opened while the suite ran. The reaper judges the +command's own processes only, found through the subreaper bit rather than an +environment variable or a session, which a test's subprocess is free to drop. +""" +import os +import pathlib +import socket +import subprocess +import sys +import tempfile +import time +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +REAPER = str(REPO / "tests" / "suite_reaper.py") + +# A listener that writes its port to a file, then waits to be stopped. +LISTENER = ("import socket, sys, time; s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen(); " + "open(sys.argv[1], 'w').write(str(s.getsockname()[1])); time.sleep(60)") + + +def reaper(command, grace="1"): + return subprocess.run([sys.executable, REAPER, "bash", "-c", command], capture_output=True, + text=True, timeout=60, env=dict(os.environ, SUITE_REAPER_GRACE_S=grace)) + + +def refused(port): + try: + socket.create_connection(("127.0.0.1", port), timeout=2).close() + except ConnectionRefusedError: + return True + return False + + +def gone(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + return False + + +class TheCommandsOwnLeftovers(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.portfile = os.path.join(self.dir.name, "port") + self.addCleanup(self.dir.cleanup) + + def wait_for_port(self): + return f'while [ ! -s "{self.portfile}" ]; do sleep 0.05; done' + + def test_a_command_that_leaves_nothing_keeps_its_own_exit_status(self): + r = reaper("exit 0") + self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertEqual(reaper("exit 7").returncode, 7) + + def test_an_orphaned_listener_is_named_with_its_port_then_stopped(self): + r = reaper(f'{sys.executable} -c "{LISTENER}" "{self.portfile}" & {self.wait_for_port()}') + port = int(pathlib.Path(self.portfile).read_text()) + self.assertEqual(r.returncode, 3, r.stdout + r.stderr) + self.assertIn("left a listening socket behind", r.stdout) + self.assertIn(f"127.0.0.1:{port} held by pid", r.stdout) + self.assertTrue(refused(port), "the listener must be stopped once reported") + + def test_a_new_session_and_an_empty_environment_do_not_hide_it(self): + # what an environment marker or a session id would have missed + r = reaper(f'setsid env -i {sys.executable} -c "{LISTENER}" "{self.portfile}" & ' + f'{self.wait_for_port()}') + port = int(pathlib.Path(self.portfile).read_text()) + self.assertEqual(r.returncode, 3, r.stdout + r.stderr) + self.assertIn(f"127.0.0.1:{port} held by pid", r.stdout) + self.assertTrue(refused(port)) + + def test_a_process_left_running_without_a_socket_is_named_then_stopped(self): + pidfile = os.path.join(self.dir.name, "pid") + r = reaper(f'sleep 60 & echo $! > "{pidfile}"') + pid = int(pathlib.Path(pidfile).read_text()) + self.assertEqual(r.returncode, 3, r.stdout + r.stderr) + self.assertIn(f"pid {pid}: sleep 60", r.stdout) + self.assertNotIn("listening socket", r.stdout) + self.assertTrue(gone(pid)) + + def test_a_process_on_its_way_out_is_given_the_grace(self): + r = reaper("(sleep 0.3) & exit 0", grace="3") + self.assertEqual((r.returncode, r.stdout), (0, "")) + + def test_another_programs_listener_is_not_the_commands(self): + # the VS Code case: a listener that appears while the command runs, held by a + # process the command did not start + other = subprocess.Popen([sys.executable, "-c", LISTENER, self.portfile]) + self.addCleanup(other.wait) + self.addCleanup(other.kill) + deadline = time.monotonic() + 10 + while not os.path.exists(self.portfile) or not pathlib.Path(self.portfile).read_text(): + self.assertLess(time.monotonic(), deadline, "the other listener never started") + time.sleep(0.05) + r = reaper("sleep 0.5") + self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertIsNone(other.poll(), "the reaper must leave other programs alone") + + def test_no_command_is_a_usage_error(self): + r = subprocess.run([sys.executable, REAPER], capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 2) + self.assertIn("Usage:", r.stderr) + + def test_a_command_that_cannot_start_says_so(self): + r = subprocess.run([sys.executable, REAPER, "/nonexistent/command"], capture_output=True, + text=True, timeout=30) + self.assertEqual(r.returncode, 127) + self.assertIn("cannot run /nonexistent/command", r.stderr) + + +if __name__ == "__main__": + unittest.main()