From 1dd5a2b149816922a3ba01b608d474530206dbf1 Mon Sep 17 00:00:00 2001 From: bahareh Date: Wed, 28 Oct 2026 12:25:19 +0100 Subject: [PATCH] fix: close a Codex trace when Codex exits, not at the next session Codex has no SessionEnd, so a Codex trace was only ever closed by the stale sweep: at the next Codex session start, at least an hour after the session was last seen, with spans that end then. The Rius receiver now refuses a span it gets more than an hour after its end (argus-core #677), so every Codex root would stay pending for good. The heartbeat pinger already watches the Codex process. When it sees it exit, it now closes the trace at once (exporter.close_exited_codex): it reads what the rollout holds past the last hook, so a Stop export that has not taken the lock yet loses nothing, then closes every open span ending at the exit, as a Claude Code trace ends at its SessionEnd. Only traces opened with the key in force are touched, as in the sweep. The sweep stays for a session no pinger watched. --- docs/codex.md | 15 ++++++--- scripts/exporter.py | 58 +++++++++++++++++++++++++++++++-- scripts/heartbeat.py | 32 ++++++++++++++++-- tests/test_codex_export.py | 66 ++++++++++++++++++++++++++++++++++++-- tests/test_heartbeat.py | 48 +++++++++++++++++++++++++++ 5 files changed, 207 insertions(+), 12 deletions(-) diff --git a/docs/codex.md b/docs/codex.md index 06fee10..3dbd4bb 100644 --- a/docs/codex.md +++ b/docs/codex.md @@ -141,10 +141,17 @@ open (or inside a turn a forked session copied) is dropped. ### How a session ends -Codex has no SessionEnd hook. A Codex trace is closed by the next Codex -session you start with the same key, once the old session's Codex process -has exited and it has been idle for an hour. The trace ends at the last -thing the session did. Claude Code's own rule (12 hours) is unchanged. +Codex has no SessionEnd hook. The plugin's heartbeat process watches Codex +and closes the trace when Codex exits, so the trace ends when Codex exited, +as a Claude Code trace ends at its SessionEnd. Rius refuses a span it +receives more than an hour after the span ended, so a close sent later than +that would leave the trace open for good. + +A session no heartbeat process watched (its Codex process could not be +identified, or it ran past the heartbeat's 12-hour cap) is closed by the +next Codex session you start with the same key, once the old session's Codex +process has exited and it has been idle for an hour. That trace ends at the +last thing the session did. Claude Code's own rule (12 hours) is unchanged. ## Querying traces (MCP) diff --git a/scripts/exporter.py b/scripts/exporter.py index bae43db..4718c8a 100644 --- a/scripts/exporter.py +++ b/scripts/exporter.py @@ -41,10 +41,16 @@ # The pinger's own cap (heartbeat.MAX_LIFETIME_S): it covers a session whose # process could not be identified. STALE_AFTER_S = 12 * 60 * 60 -# Codex has no SessionEnd, so the sweep is the only thing that ever closes a -# Codex trace: it waits an hour, not twelve, once the Codex process is gone. +# Codex has no SessionEnd: its pinger closes the trace when it sees Codex exit +# (close_exited_codex). The sweep is left for a session no pinger watched, and +# waits an hour, not twelve, once the Codex process is gone. CODEX_STALE_AFTER_S = 60 * 60 +# How long the pinger waits for the session lock when Codex exits: a Stop +# export still running then, waiting for the turn's final answer and +# shipping it, finishes first. +EXITED_LOCK_TIMEOUT_S = 30.0 + def _stale_after_s() -> int: if agent.active().name == agent.CODEX.name: @@ -395,6 +401,51 @@ def sweep_stale(cfg, current_id, home, now_ns=None) -> None: % (session_id, exc), force=True) +def close_exited_codex(cfg, session_id, cwd, home, now_ns=None) -> int: + """Close a Codex session's trace when its pinger sees Codex exit. + + Codex has no SessionEnd. Left to the sweep, the trace closes at the next + Codex session start, an hour or more after it was last seen, with spans + that end then; the Rius receiver refuses a span it gets more than an + hour after its end, so the root would stay pending for good. Closed + here, the trace ends when Codex exited, as a Claude Code trace ends at + its SessionEnd. The rollout is read first, so a Stop export that has not + taken the lock yet loses nothing to this close. + """ + fingerprint = config.key_fingerprint(cfg.api_key, cfg.endpoint) + if not fingerprint: + return 0 + with state.session_lock(session_id, home, + block_timeout=EXITED_LOCK_TIMEOUT_S) as acquired: + if not acquired: + _log(home, cfg, "session %s: lock held as Codex exited; leaving " + "the trace to the sweep" % session_id) + return 0 + st = codex_session.load(state.load(session_id, home)) + if not state.trace_is_open(st): + state.sync_open_marker(session_id, home, st) + return 0 + # Sent with any other key, the closing spans would land in that + # key's workspace, or none (see _close_if_stale). + if st.get("key_fingerprint") != fingerprint: + return 0 + _log(home, cfg, "session %s: Codex exited; closing its trace" + % session_id) + cwd = st.get("root_cwd") or cwd + out, offset = [], st.get("offset", 0) + if cfg.enabled and not st.get("content_stopped"): + out, offset = codex_session.build( + st, _ctx(st, session_id, cfg, cwd), + st.get("transcript_path") or None) + now_ns = _now_ns() if now_ns is None else now_ns + out += codex_session.finalize( + st, _ctx(st, session_id, cfg, cwd, capture_content=False), now_ns) + attrs = codex_session.resource_attributes( + cfg.service_name, st.get("instance_id") or "", st) + return _ship(out, attrs, st, offset, session_id, home, cfg, + on_success=_on_shipped(session_id, home, st, [])) + + def _run_stopped(event, st, cfg, session_id, cwd, transcript_path, home) -> int: """A session whose folder was disabled after its trace started. @@ -602,7 +653,8 @@ def _ensure_instance_id(st, session_id, home, instance_id): def _run_codex_session(event, cfg, payload, home, instance_id) -> int: """One hook event of a Codex session. Codex has no SessionEnd, so the - root stays open until the sweep closes it (sweep_stale).""" + root stays open until Codex exits (close_exited_codex) or, unwatched, + the sweep closes it (sweep_stale).""" session_id, cwd = payload["session_id"], payload["cwd"] block_timeout = (FINAL_EVENT_LOCK_TIMEOUT_S if event in FINAL_EVENTS else 0.0) diff --git a/scripts/heartbeat.py b/scripts/heartbeat.py index 07638e1..3fc177d 100644 --- a/scripts/heartbeat.py +++ b/scripts/heartbeat.py @@ -36,6 +36,8 @@ 2. The watched Claude Code process is no longer alive. Exits WITHOUT a stopped ping -- claiming a clean stop for a killed process would be a lie; the backend's stale -> gone path exists for exactly this case. + Codex has no SessionEnd, so for Codex this is how a session ends: the + pinger closes its trace first (``exporter.close_exited_codex``). The liveness probe lives in ``rius_cc.platform_compat.pid_alive``: ``os.kill(pid, 0)`` is a harmless probe on POSIX but an ATTACK on Windows (see that module), so it is never called there. A watch pid of @@ -130,7 +132,7 @@ def __init__(self, session_id, home, instance_id, agent_name, transport, watch_pid, interval=INTERVAL_S, max_lifetime=MAX_LIFETIME_S, ping_timeout=PING_TIMEOUT_S, final_ping_timeout=FINAL_PING_TIMEOUT_S, poll_interval=POLL_INTERVAL_S, clock=time.monotonic, sleep=time.sleep, - log=None, name_now=None): + log=None, name_now=None, on_exit=None): self.session_id = session_id self.home = home self.instance_id = instance_id @@ -146,6 +148,7 @@ def __init__(self, session_id, home, instance_id, agent_name, transport, self.sleep = sleep self._log = log or (lambda _msg: None) self._name_now = name_now or (lambda: "") + self._on_exit = on_exit or (lambda: None) def _state_dir(self) -> str: return platform_compat.rius_dir(self.home, "state") @@ -222,6 +225,12 @@ def _send(self, stopped: bool) -> None: except Exception as exc: # never retried, never raised self._log("heartbeat delivery failed: %r" % (exc,)) + def _agent_exited(self) -> None: + try: + self._on_exit() + except Exception as exc: # never raised + self._log("closing the trace on exit failed: %r" % (exc,)) + def run(self) -> None: if not self.acquire_pid_lock(): self._log("another live pinger already owns this session") @@ -241,7 +250,9 @@ def run(self) -> None: self._send(stopped=True) return if self.watch_pid > 0 and not self._pid_alive(self.watch_pid): - return # killed process: no stopped ping, that would lie + # No stopped ping, that would lie about a killed process. + self._agent_exited() + return if self.clock() - start >= self.max_lifetime: return # cap on the PINGER, not evidence the agent # stopped: a live agent past 12h must not be @@ -294,10 +305,25 @@ def log(message: str) -> None: pinger = Pinger(session_id, home, instance_id, cfg.service_name, transport, watch_pid, log=log, name_now=lambda: state.load(session_id, home).get( - "agent_name_sent") or "") + "agent_name_sent") or "", + on_exit=_closer(session_id, cwd, home)) pinger.run() +def _closer(session_id: str, cwd: str, home: str): + """What to run when the watched agent exits: for Codex, which has no + SessionEnd, closing its trace then, under the key in force at exit.""" + if agent.active().name != agent.CODEX.name: + return None + + def close() -> None: + import exporter + from rius_cc import config + cfg = config.resolve(session_id, cwd, os.environ, home) + exporter.close_exited_codex(cfg, session_id, cwd, home) + return close + + if __name__ == "__main__": try: main() diff --git a/tests/test_codex_export.py b/tests/test_codex_export.py index 547f3ea..a2e3f6e 100644 --- a/tests/test_codex_export.py +++ b/tests/test_codex_export.py @@ -1,6 +1,7 @@ """`--agent codex` end to end through the exporter: hook events re-read the -rollout, subagents land under the spawn_agent call that started them, and -the sweep closes a dead Codex session's trace after an hour. +rollout, subagents land under the spawn_agent call that started them, Codex +exiting closes the trace, and the sweep closes a dead Codex session's trace +no pinger closed after an hour. The subagent fixtures are one real codex-cli 0.144.1 run against a mock model: a `tools please` turn, then a resumed turn that spawns a `default` @@ -243,6 +244,67 @@ def test_the_closing_spans_carry_no_content(codex_home, tmp_path, sent, assert "output.value" not in s.attributes +# --- Codex exiting: its pinger closes the trace -------------------------------- + +def _exit(tmp_path, now_ns): + cfg = config.resolve(PARENT, "/tmp/proj", ENV, str(tmp_path)) + exporter.close_exited_codex(cfg, PARENT, "/tmp/proj", str(tmp_path), + now_ns=now_ns) + + +def test_codex_exiting_closes_its_trace_as_it_exits(codex_home, tmp_path, sent, + rollouts): + """Not when it was last seen: the receiver refuses a span it gets more + than an hour after its end, and a session can sit idle longer than that + before Codex is quit.""" + last_ns = _open_dead_session(tmp_path, rollouts) + del sent[:] + exited_ns = last_ns + 3 * HOUR_NS + _exit(tmp_path, exited_ns) + roots = {s.name: s for s in _spans(sent) if s.kind_oi == "AGENT"} + assert set(roots) == {"codex session", "default"} + assert all(not s.pending and s.end_ns == exited_ns for s in roots.values()) + assert not state.trace_is_open(_state(tmp_path)) + del sent[:] + _sweep(tmp_path, exited_ns + 2 * HOUR_NS) + assert sent == [], "the sweep finds nothing left to close" + + +def test_codex_exiting_sends_what_the_rollout_holds_past_the_last_hook( + codex_home, tmp_path, sent, rollouts): + """A Stop export that has not taken the lock when Codex exits reads + nothing after the close, so the close reads it.""" + whole = rollouts[PARENT].read_bytes() + _run("Stop", tmp_path, rollouts[PARENT]) + expected = set(_finished(sent)) + del sent[:] + shutil.rmtree(str(tmp_path / ".codex" / "rius" / "state")) + rollouts[PARENT].write_bytes(b"".join(whole.splitlines(keepends=True)[:12])) + _run("Stop", tmp_path, rollouts[PARENT]) + rollouts[PARENT].write_bytes(whole) + _exit(tmp_path, _state(tmp_path)["last_ns"] + HOUR_NS) + assert expected <= set(_finished(sent)) + + +def test_codex_exiting_leaves_a_trace_opened_with_another_key( + codex_home, tmp_path, sent, rollouts): + last_ns = _open_dead_session(tmp_path, rollouts) + del sent[:] + signed_in.sign_in(str(tmp_path), api_key="gf_otherworkspace99.sig") + _exit(tmp_path, last_ns + HOUR_NS) + assert sent == [] + assert state.trace_is_open(_state(tmp_path)) + + +def test_a_closed_codex_trace_sends_nothing_more_on_exit(codex_home, tmp_path, + sent, rollouts): + last_ns = _open_dead_session(tmp_path, rollouts) + _exit(tmp_path, last_ns + 1) + del sent[:] + _exit(tmp_path, last_ns + 2) + assert sent == [] + + def test_a_subagent_id_that_is_not_an_id_is_ignored(codex_home, tmp_path, sent, rollouts): _run("SubagentStop", tmp_path, rollouts[PARENT], agent_id="../../x", diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index 1fda2cc..a506f3e 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -177,6 +177,54 @@ def test_dead_parent_exits_without_stopped_ping(tmp_path): assert all(not p.get("stopped") for p in sent) +def test_a_dead_parent_runs_the_exit_hook_once(tmp_path): + exits = [] + pinger, _, _ = _make_pinger(tmp_path, lambda p, t: None, watch_pid=999999, + on_exit=lambda: exits.append(1)) + pinger.run() + assert exits == [1] + + +def test_a_stop_file_or_the_cap_never_runs_the_exit_hook(tmp_path): + exits = [] + pinger, _, _ = _make_pinger(tmp_path, _stop_writer(tmp_path, []), + on_exit=lambda: exits.append(1)) + pinger.run() + pinger, _, _ = _make_pinger(tmp_path, lambda p, t: None, max_lifetime=1.0, + on_exit=lambda: exits.append(1)) + pinger.run() + assert exits == [] + + +def test_a_failing_exit_hook_is_logged_not_raised(tmp_path): + logged = [] + + def boom(): + raise OSError("boom") + + pinger, _, _ = _make_pinger(tmp_path, lambda p, t: None, watch_pid=999999, + on_exit=boom, log=logged.append) + pinger.run() + assert any("closing the trace on exit failed" in m for m in logged) + assert not os.path.exists(pinger.pid_path()) + + +def test_only_codex_closes_its_trace_when_it_exits(monkeypatch, tmp_path): + """Codex has no SessionEnd; Claude Code's own SessionEnd closes its + trace, and its killed sessions are left to the sweep.""" + import exporter + from rius_cc import agent + home = str(tmp_path) + assert heartbeat._closer("s1", "/tmp/proj", home) is None + closed = [] + monkeypatch.setattr(exporter, "close_exited_codex", + lambda cfg, *args: closed.append((cfg.api_key,) + args)) + with agent.using(agent.CODEX): + sign_in(home, api_key="glassflow_k") + heartbeat._closer("s1", "/tmp/proj", home)() + assert closed == [("glassflow_k", "s1", "/tmp/proj", home)] + + def test_max_lifetime_cap_exits_without_stopped_ping(tmp_path): """The cap bounds the PINGER's lifetime, not the agent's. A stopped ping at the cap would falsely assert a still-running agent had