Skip to content

Make compaction cheaper and safer for long-lived sessions #2942

Open

Description

@sentry-junior

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.5 with reason capacity, 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_compaction spans across 568 conversations.
    • background ready: 1,288
    • blocking: applied 1,092, not_ready 174, over_target discards 59
    • active: compacted 554
    • summary_failed: 4

Cost

  • Summary calls:
  • 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.
  • 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-S9 and JUNIOR-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 readConversationEvent read-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 markSeq verbatim
    • trims old tool results over 2K chars down to the first and last 500 chars plus a readConversationEvent pointer
  • 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.
    • JetBrains found that hiding old observations matches or beats LLM summarization at about half the cost, and a hybrid of the two is best (paper, blog).
    • Anthropic ships this as clear_tool_uses_20250919. Its clear_at_least option clears in large batches so each cache rewrite pays for itself (docs).
  • 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:
    • Anthropic compact_20260112: custom instructions, pause_after_compaction, and a cache breakpoint on the compaction block (docs).
    • OpenAI Responses compaction: returns an opaque, encrypted item (docs).
  • 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:
    • Factory's anchored, incremental summaries score best on its own probe-question eval (vendor-run) (post).
    • CliffCompaction never re-summarizes a summary: it only drops or truncates the original content, for up to 50% lower cost (paper).
  • 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:
    • Handoff to a fresh thread instead of compacting (Amp, post).
    • Learned compression guidelines (ACON, paper).
    • Context isolation in subagents (Anthropic).
  • 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.

  1. 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.
  2. 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.
  3. 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.
  4. Make the reduction layered and restorable.
    • In live compaction, first clear stale tool results in large batches, with readConversationEvent pointers, 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.
  5. 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.
  6. 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.
  7. 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.
  8. Evals and telemetry before tuning thresholds.

Gaps

  • agent.context_compaction spans 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.

--

View Session [Sentry]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions