cozempic icon indicating copy to clipboard operation
cozempic copied to clipboard

fix(guard): SIGTERM-leak + test /tmp-log isolation + _pid_is_alive consolidation (GC-1/2/3)

Open ynaamane opened this issue 5 months ago • 3 comments

Three guard.py lifecycle / resource cleanups (LOW–MED), none touching the hot reload path. Per-line analysis confirmed no overlap with the in-flight reload-gate PRs.

GC-1 — SIGTERM startup-leak

_graceful_shutdown (the SIGTERM handler, registered before the daemon's main try/finally) called checkpoint_team + sys.exit(0) but not the pidfile / armed-file cleanup. If SIGTERM fired in the ~200-line startup window before the try:, the finally that unlinks the pidfile never ran → pidfile AND armed-file leaked.

Fix: extracted the handler to a testable _make_sigterm_handler(session_id, session_path, overflow_watcher) factory that calls _safe_unlink_session_pidfile(session_id) + clear_armed(session_id, session_path) before sys.exit(0). The call-site passes sess["session_id"] (the resolved id — the bare CLI arg is None on the auto-detect path).

GC-2 — test /tmp log leaks

Two tests wrote real /tmp log files with no cleanup (test_guard_robustness.py, test_guard_reload_watcher_poll.py). Fix: patch _guard_tmp_root → tmp_path / use _guard_tmp_root() for the log path, matching the production log location.

Out of scope, flagged for follow-up: production's reload status file (guard.py:2262, documented GAP-B) still uses hardcoded /tmp, while the log uses _guard_tmp_root(). The test correctly checks the real /tmp status path; the production status-vs-log path inconsistency is a separate consistency item.

GC-3 — _pid_is_alive consolidation

Three liveness implementations (guard.py, session.py, watchdog.py) → one canonical _pid_is_alive in helpers.py (a leaf module — no import cycle). session.py + watchdog.py now import it (identical function object). Behavioral fix: session.py's old impl returned False on a POSIX unknown OSError; the canonical returns True (fail-open — the process most likely exists). reload_lock / spawn_lock _is_process_alive are deliberately not consolidated — they carry a purpose-specific PermissionError semantic (lock-acquisition liveness), distinct from general liveness.

Tests

tests/test_guard_cleanup.py (new, 14 tests) — RED-at-base proven per item: GC-1 (AttributeError at base → handler-calls-cleanups after), GC-2 (assertNotIn hardcoded /tmp at base), GC-3 (ImportError at base → single-source assertIs + a POSIX-OSError fail-open behavioral test). Full suite: 1383 passed, 0 failed.

Scope

L3 / L4 resource + test isolation. guard.py, session.py, watchdog.py, helpers.py, 2 test files. stdlib only.

ynaamane avatar Jun 15 '26 12:06 ynaamane

Converting to draft — do not merge yet. An adversarial review caught a CRITICAL regression in GC-3 that the test suite masks:

The consolidated helpers._pid_is_alive was taken from guard's int-only variant (isinstance(pid, int) → rejects non-ints), but it dropped the string coercion the old session._pid_alive had (os.kill(int(pid), 0)). record_active_transcript's prune (session.py:581) passes dict keys, which are JSON strings ("12345") — so _pid_is_alive("12345") now returns False, and the prune reads every entry as dead and drops live ones. This breaks the #124 two-terminal active-transcript store (the second terminal evicts the first).

The suite stayed green because every active-transcript test mocks _pid_alive, so the real string-key path is never exercised — and one new test enshrined the int-only contract.

Pushing a fix (coerce int(pid) in the helper + an unmocked record_active_transcript regression test with two live pids) plus a MED fix (wrap checkpoint_team in the SIGTERM handler so the pidfile/armed cleanup runs even if checkpoint raises). Will mark ready once verified.

ynaamane avatar Jun 15 '26 12:06 ynaamane

Added 4 robustness fixes from an independent code-review max pass over this PR (commits b7e6615 test + 9380c29 fix + ab3acea):

  • A (SIGTERM handler): the finally cleanups (overflow_watcher.stop(), _safe_unlink_session_pidfile, clear_armed) were unguarded and sys.exit(0) sat outside the try/finally — a raising overflow_watcher.stop() would skip the remaining cleanups AND sys.exit(0), leaving the daemon alive after SIGTERM. Each cleanup is now individually try/except'd so sys.exit(0) always fires. RED-at-prev proven with a raising watcher — the overflow_watcher != None path was previously untested (both tests passed None).
  • C (_pid_is_alive coercion): didn't catch OverflowError, so float('inf') raised instead of returning False (the old session._pid_alive caught it). Added OverflowError.
  • E (test leak): the watcher-poll test's guard_log (_guard_tmp_root() = /tmp on POSIX) had no addCleanup → real /tmp leak. Added.
  • alias: replaced the guard._pid_is_alive one-line wrapper with a module-level alias.

Full suite green (1423 passed, 0 failed).

ynaamane avatar Jun 15 '26 14:06 ynaamane

Marking ready — independently re-reviewed → PASS after the 4 robustness fixes (SIGTERM per-step cleanup hardening with the previously-untested overflow_watcher-raise path now covered + RED-at-prev proven; OverflowError coercion; test-leak addCleanup; module-level alias verified patchable — 40 monkeypatch tests pass). The earlier CRITICAL (the string-pid coercion regression in the _pid_is_alive consolidation) is closed with an unmocked record_active_transcript regression test (2 live pids, RED at the pre-fix commit). Full suite green (1423 passed / 0 failed). Ready for merge.

ynaamane avatar Jun 15 '26 14:06 ynaamane

Thanks @ynaamane — merged to main (b1747c2), rebased onto current 1.8.33 (the branch base predated #138). All of GC-1/2/3 landed: the SIGTERM-handler factory wiring, the /tmp test-log isolation, and the _pid_is_alive consolidation into helpers. The only conflict was guard.py's helpers import line — resolved by keeping BOTH hashable_str (added on main via #138) and your new _pid_is_alive import. Full suite green. Credited to you in the commit. 🙏

junaidtitan avatar Jun 17 '26 20:06 junaidtitan