From f97620dea4c575423802095ffd8e3477f617d9dd Mon Sep 17 00:00:00 2001 From: Kiran Date: Thu, 22 Oct 2026 00:41:04 +0200 Subject: [PATCH] feat: Claude Code compactions become compaction spans, with the summary that replaced the history (RIUS-1543) A compact_boundary entry is exported as a compaction span (kind summarize, executor client, trigger, tokens before/after/dropped, messages kept, id, summary bytes, and the summary text when content capture is on). The first LLM call after it carries gen_ai.conversation.compacted. The isCompactSummary entry is no longer a user turn. Re-vendors rius-semconv v1.8.0. Signed-off-by: Kiran --- docs/how-it-works.md | 12 + scripts/rius_cc/_semconv_generated.py | 231 ++++++++++++- scripts/rius_cc/continuation.py | 1 + scripts/rius_cc/spans.py | 123 ++++++- scripts/rius_cc/state.py | 8 + scripts/rius_cc/transcript.py | 21 +- tests/fixtures/compaction.jsonl | 12 + tests/test_compaction.py | 475 ++++++++++++++++++++++++++ tests/test_transcript.py | 28 ++ 9 files changed, 900 insertions(+), 11 deletions(-) create mode 100644 tests/fixtures/compaction.jsonl create mode 100644 tests/test_compaction.py diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 718cf3c..36a9a5e 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -36,6 +36,18 @@ span with its usage counted once, and every tool it called hangs beneath it. A response whose lines arrive over several hook events is re-sent under the same span id; the backend keeps the latest copy. +**Each compaction is a `CHAIN` span** with `gen_ai.operation.name` set to +`compaction`, beside the generations in the turn it happened in. It carries +the trigger (`auto` or `manual`), the tokens before and after, the tokens +dropped, how many messages were kept, and the size of the summary in bytes +(`rius.compaction.*`). It starts `durationMs` before Claude Code's boundary +entry and ends at it. The summary text is content: it is sent only where +content is, and capped like the rest. The first model call after a +compaction has `gen_ai.conversation.compacted` set; later calls do not. The +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. + **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/_semconv_generated.py b/scripts/rius_cc/_semconv_generated.py index 19b27b5..ca72ee5 100644 --- a/scripts/rius_cc/_semconv_generated.py +++ b/scripts/rius_cc/_semconv_generated.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv v1.6.0 out/python/_semconv_generated.py by +# Vendored from rius-semconv v1.8.0 out/python/_semconv_generated.py by # scripts/sync-semconv.sh. Do not edit: change the registry in rius-semconv. """Rius semantic conventions: the constants and tables, generated. @@ -53,8 +53,9 @@ # the old per-agent spellings for traces stored before. VCS_REF_HEAD_NAME = "vcs.ref.head.name" -# Names the distribution that exported the span. Both SDKs set it as an -# inline literal, "glassflow-rius". The coding-agent plugin sets +# Names the distribution that exported the span. Both SDKs set it to +# "glassflow-rius", a literal with no value row since the backend never +# matches on it. The coding-agent plugin sets # TELEMETRY_DISTRO_NAME_CODING_AGENTS, and the backend reads # process.working_directory and vcs.ref.head.name as a coding session's # repo and branch only on spans carrying that value: both keys are general @@ -63,8 +64,7 @@ TELEMETRY_DISTRO_NAME_CODING_AGENTS = "rius-coding-agents" # The version of the distribution that exported the span: the SDK's, or the -# coding-agent plugin's. Inline literal in both SDKs, like -# telemetry.distro.name. +# coding-agent plugin's. TELEMETRY_DISTRO_VERSION = "telemetry.distro.version" # The agent this process IS, stamped once on the resource so every span it @@ -252,6 +252,19 @@ GEN_AI_REQUEST_ENCODING_FORMATS = "gen_ai.request.encoding_formats" GEN_AI_REQUEST_PREVIOUS_RESPONSE_ID = "gen_ai.request.previous_response.id" GEN_AI_REQUEST_STREAM_CURSOR = "gen_ai.request.stream_cursor" + +# The convention's positive marker that the context a model call ran on is +# a compacted view of a prior conversation. A producer sets it only when +# true, on every LLM span whose context was compacted, and leaves it unset +# otherwise: the convention says never to write false, so a reader treats a +# missing key as "not known to be compacted". The compaction itself, and +# how much it removed, is the rius.compaction span or event; this key only +# marks the calls that ran on the result. Metadata, not identity: the +# producer learns the context was compacted when it links the call to the +# compaction, which can be after the call span has started, so it never +# rides a pending snapshot. Not content, so it survives +# capture_content=False. +GEN_AI_CONVERSATION_COMPACTED = "gen_ai.conversation.compacted" GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens" GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens" GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.cache_read.input_tokens" @@ -260,6 +273,42 @@ # cache fields first shipped; no released SDK version carries the old name. GEN_AI_USAGE_CACHE_WRITE_INPUT_TOKENS = "gen_ai.usage.cache_write.input_tokens" GEN_AI_USAGE_REASONING_OUTPUT_TOKENS = "gen_ai.usage.reasoning.output_tokens" + +# A per-modality subset of gen_ai.usage.input_tokens: never summed +# into it. +GEN_AI_USAGE_TEXT_INPUT_TOKENS = "gen_ai.usage.text.input_tokens" + +# A per-modality subset of gen_ai.usage.output_tokens: never summed +# into it. +GEN_AI_USAGE_TEXT_OUTPUT_TOKENS = "gen_ai.usage.text.output_tokens" + +# A per-modality subset of gen_ai.usage.cache_read.input_tokens: never summed +# into it. +GEN_AI_USAGE_TEXT_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.text.cache_read.input_tokens" + +# A per-modality subset of gen_ai.usage.input_tokens: never summed +# into it. +GEN_AI_USAGE_IMAGE_INPUT_TOKENS = "gen_ai.usage.image.input_tokens" + +# A per-modality subset of gen_ai.usage.output_tokens: never summed +# into it. +GEN_AI_USAGE_IMAGE_OUTPUT_TOKENS = "gen_ai.usage.image.output_tokens" + +# A per-modality subset of gen_ai.usage.cache_read.input_tokens: never summed +# into it. +GEN_AI_USAGE_IMAGE_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.image.cache_read.input_tokens" + +# A per-modality subset of gen_ai.usage.input_tokens: never summed +# into it. +GEN_AI_USAGE_AUDIO_INPUT_TOKENS = "gen_ai.usage.audio.input_tokens" + +# A per-modality subset of gen_ai.usage.output_tokens: never summed +# into it. +GEN_AI_USAGE_AUDIO_OUTPUT_TOKENS = "gen_ai.usage.audio.output_tokens" + +# A per-modality subset of gen_ai.usage.cache_read.input_tokens: never summed +# into it. +GEN_AI_USAGE_AUDIO_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.audio.cache_read.input_tokens" GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages" GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages" GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons" @@ -387,6 +436,9 @@ # output_messages (literal role, parts typed text / tool_call / # tool_call_response with bytes and tool name), cache_marker, and a folded # summary of older input. +# A media part (blob / uri / file) carries its modality (image, video, +# audio or document) and, when known, byte_size, never bytes: the size of +# the media itself, not of any content, which a blob does not carry. # A Rius vendor attribute, NOT a convention: # the backend reads it to attribute gen_ai.usage.input_tokens across the # context, and no convention describes context composition. Deliberately @@ -396,6 +448,115 @@ # (content is unknown at span start, so a pending snapshot never has it). RIUS_CONTEXT_SIZES = "rius.context.sizes" +# --- Context compaction --- +# An agent's context can shrink in two ways: the history is dropped without +# a word, or the producer compacts it on purpose. A backend can tell the two +# apart only if the producer says so, and no convention carries more than a +# boolean on the calls that ran on a compacted context +# (gen_ai.conversation.compacted). +# The rius.compaction.* keys say what was compacted, by whom and how much. +# +# They ride in two placements, because compaction happens in two ways. A +# compaction that is a step of its own (Claude Code, Codex, an on-demand +# provider call) is a CHAIN span whose gen_ai.operation.name is +# "compaction", carrying the keys itself. A compaction that happens inside +# one request (provider-side context editing, Cursor's preCompact) is a +# rius.compaction span event on that LLM span, carrying the same keys. +# Every LLM call that runs on the compacted context sets +# gen_ai.conversation.compacted. +# How the context was shrunk: summarize (a summary replaces older turns), +# clear_tool_results (old tool results are emptied), clear_thinking (old +# thinking blocks are dropped) or truncate (old turns are cut with nothing +# in their place). A reader needs it because the four lose different +# things, and a drop in context between two calls means something else +# after each. +# Required on a compaction span and a rius.compaction event, which is why +# it is conditionally required rather than required: only those carry it, +# and a CHAIN or LLM span that is no compaction has nothing to say here. +# The span form is keyed by gen_ai.operation.name, not by the span name: +# the registry's conventions already key spans by the operation, and +# taxonomy.yaml maps "compaction" to the CHAIN kind from it, so a reader +# that finds compaction spans by operation needs no name parsing. +# A Rius key under rius.*, never gen_ai.*: no convention defines a +# compaction span or event, and the GenAI registry is free to define one +# later and mean something else. +RIUS_COMPACTION_KIND = "rius.compaction.kind" +RIUS_COMPACTION_KIND_SUMMARIZE = "summarize" +RIUS_COMPACTION_KIND_CLEAR_TOOL_RESULTS = "clear_tool_results" +RIUS_COMPACTION_KIND_CLEAR_THINKING = "clear_thinking" +RIUS_COMPACTION_KIND_TRUNCATE = "truncate" + +# client when the application or agent did the work (it summarized the +# history itself, or cut it before sending), provider when the model +# provider did it on its side (context editing, a server-side compaction +# call). It tells a reader whose behaviour to look at when context +# shrinks: the agent's own policy, or a provider setting. Required where +# rius.compaction.kind is, for the same reason. +RIUS_COMPACTION_EXECUTOR = "rius.compaction.executor" +RIUS_COMPACTION_EXECUTOR_CLIENT = "client" +RIUS_COMPACTION_EXECUTOR_PROVIDER = "provider" + +# auto when the producer or provider compacted because the context neared +# its limit, manual when a person or the calling code asked for it (a +# /compact command, an explicit call). Absent when the producer cannot +# tell. It separates a compaction that was a cost of the run from one +# somebody chose. +RIUS_COMPACTION_TRIGGER = "rius.compaction.trigger" +RIUS_COMPACTION_TRIGGER_AUTO = "auto" +RIUS_COMPACTION_TRIGGER_MANUAL = "manual" + +# The size of the context the compaction started from, in the model's +# tokens. Not gen_ai.usage.input_tokens: that bills one request, while this +# measures the context window's contents at a point in time. +RIUS_COMPACTION_TOKENS_BEFORE = "rius.compaction.tokens.before" + +# The size of the context the compaction left behind, measured the same +# way as rius.compaction.tokens.before. +RIUS_COMPACTION_TOKENS_AFTER = "rius.compaction.tokens.after" + +# What the compaction removed: tokens.before minus tokens.after when both +# are known. Its own key because a provider that clears tool results often +# reports only how much it cleared and never the two sizes, and a reader +# should not have to subtract to answer "how much was lost". +RIUS_COMPACTION_TOKENS_DROPPED = "rius.compaction.tokens.dropped" + +# The limit the context was measured against, so tokens.before reads as how +# full the window was. Shared form of what Cursor's preCompact hook reports +# as cursor.context.context_window_size. +RIUS_COMPACTION_CONTEXT_WINDOW = "rius.compaction.context_window" + +# The number of messages that were summarized, cut or emptied, whichever +# the kind says. +RIUS_COMPACTION_MESSAGES_COMPACTED = "rius.compaction.messages.compacted" + +# The messages the next call still sees unchanged, usually the most recent +# turns. The summary, when there is one, is not counted here. +RIUS_COMPACTION_MESSAGES_KEPT = "rius.compaction.messages.kept" + +# Set for a clear_tool_results compaction, where the messages stay but +# their tool results are replaced by a placeholder, so +# rius.compaction.messages.compacted does not describe the loss. +RIUS_COMPACTION_TOOL_RESULTS_CLEARED = "rius.compaction.tool_results.cleared" + +# Lets a reader join a compaction to the record the provider or the agent +# keeps for it. Set only when one exists: an id is never made up, as with +# gen_ai.conversation.id. +RIUS_COMPACTION_ID = "rius.compaction.id" + +# A size, not content, like rius.context.sizes: deliberately absent from +# CONTENT_ATTRIBUTES, so it survives masking and capture_content=False and +# a reader can see how big the summary was when its text is withheld. +RIUS_COMPACTION_SUMMARY_BYTES = "rius.compaction.summary.bytes" + +# What the summary said, for a summarize compaction. Content in the same +# sense messages are: a summary restates the conversation, so it is on +# CONTENT_ATTRIBUTES and is masked or stripped at export. Never on a +# pending snapshot, since it exists only once the compaction ran. +# A leaf under rius.compaction.summary rather than the key itself, so the +# name is not also the namespace of rius.compaction.summary.bytes, which +# the OpenTelemetry naming rules do not allow for an attribute. +RIUS_COMPACTION_SUMMARY_TEXT = "rius.compaction.summary.text" + # --- Span event names --- # Deprecated: replaced by the gen_ai.response.time_to_first_chunk span attribute. # First streamed token/chunk arrived. The standard signal is the span @@ -410,6 +571,15 @@ # until a major release. GEN_AI_FIRST_TOKEN_EVENT = "gen_ai.first_token" +# A compaction that happens inside one request, with no step of its own: +# the provider edits the context as part of the call, or the agent's hook +# reports it while the call is open. It is an event on that LLM span and +# carries the rius.compaction.* attributes. A compaction that is a step of +# its own is a CHAIN span with gen_ai.operation.name "compaction" instead, +# never both for the same compaction. Every LLM call that runs on the +# compacted context sets gen_ai.conversation.compacted. +RIUS_COMPACTION_EVENT = "rius.compaction" + # --- Pending (partial) spans --- # Marks the content-free snapshot exported at span START; the backend maps it # to Finished=0 and the real span replaces it at end. This key knowingly bends @@ -903,6 +1073,11 @@ # recognises onto gen_ai.request.*, so what reaches here is exactly # the set nothing has classified. LLM_INVOCATION_PARAMETERS, + # A compaction's summary restates the conversation it replaced, so it + # is content in the same sense messages are. Its size, + # rius.compaction.summary.bytes, is not: it stays off this list and + # survives masking. + RIUS_COMPACTION_SUMMARY_TEXT, } # The NAMED EXCEPTION to the rule that request parameters export in clear. # That rule is right for scalar knobs, but a caller passing tools through @@ -1006,8 +1181,8 @@ class SpanKind(str, Enum): } # The inverse, for spans that speak the conventions (and the GenAI-native -# vendor operations listed below, such as agent_step and rerank). A -# GenAI-native instrumentation sets gen_ai.operation.name and never heard of +# vendor operations listed below, such as agent_step, compaction and rerank). +# A GenAI-native instrumentation sets gen_ai.operation.name and never heard of # openinference.span.kind, and both keys must be present on every span, so # the derivation has to run in both directions. # @@ -1017,7 +1192,7 @@ class SpanKind(str, Enum): # are LLM calls the same way chat is, and create_agent is an AGENT span # just as invoke_agent is, so the mapping is many-to-one and only the # chat/invoke_agent entries round-trip. -# - CHAIN has no operation of its own, but three operations land on it. +# - CHAIN has no operation of its own, but four operations land on it. # invoke_workflow and plan are real GenAI operations with no taxonomy # value of their own; CHAIN is the honest home for both, and the reverse # direction is the only one that can say so. agent_step is not a @@ -1025,6 +1200,13 @@ class SpanKind(str, Enum): # each step of an agent run (one model call and the tools it asked # for), a step within the run rather than an agent invocation, so # CHAIN as well. +# - compaction is not a conventions operation either. A producer writes it +# on the span of a step that shrinks the agent's context (a summary +# replaces older turns, tool results are cleared, old turns are cut). The +# step is not a model call and not an agent invocation, so neither LLM +# nor AGENT fits, even when a model writes the summary: the cost of that +# call, if any, is its own LLM span. CHAIN is the honest home, as for +# agent_step. The span's attributes are the rius.compaction.* keys. # - LLM also takes four operations @ai-sdk/otel writes that no convention # defines, kept as written rather than rewritten to chat or given an # invented name: decide (the experimental decision call: an operation @@ -1046,6 +1228,7 @@ class SpanKind(str, Enum): "invoke_workflow": SpanKind.CHAIN, "plan": SpanKind.CHAIN, "agent_step": SpanKind.CHAIN, + "compaction": SpanKind.CHAIN, "decide": SpanKind.LLM, "ai.generateSpeech": SpanKind.LLM, "ai.transcribe": SpanKind.LLM, @@ -1141,6 +1324,7 @@ class SpanKind(str, Enum): "GEN_AI_AGENT_ID", "GEN_AI_AGENT_NAME", "GEN_AI_AGENT_VERSION", + "GEN_AI_CONVERSATION_COMPACTED", "GEN_AI_DATA_SOURCE_ID", "GEN_AI_FIRST_TOKEN_EVENT", "GEN_AI_INPUT_MESSAGES", @@ -1178,12 +1362,21 @@ class SpanKind(str, Enum): "GEN_AI_TOOL_DEFINITIONS", "GEN_AI_TOOL_NAME", "GEN_AI_TOOL_TYPE", + "GEN_AI_USAGE_AUDIO_CACHE_READ_INPUT_TOKENS", + "GEN_AI_USAGE_AUDIO_INPUT_TOKENS", + "GEN_AI_USAGE_AUDIO_OUTPUT_TOKENS", "GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS", "GEN_AI_USAGE_CACHE_WRITE_INPUT_TOKENS", + "GEN_AI_USAGE_IMAGE_CACHE_READ_INPUT_TOKENS", + "GEN_AI_USAGE_IMAGE_INPUT_TOKENS", + "GEN_AI_USAGE_IMAGE_OUTPUT_TOKENS", "GEN_AI_USAGE_INPUT_TOKENS", "GEN_AI_USAGE_OUTPUT_TOKENS", "GEN_AI_USAGE_PREFIX", "GEN_AI_USAGE_REASONING_OUTPUT_TOKENS", + "GEN_AI_USAGE_TEXT_CACHE_READ_INPUT_TOKENS", + "GEN_AI_USAGE_TEXT_INPUT_TOKENS", + "GEN_AI_USAGE_TEXT_OUTPUT_TOKENS", "INPUT_VALUE", "INVOCATION_PARAMETERS_CONTENT_MEMBERS", "LLM_INVOCATION_PARAMETERS", @@ -1205,6 +1398,28 @@ class SpanKind(str, Enum): "RIUS_COMMAND_CLASS_OTHER", "RIUS_COMMAND_CLASS_PACKAGE", "RIUS_COMMAND_CLASS_TEST", + "RIUS_COMPACTION_CONTEXT_WINDOW", + "RIUS_COMPACTION_EVENT", + "RIUS_COMPACTION_EXECUTOR", + "RIUS_COMPACTION_EXECUTOR_CLIENT", + "RIUS_COMPACTION_EXECUTOR_PROVIDER", + "RIUS_COMPACTION_ID", + "RIUS_COMPACTION_KIND", + "RIUS_COMPACTION_KIND_CLEAR_THINKING", + "RIUS_COMPACTION_KIND_CLEAR_TOOL_RESULTS", + "RIUS_COMPACTION_KIND_SUMMARIZE", + "RIUS_COMPACTION_KIND_TRUNCATE", + "RIUS_COMPACTION_MESSAGES_COMPACTED", + "RIUS_COMPACTION_MESSAGES_KEPT", + "RIUS_COMPACTION_SUMMARY_BYTES", + "RIUS_COMPACTION_SUMMARY_TEXT", + "RIUS_COMPACTION_TOKENS_AFTER", + "RIUS_COMPACTION_TOKENS_BEFORE", + "RIUS_COMPACTION_TOKENS_DROPPED", + "RIUS_COMPACTION_TOOL_RESULTS_CLEARED", + "RIUS_COMPACTION_TRIGGER", + "RIUS_COMPACTION_TRIGGER_AUTO", + "RIUS_COMPACTION_TRIGGER_MANUAL", "RIUS_CONTEXT_SIZES", "RIUS_MAIN_AGENT_DESCRIPTION", "RIUS_MAIN_AGENT_ID", diff --git a/scripts/rius_cc/continuation.py b/scripts/rius_cc/continuation.py index 44f18f1..276c117 100644 --- a/scripts/rius_cc/continuation.py +++ b/scripts/rius_cc/continuation.py @@ -127,6 +127,7 @@ def drop_copied(entries: List[Any], uuids: Set[str]) -> Tuple[List[Any], bool]: # id: it names files under the old id's directory. _MOVED = ("root_started", "root_start_ns", "content_stopped", "open_turns", "open_tools", "open_task_spans", "last_ns", "context", + "open_compaction", "compact_next", "last_compaction", "title_custom", "title_ai", "root_name_sent") HANDOFF_LOCK_TIMEOUT_S = 1.0 diff --git a/scripts/rius_cc/spans.py b/scripts/rius_cc/spans.py index b002b30..054adca 100644 --- a/scripts/rius_cc/spans.py +++ b/scripts/rius_cc/spans.py @@ -69,6 +69,10 @@ " dict: """ return {"open_tools": {}, "open_turns": {}, "open_task_spans": [], "last_ns": 0, "started": False, "start_ns": 0, "open_gen": None, - "context": None} + "context": None, "open_compaction": None, "compact_next": False, + "last_compaction": None} def _generation_for(entry: Any, scope: dict, root_span_id: str, @@ -330,6 +335,13 @@ def _generation_for(entry: Any, scope: dict, root_span_id: str, # What the prompt held when this call was made: sizes, not content. "context_sizes": context_sizes.snapshot(scope), } + if scope.get("compact_next"): + # The first call after a compaction, and no other: the later ones + # also run on the compacted context, but only this one is the call + # that first saw it. Kept in the persisted gen so a later hook + # re-emitting the span still says it. + gen["compacted"] = True + scope["compact_next"] = False scope["open_gen"] = gen return gen, True @@ -416,6 +428,8 @@ def _generation_span(ctx: Ctx, trace_id: str, gen: dict, lines: List[Any], attrs["gen_ai.usage.cache_creation.input_tokens"] = usage["cache_creation_input_tokens"] if stop_reason: attrs[semconv.GEN_AI_RESPONSE_FINISH_REASONS] = [stop_reason] + if gen.get("compacted"): + attrs[semconv.GEN_AI_CONVERSATION_COMPACTED] = True if gen.get("context_sizes"): # Sizes, not content: sent whatever the capture setting. attrs[semconv.RIUS_CONTEXT_SIZES] = gen["context_sizes"] @@ -430,6 +444,75 @@ def _generation_span(ctx: Ctx, trace_id: str, gen: dict, lines: List[Any], ) +def _count(value: Any) -> Optional[int]: + """`value` when it is a non-negative integer, else None: Claude Code's + metadata is not ours, and a size is never written as garbage.""" + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + return value + return None + + +def _open_compaction(entry: Any, scope: dict, root_span_id: str, + key_prefix: str) -> Dict[str, Any]: + """What a compact_boundary entry says, as plain JSON for the state file. + + Sizes, ids and words only: the summary text is never kept, it is used the + moment its entry is read (see emit_entries). + """ + meta = entry.compact_metadata() + attrs: Dict[str, Any] = { + semconv.RIUS_COMPACTION_KIND: semconv.RIUS_COMPACTION_KIND_SUMMARIZE, + semconv.RIUS_COMPACTION_EXECUTOR: semconv.RIUS_COMPACTION_EXECUTOR_CLIENT, + } + if meta.get("trigger") in (semconv.RIUS_COMPACTION_TRIGGER_AUTO, + semconv.RIUS_COMPACTION_TRIGGER_MANUAL): + attrs[semconv.RIUS_COMPACTION_TRIGGER] = meta["trigger"] + before, after = _count(meta.get("preTokens")), _count(meta.get("postTokens")) + if before is not None: + attrs[semconv.RIUS_COMPACTION_TOKENS_BEFORE] = before + if after is not None: + attrs[semconv.RIUS_COMPACTION_TOKENS_AFTER] = after + if before is not None and after is not None and before >= after: + attrs[semconv.RIUS_COMPACTION_TOKENS_DROPPED] = before - after + preserved = meta.get("preservedMessages") + kept = preserved.get("uuids") if isinstance(preserved, dict) else None + if isinstance(kept, list): + attrs[semconv.RIUS_COMPACTION_MESSAGES_KEPT] = len(kept) + uuid = entry.uuid if isinstance(entry.uuid, str) else "" + if uuid: + attrs[semconv.RIUS_COMPACTION_ID] = uuid + # The boundary is written when the compaction is done, so it is the end. + duration_ms = _count(meta.get("durationMs")) or 0 + return { + # The timestamp stands in for a missing uuid, so two boundaries + # never share an id. + "span_id": span_id_for(key_prefix + "compaction:" + + (uuid or str(entry.timestamp_ns))), + "parent_span_id": _current_turn_parent(scope, root_span_id), + "start_ns": max(entry.timestamp_ns - duration_ms * 1_000_000, 0), + "end_ns": entry.timestamp_ns, + "attrs": attrs, + } + + +def _compaction_span(ctx: Ctx, trace_id: str, rec: Dict[str, Any], + summary: str) -> Span: + attrs = _base_attrs(ctx, "CHAIN") + attrs[semconv.GEN_AI_OPERATION_NAME] = COMPACTION_OPERATION + attrs.update(rec["attrs"]) + if summary: + # A size, not content: sent whatever the capture setting. The text + # is content and goes through the same gate as every other. + attrs[semconv.RIUS_COMPACTION_SUMMARY_BYTES] = len(summary.encode("utf-8")) + _content_attr(ctx, attrs, semconv.RIUS_COMPACTION_SUMMARY_TEXT, summary) + return Span( + trace_id=trace_id, span_id=rec["span_id"], + parent_span_id=rec["parent_span_id"], name=COMPACTION_OPERATION, + kind_oi="CHAIN", start_ns=rec["start_ns"], end_ns=rec["end_ns"], + attributes=attrs, status_code="OK", status_message="", pending=False, + ) + + def emit_entries(entries: List[Any], scope: dict, ctx: Ctx, trace_id: str, root_span_id: str, links: dict, depth: int = 0, key_prefix: str = "", make_turns: bool = True, @@ -450,8 +533,42 @@ def emit_entries(entries: List[Any], scope: dict, ctx: Ctx, trace_id: str, # One generation span per API response in this batch, emitted after the # loop so it carries every line of the response that has arrived. batch_gens: Dict[str, Any] = {} + # (record, summary text) per compaction touched in this batch, for the + # same reason: a boundary and its summary entry are separate lines. + batch_compactions: Dict[str, Any] = {} for entry in entries: - if entry.kind == "user": + if entry.is_compact_boundary(): + # Claude Code writes the boundary, then (a few lines later, with + # an EARLIER timestamp) the user entry holding the summary. A + # hook can read between the two, so the span is sent as soon as + # the boundary is seen, and again with the summary once that + # arrives: same id, start and end, which the backend collapses + # like a response that grows. The record waits in the state + # (sizes only) for its summary; a summary that never comes just + # leaves the span without summary attributes. + rec = _open_compaction(entry, scope, root_span_id, key_prefix) + if entry.timestamp_ns <= (scope.get("last_compaction") or 0): + # Read again (a copied history, a rewound offset), this one + # or an earlier one: the span went out the first time, and + # the call it flagged is past. A transcript runs forward in + # time, so the latest boundary's time covers them all. + continue + scope["last_compaction"] = entry.timestamp_ns + scope["open_compaction"] = rec + scope["compact_next"] = True + batch_compactions[rec["span_id"]] = (rec, "") + elif entry.is_compact_summary(): + # Not a prompt: no turn, whatever promptId it carries. The + # context account still restarts from it. + context_sizes.user_text(scope, entry) + rec = scope.get("open_compaction") + if isinstance(rec, dict): + batch_compactions[rec["span_id"]] = (rec, entry.text()) + scope["open_compaction"] = None + # Its timestamp predates the boundary's: leave the clock alone, + # or the first call after the compaction would start before it. + continue + elif entry.kind == "user": tool_results = entry.tool_results() if tool_results: result_sizes = [] @@ -615,6 +732,8 @@ def emit_entries(entries: List[Any], scope: dict, ctx: Ctx, trace_id: str, scope["last_ns"] = entry.timestamp_ns + for rec, summary in batch_compactions.values(): + out.append(_compaction_span(ctx, trace_id, rec, summary)) for gen, lines in batch_gens.values(): earlier = _earlier_text(ctx, source_path, gen, lines) out.append(_generation_span(ctx, trace_id, gen, lines, earlier)) diff --git a/scripts/rius_cc/state.py b/scripts/rius_cc/state.py index bfb49a1..f3dfe64 100644 --- a/scripts/rius_cc/state.py +++ b/scripts/rius_cc/state.py @@ -50,6 +50,14 @@ def new_state() -> dict: "open_gen": None, # Running prompt-size account (context_sizes.py): sizes, no content. "context": None, + # The compaction whose summary entry has not been read yet (sizes + # and ids only), and whether the next model call is the first one + # after a compaction (see spans.emit_entries). + "open_compaction": None, + "compact_next": False, + # The time (ns) of the latest boundary read, so reading it or an + # earlier one again emits and flags nothing. + "last_compaction": None, # Subagent drilldown. A subagent's transcript is a separate file, so # each one needs its own byte offset and its own span bookkeeping, # keyed by agent id; sub_links maps the spawning tool_use id to the diff --git a/scripts/rius_cc/transcript.py b/scripts/rius_cc/transcript.py index d6efb76..9a60ae3 100644 --- a/scripts/rius_cc/transcript.py +++ b/scripts/rius_cc/transcript.py @@ -10,6 +10,11 @@ CONVERSATIONAL = ("user", "assistant") +# The one system record that is read: Claude Code writes it when it compacts +# the context, and spans.py turns it into a compaction span. The rest of its +# system records (hook results, turn durations, ...) stay skipped. +COMPACT_BOUNDARY_SUBTYPE = "compact_boundary" + # The records Claude Code names a session with, and the key holding the name: # "custom" is /rename, --name or a hook's sessionTitle; "ai" is the summary it # writes of the first prompt. Both are rewritten throughout the session. @@ -100,6 +105,18 @@ def generation_key(self) -> str: return mid return self.uuid + def is_compact_boundary(self) -> bool: + return (self.kind == "system" + and self.raw.get("subtype") == COMPACT_BOUNDARY_SUBTYPE) + + def is_compact_summary(self) -> bool: + """The user entry that holds a compaction's summary text.""" + return self.kind == "user" and bool(self.raw.get("isCompactSummary")) + + def compact_metadata(self) -> Dict[str, Any]: + meta = self.raw.get("compactMetadata") + return meta if isinstance(meta, dict) else {} + def tool_uses(self) -> List[Dict[str, Any]]: return self._blocks("tool_use") @@ -131,7 +148,9 @@ def parse_line_ex(line: str) -> Tuple[Optional[Entry], Optional[str]]: return None, "not valid JSON" if not isinstance(raw, dict): return None, "not a JSON object" - if raw.get("type") not in CONVERSATIONAL: + if raw.get("type") not in CONVERSATIONAL and not ( + raw.get("type") == "system" + and raw.get("subtype") == COMPACT_BOUNDARY_SUBTYPE): return None, None # normal: summary, mode, file-history, ... if "timestamp" not in raw or "uuid" not in raw: return None, "conversational line with no timestamp or uuid" diff --git a/tests/fixtures/compaction.jsonl b/tests/fixtures/compaction.jsonl new file mode 100644 index 0000000..90dab77 --- /dev/null +++ b/tests/fixtures/compaction.jsonl @@ -0,0 +1,12 @@ +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": null, "type": "user", "uuid": "u1", "timestamp": "2026-09-30T10:00:00.000Z", "promptId": "p1", "message": {"role": "user", "content": "say hello"}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "u1", "type": "assistant", "uuid": "a1", "timestamp": "2026-09-30T10:00:01.000Z", "message": {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-5", "stop_reason": "end_turn", "content": [{"type": "text", "text": "reply msg_1"}], "usage": {"input_tokens": 10, "output_tokens": 5}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": null, "type": "system", "subtype": "compact_boundary", "uuid": "b1", "timestamp": "2026-09-30T10:10:30.000Z", "level": "info", "content": "Conversation compacted", "compactMetadata": {"trigger": "auto", "preTokens": 150000, "postTokens": 20000, "durationMs": 30000, "preservedMessages": {"anchorUuid": "k0", "uuids": ["k1", "k2", "k3"], "allUuids": ["k1", "k2", "k3"]}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "type": "attachment", "uuid": "t1", "timestamp": "2026-09-30T10:10:30.000Z", "parentUuid": "b1", "attachment": {"type": "skill_listing"}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "t1", "type": "user", "uuid": "s1", "timestamp": "2026-09-30T10:10:29.500Z", "promptId": "ps1", "message": {"role": "user", "content": "Summary of the first stretch: the user asked for a greeting."}, "isCompactSummary": true, "isVisibleInTranscriptOnly": true} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "s1", "type": "assistant", "uuid": "a2", "timestamp": "2026-09-30T10:10:32.000Z", "message": {"id": "msg_2", "type": "message", "role": "assistant", "model": "claude-opus-5", "stop_reason": "end_turn", "content": [{"type": "text", "text": "reply msg_2"}], "usage": {"input_tokens": 10, "output_tokens": 6}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "a2", "type": "assistant", "uuid": "a3", "timestamp": "2026-09-30T10:10:40.000Z", "message": {"id": "msg_3", "type": "message", "role": "assistant", "model": "claude-opus-5", "stop_reason": "end_turn", "content": [{"type": "text", "text": "reply msg_3"}], "usage": {"input_tokens": 10, "output_tokens": 7}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": null, "type": "user", "uuid": "u2", "timestamp": "2026-09-30T10:20:00.000Z", "promptId": "p2", "message": {"role": "user", "content": "/compact"}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": null, "type": "system", "subtype": "compact_boundary", "uuid": "b2", "timestamp": "2026-09-30T10:20:20.000Z", "level": "info", "content": "Conversation compacted", "compactMetadata": {"trigger": "manual", "preTokens": 90000, "postTokens": 15000, "durationMs": 20000, "preservedMessages": {"anchorUuid": "k0", "uuids": ["k4"], "allUuids": ["k4"]}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "b2", "type": "user", "uuid": "s2", "timestamp": "2026-09-30T10:20:19.500Z", "promptId": "p2", "message": {"role": "user", "content": "Summary of the second stretch: a caf\u00e9 menu was drafted."}, "isCompactSummary": true, "isVisibleInTranscriptOnly": true} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "s2", "type": "assistant", "uuid": "a4", "timestamp": "2026-09-30T10:20:22.000Z", "message": {"id": "msg_4", "type": "message", "role": "assistant", "model": "claude-opus-5", "stop_reason": "end_turn", "content": [{"type": "text", "text": "reply msg_4"}], "usage": {"input_tokens": 10, "output_tokens": 8}}} +{"isSidechain": false, "sessionId": "99999999-9999-9999-9999-999999999999", "cwd": "/tmp/proj", "gitBranch": "main", "version": "2.1.304", "parentUuid": "a4", "type": "assistant", "uuid": "a5", "timestamp": "2026-09-30T10:20:30.000Z", "message": {"id": "msg_5", "type": "message", "role": "assistant", "model": "claude-opus-5", "stop_reason": "end_turn", "content": [{"type": "text", "text": "reply msg_5"}], "usage": {"input_tokens": 10, "output_tokens": 9}}} diff --git a/tests/test_compaction.py b/tests/test_compaction.py new file mode 100644 index 0000000..0e115ec --- /dev/null +++ b/tests/test_compaction.py @@ -0,0 +1,475 @@ +"""Every compaction is a span, and the call after it says it ran on one. + +Claude Code writes a `compact_boundary` system entry (the trigger, the sizes +before and after, how long it took) and then a user entry holding the summary +text, flagged `isCompactSummary`. The summary is stamped slightly BEFORE the +boundary and may be read in a later hook than it. The boundary becomes a +CHAIN span with gen_ai.operation.name "compaction"; the summary is never a +turn. tests/fixtures/compaction.jsonl has an automatic and a manual +compaction, each followed by two model calls. +""" +import json + +import pytest + +import exporter +from rius_cc import config, spans, state, transcript +from rius_cc import _semconv_generated as semconv +from tests.signed_in import sign_in + +FIXTURE = "compaction.jsonl" +SESSION = "99999999-9999-9999-9999-999999999999" +T0 = 1790762400000000000 # 2026-09-30T10:00:00Z +SUMMARY_1 = "Summary of the first stretch: the user asked for a greeting." +SUMMARY_2 = "Summary of the second stretch: a café menu was drafted." + + +def _ctx(capture=True, max_attr_bytes=32768): + return spans.Ctx(session_id=SESSION, cwd="/tmp/proj", git_branch="main", + cc_version="2.1.304", service_name="claude-code", + capture_content=capture, max_attr_bytes=max_attr_bytes) + + +def _build(entries, st=None, capture=True, max_attr_bytes=32768): + st = st if st is not None else state.new_state() + return spans.build(entries, st, _ctx(capture, max_attr_bytes)), st + + +def _entries(fixtures_dir): + return transcript.read_from(str(fixtures_dir / FIXTURE), 0)[0] + + +def _compactions(out): + return [s for s in out if s.attributes.get("gen_ai.operation.name") == "compaction"] + + +def _llm(out): + """The latest copy of each LLM span, by response.""" + return {s.attributes["gen_ai.usage.output_tokens"]: s + for s in out if s.kind_oi == "LLM"} + + +def _boundary_line(uuid="b1", ts="2026-09-30T10:10:30.000Z", **meta): + return {"sessionId": SESSION, "cwd": "/tmp/proj", "gitBranch": "main", + "version": "2.1.304", "isSidechain": False, "parentUuid": None, + "type": "system", "subtype": "compact_boundary", "uuid": uuid, + "timestamp": ts, "compactMetadata": meta} + + +def _summary_line(text, uuid="s1", ts="2026-09-30T10:10:29.500Z", pid="ps1"): + return {"sessionId": SESSION, "cwd": "/tmp/proj", "gitBranch": "main", + "version": "2.1.304", "isSidechain": False, "parentUuid": "b1", + "type": "user", "uuid": uuid, "timestamp": ts, "promptId": pid, + "isCompactSummary": True, + "message": {"role": "user", "content": text}} + + +def _assistant_line(uuid, ts, msg_id, out_tokens): + return {"sessionId": SESSION, "cwd": "/tmp/proj", "gitBranch": "main", + "version": "2.1.304", "isSidechain": False, "parentUuid": None, + "type": "assistant", "uuid": uuid, "timestamp": ts, + "message": {"id": msg_id, "type": "message", "role": "assistant", + "model": "claude-opus-5", "stop_reason": "end_turn", + "content": [{"type": "text", "text": "ok"}], + "usage": {"input_tokens": 1, "output_tokens": out_tokens}}} + + +def _parse(*lines): + entries = [] + for raw in lines: + entry, reason = transcript.parse_line_ex(json.dumps(raw)) + assert reason is None + entries.append(entry) + return entries + + +def test_each_compaction_is_a_span_with_its_numbers(fixtures_dir): + out, _ = _build(_entries(fixtures_dir), capture=False) + auto, manual = _compactions(out) + + assert auto.attributes == { + "openinference.span.kind": "CHAIN", + "session.id": SESSION, + "gen_ai.operation.name": "compaction", + "rius.compaction.kind": "summarize", + "rius.compaction.executor": "client", + "rius.compaction.trigger": "auto", + "rius.compaction.tokens.before": 150000, + "rius.compaction.tokens.after": 20000, + "rius.compaction.tokens.dropped": 130000, + "rius.compaction.messages.kept": 3, + "rius.compaction.id": "b1", + "rius.compaction.summary.bytes": len(SUMMARY_1.encode("utf-8")), + } + assert manual.attributes == { + "openinference.span.kind": "CHAIN", + "session.id": SESSION, + "gen_ai.operation.name": "compaction", + "rius.compaction.kind": "summarize", + "rius.compaction.executor": "client", + "rius.compaction.trigger": "manual", + "rius.compaction.tokens.before": 90000, + "rius.compaction.tokens.after": 15000, + "rius.compaction.tokens.dropped": 75000, + "rius.compaction.messages.kept": 1, + "rius.compaction.id": "b2", + # bytes, not characters: the e-acute is two + "rius.compaction.summary.bytes": len(SUMMARY_2.encode("utf-8")), + } + assert len(SUMMARY_2.encode("utf-8")) == len(SUMMARY_2) + 1 + assert auto.name == manual.name == "compaction" + assert auto.pending is manual.pending is False + assert auto.status_code == "OK" + + +def test_a_compaction_ends_at_its_boundary_and_started_duration_ms_before(fixtures_dir): + out, _ = _build(_entries(fixtures_dir)) + auto, manual = _compactions(out) + assert auto.end_ns == T0 + 630 * 1_000_000_000 # 10:10:30 + assert auto.start_ns == auto.end_ns - 30_000 * 1_000_000 + assert manual.end_ns == T0 + 1220 * 1_000_000_000 # 10:20:20 + assert manual.start_ns == manual.end_ns - 20_000 * 1_000_000 + + +def test_a_compaction_hangs_off_the_open_turn(fixtures_dir): + out, st = _build(_entries(fixtures_dir)) + auto, manual = _compactions(out) + assert auto.parent_span_id == spans.span_id_for("turn:p1") + assert manual.parent_span_id == spans.span_id_for("turn:p2") + assert auto.span_id == spans.span_id_for("compaction:b1") + assert manual.span_id == spans.span_id_for("compaction:b2") + + # With no turn open, the root. + fresh, _ = _build(_parse(_boundary_line(trigger="auto", preTokens=5, + postTokens=1, durationMs=1))) + (only,) = _compactions(fresh) + assert only.parent_span_id == spans.span_id_for("session:" + SESSION) + + +def test_only_the_first_call_after_a_compaction_is_flagged(fixtures_dir): + out, _ = _build(_entries(fixtures_dir)) + calls = _llm(out) + key = "gen_ai.conversation.compacted" + assert calls[5].attributes.get(key) is None # before any + assert calls[6].attributes[key] is True # first after #1 + assert calls[7].attributes.get(key) is None + assert calls[8].attributes[key] is True # first after #2 + assert calls[9].attributes.get(key) is None + assert key not in [s for s in _compactions(out)][0].attributes + + +def test_the_flag_survives_the_hooks_a_response_arrives_in(): + """Boundary and summary in one hook, the call's lines in the next two.""" + st = state.new_state() + _build(_parse(_boundary_line(trigger="auto", preTokens=5, postTokens=1, + durationMs=1), + _summary_line("sum")), st) + first = _parse(_assistant_line("a1", "2026-09-30T10:10:31.000Z", "msg_1", 3)) + out, _ = _build(first, st) + assert _llm(out)[3].attributes["gen_ai.conversation.compacted"] is True + # The same response, one line later, in another hook. + more = _parse(_assistant_line("a2", "2026-09-30T10:10:32.000Z", "msg_1", 3)) + out, _ = _build(more, st) + assert _llm(out)[3].attributes["gen_ai.conversation.compacted"] is True + # The next response is not. + nxt = _parse(_assistant_line("a3", "2026-09-30T10:10:33.000Z", "msg_2", 4)) + out, _ = _build(nxt, st) + assert "gen_ai.conversation.compacted" not in _llm(out)[4].attributes + + +def test_reading_a_boundary_again_flags_no_later_call(): + """A copied history or a rewound offset shows the same boundaries twice.""" + st = state.new_state() + flag = "gen_ai.conversation.compacted" + first = _parse(_boundary_line(trigger="auto", preTokens=5, postTokens=1, + durationMs=1), + _summary_line("sum")) + second = _parse(_boundary_line(uuid="b2", ts="2026-09-30T10:20:30.000Z", + trigger="manual", preTokens=9, postTokens=2, + durationMs=1), + _summary_line("sum2", uuid="s2", ts="2026-09-30T10:20:29.500Z")) + _build(first, st) + out, _ = _build(_parse(_assistant_line("a1", "2026-09-30T10:10:31.000Z", + "msg_1", 3)), st) + assert _llm(out)[3].attributes[flag] is True + _build(second, st) + out, _ = _build(_parse(_assistant_line("a2", "2026-09-30T10:20:31.000Z", + "msg_2", 4)), st) + assert _llm(out)[4].attributes[flag] is True + # The whole history comes round again: both boundaries are old news. + out, _ = _build(first + second, st) + assert _compactions(out) == [] + out, _ = _build(_parse(_assistant_line("a3", "2026-09-30T10:20:33.000Z", + "msg_3", 5)), st) + assert flag not in _llm(out)[5].attributes + + +def test_replaying_the_transcript_gives_the_same_span_ids(fixtures_dir): + first, _ = _build(_entries(fixtures_dir)) + again, _ = _build(_entries(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_summary_entry_is_not_a_turn(fixtures_dir): + out, st = _build(_entries(fixtures_dir)) + # ps1 is a promptId only the summary carries; p2 is shared with a prompt. + assert list(st["open_turns"]) == ["p1", "p2"] + turns = [s for s in out if s.name == "turn"] + assert {s.span_id for s in turns} == {spans.span_id_for("turn:p1"), + spans.span_id_for("turn:p2")} + assert spans.span_id_for("turn:ps1") not in {s.span_id for s in out} + + # ... and with nothing open, it still opens none. + only, st2 = _build(_parse(_boundary_line(trigger="auto"), + _summary_line("sum", pid="ps9"))) + assert st2["open_turns"] == {} + assert [s for s in only if s.name == "turn"] == [] + + +def test_the_summary_still_restarts_the_context_account(fixtures_dir): + out, _ = _build(_entries(fixtures_dir)) + sizes = json.loads(_llm(out)[6].attributes["rius.context.sizes"]) + assert sizes["input_messages"] == [ + {"role": "user", + "parts": [{"type": "text", "bytes": len(SUMMARY_1.encode("utf-8"))}]}] + assert "folded" not in sizes + + +def test_the_summary_text_is_content_and_follows_the_capture_gate(fixtures_dir): + off, _ = _build(_entries(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(_entries(fixtures_dir), capture=True) + auto, manual = _compactions(on) + assert auto.attributes["rius.compaction.summary.text"] == SUMMARY_1 + assert manual.attributes["rius.compaction.summary.text"] == SUMMARY_2 + assert auto.attributes["rius.compaction.summary.bytes"] == len(SUMMARY_1) + assert "rius.compaction.summary.text" in semconv.CONTENT_ATTRIBUTES + assert "rius.compaction.summary.bytes" not in semconv.CONTENT_ATTRIBUTES + + +def test_the_summary_text_is_capped_and_scrubbed_like_other_content(): + secret = "AKIA" + "ABCDEFGHIJKLMNOP" + text = "keys: %s then a long tail %s" % (secret, "x" * 200) + out, _ = _build(_parse(_boundary_line(trigger="auto"), + _summary_line(text)), max_attr_bytes=40) + (span,) = _compactions(out) + 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")) + + # Under the cap it is whole. + out, _ = _build(_parse(_boundary_line(trigger="auto"), + _summary_line("short")), max_attr_bytes=40) + assert _compactions(out)[0].attributes["rius.compaction.summary.text"] == "short" + + +def test_a_summary_read_in_a_later_hook_updates_the_same_span(): + """The boundary is sent at once; the summary arrives in another hook.""" + boundary = _parse(_boundary_line(trigger="auto", preTokens=900, + postTokens=100, durationMs=2000)) + summary = _parse(_summary_line("what was said")) + st = state.new_state() + + out1, _ = _build(boundary, st) + (first,) = _compactions(out1) + assert "rius.compaction.summary.bytes" not in first.attributes + assert "rius.compaction.summary.text" not in first.attributes + assert st["open_compaction"] is not None + # What waits in the state is sizes and ids, never the text to come. + assert "what was said" not in json.dumps(st) + + out2, _ = _build(summary, st) + (second,) = _compactions(out2) + assert second.span_id == first.span_id + assert (second.start_ns, second.end_ns) == (first.start_ns, first.end_ns) + assert second.parent_span_id == first.parent_span_id + assert second.attributes["rius.compaction.summary.bytes"] == len("what was said") + assert second.attributes["rius.compaction.summary.text"] == "what was said" + assert {k: v for k, v in second.attributes.items() + if not k.startswith("rius.compaction.summary")} == first.attributes + assert st["open_compaction"] is None + assert "what was said" not in json.dumps(st) + + # Nothing left to say: a later hook sends no compaction span again. + out3, _ = _build(_parse(_assistant_line("a1", "2026-09-30T10:11:00.000Z", + "msg_1", 3)), st) + assert _compactions(out3) == [] + + +def test_state_that_survives_a_json_round_trip_still_gets_its_summary(): + st = state.new_state() + _build(_parse(_boundary_line(trigger="manual", preTokens=9, postTokens=3, + durationMs=500)), st) + st = json.loads(json.dumps(st)) + out, _ = _build(_parse(_summary_line("abc")), st) + (span,) = _compactions(out) + assert span.attributes["rius.compaction.summary.bytes"] == 3 + assert span.attributes["rius.compaction.trigger"] == "manual" + + +def test_a_boundary_with_no_summary_is_exported_without_summary_attributes(): + out, st = _build(_parse( + _boundary_line(trigger="auto", preTokens=50, postTokens=10, durationMs=0), + _assistant_line("a1", "2026-09-30T10:10:31.000Z", "msg_1", 3))) + (span,) = _compactions(out) + assert span.attributes["rius.compaction.tokens.dropped"] == 40 + assert not [k for k in span.attributes if k.startswith("rius.compaction.summary")] + assert _llm(out)[3].attributes["gen_ai.conversation.compacted"] is True + + +def test_a_summary_with_no_boundary_exports_nothing_and_is_no_turn(): + out, st = _build(_parse(_summary_line("orphan"))) + assert _compactions(out) == [] + assert [s for s in out if s.name == "turn"] == [] + assert st["open_turns"] == {} + + +@pytest.mark.parametrize("meta, expected_absent", [ + ({}, ["trigger", "tokens.before", "tokens.after", "tokens.dropped", + "messages.kept"]), + ({"trigger": "scheduled", "preTokens": "150000", "postTokens": 2.5}, + ["trigger", "tokens.before", "tokens.after", "tokens.dropped"]), + ({"preTokens": -5, "postTokens": -1}, + ["tokens.before", "tokens.after", "tokens.dropped"]), + ({"preTokens": True, "postTokens": None}, + ["tokens.before", "tokens.after", "tokens.dropped"]), + ({"preTokens": 1000}, ["tokens.after", "tokens.dropped"]), + ({"postTokens": 1000}, ["tokens.before", "tokens.dropped"]), + # after bigger than before: both are kept, the "dropped" is not made up + ({"preTokens": 10, "postTokens": 20}, ["tokens.dropped"]), + ({"preservedMessages": "all"}, ["messages.kept"]), + ({"preservedMessages": {"uuids": "k1"}}, ["messages.kept"]), + ({"preservedMessages": {"allUuids": ["k1"]}}, ["messages.kept"]), +]) +def test_malformed_metadata_never_writes_garbage(meta, expected_absent): + out, _ = _build(_parse(_boundary_line(durationMs=1000, **meta), + _summary_line("s"))) + (span,) = _compactions(out) + for name in expected_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"] == "client" + assert span.attributes["rius.compaction.id"] == "b1" + + +def test_a_boundary_with_no_metadata_or_a_bad_duration_does_not_crash(): + raw = _boundary_line() + del raw["compactMetadata"] + out, _ = _build(_parse(raw)) + (span,) = _compactions(out) + assert span.start_ns == span.end_ns + + for bad in ("30s", -5, None, 1.5, True): + out, _ = _build(_parse(_boundary_line(durationMs=bad, trigger="auto"))) + (span,) = _compactions(out) + assert span.start_ns == span.end_ns, bad + garbage = _boundary_line() + garbage["compactMetadata"] = "not a dict" + (span,) = _compactions(_build(_parse(garbage))[0]) + assert span.attributes["rius.compaction.kind"] == "summarize" + + +def test_a_compaction_in_a_subagent_hangs_off_the_agent_span(): + scope = spans.new_scope() + agent_span = spans.span_id_for("subagent:a1") + out = spans.emit_entries( + _parse(_boundary_line(trigger="auto", preTokens=5, postTokens=1, + durationMs=10), + _summary_line("s"), + _assistant_line("x1", "2026-09-30T10:10:31.000Z", "msg_1", 3)), + scope, _ctx(), spans.trace_id_for(SESSION), agent_span, {}, + depth=1, key_prefix="agent:a1:", make_turns=False, + inline_sidechains=False) + (span,) = _compactions(out) + assert span.parent_span_id == agent_span + assert span.span_id == spans.span_id_for("agent:a1:compaction:b1") + assert span.span_id != spans.span_id_for("compaction:b1") + assert _llm(out)[3].attributes["gen_ai.conversation.compacted"] is True + + +def test_the_boundary_and_summary_leave_the_other_lines_alone(fixtures_dir): + """Turn count, calls and their order are what they were without them.""" + entries = _entries(fixtures_dir) + plain = [e for e in entries + if not (e.is_compact_boundary() or e.is_compact_summary())] + with_out, _ = _build(entries) + plain_out, _ = _build(plain) + kept = lambda out: [(s.span_id, s.kind_oi, s.name) for s in out + if s.attributes.get("gen_ai.operation.name") != "compaction"] + assert kept(with_out) == kept(plain_out) + # the one clock that must not run backwards: the summary is stamped + # before the boundary, and the call after both starts at the boundary + boundary_end = _compactions(with_out)[0].end_ns + assert _llm(with_out)[6].start_ns == boundary_end + + + +def _otlp_spans(body): + from tests import otlp_json # skips the test, not the module, without the proto package + req = otlp_json.to_request(body) + return [sp for rs in req.resource_spans for ss in rs.scope_spans + for sp in ss.spans] + + +def _attrs(span): + out = {} + for kv in span.attributes: + which = kv.value.WhichOneof("value") + out[kv.key] = getattr(kv.value, which) + return out + + +def test_through_the_hooks_a_summary_written_after_the_boundary_is_not_lost( + tmp_path, monkeypatch): + """The real path: the file grows between two hook runs, the first one + reads the boundary alone, the second the summary and the call after.""" + home = tmp_path / "home" + (home / ".claude" / "rius").mkdir(parents=True) + sign_in(home) + with open(config.path_rules_path(str(home)), "w") as fh: + json.dump({"enabled_paths": ["/tmp"]}, fh) + sent = [] + monkeypatch.setattr(exporter.otlp, "export", + lambda ep, key, body, timeout=5.0: + sent.append(body) or 200) + path = tmp_path / "t.jsonl" + lines = [_boundary_line(trigger="auto", preTokens=900, postTokens=100, + durationMs=2000), + _summary_line("what was said"), + _assistant_line("a1", "2026-09-30T10:10:31.000Z", "msg_1", 3)] + path.write_text(json.dumps(lines[0]) + "\n") + payload = {"session_id": SESSION, "transcript_path": str(path), + "cwd": "/tmp/proj", "hook_event_name": "PostToolUse"} + + exporter.run("PostToolUse", payload, {}, str(home)) + with open(path, "a") as fh: + fh.write(json.dumps(lines[1]) + "\n" + json.dumps(lines[2]) + "\n") + exporter.run("PostToolUse", payload, {}, str(home)) + + sent_spans = [sp for body in sent for sp in _otlp_spans(body)] + compaction = [sp for sp in sent_spans + if _attrs(sp).get("gen_ai.operation.name") == "compaction"] + assert len(compaction) == 2 # the boundary, then with its summary + assert compaction[0].span_id == compaction[1].span_id + assert compaction[0].start_time_unix_nano == compaction[1].start_time_unix_nano + first, last = _attrs(compaction[0]), _attrs(compaction[1]) + assert "rius.compaction.summary.bytes" not in first + assert last["rius.compaction.summary.bytes"] == len("what was said") + assert last["rius.compaction.tokens.dropped"] == 800 + llm = [_attrs(sp) for sp in sent_spans + if _attrs(sp).get("gen_ai.operation.name") == "chat"] + assert llm[-1]["gen_ai.conversation.compacted"] is True diff --git a/tests/test_transcript.py b/tests/test_transcript.py index dc788e3..f0df72d 100644 --- a/tests/test_transcript.py +++ b/tests/test_transcript.py @@ -148,3 +148,31 @@ def test_tool_use_and_result_blocks(fixtures_dir): def test_text_concatenates_text_blocks(fixtures_dir): entries, _ = transcript.read_from(str(fixtures_dir / "simple.jsonl"), 0) assert entries[1].text() == "hi there" + + +def test_a_compact_boundary_is_read_and_other_system_records_are_not(fixtures_dir): + entries, _ = transcript.read_from(str(fixtures_dir / "compaction.jsonl"), 0) + boundaries = [e for e in entries if e.is_compact_boundary()] + assert [e.uuid for e in boundaries] == ["b1", "b2"] + assert boundaries[0].kind == "system" + assert boundaries[0].timestamp_ns == 1790762400000000000 + 630 * 1_000_000_000 + assert boundaries[0].compact_metadata()["preTokens"] == 150000 + # the summary is a user entry that says what it is; the attachment line + # in between is not an entry at all + assert [e.uuid for e in entries if e.is_compact_summary()] == ["s1", "s2"] + assert [e.kind for e in entries].count("system") == 2 + assert "t1" not in [e.uuid for e in entries] + + other = ('{"type":"system","subtype":"turn_duration","uuid":"x",' + '"timestamp":"2026-09-30T10:00:00.000Z"}') + assert transcript.parse_line_ex(other) == (None, None) + + +def test_a_boundary_with_no_timestamp_is_counted_as_skipped(): + entry, reason = transcript.parse_line_ex( + '{"type":"system","subtype":"compact_boundary","uuid":"b"}') + assert entry is None and reason + entry, _ = transcript.parse_line_ex( + '{"type":"system","subtype":"compact_boundary","uuid":"b",' + '"timestamp":"2026-09-30T10:00:00.000Z","compactMetadata":[1]}') + assert entry.compact_metadata() == {}