test(e2e): add isolated browser journey and cleanup supervision

Add a fake-only end-to-end stack, Firefox journey, and bounded process cleanup for normal, failed, and interrupted runs.

Refs #12

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 23:39:02 +01:00
parent 8f42c30ec6
commit 4459a81206
28 changed files with 1647 additions and 51 deletions

View File

@ -0,0 +1,270 @@
#!/usr/bin/env python3
"""Linux-only E2E lifecycle owner, independent of make's signal disposition.
The detached watcher outlives a killed launcher/make, acts as child subreaper,
then terminates and reaps the whole descendant tree before removing its workspace.
Never scans/kills by executable name and never removes shared caches.
"""
import ctypes
import json
import os
import math
import re
from pathlib import Path
import select
import shutil
import signal
import subprocess
import sys
import tempfile
import time
PR_SET_CHILD_SUBREAPER = 36
PR_SET_PDEATHSIG = 1
def process(pid):
"""Identity includes start ticks to avoid acting on a recycled PID."""
try:
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
return int(fields[1]), fields[19], fields[0] # ppid, starttime, state
except (OSError, ValueError, IndexError):
return None
def same_process(pid, identity):
current = process(pid)
return current is not None and current[1] == identity[1] and current[2] != "Z"
def descendants(root):
records = {}
for item in Path("/proc").iterdir():
if item.name.isdigit():
identity = process(int(item.name))
if identity is not None:
records[int(item.name)] = identity
owned = {root}
while True:
found = {pid for pid, identity in records.items() if identity[0] in owned}
if found <= owned:
break
owned |= found
return {pid: records[pid] for pid in owned if pid != root and pid in records}
def direct_children(root):
# Unlike a cross-process ancestry scan, these lists come from the kernel's
# actual child ownership. Include every thread, not just the group leader.
records = {}
for entry in Path(f"/proc/{root}/task").glob("*/children"):
for value in entry.read_text().split():
pid = int(value)
identity = process(pid)
if identity is not None and identity[0] == root:
records[pid] = identity
return records
def reap():
"""Return True while the kernel still owns a live child, False on ECHILD."""
while True:
try:
pid, _ = os.waitpid(-1, os.WNOHANG)
if pid == 0:
return True
except ChildProcessError:
return False
def stop_tree(worker):
root = os.getpid()
known = {}
identity = process(worker.pid)
if identity is not None:
known[worker.pid] = identity
signalled = set()
grace = time.monotonic() + 1.5
deadline = grace + 3
empty_confirmations = 0
while time.monotonic() < deadline:
# Never forget previously observed live identities when an ancestry
# snapshot temporarily loses a parent during exit/adoption.
known.update(descendants(root))
known.update(direct_children(root))
force = time.monotonic() >= grace
for pid, identity in known.items():
if same_process(pid, identity):
key = (pid, identity[1])
if force or key not in signalled:
try:
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
signalled.add(key)
except ProcessLookupError:
pass
worker.poll()
has_children = reap()
alive = any(same_process(pid, identity) for pid, identity in known.items())
if not has_children and not alive:
empty_confirmations += 1
if empty_confirmations >= 2:
return
else:
empty_confirmations = 0
time.sleep(0.03)
raise RuntimeError("E2E kernel-owned descendants failed to terminate; workspace retained")
def timeout_duration(arguments):
"""Read a GNU timeout soft duration; never extend an enclosing deadline."""
position = 1
while position < len(arguments):
value = arguments[position]
if value == "--":
position += 1
break
if value in ("-k", "--kill-after", "-s", "--signal"):
position += 2
elif value in ("--foreground", "--preserve-status", "--verbose", "-v") or value.startswith(("--signal=", "--kill-after=")):
position += 1
elif value.startswith("-"):
return None
else:
break
if position >= len(arguments):
return None
match = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?)([smhd]?)", arguments[position])
if not match:
return None
duration = float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}[match[2]]
return duration if duration > 0 and math.isfinite(duration) else None
def enclosing_deadline(pid):
deadlines = []
for _ in range(64):
identity = process(pid)
if identity is None:
break
try:
executable = Path(os.readlink(f"/proc/{pid}/exe")).name
if executable == "timeout":
arguments = Path(f"/proc/{pid}/cmdline").read_bytes().decode().strip("\0").split("\0")
duration = timeout_duration(arguments)
if duration is not None:
boot_now = time.clock_gettime(time.CLOCK_BOOTTIME)
started = int(identity[1]) / os.sysconf("SC_CLK_TCK")
remaining = max(0, duration - (boot_now - started))
deadlines.append(time.monotonic() + remaining)
except (OSError, ValueError):
pass
if identity[0] <= 0 or identity[0] == pid:
break
pid = identity[0]
return min(deadlines) if deadlines else None
def watcher(project, owner_pid, owner_start, life_fd, deadline=None):
libc = ctypes.CDLL(None, use_errno=True)
if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), "E2E subreaper setup failed")
interrupted = []
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signal.signal(sig, lambda received, _frame: interrupted.append(received))
base = os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp"
work = Path(tempfile.mkdtemp(prefix="tradarr-e2e.", dir=base))
worker = None
expected_parent = os.getpid()
def parent_death_guard():
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
os._exit(125)
if os.getppid() != expected_parent:
os._exit(125)
try:
env = dict(os.environ, TRADARR_E2E_RUN_DIR=str(work))
worker = subprocess.Popen(
["bash", str(project / "backend/scripts/test-e2e-worker.sh")],
cwd=project, env=env, start_new_session=True, preexec_fn=parent_death_guard,
)
# Diagnostic process identities only; never credentials or DSNs.
(work / "supervisor.json").write_text(json.dumps({
"watcher": os.getpid(), "worker": worker.pid, "owner": owner_pid,
}))
while True:
result = worker.poll()
if result is not None:
return result if result >= 0 else 128 - result
ready, _, _ = select.select([life_fd], [], [], 0.05)
alive = process(owner_pid)
if (deadline is not None and time.monotonic() >= deadline) or interrupted or alive is None or alive[1] != owner_start or alive[2] == "Z":
return 130
if ready and os.read(life_fd, 1) == b"":
return 130
finally:
if worker is not None:
stop_tree(worker)
shutil.rmtree(work)
os.close(life_fd)
def launch(project):
if sys.platform != "linux" or not Path("/proc/self/stat").exists():
raise RuntimeError("E2E supervision requires Linux /proc and child-subreaper support")
owner_pid = os.getppid()
owner = process(owner_pid)
if owner is None:
raise RuntimeError("E2E owner disappeared before supervision")
read_fd, write_fd = os.pipe()
watch = None
pending = []
def forward(received, _frame):
pending.append(received)
if watch is not None:
try:
os.kill(watch.pid, signal.SIGTERM)
except ProcessLookupError:
pass
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signal.signal(sig, forward)
# Kernel notification complements polling when make itself is SIGKILLed.
# Install handlers first, then close the setup race by rechecking the parent.
libc = ctypes.CDLL(None, use_errno=True)
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), "E2E launcher parent-death guard failed")
if os.getppid() != owner_pid:
os.close(read_fd)
os.close(write_fd)
raise RuntimeError("E2E owner disappeared during launcher setup")
try:
watch = subprocess.Popen(
[sys.executable, "-E", __file__, "--watch", str(project),
str(owner_pid), owner[1], str(read_fd), str(enclosing_deadline(owner_pid) or 0)],
pass_fds=(read_fd,), start_new_session=True,
)
os.close(read_fd)
if pending:
os.kill(watch.pid, signal.SIGTERM)
return watch.wait()
finally:
os.close(write_fd) # abrupt launcher death closes it in the kernel too
if watch is not None and watch.poll() is None:
os.kill(watch.pid, signal.SIGTERM)
watch.wait(timeout=6)
if __name__ == "__main__":
try:
if len(sys.argv) == 7 and sys.argv[1] == "--watch":
code = watcher(Path(sys.argv[2]), int(sys.argv[3]), sys.argv[4], int(sys.argv[5]), float(sys.argv[6]) or None)
elif len(sys.argv) == 2:
code = launch(Path(sys.argv[1]))
else:
raise RuntimeError("invalid E2E supervisor invocation")
sys.exit(code)
except Exception as error:
print(f"E2E supervisor: {error}", file=sys.stderr)
sys.exit(1)

View File

@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Offline lifecycle regression: kill the owner/launcher, not their process group."""
import importlib.util
import os
from pathlib import Path
import shlex
import signal
import subprocess
import sys
import tempfile
import time
import unittest
import json
sys.dont_write_bytecode = True
SUPERVISOR = Path(__file__).with_name("e2e-supervisor.py")
spec = importlib.util.spec_from_file_location("e2e_supervisor", SUPERVISOR)
supervision = importlib.util.module_from_spec(spec)
spec.loader.exec_module(supervision)
@unittest.skipUnless(sys.platform == "linux", "Linux /proc supervision")
class Lifecycle(unittest.TestCase):
def run_case(self, victim, normal_exit=False):
with tempfile.TemporaryDirectory(prefix="e2e-supervisor-test-", dir=os.environ.get("TMPDIR")) as temporary:
root = Path(temporary)
project = root / "project"
scripts = project / "backend/scripts"
scripts.mkdir(parents=True)
sleeper = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);time.sleep(60)"
code = (
"import subprocess,sys,signal,time;"
f"subprocess.Popen([sys.executable,'-E','-c',{sleeper!r}],start_new_session=True);"
"signal.signal(signal.SIGTERM,signal.SIG_IGN);"
+ ("time.sleep(.2)" if normal_exit else "time.sleep(60)")
)
(scripts / "test-e2e-worker.sh").write_text(
"#!/bin/sh\nexec " + shlex.quote(sys.executable) + " -E -c " + shlex.quote(code) + "\n"
)
owner_code = (
"import subprocess,sys,time;"
f"p=subprocess.Popen([sys.executable,'-E',{str(SUPERVISOR)!r},{str(project)!r}]);"
"p.wait();time.sleep(60)"
)
with (root / "output.log").open("w") as output:
owner = subprocess.Popen([sys.executable, "-E", "-c", owner_code], env=dict(os.environ, TMPDIR=str(root)), stdout=output, stderr=output)
identities = {}
try:
deadline = time.monotonic() + 5
info = None
while time.monotonic() < deadline:
files = list(root.glob("tradarr-e2e.*/supervisor.json"))
if files:
try:
info = json.loads(files[0].read_text())
identities = supervision.descendants(info["watcher"])
if len(identities) >= 2:
workspace = files[0].parent
break
except (OSError, ValueError):
pass
time.sleep(.02)
else:
self.fail("supervised descendants did not start")
if not normal_exit:
if victim == "owner":
os.kill(owner.pid, signal.SIGKILL)
else:
launcher = supervision.process(info["watcher"])[0]
os.kill(launcher, signal.SIGKILL)
deadline = time.monotonic() + 7
while time.monotonic() < deadline:
alive = [pid for pid, identity in identities.items() if supervision.same_process(pid, identity)]
if not alive and not workspace.exists():
break
time.sleep(.02)
self.assertFalse(alive, f"surviving descendants: {alive}")
self.assertFalse(workspace.exists(), "workspace leaked")
if victim == "launcher":
self.assertIsNone(owner.poll(), "owner should remain alive for broken-pipe case")
finally:
# Tests never kill by a name/shared group, even on failure.
for pid, identity in identities.items():
if supervision.same_process(pid, identity):
os.kill(pid, signal.SIGKILL)
if owner.poll() is None:
owner.kill()
owner.wait(timeout=5)
def test_empty_proc_snapshot_is_not_cleanup_confirmation(self):
# /proc traversal is not atomic during exit/reparenting. Even an empty
# ancestry snapshot must not override the kernel's live-child state.
code = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print('ready',flush=True);time.sleep(60)"
child = subprocess.Popen([sys.executable, "-E", "-c", code], stdout=subprocess.PIPE, text=True)
original = supervision.descendants
try:
self.assertEqual(child.stdout.readline().strip(), "ready")
supervision.descendants = lambda _root: {}
supervision.stop_tree(child)
self.assertIsNotNone(child.poll(), "empty /proc snapshot left a live child")
finally:
supervision.descendants = original
if child.poll() is None:
child.kill()
child.wait()
child.stdout.close()
def test_gnu_timeout_duration_parsing(self):
self.assertEqual(supervision.timeout_duration(["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]), 8)
self.assertEqual(supervision.timeout_duration(["timeout", "-k", "8s", "-s", "INT", "1.5m", "make"]), 90)
self.assertIsNone(supervision.timeout_duration(["timeout", "0", "make"]))
self.assertIsNone(supervision.timeout_duration(["timeout", "--unknown", "8s", "make"]))
def test_sigkill_owner_only(self):
self.run_case("owner")
def test_sigkill_launcher_broken_liveness_pipe(self):
self.run_case("launcher")
def test_normal_worker_exit_reaps_detached_grandchildren(self):
self.run_case("normal", normal_exit=True)
if __name__ == "__main__":
unittest.main(verbosity=2)

View File

@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Integration regression: real make/embedded PG/E2E runner, single-PID timeout.
Pass --wrapper-dir to use QA's exact node wrapper. Without it, Playwright is
blocked before execution, after the real Vite server has started.
"""
import argparse
import importlib.util
import json
import os
from pathlib import Path
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import time
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("supervisor", Path(__file__).with_name("e2e-supervisor.py"))
supervision = importlib.util.module_from_spec(spec)
spec.loader.exec_module(supervision)
def run(wrapper_dir):
base = Path(os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp")
with tempfile.TemporaryDirectory(prefix="ticket12-timeout-integration.", dir=base) as temporary:
evidence = Path(temporary)
if wrapper_dir:
wrapper = Path(wrapper_dir).resolve()
if not (wrapper / "node").is_file():
raise RuntimeError("QA wrapper node is absent; exact reproduction refused")
else:
wrapper = evidence / "wrapper"
wrapper.mkdir()
node = shutil.which("node")
(wrapper / "node").write_text(
'#!/bin/bash\nif [[ "$*" == *playwright* ]]; then\n'
' exec sleep 60\nelse\n exec ' + shlex.quote(node) + ' "$@"\nfi\n'
)
(wrapper / "node").chmod(0o755)
command = ["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]
known = {}
workspace = None
process = None
watcher = None
names = set()
real_ready = False
try:
with (evidence / "runner.log").open("w") as log:
process = subprocess.Popen(command, cwd=ROOT, env=dict(os.environ, PATH=str(wrapper) + ":" + os.environ["PATH"]), stdout=log, stderr=log)
deadline = time.monotonic() + 35
while process.poll() is None and time.monotonic() < deadline:
if workspace is None:
for metadata in base.glob("tradarr-e2e.*/supervisor.json"):
try:
info = json.loads(metadata.read_text())
owner = supervision.process(info["owner"])
if owner is not None and owner[0] == process.pid:
workspace = metadata.parent
watcher = info["watcher"]
identity = supervision.process(watcher)
if identity:
known[watcher] = identity
break
except (OSError, ValueError, KeyError):
pass
if watcher:
known.update(supervision.descendants(watcher))
if workspace is not None and (workspace / "stack.json").exists():
real_ready = True
for pid in known:
try:
names.add(Path(f"/proc/{pid}/comm").read_text().strip())
except OSError:
pass
time.sleep(.03)
code = process.wait(timeout=2)
if workspace is None:
raise RuntimeError("real runner did not create a supervised workspace")
if not real_ready or not {"postgres", "e2e-stack", "sleep"}.issubset(names):
raise RuntimeError(f"real stack incomplete: ready={real_ready}, observed process names={sorted(names)}")
# This assertion is deliberately immediate. Waiting after timeout
# returns keeps the test supervisor alive and masked the QA leak.
if watcher:
known.update(supervision.descendants(watcher))
survivors = [pid for pid, identity in known.items() if supervision.same_process(pid, identity)]
if survivors or workspace.exists():
raise RuntimeError(f"timeout returned before cleanup: {len(survivors)} survivors; workspace remains={workspace.exists()}")
if code not in (130, 2):
raise RuntimeError(f"runner failed to clean during timeout grace period: exit={code}")
print(f"PASS real runner + exact timeout flags: exit={code}, observed={len(known)}, no survivor/workspace when timeout returns")
except Exception:
print((evidence / "runner.log").read_text()[-5000:] if (evidence / "runner.log").exists() else "", file=sys.stderr)
raise
finally:
# Independent fallback so a red regression does not itself leak.
if watcher:
known.update(supervision.descendants(watcher))
for pid, identity in known.items():
if supervision.same_process(pid, identity):
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
if process is not None and process.poll() is None:
process.kill()
process.wait()
if workspace is not None and workspace.exists():
shutil.rmtree(workspace)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--wrapper-dir")
args = parser.parse_args()
try:
run(args.wrapper_dir)
except Exception as error:
print(f"FAIL E2E timeout integration: {error}", file=sys.stderr)
sys.exit(1)

View File

@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
managed_tmp="${TMPDIR:-${IDEA_MANAGED_TMP:-/tmp}}"
pg_home="$managed_tmp/tradarr-embedded-postgres"
cli="$pg_home/bin/embedded-postgres"
if [[ ! -x "$cli" ]] || [[ "$("$cli" version)" != *'"version":"v2.0.1"'* ]]; then
echo 'E2E requires cached embedded-postgres v2.0.1; prepare with make test-postgres.' >&2
exit 2
fi
psql_path="$(find "$pg_home/cache" -type f -path '*/postgresql-16.15.1-*/bin/psql' -print -quit)"
if [[ -z "$psql_path" ]]; then
echo 'E2E requires cached PostgreSQL 16.15.1; prepare with make test-postgres.' >&2
exit 2
fi
# The independent supervisor owns this directory and every process below us.
: "${TRADARR_E2E_RUN_DIR:?invoke make test-e2e through its supervisor}"
run_dir="$TRADARR_E2E_RUN_DIR"
export GOCACHE="${GOCACHE:-$managed_tmp/go-build}"
export GOMODCACHE="${GOMODCACHE:-$managed_tmp/gomodcache}"
# No dependency installation/network downloads during an E2E run.
export GOPROXY=off GOSUMDB=off npm_config_update_notifier=false
unset DATABASE_URL TEST_DATABASE_URL PGHOST PGPORT PGUSER PGPASSWORD PGDATABASE PGSSLMODE TRADARR_E2E_STACK_MANIFEST NO_COLOR FORCE_COLOR
cd "$project_root/backend"
go build -o "$run_dir/e2e-stack" ./cmd/e2e
exec "$cli" exec --offline --postgres-version 16.15.1 --database tradarr_e2e \
--cache-dir "$pg_home/cache" --work-dir "$run_dir/db" \
-- "$run_dir/e2e-stack" -work "$run_dir" -psql "$psql_path"

6
backend/scripts/test-e2e.sh Executable file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
# exec preserves our parent (make) identity; Python -E ignores bundled-app
# PYTHONHOME/PYTHONPATH without altering the caller's environment.
exec python3 -E -B "$project_root/backend/scripts/e2e-supervisor.py" "$project_root"