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
43 changes: 43 additions & 0 deletions docs/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ One trace per Codex session (thread). A resumed session (`codex resume`,
| LLM `<model>` | one per model call: `input_tokens` (includes cached), `cache_read.input_tokens`, `output_tokens`, `reasoning.output_tokens` |
| TOOL `<tool>` | one per call; a command that exits non-zero is `error.type = exec_command.exit_<n>` (`exec.exit_<n>` when a code-mode script ran it), an MCP error is `<tool>.tool_error`; a shell call (`exec_command`, or a code-mode script that calls it) carries `rius.command.class` (`test`, `build`, `lint`, `package`, `git`, `other`) and `process.exit.code` |
| AGENT `<role>` | a subagent, under the `spawn_agent` call that started it (`multi_agent_v1`, or the opt-in `multi_agent_v2`), with its own turns and calls |
| CHAIN `compaction` | one per compaction Codex records, in the turn it happened in (below) |

Resource attributes: `service.name=codex`, `service.version` (Codex's
version), `process.working_directory`, `vcs.ref.head.name`,
Expand All @@ -96,6 +97,48 @@ the plugin's version. Content rules are the same as for Claude Code:
adds content with secrets removed, and `RIUS_CAPTURE_CONTENT=false` turns
content off everywhere.

### Compactions

When Codex compacts a conversation it writes a `compacted` line, and Rius
sends it as a `CHAIN` span with `gen_ai.operation.name` set to `compaction`
(`rius.compaction.*`):

- `kind` is `summarize`. `executor` is `client` when the `compacted` line
carries the summary text Codex wrote, and `provider` when its message is
empty (a remote compaction, where the provider wrote the summary). The
response id cannot tell them apart: Codex 0.162.1 sets it on both. The
trigger (`auto` or `manual`) is not set: the rollout does not say.
- `tokens.before` is the prompt size of the last model call before it,
`tokens.after` the size of the context Codex counts next, and
`tokens.dropped` the difference when it is positive. After a local
compaction Codex counts its own estimate of the new context (a
`token_count` that used no tokens); that is `tokens.after`, and it is not a
model call, so it gets no `LLM` span (a remote compaction is counted the
same way). Otherwise the next call's prompt size is used. `tokens.before`
is a measured prompt size and `tokens.after` may be Codex's estimate, so
`tokens.dropped` mixes the two. A compaction that follows another before
any count arrived has no `tokens.before`: the size known then is from
before the older one. `context_window` and `id` (Codex's window id) are
set when known.
- The span has no duration: Codex does not say how long a compaction took,
so it starts and ends at its line. It is sent when the line is read and
sent again, under the same span id, once the size after it is known.
- The first model call after a compaction has `gen_ai.conversation.compacted`
set; the later ones do not.
- `summary.bytes` is the size of the summary. The summary text
(`summary.text`) is content: it is sent only where content is, with
secrets removed and capped like the rest, and is not kept in the state
file.

This was written from Codex's source (openai/codex: the `compacted` rollout
line and the `token_count` event), not from a recorded compaction: none of
the rollouts used here holds one, and the tests run on a synthetic rollout
(`tests/fixtures/codex/synthetic_compaction.jsonl`). The `executor`
rule (an empty message means the provider did it) was checked against the
0.162.1 source (`compact.rs`, `compact_remote_v2.rs`), and holds for that
version only; older writers were not read. A compaction written while no turn is
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
Expand Down
5 changes: 5 additions & 0 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ summary entry itself is not a turn. Claude Code writes it just after the
boundary, so the span can be sent once without the summary and again, under
the same span id, with it.

**Codex compactions are `CHAIN` spans too**, read from the `compacted` line
in the rollout, with the same flag on the next model call. See
[Rius for Codex](codex.md#compactions) for what they carry and what is not
known.

**Each generation says what its prompt held**, as sizes, in
`rius.context.sizes` (the attribute the Rius SDKs send). The console's
Context panel uses it to split a call's prompt into user and assistant
Expand Down
33 changes: 32 additions & 1 deletion scripts/rius_cc/codex_rollout.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Codex rollout JSONL -> neutral Record objects.

A rollout (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl`) is one
`{timestamp, type, payload}` object per line. Only the lines that say what
`{timestamp, type, payload}` object per line (Codex's `RolloutLine`, whose
item is flattened into it: a compaction is `type: "compacted"`). Only the lines that say what
happened are turned into records; prompts Codex injects, world state and the
like are skipped. Knows nothing about spans (that's codex_spans.py).
"""
Expand All @@ -25,6 +26,7 @@
MCP_RESULT = "mcp_result"
SUBAGENT_STARTED = "subagent_started"
COMMAND_END = "command_end"
COMPACTED = "compacted"


class Record:
Expand Down Expand Up @@ -92,6 +94,33 @@ def _usage(p: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"output_tokens": _int(last.get("output_tokens")),
"reasoning_output_tokens": _int(last.get("reasoning_output_tokens")),
"context_window": _int(info.get("model_context_window")),
# What Codex writes when it re-counts its context without calling
# the model (right after a compaction, say): the size it estimates
# in `total_tokens`, and nothing used. No model call is behind it.
"local_estimate": _estimate(last),
"context_tokens": _int(last.get("total_tokens")),
}


def _estimate(last: Dict[str, Any]) -> bool:
return (_int(last.get("total_tokens")) > 0 and not _int(last.get("input_tokens"))
and not _int(last.get("output_tokens")))


def _compacted(p: Dict[str, Any]) -> Dict[str, Any]:
"""A `compacted` line: Codex replaced the history. `message` is the
summary text (empty when the summary is not readable text); the ids are
strings, and `window_id` an older Codex wrote as a number is no id."""
record = p.get("latest_token_usage_record")
usage = record.get("usage") if isinstance(record, dict) else None
return {
"message": _text(p.get("message")),
"window_id": _text(p.get("window_id")),
"compaction_response_id": _text(p.get("compaction_response_id")),
# The last call's prompt size, as Codex stamped it on the line: what
# to go by when no token_count was seen before it.
"recorded_tokens": _int(usage.get("input_tokens")
if isinstance(usage, dict) else None),
}


Expand Down Expand Up @@ -198,6 +227,8 @@ def _fields_for(line_type: str, payload: Dict[str, Any]):
return SESSION, _session(payload)
if line_type == "turn_context":
return TURN_CONTEXT, _turn_context(payload)
if line_type == "compacted":
return COMPACTED, _compacted(payload)
table = _EVENTS if line_type == "event_msg" else _ITEMS if line_type == "response_item" else {}
kind, parse = table.get(_text(payload.get("type")), (None, None))
if kind is None:
Expand Down
141 changes: 138 additions & 3 deletions scripts/rius_cc/codex_spans.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
AGENT "codex session" session:<thread id>
CHAIN turn one per Codex turn id
LLM <model> one per token_count (one model call)
CHAIN compaction one per `compacted` line (see _on_compacted)
TOOL <tool> function_call / custom_tool_call, by call_id
AGENT <agent type> a subagent, built from its own rollout
CHAIN turn ... with a state of its own (new_subagent_state)
Expand All @@ -27,7 +28,8 @@

from . import codex_rollout as cr
from . import codex_script, command_class, distro, scrub
from .spans import (ERROR_MESSAGE_MAX_BYTES, TOOL_ERROR_WITHHELD, Ctx, Span,
from .spans import (COMPACTION_OPERATION, ERROR_MESSAGE_MAX_BYTES,
TOOL_ERROR_WITHHELD, Ctx, Span,
_base_attrs, _content_attr, span_id_for, trace_id_for,
truncate)
from . import _semconv_generated as semconv
Expand Down Expand Up @@ -64,7 +66,14 @@
def new_state() -> dict:
return {"root_started": False, "root_start_ns": 0, "finalized": False,
"session": {}, "model": "", "turn": None, "open_tools": {},
"spawned": {}, "execs": []}
"spawned": {}, "execs": [],
# A compaction still waiting for the size of the context it left
# (ids and sizes only), whether the next model call is the first
# after one, the time (ns) of the latest `compacted` line read,
# and the size of the context and its window as the last
# token_count said.
"open_compaction": None, "compact_next": False,
"last_compaction": None, "context_tokens": 0, "context_window": 0}


def upgrade_state(state: dict) -> None:
Expand All @@ -73,6 +82,10 @@ def upgrade_state(state: dict) -> None:
in `tool_starts`; none of that is left behind, so the plaintext does not
outlive the upgrade and a subagent spawned by a call that began before it
still finds that call."""
for key, value in (("open_compaction", None), ("compact_next", False),
("last_compaction", None), ("context_tokens", 0),
("context_window", 0)):
state.setdefault(key, value)
open_ids = {tool["span_id"] for tool in state["open_tools"].values()}
execs = state.setdefault("execs", [])
for start_ns, span_id, name in state.pop("tool_starts", None) or []:
Expand Down Expand Up @@ -248,10 +261,28 @@ def _reply(ctx: Ctx, turn: dict) -> str:


def _on_usage(rec, state, ctx, out):
if rec.get("context_window"):
state["context_window"] = rec.get("context_window")
if rec.get("local_estimate"):
# Codex re-counted its context itself: no model call, so no LLM span
# and no flag, but it is the size the context was left at. (Codex's
# "context window full" update has the same shape, with a delta that
# is not a size; it is rare and, in a long session, zero.)
state["context_tokens"] = rec.get("context_tokens")
_settle_compaction(state, ctx, out, rec.get("context_tokens"),
rec.timestamp_ns)
return
if _repeats_last_call(rec, state):
return
turn = state["turn"]
state["context_tokens"] = rec.get("input_tokens")
_settle_compaction(state, ctx, out, rec.get("input_tokens"), rec.timestamp_ns)
attrs = _usage_attrs(ctx, state["model"], rec)
if state.get("compact_next") and rec.timestamp_ns >= (state.get("last_compaction") or 0):
# The first call after a compaction, and no other: the later ones
# also run on the compacted context, but only this one first saw it.
attrs[semconv.GEN_AI_CONVERSATION_COMPACTED] = True
state["compact_next"] = False
_content_attr(ctx, attrs, semconv.OUTPUT_VALUE, _reply(ctx, turn))
out.append(_finished(ctx, _llm_span_id(turn), turn["span_id"],
state["model"] or "model call", "LLM",
Expand All @@ -261,6 +292,109 @@ def _on_usage(rec, state, ctx, out):
turn["reply_at"] = []


def _positive(value: Any) -> Optional[int]:
"""`value` when it is a positive integer: a size of 0 is Codex not
knowing, and is never sent."""
ok = isinstance(value, int) and not isinstance(value, bool) and value > 0
return value if ok else None


def _on_compacted(rec, state, ctx, out):
"""Codex replaced the history with a summary (a `compacted` line).

The span is sent as soon as the line is read, and again, under the same
id, when the size of the context it left arrives (the next token_count,
which a later hook may be the one to read). The summary text is not
kept in the state: only where to read it again, as for any content."""
if rec.timestamp_ns <= (state.get("last_compaction") or 0):
# Read again (a rewound offset, a copied history): the span went
# out the first time, and the call it flagged is past.
return
state["last_compaction"] = rec.timestamp_ns
attrs: Dict[str, Any] = {
semconv.RIUS_COMPACTION_KIND: semconv.RIUS_COMPACTION_KIND_SUMMARIZE,
# Codex 0.162.1 sets compaction_response_id on every compaction, the
# local summarizer's too, so the id says nothing about who did it.
# What differs: a local one carries the summary text it wrote, and a
# remote (provider-side) one writes an empty message. The trigger is
# not known (Codex registers no hook for it), so it is not set.
semconv.RIUS_COMPACTION_EXECUTOR: (
semconv.RIUS_COMPACTION_EXECUTOR_CLIENT
if rec.get("message")
else semconv.RIUS_COMPACTION_EXECUTOR_PROVIDER),
}
# tokens.before is a measured prompt size and tokens.after (when Codex
# estimates it) is Codex's own count, so `dropped` mixes the two.
# A compaction right after one still waiting for its size has no size of
# its own before it: what is known is the size before the older one.
older_unsettled = isinstance(state.get("open_compaction"), dict)
before = None if older_unsettled else (
_positive(state.get("context_tokens"))
or _positive(rec.get("recorded_tokens")))
if before:
attrs[semconv.RIUS_COMPACTION_TOKENS_BEFORE] = before
if _positive(state.get("context_window")):
attrs[semconv.RIUS_COMPACTION_CONTEXT_WINDOW] = state["context_window"]
ident = rec.get("window_id")
if ident:
attrs[semconv.RIUS_COMPACTION_ID] = ident
summary = rec.get("message")
if summary:
# A size, not content: sent whatever the capture setting.
attrs[semconv.RIUS_COMPACTION_SUMMARY_BYTES] = len(
summary.encode("utf-8", "surrogatepass"))
# A subagent's compaction is its own: its root id keeps the ids apart.
key = "compaction:" + (state.get("root_id") or "")
pending = {
"span_id": span_id_for(key + (ident or str(rec.timestamp_ns))),
"parent_span_id": state["turn"]["span_id"],
# Codex does not say how long it took: the line is the moment.
"start_ns": rec.timestamp_ns, "end_ns": rec.timestamp_ns,
"attrs": attrs, "summary_at": _hold(ctx, rec),
}
# A newer compaction takes over: the one still waiting for its size
# keeps what it was sent with, and is not given the newer one's.
state["open_compaction"] = pending
state["compact_next"] = True
_emit_compaction(ctx, pending, out)


def _settle_compaction(state, ctx, out, tokens_after, at_ns) -> None:
"""The first size Codex gives for the context after a compaction. A count
dated before the line (the rollout read from the top again) is not it."""
pending = state.get("open_compaction")
if not isinstance(pending, dict) or at_ns < pending["start_ns"]:
return
state["open_compaction"] = None
attrs = pending["attrs"]
after = _positive(tokens_after)
if after:
attrs[semconv.RIUS_COMPACTION_TOKENS_AFTER] = after
before = attrs.get(semconv.RIUS_COMPACTION_TOKENS_BEFORE)
if before is not None and before >= after:
attrs[semconv.RIUS_COMPACTION_TOKENS_DROPPED] = before - after
if (_positive(state.get("context_window"))
and semconv.RIUS_COMPACTION_CONTEXT_WINDOW not in attrs):
attrs[semconv.RIUS_COMPACTION_CONTEXT_WINDOW] = state["context_window"]
_emit_compaction(ctx, pending, out)


def _emit_compaction(ctx: Ctx, pending: dict, out: list) -> None:
"""The compaction's span, once per id in `out`: a batch that holds the
line and the count after it sends only the finished copy."""
attrs = _attrs(ctx, "CHAIN")
attrs[semconv.GEN_AI_OPERATION_NAME] = COMPACTION_OPERATION
attrs.update(pending["attrs"])
# The summary is content: read again from the rollout, behind the gate.
summary = _recall(ctx, pending.get("summary_at"), "message")
if summary:
_content_attr(ctx, attrs, semconv.RIUS_COMPACTION_SUMMARY_TEXT, summary)
out[:] = [s for s in out if s.span_id != pending["span_id"]]
out.append(_finished(ctx, pending["span_id"], pending["parent_span_id"],
COMPACTION_OPERATION, "CHAIN", pending["start_ns"],
pending["end_ns"], attrs))


def _on_tool_call(rec, state, ctx, out):
call_id = rec.get("call_id")
name = rec.get("name")
Expand Down Expand Up @@ -684,6 +818,7 @@ def _on_turn_end(rec, state, ctx, out):
cr.USER_MESSAGE: _on_user_message,
cr.AGENT_MESSAGE: _on_agent_message,
cr.USAGE: _on_usage,
cr.COMPACTED: _on_compacted,
cr.TOOL_CALL: _on_tool_call,
cr.MCP_RESULT: _on_mcp_result,
cr.SUBAGENT_STARTED: _on_subagent_started,
Expand All @@ -695,7 +830,7 @@ def _on_turn_end(rec, state, ctx, out):
# Kinds that only mean something inside a turn. One seen with no turn open
# began before this session was traced, and is dropped.
_NEEDS_TURN = {cr.USER_MESSAGE, cr.AGENT_MESSAGE, cr.USAGE, cr.TOOL_CALL,
cr.TURN_END}
cr.COMPACTED, cr.TURN_END}


def _inherited(rec, state: dict) -> bool:
Expand Down
Loading
Loading