Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): keep the hard watchdog out of pytest and alive when sys.stderr is swapped (#3875)

gglucass7d856b81f522
diff --git a/headroom/proxy/hard_watchdog.py b/headroom/proxy/hard_watchdog.py
index a04816c26..0393d6576 100644
--- a/headroom/proxy/hard_watchdog.py
+++ b/headroom/proxy/hard_watchdog.py
@@ -58,17 +58,21 @@ def _resolve_secs() -> float:
return max(secs, MIN_SECS)
-def _arm(secs: float) -> None:
+def _arm(secs: float, fd: int) -> None:
# Re-arming replaces the previous timer, so a healthy interpreter never
- # lets it expire. ``file`` is the underlying stderr fd, which supervisors
- # already redirect into the proxy log.
- faulthandler.dump_traceback_later(secs, exit=True, file=sys.stderr)
+ # lets it expire. ``fd`` is the stderr fd resolved once at start, which
+ # supervisors already redirect into the proxy log. Passing ``sys.stderr``
+ # on every tick would raise whenever something swaps it for a stream
+ # without a fileno (redirect_stderr(StringIO()), click's CliRunner,
+ # pytest's capsys): the heartbeat thread dies and the timer armed on the
+ # previous tick shoots a healthy process.
+ faulthandler.dump_traceback_later(secs, exit=True, file=fd)
-def _heartbeat(secs: float) -> None:
+def _heartbeat(secs: float, fd: int) -> None:
while True:
time.sleep(secs / 3.0)
- _arm(secs)
+ _arm(secs, fd)
def start_hard_watchdog() -> bool:
@@ -90,9 +94,10 @@ def start_hard_watchdog() -> bool:
# First arm happens here, synchronously: the caller is covered from the
# moment this returns, even if the very next call seizes the GIL before
# the heartbeat thread gets scheduled.
- _arm(secs)
+ fd = sys.stderr.fileno()
+ _arm(secs, fd)
threading.Thread(
- target=_heartbeat, args=(secs,), name="headroom-hard-watchdog", daemon=True
+ target=_heartbeat, args=(secs, fd), name="headroom-hard-watchdog", daemon=True
).start()
logger.info(
"Hard watchdog armed: dump all stacks and exit if the interpreter "
diff --git a/tests/conftest.py b/tests/conftest.py
index 52c8a50e5..488325375 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -73,6 +73,11 @@ def _scrub_developer_headroom_env(monkeypatch, tmp_path):
# test its own store so proxy/CLI startup cannot load developer settings and
# saves cannot rewrite them. Tests of path precedence can override this.
monkeypatch.setenv("HEADROOM_SETTINGS_PATH", str(tmp_path / "headroom-settings.json"))
+ # The scrub also deletes the HEADROOM_HARD_WATCHDOG_SECS=0 opt-out CI sets
+ # (#3845), so every test that enters the proxy lifespan armed the 90s
+ # production watchdog inside pytest; it hard-exits the process with code 1
+ # and no summary. Tests of the watchdog set the variable themselves.
+ monkeypatch.setenv("HEADROOM_HARD_WATCHDOG_SECS", "0")
# The scrub above deletes every HEADROOM_* var — which includes HEADROOM_BEACON,
diff --git a/tests/test_hard_watchdog.py b/tests/test_hard_watchdog.py
index 33c6bc18c..1996bc01e 100644
--- a/tests/test_hard_watchdog.py
+++ b/tests/test_hard_watchdog.py
@@ -68,6 +68,21 @@ _HEALTHY = textwrap.dedent(
)
+_SWAPPED_STDERR = textwrap.dedent(
+ """
+ import io, sys, time
+ from headroom.proxy.hard_watchdog import start_hard_watchdog
+
+ assert start_hard_watchdog()
+ # What redirect_stderr(StringIO()), click's CliRunner and pytest's capsys
+ # do: a stderr without a fileno while the heartbeat keeps ticking.
+ sys.stderr = io.StringIO()
+ time.sleep(12) # well past the 5s deadline; the GIL is free throughout
+ print("SURVIVED", flush=True)
+ """
+)
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="libc lookup is POSIX-only")
def test_seized_gil_is_dumped_and_exited():
proc = subprocess.run(
@@ -104,3 +119,22 @@ def test_disabled_by_env(monkeypatch):
monkeypatch.setattr(hard_watchdog, "_started", type(hard_watchdog._started)())
assert hard_watchdog.start_hard_watchdog() is False
+
+
[email protected](sys.platform == "win32", reason="keep the pair symmetric")
+def test_swapped_stderr_does_not_kill_the_heartbeat():
+ proc = subprocess.run(
+ [sys.executable, "-c", _SWAPPED_STDERR],
+ env={"HEADROOM_HARD_WATCHDOG_SECS": "5", "PATH": "/usr/bin:/bin"},
+ capture_output=True,
+ text=True,
+ timeout=40,
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert "SURVIVED" in proc.stdout
+
+
+def test_pytest_never_arms_the_production_watchdog():
+ """The conftest scrub must not strip CI's opt-out (#3845): ~100 test files
+ enter the proxy lifespan, and an armed watchdog hard-exits the whole shard."""
+ assert _resolve_secs() == 0.0