From d0a281193e0e5055c9ef200755f554b098a1e6aa Mon Sep 17 00:00:00 2001 From: Kiran Date: Thu, 22 Oct 2026 08:09:18 +0200 Subject: [PATCH 1/2] feat: Codex compactions become compaction spans, and the next model call is flagged (RIUS-1547) A compacted rollout line is a compaction span (kind summarize, executor client or provider, sizes before and after, window id, summary bytes and gated text). The first real model call after it carries gen_ai.conversation.compacted. The format is from Codex source: no real compaction was captured. --- docs/codex.md | 36 + docs/how-it-works.md | 5 + scripts/rius_cc/codex_rollout.py | 33 +- scripts/rius_cc/codex_spans.py | 131 +++- .../fixtures/codex/synthetic_compaction.jsonl | 24 + tests/test_codex_compaction.py | 637 ++++++++++++++++++ tests/test_content_never_in_state.py | 8 +- 7 files changed, 868 insertions(+), 6 deletions(-) create mode 100644 tests/fixtures/codex/synthetic_compaction.jsonl create mode 100644 tests/test_codex_compaction.py diff --git a/docs/codex.md b/docs/codex.md index 9931ba0..bf30977 100644 --- a/docs/codex.md +++ b/docs/codex.md @@ -87,6 +87,7 @@ One trace per Codex session (thread). A resumed session (`codex resume`, | LLM `` | one per model call: `input_tokens` (includes cached), `cache_read.input_tokens`, `output_tokens`, `reasoning.output_tokens` | | TOOL `` | one per call; a command that exits non-zero is `error.type = exec_command.exit_` (`exec.exit_` when a code-mode script ran it), an MCP error is `.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 `` | 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`, @@ -96,6 +97,41 @@ 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 `provider` when Codex recorded the id + of a model response for the compaction, else `client`. 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. Otherwise the next call's prompt size + is used. `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`). In particular, whether +a response id is set only for a compaction a model did on the provider's +side is not confirmed: Codex's own, model-written summaries may carry one +too, and would read as `provider`. 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 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 36a9a5e..2235efd 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -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 diff --git a/scripts/rius_cc/codex_rollout.py b/scripts/rius_cc/codex_rollout.py index 0bd17f5..7413f66 100644 --- a/scripts/rius_cc/codex_rollout.py +++ b/scripts/rius_cc/codex_rollout.py @@ -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). """ @@ -25,6 +26,7 @@ MCP_RESULT = "mcp_result" SUBAGENT_STARTED = "subagent_started" COMMAND_END = "command_end" +COMPACTED = "compacted" class Record: @@ -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), } @@ -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: diff --git a/scripts/rius_cc/codex_spans.py b/scripts/rius_cc/codex_spans.py index d9d2250..7c17bee 100644 --- a/scripts/rius_cc/codex_spans.py +++ b/scripts/rius_cc/codex_spans.py @@ -6,6 +6,7 @@ AGENT "codex session" session: CHAIN turn one per Codex turn id LLM one per token_count (one model call) + CHAIN compaction one per `compacted` line (see _on_compacted) TOOL function_call / custom_tool_call, by call_id AGENT a subagent, built from its own rollout CHAIN turn ... with a state of its own (new_subagent_state) @@ -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 @@ -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: @@ -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 []: @@ -248,10 +261,26 @@ 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. + 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", @@ -261,6 +290,101 @@ 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, + # A compaction answered by a model response was done on the + # provider's side; the trigger is not known (Codex registers no + # hook for it), so it is not set. + semconv.RIUS_COMPACTION_EXECUTOR: ( + semconv.RIUS_COMPACTION_EXECUTOR_PROVIDER + if rec.get("compaction_response_id") + else semconv.RIUS_COMPACTION_EXECUTOR_CLIENT), + } + before = (_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") @@ -684,6 +808,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, @@ -695,7 +820,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: diff --git a/tests/fixtures/codex/synthetic_compaction.jsonl b/tests/fixtures/codex/synthetic_compaction.jsonl new file mode 100644 index 0000000..c5427d9 --- /dev/null +++ b/tests/fixtures/codex/synthetic_compaction.jsonl @@ -0,0 +1,24 @@ +{"timestamp": "2026-10-20T10:00:00.000Z", "type": "session_meta", "payload": {"id": "01a10c00-0000-7000-8000-00000000c0de", "timestamp": "2026-10-20T10:00:00.000Z", "cwd": "/tmp/proj", "originator": "codex_exec", "cli_version": "0.162.1", "model_provider": "openai", "git": {"branch": "main"}}} +{"timestamp": "2026-10-20T10:00:01.000Z", "type": "event_msg", "payload": {"type": "task_started", "turn_id": "01a10c00-0001-7000-8000-000000000001"}} +{"timestamp": "2026-10-20T10:00:01.001Z", "type": "turn_context", "payload": {"turn_id": "01a10c00-0001-7000-8000-000000000001", "model": "mock-model"}} +{"timestamp": "2026-10-20T10:00:01.500Z", "type": "event_msg", "payload": {"type": "user_message", "message": "map the repository layout"}} +{"timestamp": "2026-10-20T10:00:05.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 100000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 40, "reasoning_output_tokens": 0, "total_tokens": 100040}, "last_token_usage": {"input_tokens": 100000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 40, "reasoning_output_tokens": 0, "total_tokens": 100040}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:00:05.001Z", "type": "event_msg", "payload": {"type": "agent_message", "message": "working on the layout"}} +{"timestamp": "2026-10-20T10:00:09.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "last_token_usage": {"input_tokens": 150000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 60, "reasoning_output_tokens": 0, "total_tokens": 150060}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:00:12.000Z", "type": "compacted", "payload": {"message": "The user asked for the repository layout; src holds the app and tests mirrors it.", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "map the repository layout"}]}, {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "The user asked for the repository layout; src holds the app and tests mirrors it."}]}], "window_number": 2, "first_window_id": "win-1", "previous_window_id": "win-1", "window_id": "win-2", "compaction_response_id": null, "latest_token_usage_record": {"thread_id": "01a10c00-0000-7000-8000-00000000c0de", "turn_id": "01a10c00-0001-7000-8000-000000000001", "session_id": "01a10c00-0000-7000-8000-00000000c0de", "root_turn_id": "01a10c00-0001-7000-8000-000000000001", "response_id": "resp_2", "usage": {"input_tokens": 150000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 60, "reasoning_output_tokens": 0, "total_tokens": 150060}, "turn_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "thread_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}}}} +{"timestamp": "2026-10-20T10:00:12.001Z", "type": "event_msg", "payload": {"type": "context_compacted"}} +{"timestamp": "2026-10-20T10:00:12.002Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "last_token_usage": {"input_tokens": 0, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 0, "reasoning_output_tokens": 0, "total_tokens": 20000}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:00:15.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 271000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 130, "reasoning_output_tokens": 0, "total_tokens": 271130}, "last_token_usage": {"input_tokens": 21000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 30, "reasoning_output_tokens": 0, "total_tokens": 21030}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:00:15.001Z", "type": "event_msg", "payload": {"type": "agent_message", "message": "layout mapped"}} +{"timestamp": "2026-10-20T10:00:18.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 293000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 150, "reasoning_output_tokens": 0, "total_tokens": 293150}, "last_token_usage": {"input_tokens": 22000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 20, "reasoning_output_tokens": 0, "total_tokens": 22020}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:00:19.000Z", "type": "event_msg", "payload": {"type": "task_complete", "turn_id": "01a10c00-0001-7000-8000-000000000001", "last_agent_message": "layout mapped", "duration_ms": 18000}} +{"timestamp": "2026-10-20T10:01:00.000Z", "type": "event_msg", "payload": {"type": "task_started", "turn_id": "01a10c00-0002-7000-8000-000000000002"}} +{"timestamp": "2026-10-20T10:01:00.001Z", "type": "turn_context", "payload": {"turn_id": "01a10c00-0002-7000-8000-000000000002", "model": "mock-model"}} +{"timestamp": "2026-10-20T10:01:00.500Z", "type": "event_msg", "payload": {"type": "user_message", "message": "now list the café menu code"}} +{"timestamp": "2026-10-20T10:01:04.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 493000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 200, "reasoning_output_tokens": 0, "total_tokens": 493200}, "last_token_usage": {"input_tokens": 200000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 50, "reasoning_output_tokens": 0, "total_tokens": 200050}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:01:08.000Z", "type": "compacted", "payload": {"message": "Summary of the second stretch: the café menu code lives in menu.py.", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Summary of the second stretch: the café menu code lives in menu.py."}]}], "window_number": 3, "first_window_id": "win-1", "previous_window_id": "win-2", "window_id": "win-3", "compaction_response_id": "resp_remote_1", "latest_token_usage_record": null}} +{"timestamp": "2026-10-20T10:01:08.001Z", "type": "event_msg", "payload": {"type": "context_compacted"}} +{"timestamp": "2026-10-20T10:01:11.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 511000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 225, "reasoning_output_tokens": 0, "total_tokens": 511225}, "last_token_usage": {"input_tokens": 18000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 25, "reasoning_output_tokens": 0, "total_tokens": 18025}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:01:11.001Z", "type": "event_msg", "payload": {"type": "agent_message", "message": "menu code is in menu.py"}} +{"timestamp": "2026-10-20T10:01:14.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 529500, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 240, "reasoning_output_tokens": 0, "total_tokens": 529740}, "last_token_usage": {"input_tokens": 18500, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 15, "reasoning_output_tokens": 0, "total_tokens": 18515}, "model_context_window": 258400}, "rate_limits": null}} +{"timestamp": "2026-10-20T10:01:15.000Z", "type": "event_msg", "payload": {"type": "task_complete", "turn_id": "01a10c00-0002-7000-8000-000000000002", "last_agent_message": "menu code is in menu.py", "duration_ms": 15000}} diff --git a/tests/test_codex_compaction.py b/tests/test_codex_compaction.py new file mode 100644 index 0000000..00e04c4 --- /dev/null +++ b/tests/test_codex_compaction.py @@ -0,0 +1,637 @@ +"""A Codex compaction is a span, and the model call after it says it ran on one. + +Codex writes a `compacted` line (a summary, ids, the new context window) and, +right after it, an `event_msg` `context_compacted` marker. After a local +compaction it also re-counts its context itself: a `token_count` whose +`last_token_usage` uses nothing and whose `total_tokens` is its own estimate +of the new context. The `compacted` line becomes a CHAIN span with +gen_ai.operation.name "compaction"; the size it left behind comes from the +first token_count after it, which a later hook may be the one to read. + +THE FIXTURE IS SYNTHETIC. No rollout recorded by the installed Codex +(0.162.1) holds a compaction. tests/fixtures/codex/synthetic_compaction.jsonl +is built from the field names and nesting in openai/codex +(codex-rs/history/src/lib.rs, rollout_payload.rs, protocol/src/protocol.rs), +not captured from a real run. It has a local compaction (150000 tokens down +to an estimated 20000) and a remote one (answered by a model response, no +estimate after it), each followed by two model calls. +""" +import json +import shutil + +import pytest + +import exporter +from rius_cc import agent, codex_rollout as cr +from rius_cc import codex_spans as cs +from rius_cc import config, spans +from rius_cc import _semconv_generated as semconv + +from tests import signed_in + +FIXTURE = "codex/synthetic_compaction.jsonl" +THREAD = "01a10c00-0000-7000-8000-00000000c0de" +T1 = "01a10c00-0001-7000-8000-000000000001" +T2 = "01a10c00-0002-7000-8000-000000000002" +T0 = 1792490400 * 10**9 # 2026-10-20T10:00:00Z +FLAG = "gen_ai.conversation.compacted" +SUMMARY_1 = "The user asked for the repository layout; src holds the app and tests mirrors it." +SUMMARY_2 = "Summary of the second stretch: the café menu code lives in menu.py." +END_NS = T0 + 3600 * 10**9 + + +def _ctx(capture=True, max_attr_bytes=32768): + return spans.Ctx(session_id=THREAD, cwd="/tmp/proj", git_branch="", + cc_version="", service_name="codex", + capture_content=capture, max_attr_bytes=max_attr_bytes) + + +def _fixture_lines(fixtures_dir): + return [json.loads(line) for line in + (fixtures_dir / FIXTURE).read_text(encoding="utf-8").splitlines()] + + +def _write(tmp_path, lines, name="rollout.jsonl"): + path = tmp_path / name + path.write_text("".join(json.dumps(line, ensure_ascii=False) + "\n" + for line in lines), encoding="utf-8") + return path + + +def _build_path(path, capture=True, cuts=(), round_trip=False, state=None, + max_attr_bytes=32768, each=None): + """Every span of a rollout, read in one go or cut after the given line + numbers, the way successive hooks read a growing file. `round_trip` saves + the state as JSON between hooks, as the exporter does; `each` is called + with the state after every read.""" + ctx, st = _ctx(capture, max_attr_bytes), state or cs.new_state() + lines = path.read_bytes().splitlines(keepends=True) + stops = [len(b"".join(lines[:n])) for n in cuts] + [None] + out, offset = [], 0 + for stop in stops: + records, after = cr.read_from(str(path), offset) + records = [r for r in records if stop is None or r.offset < stop] + out += cs.build(records, st, ctx) + offset = stop if stop is not None else after + if each: + each(st) + if round_trip: + st = json.loads(json.dumps(st)) + return out, st + + +def _build(fixtures_dir, **kwargs): + return _build_path(fixtures_dir / FIXTURE, **kwargs) + + +def _compactions(out): + return [s for s in out if s.attributes.get("gen_ai.operation.name") == "compaction"] + + +def _latest(out): + """The last copy of each span, by id: what the backend keeps.""" + return {s.span_id: s for s in out} + + +def _final_compactions(out): + return sorted(_compactions(list(_latest(out).values())), + key=lambda s: s.end_ns) + + +def _llm(out): + """The model calls, by the input tokens they were counted with.""" + return {s.attributes["gen_ai.usage.input_tokens"]: s + for s in out if s.kind_oi == "LLM"} + + +def _compacted_line(ts="10:00:30.000Z", **payload): + body = {"message": "sum", "window_id": "win-x"} + body.update(payload) + return {"timestamp": "2026-10-20T" + ts, "type": "compacted", "payload": body} + + +def _count_line(ts, input_tokens, output_tokens=5, total=None, estimate=None, + window=258400): + """A token_count line. `total` is the session's running total, which has + to move for the line to count as a model call.""" + def use(i, o, t): + return {"input_tokens": i, "cached_input_tokens": 0, + "output_tokens": o, "reasoning_output_tokens": 0, + "total_tokens": t} + last = (use(0, 0, estimate) if estimate is not None + else use(input_tokens, output_tokens, input_tokens + output_tokens)) + total = total if total is not None else input_tokens + output_tokens + return {"timestamp": "2026-10-20T" + ts, "type": "event_msg", "payload": { + "type": "token_count", "info": { + "total_token_usage": use(total, 0, total), + "last_token_usage": last, "model_context_window": window}}} + + +def _turn(lines, turn_id=T1): + """`lines` inside one open turn, with a session record before it.""" + head = [{"timestamp": "2026-10-20T10:00:00.000Z", "type": "session_meta", + "payload": {"id": THREAD, "cwd": "/tmp/proj", "cli_version": "0.162.1"}}, + {"timestamp": "2026-10-20T10:00:01.000Z", "type": "event_msg", + "payload": {"type": "task_started", "turn_id": turn_id}}, + {"timestamp": "2026-10-20T10:00:01.001Z", "type": "turn_context", + "payload": {"turn_id": turn_id, "model": "mock-model"}}] + return head + lines + + +def test_a_local_compaction_is_a_span_with_its_numbers(fixtures_dir): + out, _ = _build(fixtures_dir, capture=False) + local, _remote = _final_compactions(out) + assert local.attributes == { + "openinference.span.kind": "CHAIN", + "session.id": THREAD, + "gen_ai.operation.name": "compaction", + "rius.compaction.kind": "summarize", + "rius.compaction.executor": "client", + "rius.compaction.tokens.before": 150000, # the last call before it + "rius.compaction.tokens.after": 20000, # Codex's own estimate + "rius.compaction.tokens.dropped": 130000, + "rius.compaction.context_window": 258400, + "rius.compaction.id": "win-2", + "rius.compaction.summary.bytes": len(SUMMARY_1.encode("utf-8")), + } + assert local.name == "compaction" + assert local.kind_oi == "CHAIN" + assert local.pending is False and local.status_code == "OK" + assert "rius.compaction.trigger" not in local.attributes + + +def test_a_remote_compaction_is_done_by_the_provider(fixtures_dir): + out, _ = _build(fixtures_dir, capture=False) + _local, remote = _final_compactions(out) + assert remote.attributes["rius.compaction.executor"] == "provider" + assert remote.attributes["rius.compaction.kind"] == "summarize" + assert remote.attributes["rius.compaction.id"] == "win-3" + # no estimate follows it: the first call's prompt is the size left behind + assert remote.attributes["rius.compaction.tokens.before"] == 200000 + assert remote.attributes["rius.compaction.tokens.after"] == 18000 + assert remote.attributes["rius.compaction.tokens.dropped"] == 182000 + # bytes, not characters: the e-acute is two + assert remote.attributes["rius.compaction.summary.bytes"] == len(SUMMARY_2) + 1 + + +def test_the_executor_is_the_provider_only_when_a_response_id_is_set(tmp_path): + for response_id, executor in (("resp_1", "provider"), (None, "client"), + ("", "client"), (7, "client")): + path = _write(tmp_path, _turn([_compacted_line(compaction_response_id=response_id)])) + (span,), = [_compactions(_build_path(path)[0])] + assert span.attributes["rius.compaction.executor"] == executor, response_id + + +def test_a_compaction_is_the_moment_of_its_line_under_the_open_turn(fixtures_dir): + out, _ = _build(fixtures_dir) + local, remote = _final_compactions(out) + assert local.start_ns == local.end_ns == T0 + 12 * 10**9 + assert remote.start_ns == remote.end_ns == T0 + 68 * 10**9 + assert local.parent_span_id == spans.span_id_for("turn:" + T1) + assert remote.parent_span_id == spans.span_id_for("turn:" + T2) + assert local.span_id == spans.span_id_for("compaction:win-2") + assert remote.span_id == spans.span_id_for("compaction:win-3") + assert {s.trace_id for s in out} == {spans.trace_id_for(THREAD)} + + +def test_only_the_first_call_after_a_compaction_is_flagged(fixtures_dir): + out, _ = _build(fixtures_dir) + calls = _llm(out) + assert len(calls) == 7 + assert calls[100000].attributes.get(FLAG) is None # before any + assert calls[150000].attributes.get(FLAG) is None # the summarizing call + assert calls[21000].attributes[FLAG] is True # first after #1 + assert calls[22000].attributes.get(FLAG) is None + assert calls[200000].attributes.get(FLAG) is None + assert calls[18000].attributes[FLAG] is True # first after #2 + assert calls[18500].attributes.get(FLAG) is None + assert FLAG not in _final_compactions(out)[0].attributes + + +def test_codex_own_estimate_after_a_compaction_is_no_call_and_takes_no_flag(fixtures_dir): + """total_tokens=20000, nothing used: no model call is behind it, so no + LLM span, and the flag waits for the call that really ran.""" + out, _ = _build(fixtures_dir) + assert 20000 not in _llm(out) + assert sum(1 for s in out if s.kind_oi == "LLM") == 7 + first_real = _llm(out)[21000] + assert first_real.attributes[FLAG] is True + # the sum of what was used is the sum of the real calls + assert sum(s.attributes["gen_ai.usage.output_tokens"] + for s in out if s.kind_oi == "LLM") == 40 + 60 + 30 + 20 + 50 + 25 + 15 + + +def test_a_rollout_cut_anywhere_gives_the_same_spans_as_one_pass(fixtures_dir): + whole, _ = _build(fixtures_dir) + expected = {sid: (s.attributes, s.start_ns, s.end_ns, s.parent_span_id) + for sid, s in _latest(whole).items() if not s.pending} + count = len((fixtures_dir / FIXTURE).read_text().splitlines()) + for cut in range(1, count): + for trip in (False, True): + out, _ = _build(fixtures_dir, cuts=[cut], round_trip=trip) + got = {sid: (s.attributes, s.start_ns, s.end_ns, s.parent_span_id) + for sid, s in _latest(out).items() if not s.pending} + assert got == expected, (cut, trip) + # a hook per line, the state saved as JSON between them + out, _ = _build(fixtures_dir, cuts=range(1, count), round_trip=True) + assert {sid: (s.attributes, s.start_ns, s.end_ns, s.parent_span_id) + for sid, s in _latest(out).items() if not s.pending} == expected + assert [s.attributes.get(FLAG) for s in out if s.kind_oi == "LLM"] \ + == [s.attributes.get(FLAG) for s in whole if s.kind_oi == "LLM"] + + +def test_the_size_after_is_sent_again_under_the_same_id_when_it_arrives(fixtures_dir): + lines = (fixtures_dir / FIXTURE).read_text().splitlines() + cut = next(i for i, line in enumerate(lines) if '"compacted"' in line) + 1 + out, st = _build(fixtures_dir, cuts=[cut], round_trip=True) + sent = _compactions(out) + first, last = sent[0], _final_compactions(out)[0] + assert len(sent) == 3 # the line, then its size after, then the remote one's two + assert "rius.compaction.tokens.after" not in first.attributes + assert last.span_id == first.span_id + assert (last.start_ns, last.end_ns) == (first.start_ns, first.end_ns) + assert last.attributes["rius.compaction.tokens.after"] == 20000 + assert {k: v for k, v in last.attributes.items() + if not k.startswith("rius.compaction.tokens.after") + and k != "rius.compaction.tokens.dropped"} == first.attributes + + +def test_replaying_the_rollout_gives_the_same_span_ids(fixtures_dir): + first, _ = _build(fixtures_dir) + again, _ = _build(fixtures_dir) + assert [(s.span_id, s.start_ns, s.end_ns) for s in _compactions(first)] \ + == [(s.span_id, s.start_ns, s.end_ns) for s in _compactions(again)] + assert [s.span_id for s in first] == [s.span_id for s in again] + assert len({s.span_id for s in _compactions(first)}) == 2 + + +def test_the_id_falls_back_to_the_time_when_there_is_no_window_id(tmp_path): + lines = _turn([_compacted_line(ts="10:00:30.000Z", window_id=None), + _compacted_line(ts="10:00:40.000Z", window_id=None)]) + (a, b) = _compactions(_build_path(_write(tmp_path, lines))[0]) + assert "rius.compaction.id" not in a.attributes + assert a.span_id == spans.span_id_for("compaction:%d" % (T0 + 30 * 10**9)) + assert a.span_id != b.span_id + + +def test_reading_a_compacted_line_again_flags_no_later_call(fixtures_dir, tmp_path): + lines = _fixture_lines(fixtures_dir) + upto = next(i for i, line in enumerate(lines) if line["type"] == "compacted") + 1 + first = _write(tmp_path, lines[:upto], "first.jsonl") + _, st = _build_path(first) + # the offset is rewound (or the file replaced): the same lines again + out, st = _build_path(first, state=st) + assert _compactions(out) == [] + # The calls from before the compaction are not the first one after it ... + assert all(s.attributes.get(FLAG) is None for s in out if s.kind_oi == "LLM") + assert st["open_compaction"] is not None and st["compact_next"] is True + # ... the one that follows it is, once. + rest = _write(tmp_path, lines[:upto + 3], "rest.jsonl") + out, st = _build_path(rest, state=st) + calls = [s for s in out if s.kind_oi == "LLM"] + assert [s.attributes.get(FLAG) for s in calls[-1:]] == [True] + assert [s.attributes.get(FLAG) for s in calls[:-1]] == [None, None] + (span,) = _compactions(out) + assert span.attributes["rius.compaction.tokens.after"] == 20000 + out, st = _build_path(rest, state=st) + assert _compactions(out) == [] + assert all(s.attributes.get(FLAG) is None for s in out if s.kind_oi == "LLM") + + +def test_a_newer_compaction_takes_the_size_after_not_the_older_one(tmp_path): + lines = _turn([ + _count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(ts="10:00:10.000Z", window_id="old"), + _compacted_line(ts="10:00:11.000Z", window_id="new"), + _count_line("10:00:12.000Z", 0, estimate=700), + _count_line("10:00:20.000Z", 800, total=9800), + ]) + out, _ = _build_path(_write(tmp_path, lines)) + old, new = _final_compactions(out) + assert old.attributes["rius.compaction.id"] == "old" + assert "rius.compaction.tokens.after" not in old.attributes + assert new.attributes["rius.compaction.id"] == "new" + assert new.attributes["rius.compaction.tokens.after"] == 700 + # one flag for the two: the older one is not owed a call of its own + assert [s.attributes.get(FLAG) for s in out if s.kind_oi == "LLM"] == [None, True] + + +def test_a_count_that_repeats_the_last_call_is_not_the_size_after(tmp_path): + """Codex re-sends the last usage with a rate-limit update: the running + total does not move, so it is neither a call nor the new context.""" + lines = _turn([ + _count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(ts="10:00:10.000Z"), + _count_line("10:00:11.000Z", 9000, total=9000), # a repeat + _count_line("10:00:20.000Z", 800, total=9800), + ]) + out, _ = _build_path(_write(tmp_path, lines)) + (span,) = _final_compactions(out) + assert span.attributes["rius.compaction.tokens.after"] == 800 + assert [s.attributes.get(FLAG) for s in out if s.kind_oi == "LLM"] == [None, True] + + +def test_the_summary_text_is_content_and_follows_the_capture_gate(fixtures_dir): + off, st_off = _build(fixtures_dir, capture=False) + for span in _compactions(off): + assert "rius.compaction.summary.text" not in span.attributes + assert "rius.compaction.summary.bytes" in span.attributes + on, _ = _build(fixtures_dir, capture=True) + local, remote = _final_compactions(on) + assert local.attributes["rius.compaction.summary.text"] == SUMMARY_1 + assert remote.attributes["rius.compaction.summary.text"] == SUMMARY_2 + assert "rius.compaction.summary.text" in semconv.CONTENT_ATTRIBUTES + assert "rius.compaction.summary.bytes" not in semconv.CONTENT_ATTRIBUTES + + +def test_the_summary_text_never_waits_in_the_state_file(fixtures_dir): + path = fixtures_dir / FIXTURE + count = len(path.read_text().splitlines()) + blobs = [] + for capture in (True, False): + for cut in range(1, count): + _build_path(path, capture=capture, cuts=[cut], + each=lambda st: blobs.append(json.dumps(st, ensure_ascii=False))) + assert len(blobs) == 2 * 2 * (count - 1) + for blob in blobs: + assert "repository layout" not in blob + assert "menu code lives" not in blob + # With capture off, nothing of where to read it from is kept either. + seen = [] + _build_path(path, capture=False, cuts=range(1, count), + each=lambda st: seen.append(st["open_compaction"])) + held = [p for p in seen if p] + assert held and all(p["summary_at"] is None for p in held) + seen = [] + _build_path(path, capture=True, cuts=range(1, count), + each=lambda st: seen.append(st["open_compaction"])) + assert any(p and p["summary_at"] for p in seen) + + +def test_the_summary_text_is_capped_and_scrubbed_like_other_content(tmp_path): + secret = "AKIA" + "ABCDEFGHIJKLMNOP" + text = "keys: %s then a long tail %s" % (secret, "x" * 200) + path = _write(tmp_path, _turn([_compacted_line(message=text)])) + (span,) = _compactions(_build_path(path, max_attr_bytes=40)[0]) + shown = span.attributes["rius.compaction.summary.text"] + assert secret not in shown + assert "…[truncated" in shown + assert len(shown.encode("utf-8")) < len(text.encode("utf-8")) + # The size is the whole summary's, not what was kept. + assert span.attributes["rius.compaction.summary.bytes"] == len(text.encode("utf-8")) + + +def test_a_summary_that_cannot_be_read_again_is_sent_without_its_text(fixtures_dir, tmp_path): + """The text is read from the rollout when the span is built; a rollout + that is gone by then leaves the size, not a guess.""" + work = tmp_path / "rollout.jsonl" + shutil.copy(str(fixtures_dir / FIXTURE), str(work)) + lines = work.read_bytes().splitlines(keepends=True) + cut = next(i for i, line in enumerate(lines) if b'"compacted"' in line) + 1 + ctx, st = _ctx(), cs.new_state() + records, offset = cr.read_from(str(work), 0) + before = [r for r in records if r.offset < len(b"".join(lines[:cut]))] + cs.build(before, st, ctx) + work.write_bytes(b"") # the file is gone under the state + after = [r for r in records if r.offset >= len(b"".join(lines[:cut]))] + out = cs.build(after[:1], st, ctx) + (span,) = [s for s in out if s.attributes.get("gen_ai.operation.name") == "compaction"] + assert "rius.compaction.summary.text" not in span.attributes + assert span.attributes["rius.compaction.summary.bytes"] == len(SUMMARY_1.encode("utf-8")) + + +@pytest.mark.parametrize("payload, absent", [ + ({}, ["summary.bytes", "id"]), + ({"message": None}, ["summary.bytes"]), + ({"message": ["not", "text"]}, ["summary.bytes"]), + ({"message": ""}, ["summary.bytes"]), + ({"window_id": 4}, ["id"]), # an older Codex wrote a number + ({"window_id": ["w"]}, ["id"]), + ({"compaction_response_id": {"x": 1}}, []), + ({"latest_token_usage_record": "garbage"}, ["tokens.before"]), + ({"latest_token_usage_record": {"usage": [1]}}, ["tokens.before"]), + ({"latest_token_usage_record": {"usage": {"input_tokens": "7"}}}, ["tokens.before"]), + ({"latest_token_usage_record": {"usage": {"input_tokens": -7}}}, ["tokens.before"]), + ({"replacement_history": "all", "window_number": "two"}, []), +]) +def test_malformed_fields_never_write_garbage(tmp_path, payload, absent): + body = {"timestamp": "2026-10-20T10:00:30.000Z", "type": "compacted", + "payload": payload} + out, _ = _build_path(_write(tmp_path, _turn([body]))) + (span,) = _compactions(out) + for name in absent: + assert "rius.compaction." + name not in span.attributes + for key, value in span.attributes.items(): + if key.startswith("rius.compaction.tokens."): + assert isinstance(value, int) and not isinstance(value, bool) + assert value > 0 + # What is always known is always there. + assert span.attributes["rius.compaction.kind"] == "summarize" + assert span.attributes["rius.compaction.executor"] in ("client", "provider") + assert span.parent_span_id == spans.span_id_for("turn:" + T1) + + +def test_a_payload_that_is_not_a_dict_or_has_no_time_is_no_record(): + for line in ('{"type": "compacted", "payload": "text"}', + '{"type": "compacted", "payload": [1]}', + '{"type": "compacted"}', + '{"timestamp": "yesterday", "type": "compacted", "payload": {}}'): + assert cr.parse_line(line) is None + + +def test_sizes_that_are_not_sizes_are_not_sent(tmp_path): + lines = _turn([ + _compacted_line(ts="10:00:10.000Z"), + {"timestamp": "2026-10-20T10:00:11.000Z", "type": "event_msg", "payload": { + "type": "token_count", "info": { + "total_token_usage": {"total_tokens": "many"}, + "last_token_usage": {"input_tokens": "x", "output_tokens": None, + "total_tokens": True}, + "model_context_window": "big"}}}, + ]) + out, _ = _build_path(_write(tmp_path, lines)) + (span,) = _final_compactions(out) + assert not [k for k in span.attributes if k.startswith("rius.compaction.tokens.")] + assert "rius.compaction.context_window" not in span.attributes + + +def test_the_size_before_falls_back_to_what_the_line_recorded(tmp_path): + """A session traced from the middle has seen no count before the line.""" + record = {"usage": {"input_tokens": 4321}} + lines = _turn([_compacted_line(latest_token_usage_record=record), + _count_line("10:00:40.000Z", 0, estimate=321)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.tokens.before"] == 4321 + assert span.attributes["rius.compaction.tokens.dropped"] == 4000 + # a count seen before the line wins over it + lines = _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(latest_token_usage_record=record)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.tokens.before"] == 9000 + + +def test_no_dropped_count_when_the_context_grew(tmp_path): + lines = _turn([_count_line("10:00:05.000Z", 100, total=100), + _compacted_line(), _count_line("10:00:40.000Z", 0, estimate=250)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.tokens.before"] == 100 + assert span.attributes["rius.compaction.tokens.after"] == 250 + assert "rius.compaction.tokens.dropped" not in span.attributes + + +def test_a_context_left_the_same_size_drops_zero(tmp_path): + lines = _turn([_count_line("10:00:05.000Z", 250, total=250), + _compacted_line(), _count_line("10:00:40.000Z", 0, estimate=250)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.tokens.dropped"] == 0 + + +def test_a_compaction_with_nothing_after_it_is_still_a_span(tmp_path): + path = _write(tmp_path, _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line()])) + out, st = _build_path(path) + (span,) = _compactions(out) + assert span.attributes["rius.compaction.tokens.before"] == 9000 + assert "rius.compaction.tokens.after" not in span.attributes + assert st["open_compaction"] is not None and st["compact_next"] is True + # closing the session leaves it as it was sent + done = cs.finalize_session(st, _ctx(), END_NS) + assert _compactions(done) == [] + + +def test_a_compaction_outside_any_turn_is_dropped_and_flags_nothing(tmp_path): + """Before this session was traced, or inside a turn a fork copied.""" + lines = _turn([])[:1] + [_compacted_line()] + _turn([_count_line( + "10:00:40.000Z", 500, total=500)])[1:] + out, st = _build_path(_write(tmp_path, lines)) + assert _compactions(out) == [] + assert st["compact_next"] is False + assert [s.attributes.get(FLAG) for s in out if s.kind_oi == "LLM"] == [None] + + +def test_a_turn_inherited_from_a_fork_brings_no_compaction(tmp_path): + st = cs.new_state() + st["forked_at_ms"] = 2 ** 47 # after the turn's UUIDv7 time + path = _write(tmp_path, _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line()])) + out, st = _build_path(path, state=st) + assert _compactions(out) == [] + assert st["compact_next"] is False + + +def test_a_subagents_compaction_has_an_id_of_its_own(fixtures_dir): + parent, _ = _build(fixtures_dir) + sub_state = cs.new_subagent_state("0" * 8 + "-0000-7000-8000-" + "0" * 12, + "default", "p" * 16) + sub, _ = _build(fixtures_dir, state=sub_state) + assert {s.span_id for s in _compactions(sub)} \ + .isdisjoint({s.span_id for s in _compactions(parent)}) + assert len({s.span_id for s in _compactions(sub)}) == 2 + assert _llm(sub)[21000].attributes[FLAG] is True + + +def test_a_state_saved_before_compactions_were_known_still_builds(fixtures_dir): + old = cs.new_state() + for key in ("open_compaction", "compact_next", "last_compaction", + "context_tokens", "context_window"): + del old[key] + cs.upgrade_state(old) + assert old["open_compaction"] is None and old["compact_next"] is False + out, _ = _build(fixtures_dir, state=old) + assert len(_final_compactions(out)) == 2 + + +def test_the_context_compacted_marker_is_not_a_record(fixtures_dir): + records, _ = cr.read_from(str(fixtures_dir / FIXTURE), 0) + assert [r.kind for r in records].count(cr.COMPACTED) == 2 + marker = ('{"timestamp": "2026-10-20T10:00:12.001Z", "type": "event_msg", ' + '"payload": {"type": "context_compacted"}}') + assert cr.parse_line(marker) is None + compacted = [r for r in records if r.kind == cr.COMPACTED] + assert compacted[0].get("window_id") == "win-2" + assert compacted[0].get("compaction_response_id") == "" + assert compacted[0].get("recorded_tokens") == 150000 + assert compacted[1].get("compaction_response_id") == "resp_remote_1" + usage = [r for r in records if r.kind == cr.USAGE] + assert [bool(u.get("local_estimate")) for u in usage].count(True) == 1 + estimate = next(u for u in usage if u.get("local_estimate")) + assert estimate.get("context_tokens") == 20000 + assert estimate.get("input_tokens") == 0 + + +def test_a_real_call_is_not_taken_for_an_estimate(): + for last in ({"input_tokens": 5, "output_tokens": 0, "total_tokens": 5}, + {"input_tokens": 0, "output_tokens": 3, "total_tokens": 3}, + {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}): + line = json.dumps({"timestamp": "2026-10-20T10:00:12.000Z", + "type": "event_msg", "payload": { + "type": "token_count", "info": { + "total_token_usage": {"total_tokens": 9}, + "last_token_usage": last}}}) + assert cr.parse_line(line).get("local_estimate") is False + + +# --- through the exporter, one hook per growth of the file --- + +@pytest.fixture +def codex_home(tmp_path): + home = tmp_path / ".codex" + with agent.using(agent.CODEX): + signed_in.sign_in(str(tmp_path)) + config.write_path_rules(str(tmp_path), {"enabled_paths": ["/tmp"]}) + yield home + + +@pytest.fixture +def sent(monkeypatch): + batches, pending = [], {} + + def encode(resource, out): + pending["batch"] = (resource, list(out)) + return b"x" + + def export(endpoint, key, body, timeout=5.0): + batches.append(pending.pop("batch")) + return 200 + + monkeypatch.setattr(exporter.otlp, "encode", encode) + monkeypatch.setattr(exporter.otlp, "export", export) + return batches + + +def test_through_the_hooks_the_size_after_is_not_lost(codex_home, tmp_path, sent, + fixtures_dir): + """The real path: the rollout grows between two hook runs, the first + reads up to the compaction, the second the count that follows it.""" + lines = (fixtures_dir / FIXTURE).read_bytes().splitlines(keepends=True) + cut = next(i for i, line in enumerate(lines) if b'"compacted"' in line) + 2 + rollout = tmp_path / "sessions" / ("rollout-2026-10-20T10-00-00-%s.jsonl" % THREAD) + rollout.parent.mkdir() + + def hook(event, upto): + rollout.write_bytes(b"".join(lines[:upto])) + payload = {"session_id": THREAD, "cwd": "/tmp/proj", + "transcript_path": str(rollout), "hook_event_name": event} + exporter.run(event, payload, {}, str(tmp_path)) + + hook("PostToolUse", cut) + hook("PostToolUse", len(lines)) + hook("Stop", len(lines)) + + everything = [s for _, out in sent for s in out] + sent_compactions = _compactions(everything) + local = [s for s in sent_compactions if s.attributes["rius.compaction.id"] == "win-2"] + assert len(local) == 2 # the line, then with its size after + assert local[0].span_id == local[1].span_id + assert "rius.compaction.tokens.after" not in local[0].attributes + assert local[1].attributes["rius.compaction.tokens.after"] == 20000 + assert local[1].attributes["rius.compaction.summary.text"] == SUMMARY_1 + # sent once: the second hook did not read the line again + remote = [s for s in sent_compactions if s.attributes["rius.compaction.id"] == "win-3"] + assert len(remote) == 1 and remote[0].attributes["rius.compaction.tokens.after"] == 18000 + flagged = [s.attributes["gen_ai.usage.input_tokens"] + for s in everything if s.attributes.get(FLAG)] + assert flagged == [21000, 18000] + # the saved state holds ids and sizes, and no summary text + blob = (codex_home / "rius" / "state" / (THREAD + ".json")).read_text() + assert "repository layout" not in blob and "menu code lives" not in blob diff --git a/tests/test_content_never_in_state.py b/tests/test_content_never_in_state.py index 08b9ce4..52c0dd5 100644 --- a/tests/test_content_never_in_state.py +++ b/tests/test_content_never_in_state.py @@ -188,8 +188,12 @@ def codex_content_strings(path: pathlib.Path) -> set: replies, tool inputs and outputs, MCP errors.""" out = set() for line in path.read_text(encoding="utf-8").splitlines(): - payload = json.loads(line).get("payload") - for text in _codex_texts(payload if isinstance(payload, dict) else {}): + raw = json.loads(line) + payload = raw.get("payload") + payload = payload if isinstance(payload, dict) else {} + if raw.get("type") == "compacted": # the summary that replaced the history + payload = {"type": "user_message", "message": payload.get("message")} + for text in _codex_texts(payload): if isinstance(text, str) and len(text.strip()) >= CODEX_MIN_CONTENT_LEN: out.add(text.strip()) return out From 41dedda3f5b5c1b702f07d769c2d50428644d752 Mon Sep 17 00:00:00 2001 From: Kiran Date: Thu, 22 Oct 2026 09:23:38 +0200 Subject: [PATCH 2/2] fix: a Codex compaction is the provider's when its summary message is empty, and review fixes (RIUS-1547) Both Codex writers set compaction_response_id, so it cannot tell a local compaction from a remote one: the empty message can. A compaction that follows an unsettled one has no size before of its own. Tests pin the same-millisecond estimate, the estimate as the next size before, and the window learned after the line. --- docs/codex.md | 25 +++-- scripts/rius_cc/codex_spans.py | 28 ++++-- .../fixtures/codex/synthetic_compaction.jsonl | 4 +- tests/test_codex_compaction.py | 96 ++++++++++++++++--- 4 files changed, 119 insertions(+), 34 deletions(-) diff --git a/docs/codex.md b/docs/codex.md index bf30977..06fee10 100644 --- a/docs/codex.md +++ b/docs/codex.md @@ -103,16 +103,23 @@ 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 `provider` when Codex recorded the id - of a model response for the compaction, else `client`. The trigger (`auto` - or `manual`) is not set: the rollout does not say. +- `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. Otherwise the next call's prompt size - is used. `context_window` and `id` (Codex's window id) are set when known. + 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. @@ -126,10 +133,10 @@ sends it as a `CHAIN` span with `gen_ai.operation.name` set to `compaction` 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`). In particular, whether -a response id is set only for a compaction a model did on the provider's -side is not confirmed: Codex's own, model-written summaries may carry one -too, and would read as `provider`. A compaction written while no turn is +(`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 diff --git a/scripts/rius_cc/codex_spans.py b/scripts/rius_cc/codex_spans.py index 7c17bee..4d8b5d7 100644 --- a/scripts/rius_cc/codex_spans.py +++ b/scripts/rius_cc/codex_spans.py @@ -265,7 +265,9 @@ def _on_usage(rec, state, ctx, out): 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. + # 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) @@ -311,16 +313,24 @@ def _on_compacted(rec, state, ctx, out): state["last_compaction"] = rec.timestamp_ns attrs: Dict[str, Any] = { semconv.RIUS_COMPACTION_KIND: semconv.RIUS_COMPACTION_KIND_SUMMARIZE, - # A compaction answered by a model response was done on the - # provider's side; the trigger is not known (Codex registers no - # hook for it), so it is not set. + # 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_PROVIDER - if rec.get("compaction_response_id") - else semconv.RIUS_COMPACTION_EXECUTOR_CLIENT), + semconv.RIUS_COMPACTION_EXECUTOR_CLIENT + if rec.get("message") + else semconv.RIUS_COMPACTION_EXECUTOR_PROVIDER), } - before = (_positive(state.get("context_tokens")) - or _positive(rec.get("recorded_tokens"))) + # 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")): diff --git a/tests/fixtures/codex/synthetic_compaction.jsonl b/tests/fixtures/codex/synthetic_compaction.jsonl index c5427d9..3094d1c 100644 --- a/tests/fixtures/codex/synthetic_compaction.jsonl +++ b/tests/fixtures/codex/synthetic_compaction.jsonl @@ -5,7 +5,7 @@ {"timestamp": "2026-10-20T10:00:05.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 100000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 40, "reasoning_output_tokens": 0, "total_tokens": 100040}, "last_token_usage": {"input_tokens": 100000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 40, "reasoning_output_tokens": 0, "total_tokens": 100040}, "model_context_window": 258400}, "rate_limits": null}} {"timestamp": "2026-10-20T10:00:05.001Z", "type": "event_msg", "payload": {"type": "agent_message", "message": "working on the layout"}} {"timestamp": "2026-10-20T10:00:09.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "last_token_usage": {"input_tokens": 150000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 60, "reasoning_output_tokens": 0, "total_tokens": 150060}, "model_context_window": 258400}, "rate_limits": null}} -{"timestamp": "2026-10-20T10:00:12.000Z", "type": "compacted", "payload": {"message": "The user asked for the repository layout; src holds the app and tests mirrors it.", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "map the repository layout"}]}, {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "The user asked for the repository layout; src holds the app and tests mirrors it."}]}], "window_number": 2, "first_window_id": "win-1", "previous_window_id": "win-1", "window_id": "win-2", "compaction_response_id": null, "latest_token_usage_record": {"thread_id": "01a10c00-0000-7000-8000-00000000c0de", "turn_id": "01a10c00-0001-7000-8000-000000000001", "session_id": "01a10c00-0000-7000-8000-00000000c0de", "root_turn_id": "01a10c00-0001-7000-8000-000000000001", "response_id": "resp_2", "usage": {"input_tokens": 150000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 60, "reasoning_output_tokens": 0, "total_tokens": 150060}, "turn_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "thread_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}}}} +{"timestamp": "2026-10-20T10:00:12.000Z", "type": "compacted", "payload": {"message": "The user asked for the repository layout; src holds the app and tests mirrors it.", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "map the repository layout"}]}, {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "The user asked for the repository layout; src holds the app and tests mirrors it."}]}], "window_number": 2, "first_window_id": "win-1", "previous_window_id": "win-1", "window_id": "win-2", "compaction_response_id": "resp_local_1", "latest_token_usage_record": {"thread_id": "01a10c00-0000-7000-8000-00000000c0de", "turn_id": "01a10c00-0001-7000-8000-000000000001", "session_id": "01a10c00-0000-7000-8000-00000000c0de", "root_turn_id": "01a10c00-0001-7000-8000-000000000001", "response_id": "resp_2", "usage": {"input_tokens": 150000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 60, "reasoning_output_tokens": 0, "total_tokens": 150060}, "turn_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "thread_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}}}} {"timestamp": "2026-10-20T10:00:12.001Z", "type": "event_msg", "payload": {"type": "context_compacted"}} {"timestamp": "2026-10-20T10:00:12.002Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 250000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 100, "reasoning_output_tokens": 0, "total_tokens": 250100}, "last_token_usage": {"input_tokens": 0, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 0, "reasoning_output_tokens": 0, "total_tokens": 20000}, "model_context_window": 258400}, "rate_limits": null}} {"timestamp": "2026-10-20T10:00:15.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 271000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 130, "reasoning_output_tokens": 0, "total_tokens": 271130}, "last_token_usage": {"input_tokens": 21000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 30, "reasoning_output_tokens": 0, "total_tokens": 21030}, "model_context_window": 258400}, "rate_limits": null}} @@ -16,7 +16,7 @@ {"timestamp": "2026-10-20T10:01:00.001Z", "type": "turn_context", "payload": {"turn_id": "01a10c00-0002-7000-8000-000000000002", "model": "mock-model"}} {"timestamp": "2026-10-20T10:01:00.500Z", "type": "event_msg", "payload": {"type": "user_message", "message": "now list the café menu code"}} {"timestamp": "2026-10-20T10:01:04.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 493000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 200, "reasoning_output_tokens": 0, "total_tokens": 493200}, "last_token_usage": {"input_tokens": 200000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 50, "reasoning_output_tokens": 0, "total_tokens": 200050}, "model_context_window": 258400}, "rate_limits": null}} -{"timestamp": "2026-10-20T10:01:08.000Z", "type": "compacted", "payload": {"message": "Summary of the second stretch: the café menu code lives in menu.py.", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Summary of the second stretch: the café menu code lives in menu.py."}]}], "window_number": 3, "first_window_id": "win-1", "previous_window_id": "win-2", "window_id": "win-3", "compaction_response_id": "resp_remote_1", "latest_token_usage_record": null}} +{"timestamp": "2026-10-20T10:01:08.000Z", "type": "compacted", "payload": {"message": "", "replacement_history": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Summary of the second stretch: the café menu code lives in menu.py."}]}], "window_number": 3, "first_window_id": "win-1", "previous_window_id": "win-2", "window_id": "win-3", "compaction_response_id": "resp_remote_1", "latest_token_usage_record": null}} {"timestamp": "2026-10-20T10:01:08.001Z", "type": "event_msg", "payload": {"type": "context_compacted"}} {"timestamp": "2026-10-20T10:01:11.000Z", "type": "event_msg", "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 511000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 225, "reasoning_output_tokens": 0, "total_tokens": 511225}, "last_token_usage": {"input_tokens": 18000, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 25, "reasoning_output_tokens": 0, "total_tokens": 18025}, "model_context_window": 258400}, "rate_limits": null}} {"timestamp": "2026-10-20T10:01:11.001Z", "type": "event_msg", "payload": {"type": "agent_message", "message": "menu code is in menu.py"}} diff --git a/tests/test_codex_compaction.py b/tests/test_codex_compaction.py index 00e04c4..a1c10c4 100644 --- a/tests/test_codex_compaction.py +++ b/tests/test_codex_compaction.py @@ -13,8 +13,9 @@ is built from the field names and nesting in openai/codex (codex-rs/history/src/lib.rs, rollout_payload.rs, protocol/src/protocol.rs), not captured from a real run. It has a local compaction (150000 tokens down -to an estimated 20000) and a remote one (answered by a model response, no -estimate after it), each followed by two model calls. +to an estimated 20000) and a remote one (an empty message: the provider wrote +the summary; no estimate after it), each followed by two model calls. Both +carry a compaction_response_id, as Codex 0.162.1 writes it for either. """ import json import shutil @@ -170,16 +171,38 @@ def test_a_remote_compaction_is_done_by_the_provider(fixtures_dir): assert remote.attributes["rius.compaction.tokens.before"] == 200000 assert remote.attributes["rius.compaction.tokens.after"] == 18000 assert remote.attributes["rius.compaction.tokens.dropped"] == 182000 - # bytes, not characters: the e-acute is two - assert remote.attributes["rius.compaction.summary.bytes"] == len(SUMMARY_2) + 1 + # the provider wrote the summary, and Codex kept no text of it + assert "rius.compaction.summary.bytes" not in remote.attributes -def test_the_executor_is_the_provider_only_when_a_response_id_is_set(tmp_path): - for response_id, executor in (("resp_1", "provider"), (None, "client"), - ("", "client"), (7, "client")): - path = _write(tmp_path, _turn([_compacted_line(compaction_response_id=response_id)])) - (span,), = [_compactions(_build_path(path)[0])] - assert span.attributes["rius.compaction.executor"] == executor, response_id +def test_the_executor_is_the_provider_when_the_summary_message_is_empty(tmp_path): + """Both writers set the response id (compact.rs, compact_remote_v2.rs), + so it cannot tell them apart; the message can.""" + for message, response_id, executor in ( + ("summary text", "resp_1", "client"), ("summary text", None, "client"), + ("", "resp_1", "provider"), ("", None, "provider"), + (None, "resp_1", "provider")): + path = _write(tmp_path, _turn([_compacted_line( + message=message, compaction_response_id=response_id)])) + (span,) = _compactions(_build_path(path)[0]) + assert span.attributes["rius.compaction.executor"] == executor, (message, response_id) + + +def test_the_summary_size_is_in_bytes_not_characters(tmp_path): + path = _write(tmp_path, _turn([_compacted_line(message=SUMMARY_2)])) + (span,) = _compactions(_build_path(path)[0]) + assert span.attributes["rius.compaction.summary.bytes"] == len(SUMMARY_2) + 1 # the e-acute + + +def test_a_remote_compaction_is_followed_by_an_estimate_too(tmp_path): + """compact_remote_v2.rs re-counts the context after it as well.""" + lines = _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(message="", compaction_response_id="resp_r"), + _count_line("10:00:40.000Z", 0, estimate=400)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.executor"] == "provider" + assert span.attributes["rius.compaction.tokens.after"] == 400 + assert span.attributes["rius.compaction.tokens.dropped"] == 8600 def test_a_compaction_is_the_moment_of_its_line_under_the_open_turn(fixtures_dir): @@ -312,10 +335,52 @@ def test_a_newer_compaction_takes_the_size_after_not_the_older_one(tmp_path): assert "rius.compaction.tokens.after" not in old.attributes assert new.attributes["rius.compaction.id"] == "new" assert new.attributes["rius.compaction.tokens.after"] == 700 + # the size before the older one is not the size before this one + assert "rius.compaction.tokens.before" not in new.attributes + assert "rius.compaction.tokens.dropped" not in new.attributes + assert old.attributes["rius.compaction.tokens.before"] == 9000 # one flag for the two: the older one is not owed a call of its own assert [s.attributes.get(FLAG) for s in out if s.kind_oi == "LLM"] == [None, True] +def test_an_estimate_is_the_size_before_the_next_compaction(tmp_path): + """No model call between the two: Codex's own count is what the context + was when the second one ran.""" + lines = _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(ts="10:00:10.000Z", window_id="a"), + _count_line("10:00:11.000Z", 0, estimate=700), + _compacted_line(ts="10:00:30.000Z", window_id="b"), + _count_line("10:00:31.000Z", 0, estimate=300)]) + first, second = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert first.attributes["rius.compaction.tokens.after"] == 700 + assert second.attributes["rius.compaction.tokens.before"] == 700 + assert second.attributes["rius.compaction.tokens.dropped"] == 400 + + +def test_an_estimate_in_the_same_millisecond_is_the_size_after(tmp_path): + """Codex counts right after it writes the line: the same timestamp.""" + lines = _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(ts="10:00:10.000Z"), + _count_line("10:00:10.000Z", 0, estimate=700)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.tokens.after"] == 700 + + +def test_a_count_before_the_line_is_not_the_size_after(tmp_path): + lines = _turn([_count_line("10:00:05.000Z", 9000, total=9000), + _compacted_line(ts="10:00:10.000Z"), + _count_line("10:00:09.999Z", 0, estimate=123)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert "rius.compaction.tokens.after" not in span.attributes + + +def test_the_window_learned_after_the_line_is_added_when_the_size_arrives(tmp_path): + lines = _turn([_compacted_line(ts="10:00:10.000Z"), + _count_line("10:00:11.000Z", 0, estimate=700, window=111000)]) + (span,) = _final_compactions(_build_path(_write(tmp_path, lines))[0]) + assert span.attributes["rius.compaction.context_window"] == 111000 + + def test_a_count_that_repeats_the_last_call_is_not_the_size_after(tmp_path): """Codex re-sends the last usage with a rate-limit update: the running total does not move, so it is neither a call nor the new context.""" @@ -335,11 +400,12 @@ def test_the_summary_text_is_content_and_follows_the_capture_gate(fixtures_dir): off, st_off = _build(fixtures_dir, capture=False) for span in _compactions(off): assert "rius.compaction.summary.text" not in span.attributes - assert "rius.compaction.summary.bytes" in span.attributes + assert all("rius.compaction.summary.bytes" in s.attributes + for s in _final_compactions(off)[:1]) on, _ = _build(fixtures_dir, capture=True) local, remote = _final_compactions(on) assert local.attributes["rius.compaction.summary.text"] == SUMMARY_1 - assert remote.attributes["rius.compaction.summary.text"] == SUMMARY_2 + assert "rius.compaction.summary.text" not in remote.attributes # an empty message assert "rius.compaction.summary.text" in semconv.CONTENT_ATTRIBUTES assert "rius.compaction.summary.bytes" not in semconv.CONTENT_ATTRIBUTES @@ -355,7 +421,7 @@ def test_the_summary_text_never_waits_in_the_state_file(fixtures_dir): assert len(blobs) == 2 * 2 * (count - 1) for blob in blobs: assert "repository layout" not in blob - assert "menu code lives" not in blob + assert "café menu" not in blob # With capture off, nothing of where to read it from is kept either. seen = [] _build_path(path, capture=False, cuts=range(1, count), @@ -549,7 +615,9 @@ def test_the_context_compacted_marker_is_not_a_record(fixtures_dir): assert cr.parse_line(marker) is None compacted = [r for r in records if r.kind == cr.COMPACTED] assert compacted[0].get("window_id") == "win-2" - assert compacted[0].get("compaction_response_id") == "" + assert compacted[0].get("compaction_response_id") == "resp_local_1" + assert compacted[0].get("message") == SUMMARY_1 + assert compacted[1].get("message") == "" assert compacted[0].get("recorded_tokens") == 150000 assert compacted[1].get("compaction_response_id") == "resp_remote_1" usage = [r for r in records if r.kind == cr.USAGE]