Repository navigation
Description
Compaction summaries are cheap (about 1–2% of LLM spend) and they rarely lose facts that matter. Long sessions get expensive for two other reasons: prompt-cache rewrites (after each compaction, and probably after idle gaps) and compaction loops, where compaction never frees enough room. This ticket covers the measurements, current industry practice, and a proposed direction. It answers the measurement half of #2471.
Measurements (as of 2026-11-08)
Sources: the event logs of the 100 most recent public conversations (active 2026-11-06 to 11-08), and Sentry spans in sentry/junior.
How often
- 33 of the 100 conversations compacted at least once.
- Compacted sessions: median 15 turns over about 19h.
- Sessions that never compacted: median 2 turns, about 0.2h.
- The first compaction comes after a median 6 turns (about 1.3h). After that, a median 7 turns pass between compactions.
- Every compaction used
claude-opus-5.5with reasoncapacity, a 360K trigger and a 380K input limit. - Size:
- median estimate when compaction ran: 289K
- median replacement: 53K
- median summary: 6.6K chars, about 1.6K tokens, under 10% of the replacement
- Spans over 7d: 3,283
agent.context_compactionspans across 568 conversations.- background
ready: 1,288 - blocking:
applied1,092,not_ready174,over_targetdiscards 59 - active:
compacted554 summary_failed: 4
- background
Cost
- Summary calls:
- 30d: $293 of $34,280 total LLM spend (0.85%)
- 7d: $267 of $16,987 (1.6%)
- Opus summaries: $0.14 per call, p50 277K input. They are cheap because they reuse the agent's cached prefix (feat(compaction): Summarize with the agent model and cached request prefix #2602).
- Cache rewrites after compaction. In a sample of 53 compactions:
- the call just before compaction hits the cache 99.5%
- the first call after hits only 24%, and costs about $0.47 against about $0.04 at steady state
- only the static prefix, about 23–40K tokens, stays cached
- so each compaction costs about $0.42 more, about 3× the summary itself
- Estimate: about $700/week, roughly 4% of spend.
- Cache writes are 53% of main-agent spend over 30d ($17.3K of $32.9K), even though 94.3% of input tokens are cache reads.
- Junior never sets
cacheRetention, so pi-ai uses the 5-minute TTL. - Slack threads often sit idle for longer than 5 minutes between messages. Inference, not measured: most of the write spend is cache expiry between messages, not compaction.
- Junior never sets
- Calls on already-compacted context: 43% of calls and 53% of spend ($0.105 per call vs $0.070).
Compaction loop (the largest single cost)
- The most expensive conversation in 30d cost $999. It ran 470 compactions, 253 of them back-to-back in one turn (about every 32s for 2.4h).
- This one conversation accounts for 82% of all compactions in the 100-conversation sample. That turn alone sent about 101M tokens through compaction, and the turn still reported
success. - Cause:
- The turn's runtime-context message held about 223K tokens (about 890K chars) of replayed Slack thread. Compaction always keeps it, so the replacement never fell below about 260K, 72% of the trigger.
- One or two tool results crossed the trigger again.
- Each compaction folded the newest tool result into the summary, so the agent ran it again. The log shows about 250 near-identical file reads.
- This is the Active-turn compaction repeats until the turn fails #2017 pattern in production.
- Unknown: why this message got past the 60K-char thread-context cap in
services/conversation-memory.ts. - Related:
JUNIOR-S9andJUNIOR-DW(ContextInputLimitExceededError, estimates of 562K and 407K against the 380K limit).
Accuracy
- 10 compactions sampled across 10 conversations:
- 8 fine, 2 minor loss, 0 material loss
- Minor losses: commit SHAs dropped from a summary, and one tool call repeated after a compaction.
- No user re-asked or corrected anything, and no
readConversationEventread-backs.
- Caveat: this was a script-based check. It looked for IDs, URLs, paths and SHAs that dropped out, repeated tool calls and correction phrases. It does not catch paraphrase-level drift.
Current implementation
At 7d01a528, paths under packages/junior/src/chat/:
- Budget (
services/context-budget.ts):- trigger at 0.9 of the window, input limit at 0.95
- target at 0.8 of the trigger, background mark at 0.7 of the trigger
- token estimate is fixed chars-per-token: 2.5 for Claude, 4 for other models
- Live compaction (blocking or active,
services/context-compaction.ts):- keeps the runtime context, the instruction and the summary
- drops all assistant, tool and subagent history, without leaving pointers to it
- checks the replacement against the input limit, not against the trigger or target, so it can loop
- Background swap (
services/context-compaction-swap.ts):- keeps messages after
markSeqverbatim - trims old tool results over 2K chars down to the first and last 500 chars plus a
readConversationEventpointer
- keeps messages after
- Summary (
agent/context-summary.ts):- same model as the agent, reusing the cached prefix
- sectioned: goal, constraints, progress, decisions, open asks, at most 20 references, next steps
- under 1,000 words, and it rewrites the previous summary each time
- Caching: Junior sets no breakpoints itself. pi-ai marks the system prompt, the last tool and the last user message. Any replacement invalidates everything after the static prefix.
Prior art (Nov 2026)
- Clear tool results before summarizing.
- Restorable compression, cache hit rate as the main metric (Manus): keep the history append-only, keep pointers to dropped content, and recite goals near the end of the context (post).
- Server-side compaction:
- Keeping recent user messages verbatim is now standard: Codex caps them at 20K tokens, as Junior already does. Claude Code keeps the system and project layers cached through a compaction and recommends compacting at natural breaks (docs).
- Summary drift:
- Async progressive compaction (Microsoft APEC / CompactionBench):
- In 13.5M Copilot sessions, only 7.8% compact, but they use 44% of all tokens.
- Building indexed summaries in the background on top of a stable prefix cuts cost by up to 25% (pub).
- Other approaches:
- Cache pricing: Anthropic charges 1.25× base input to write a 5-minute cache and 2× for a 1-hour cache, and reads at 0.1× or less.
Recommendations
Requested as part of this ticket. Ordered by expected impact.
- Guarantee that compaction makes progress (stops the $999 loop).
- Score the replacement against the target, including the runtime context.
- Trim or cap the replayed thread in the runtime context when it sets a floor above the target.
- Keep the latest tool result raw.
- Cap compactions per turn. When a compaction frees too little room, fail clearly or hand off to a fresh context instead of looping. Fixes Active-turn compaction repeats until the turn fails #2017.
- Measure cache expiry, then use the 1-hour TTL for Slack conversations.
- First split cache-write spend by idle-gap bucket (under 5 min, 5–60 min, over 60 min).
- If most of it is in the 5–60 min bucket, a 2× write that survives the gap beats a 1.25× write repeated after every pause.
- Compact when the cache is already cold.
- When a turn starts after an idle gap longer than the TTL, the prefix gets rewritten anyway. Swap in the prepared background summary then, and avoid swapping mid-turn.
- This removes most of the extra $0.42 per compaction.
- Make the reduction layered and restorable.
- In live compaction, first clear stale tool results in large batches, with
readConversationEventpointers, the way the swap path already does. - Run the LLM summary only when that is not enough.
- Stop dropping all tool history without a trace.
- In live compaction, first clear stale tool results in large batches, with
- Keep the stable prefix cached.
- Order the request as system prompt, then tools, then stable runtime context, then summary, then live history, with a breakpoint after the stable part.
- Move volatile runtime context to the end, so only the conversation layer is rewritten after a compaction.
- Stop summary drift.
- Keep the sectioned summary.
- Add a deterministically extracted ledger of references (IDs, PRs, SHAs, URLs, paths), carried verbatim across rounds instead of re-summarized by the model.
- Keep the summarizer model. Same-model summaries that reuse the cache cost $0.14 each and are not the cost driver. A cheaper model would lose the cache reuse.
- Evals and telemetry before tuning thresholds.
- Evals: a probe-question eval (recall, artifact, decision, continuation) over 1, 3 and 10 rounds of compaction, plus a loop regression for Active-turn compaction repeats until the turn fails #2017.
- Telemetry, missing today:
- summary cost on compaction events (feat(dashboard): Attribute compaction summary costs in the usage breakdown #2925)
- a cache-hit flag on the first request after compaction
- compactions per turn and the post-compaction floor
- spend on prepared summaries that were never applied
- the rate of
readConversationEventread-backs gen_ai.conversation.id, null on about $731/30d of traffic
Gaps
agent.context_compactionspans start on 2026-11-03, so there is only 7d of op-level history.- Child-agent conversations weren't sampled.
- The accuracy sample is small and script-based.
Related: #2471, #2017, #1170, #2925, #2485, #2768.
via @dcramer.
--
Activity