Skip to content
Merged
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
27 changes: 24 additions & 3 deletions pm-stack/invariant-sweeper.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
Expand Down Expand Up @@ -178,14 +179,34 @@ 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}"]
for key, value in variables.items():
# -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)
Expand All @@ -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
Expand Down Expand Up @@ -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 = {}
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/systemd/pm-invariant-sweeper.service
Original file line number Diff line number Diff line change
Expand Up @@ -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'
64 changes: 64 additions & 0 deletions pm-stack/tests/test_invariant_sweeper_timeouts.py
Original file line number Diff line number Diff line change
@@ -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()