From 8e73ab36d2e5294a100aa31fce3bdd7403691f09 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:17:39 +0000 Subject: [PATCH] pm-stack: bound the invariant sweeper's subprocess calls gh_graphql, gh_run and kaneo_links ran gh and docker-exec psql with no timeout, and the daily oneshot unit has no start timeout, so one wedged call could hang the sweep forever. Each call now has a 120s timeout (PM_SWEEPER_SUBPROCESS_TIMEOUT overrides) that surfaces as the same RuntimeError the callers already report, and the unit gets TimeoutStartSec=45min as an outer bound. Fixes #11416 Co-Authored-By: Claude Opus 5.5 --- pm-stack/invariant-sweeper.py | 27 +++++++- pm-stack/systemd/pm-invariant-sweeper.service | 4 ++ .../tests/test_invariant_sweeper_timeouts.py | 64 +++++++++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 pm-stack/tests/test_invariant_sweeper_timeouts.py diff --git a/pm-stack/invariant-sweeper.py b/pm-stack/invariant-sweeper.py index f044968b1e..f02982407e 100644 --- a/pm-stack/invariant-sweeper.py +++ b/pm-stack/invariant-sweeper.py @@ -69,6 +69,7 @@ import argparse import hashlib import json +import os import re import subprocess import sys @@ -178,6 +179,26 @@ def resolve_gh_route(): GH_ROUTE = "gh (FALLBACK: fleet binary not on PATH — personal token)" +# #11416: every subprocess this sweeper starts is bounded. The timer +# runs a oneshot unit, so one wedged gh/psql call would otherwise hang +# the daily sweep forever. Override with PM_SWEEPER_SUBPROCESS_TIMEOUT +# (seconds). +SUBPROCESS_TIMEOUT_SECS = int(os.environ.get("PM_SWEEPER_SUBPROCESS_TIMEOUT", "120")) + + +def run_bounded(cmd, what): + """subprocess.run with a timeout; a timeout becomes a RuntimeError + naming the call, like every other failure of these helpers.""" + try: + return subprocess.run( + cmd, capture_output=True, text=True, timeout=SUBPROCESS_TIMEOUT_SECS + ) + except subprocess.TimeoutExpired: + raise RuntimeError( + f"{what} timed out after {SUBPROCESS_TIMEOUT_SECS}s" + ) from None + + def gh_graphql(query, **variables): """One GraphQL call via the gh CLI. Raises RuntimeError on failure.""" cmd = [*GH_CMD, "api", "graphql", "-f", f"query={query}"] @@ -185,7 +206,7 @@ def gh_graphql(query, **variables): # -F types the value (ints stay ints); -f keeps strings verbatim # (pagination cursors must never be re-typed). cmd += ["-F" if isinstance(value, int) else "-f", f"{key}={value}"] - out = subprocess.run(cmd, capture_output=True, text=True) + out = run_bounded(cmd, "gh api graphql") if out.returncode != 0: raise RuntimeError(f"gh api graphql failed: {out.stderr.strip()[:300]}") data = json.loads(out.stdout) @@ -195,7 +216,7 @@ def gh_graphql(query, **variables): def gh_run(*args): - out = subprocess.run([*GH_CMD, *args], capture_output=True, text=True) + out = run_bounded([*GH_CMD, *args], f"gh {' '.join(args)}") if out.returncode != 0: raise RuntimeError(f"gh {' '.join(args)} failed: {out.stderr.strip()[:300]}") return out.stdout @@ -361,7 +382,7 @@ def kaneo_links(): "JOIN task t ON t.id = el.task_id " "WHERE el.resource_type='issue'" ) - out = subprocess.run(KAN_PSQL + ["-c", sql], capture_output=True, text=True) + out = run_bounded(KAN_PSQL + ["-c", sql], "kaneo psql") if out.returncode != 0: raise RuntimeError(f"kaneo psql failed: {out.stderr.strip()[:300]}") links = {} diff --git a/pm-stack/systemd/pm-invariant-sweeper.service b/pm-stack/systemd/pm-invariant-sweeper.service index 2a3ffabf9c..6479e90f69 100644 --- a/pm-stack/systemd/pm-invariant-sweeper.service +++ b/pm-stack/systemd/pm-invariant-sweeper.service @@ -4,4 +4,8 @@ After=network.target docker.service [Service] Type=oneshot +# Outer bound for the whole sweep (#11416): each gh/psql call is +# already capped at 120s, but a oneshot unit has no start timeout +# by default, so cap the run as a whole too. +TimeoutStartSec=45min ExecStart=/bin/sh -lc 'python3 /home/user/pm-stack/invariant-sweeper.py --act --post-epic' diff --git a/pm-stack/tests/test_invariant_sweeper_timeouts.py b/pm-stack/tests/test_invariant_sweeper_timeouts.py new file mode 100644 index 0000000000..97d3449bde --- /dev/null +++ b/pm-stack/tests/test_invariant_sweeper_timeouts.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Subprocess bounds for the epic-invariant sweeper (#11416). + +Oracle: the issue's acceptance shape. Each helper that shells out +(gh_graphql, gh_run, kaneo_links) must pass a timeout to subprocess.run, +and a timed-out call must surface as a RuntimeError naming the call, +which the sweeper's existing error paths already report. + +Run: python3 pm-stack/tests/test_invariant_sweeper_timeouts.py +""" + +import importlib.util +import subprocess +import unittest +from pathlib import Path +from unittest import mock + +SWEEPER_PATH = Path(__file__).resolve().parent.parent / "invariant-sweeper.py" +spec = importlib.util.spec_from_file_location("invariant_sweeper", SWEEPER_PATH) +sweeper = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sweeper) + + +def timing_out(cmd, **kwargs): + raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout")) + + +class SubprocessBoundsTest(unittest.TestCase): + def assert_times_out(self, call, label): + seen = {} + + def fake(cmd, **kwargs): + seen.update(kwargs) + return timing_out(cmd, **kwargs) + + with mock.patch.object(sweeper.subprocess, "run", side_effect=fake): + with self.assertRaises(RuntimeError) as ctx: + call() + self.assertEqual(seen.get("timeout"), sweeper.SUBPROCESS_TIMEOUT_SECS) + self.assertIn(label, str(ctx.exception)) + self.assertIn("timed out", str(ctx.exception)) + + def test_gh_graphql_is_bounded(self): + self.assert_times_out(lambda: sweeper.gh_graphql("query{viewer{login}}"), "gh api graphql") + + def test_gh_run_is_bounded(self): + self.assert_times_out(lambda: sweeper.gh_run("api", "rate_limit"), "gh api rate_limit") + + def test_kaneo_psql_is_bounded(self): + self.assert_times_out(sweeper.kaneo_links, "kaneo psql") + + def test_completed_calls_still_return_output(self): + done = subprocess.CompletedProcess([], 0, stdout="ok\n", stderr="") + with mock.patch.object(sweeper.subprocess, "run", return_value=done) as run: + self.assertEqual(sweeper.gh_run("api", "rate_limit"), "ok\n") + self.assertEqual(run.call_args.kwargs["timeout"], sweeper.SUBPROCESS_TIMEOUT_SECS) + + def test_the_timer_unit_has_an_outer_bound(self): + unit = (SWEEPER_PATH.parent / "systemd" / "pm-invariant-sweeper.service").read_text() + self.assertIn("TimeoutStartSec=", unit) + + +if __name__ == "__main__": + unittest.main()