Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
231 changes: 223 additions & 8 deletions scripts/rius_cc/_semconv_generated.py

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions scripts/rius_cc/continuation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
123 changes: 121 additions & 2 deletions scripts/rius_cc/spans.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
"<user-prompt-submit-hook",
)

# The generated semconv module has no constant for this operation name (it
# only lists "compaction" as a key of its operation-to-kind map).
COMPACTION_OPERATION = "compaction"

_OPERATION_BY_KIND = {
"AGENT": "invoke_agent",
"LLM": "chat",
Expand Down Expand Up @@ -294,7 +298,8 @@ def new_scope() -> 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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"]
Expand All @@ -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,
Expand All @@ -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 = []
Expand Down Expand Up @@ -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))
Expand Down
8 changes: 8 additions & 0 deletions scripts/rius_cc/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion scripts/rius_cc/transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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"
Expand Down
12 changes: 12 additions & 0 deletions tests/fixtures/compaction.jsonl
Original file line number Diff line number Diff line change
@@ -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}}}
Loading
Loading