Skip to content
Open
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
15 changes: 11 additions & 4 deletions docs/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
58 changes: 55 additions & 3 deletions scripts/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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)
Expand Down
32 changes: 29 additions & 3 deletions scripts/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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")
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down
66 changes: 64 additions & 2 deletions tests/test_codex_export.py
Original file line number Diff line number Diff line change
@@ -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`
Expand Down Expand Up @@ -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",
Expand Down
48 changes: 48 additions & 0 deletions tests/test_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading