Adding Claude Code-style micro-compaction / retrieval stubbing

Author: NayanEuphoCreated Sep 27, 2026Updated Sep 27, 2026

Note: AI was used to re-prase this discription but it was crafted by a human [me :3]

Every chunk we retrieve stays in the conversation context for the rest of the session. Retrieved chunks are single-turn in value: the assistant's answer already distills what was relevant for the query that fetched them. Keeping the raw chunks in the prefix forever means we pay for them on every subsequent turn (prefill/cache-read, decode attention, latency) until we hit the context-window cliff and are forced into lossy compaction.

Claude Code and similar harnesses solve the analogous problem for tool results by stubbing: the full result is persisted elsewhere and replaced in the history with a compact pointer + preview before the next request. This issue proposes the same mechanism for retrieved chunks ("retrieval stubbing"), plus design improvements over the naive version to avoid hammering the vector DB on follow-up questions.


  1. The current issue

1.1 What happens today

Per turn, the pipeline does:

user query → embed/keyword search → rerank → top-k chunks injected into context → LLM answers

The chunks enter the message history as ordinary message content. Nothing ever removes them. Over a long conversation:

  • Context grows linearly: every turn appends (query + retrieved chunks + answer) tokens permanently.
  • The retrieved bulk dominates: with typical settings (5–10 chunks × 500–1,500 tokens each), retrieved text is 60–85% of total context — the same pattern the NeurIPS DL4Code 2025 work found for tool outputs (84% of a coding agent's turn).
  • Relevance is per-turn: a chunk retrieved for turn N is almost never relevant as raw text for turns N+1..N+k. What carries forward is the distilled information in the assistant's answer, not the chunk.

1.2 Illustrative cost model

Assumptions (adjust to our real numbers; ratios are what matter):

Parameter Value Per-turn full payload P (query 200 + chunks 5×1,000 + answer 800) 6,000 tok Stub size per turn s (5 × 40-tok pointers) 200 tok Prefill write price 2.00 / M tok Prefix-cache read price 0.20 / M tok (10× discount) Session length T 30 turns Context window 128k

Current implementation — full prefix maintained across all turns:

  • Cache writes (new tokens per turn): T · P = 180k tok → 0.36
  • Cache reads (prefix re-read every turn): P · T(T−1)/2 = 2.61M tok → 0.52
  • Total prefill ≈ 0.88, but context at turn 30 = 180k tokens → we exceed the 128k window at turn 21 and must truncate or run lossy LLM compaction from then on.

Decode and latency are the hidden quadratic. Every generated token attends over the full prefix. Average attended context across the session is 60–90k tokens in the current design. Decode cost per turn grows linearly with context length; cumulative decode compute grows roughly quadratically with session length. This shows up as p50/p95 latency creep long before the window is full.

1.3 Summary of the problem

We are paying for retrieved chunks in four currencies:

  1. Prefill/cache-read tokens — re-billed (even at 0.1×) on every turn for the whole prefix.
  2. Decode compute — quadratic growth in attention cost over a bloated prefix.
  3. Latency — larger prompts, slower TTFT/TPOT, earlier compaction triggers.
  4. Quality — "lost in the middle"; the signal from old chunks drowns current context; multi-turn accuracy degrades measurably (Laban et al. measured a 39% average drop from context degradation alone).
  5. The cliff — eventually the full-prefix strategy fails outright and forces lossy compaction, which is itself an extra LLM pass and a cache invalidation.

  1. Prior art
  • Claude Code / Codex-style tool-result clearing: oversized tool results are replaced with 2KB previews on the next turn; full results are persisted to disk and re-readable on demand. This is the pattern we want to transplant to retrieval results.
  • Atlassian Rovo Dev — structure-aware pruning: prune bulky machine-generated content (tool outputs, intermediate scaffolding) mechanically first; LLM summarization is a fallback, not a default. Their principle: "prune in stages, and stop as soon as the history is small enough."
  • Atlan — observation masking (graduated pruning): replace older tool observations with compact placeholders, keep last M per tool, reserve LLM summarization for >95% utilization. JetBrains/NeurIPS DL4Code 2025: masking alone halves cost vs. unmanaged agents while matching LLM-summarization solve rates.
  • kapa.ai — pre-hoc retrieval pruning: grade chunks against a rubric before they enter context. Complementary to this proposal (front door vs. back door), and source of the key safety argument: in an agent, pruning recall loss is tolerable because a missing chunk can be retrieved again.
  • Redis — reversible compaction hierarchy: raw context → reversible compaction (content exists elsewhere, fetchable by pointer) → lossy summarization only as last resort.

  1. The naive approach: post-hoc retrieval stubbing

3.1 Mechanism

On the request for turn N+1, walk the history and replace every retrieved-chunk block from turns ≤ N with a compact stub. The assistant's answer is kept verbatim — it is the distilled artifact and the thing follow-ups usually reference.

Stub format (naive version):

[RETRIEVED — turn 12 — 5 chunks, 5,041 tok, persisted to stub store]
query: "how does auth token refresh work"
chunks: [doc_a#c14 (score 0.81), doc_b#c02 (0.77), doc_a#c15 (0.74),
         doc_c#c30 (0.71), doc_b#c07 (0.68)]
preview: "Token refresh flow — the client exchanges a refresh token at
          POST /oauth/token. This section covers rotation policy ..."

The stub keeps just enough to (a) remind the model that a retrieval happened and what it covered, and (b) re-fetch the full text if ever needed.

Properties:

  • Deterministic, no LLM call — pure string replacement, sub-millisecond (Atlan's Step 3 "observation masking" is the same operation).
  • Assistant responses are never stubbed. The most common follow-up pattern ("tell me more about point 2 from your last answer") is served from the answer, not the chunks.
  • Stubbing is eviction, not deletion. Full chunk text lives in a stub store; the stub is an eviction notice with a pointer.

3.2 How this interacts with prefix caching

This is the part that needs care, and it changes the design.

Prefix caches key on the exact token sequence from position 0. Replacing a chunk block in the middle of history changes every token after it → the cache hit stops at the stub position, and everything after it re-prefills at full write price.

So stubbing is not free in cache terms — but the invalidation is bounded and one-time:

  • If we stub turn N's chunks when building turn N+1's request, the invalidated region is the tail: turn N's content (plus turn N+1's new tokens). Everything up to turn N−1 is still a cache hit.
  • After that request, the stubbed sequence becomes the new cacheable prefix. We bank the savings on every subsequent turn.
  • The re-prefilled tail is exactly one turn of content — small relative to the whole history, and paid once per turn boundary, not once per chunk per turn forever.

Key consequence: stub early, at every turn boundary, and the per-request full-price prefill is always ≈ one turn of tail (previous turn's query + answer + its now-stubbed chunks + the new turn's content) instead of growing with session length.

3.3 Cost model (naive approach, same numbers as §1.2)

Per turn N: cache-read the stubbed prefix ≈ s·(N−2) + full-price re-write of the tail (previous turn P + new turn P).

  • Cache writes: 2 · T · P = 360k tok → 0.72

  • Cache reads: s · T(T−1)/2 = 87k tok → 0.02

  • Total prefill ≈ 0.74

    Current (full prefix) Naive stubbing
    Context at turn 30 180k → window exceeded at turn 21 11.8k (fits 10× over) Cache writes 180k tok → 0.36 360k tok → 0.72 Cache reads 2.61M tok → 0.52 87k tok → 0.02 Total prefill 0.88 0.74 Decode attention (avg context) 60–90k tok 10× lower (8–12k) Lossy compaction events by turn 30 ≥1 (forced) 0 Multi-turn quality degrades (buried signal) preserved (signal-dense context)

Honest read of the table: with a 10× cache-read discount, prefill dollars are roughly a wash (writes go up because the moving stub boundary re-prefills one turn of tail at full price; reads collapse because the cached prefix is tiny). The naive approach wins on the things the table's lower half shows: it stays inside the window forever, decode cost stops growing quadratically, and we never hit the forced-compaction cliff. The naive approach converts a strategy that fails at turn 21 into one that scales linearly in cost and constant in context.


  1. The naive approach's weakness: vector DB hammering

4.1 Failure mode

The stub in §3.1 is a bare pointer. It works as long as follow-ups only need what the answer already distilled. But a very common follow-up pattern is:

"What exactly did the pricing section say about annual discounts?"

— a detail that was retrieved but never made it into the answer. With bare-pointer stubs, the only path to that detail is re-retrieval: embed the new query → ANN search → rerank → fetch chunk text. Now on the critical path of a chat turn.

Worse, in agentic flows this compounds:

  • The model may re-fetch the same chunk for several consecutive turns (multi-hop reasoning over one document).
  • Each re-fetch is an embedding call + vector search + reranker pass + store fetch — our most expensive and highest-latency path (100–500ms, rate-limited) — now multiplied by an unknown number of stub-triggered re-retrievals per session.
  • A cache stampede is possible under load: many sessions stubbing simultaneously → many cold re-fetches.

So the naive approach risks trading a context-window problem for a vector-DB availability/latency problem.

4.2 Redis as a band-aid — and why it isn't robust

The obvious mitigation is a Redis layer: cache chunk_id → chunk_text (KV lookup 1ms vs. full re-retrieval), and optionally query → chunk_ids. This helps:

  • Re-fetches for known chunk IDs bypass the vector DB entirely.
  • Hot chunks stay hot.

But it is not a robust solution on its own:

  1. Redis is a cache, not a store. TTL eviction under memory pressure evicts exactly the hot chunks we need; a cold Redis at peak = thundering herd on the vector DB. Chunk text needs an authoritative home anyway (SQLite / object store / disk — Claude Code spills to disk for the same reason).
  2. Invalidation on doc updates. If source documents are re-ingested, cached chunk text is stale. Without explicit invalidation hooks in the ingestion pipeline, Redis serves wrong answers silently.
  3. It doesn't fix the root cause. The re-fetch storm is a symptom of stubs being too thin. Redis makes the symptom cheaper; it doesn't reduce how often it happens.
  4. Extra dependency in the critical path. Every chat turn now depends on Redis availability for follow-up quality.

Redis is a useful L2. It should not be the plan.


  1. Proposed design: improvements over the naive approach

5.1 Tiered stubs (the core improvement)

Not all chunks are equal at stub time. We already know which chunks the model actually used — they're the ones cited in (or load-bearing for) the answer. Split stubs into two tiers:

Tier Condition Stub content Size Rich stub Chunk cited in the answer, or graded "used" Pointer + chunk heading + 1–2 sentence auto-extract + key entities/numbers 100–150 tok Bare stub Everything else retrieved that turn Pointer + first 100 chars 40 tok

The 1–2 sentence extract for rich stubs is generated at answer time, as a ride-along: the model is already generating; asking for a per-cited-chunk "key facts" extract adds a few output tokens per chunk and is nearly free relative to a separate summarization pass.

Why this fixes the hammering: the follow-ups that triggered re-fetches under the naive approach — "what did the pricing section say about X?" — are overwhelmingly about chunks the answer touched (cited, paraphrased, partially quoted). Those now carry their key facts in the stub itself and are answerable without any re-fetch. Re-fetches become reserved for the genuinely rare case: a chunk that was retrieved, never used, and later needed verbatim.

Expected mix from typical RAG traffic: 70–80% of retrieved chunks are never cited → bare stubs; the cited minority carry 1/10th of their original tokens as extract. Net stub payload ≈ 300–400 tok/turn of history instead of 5,000.

5.2 Boundary discipline

  • Stub only at turn boundaries; keep the most recent completed turn's chunks in full until one further turn has passed. This bounds the full-price re-prefill tail to one turn of content (§3.2) and gives the model one full turn of raw chunks to work with before eviction.
  • Never modify user messages or assistant responses. Only retrieved-content blocks are stub-eligible.
  • System prompt and instructions are never stub-eligible.

5.3 Stub store + Redis as index, not store

  • At retrieval time, persist full chunk text to an authoritative stub store (SQLite / object store / local disk — cheap, durable, no eviction).
  • Redis holds chunk_id → text as a hot index with explicit invalidation wired into re-ingestion. On re-fetch: Redis → stub store → (only for genuinely new semantic needs) vector DB.
  • The vector DB is hit for new retrieval, not for re-materializing already-retrieved chunks. This keeps it off the follow-up critical path.

5.4 Re-fetch guard + promote-back dedupe

  • Re-fetch budget: cap stub re-fetches per turn (default 2). Beyond the budget, the model must work from what's in context.
  • Promote-back: when a chunk is re-fetched, promote its stub to full text in context for the remainder of the session and dedupe — never re-fetch the same chunk ID twice. Prevents the multi-hop re-fetch loop.
  • Re-retrieval promotion: if a later turn retrieves a chunk that's already stubbed in history, promote the existing stub instead of injecting a duplicate block (dedupe across turns).

5.5 Config knobs

Knob Default Purpose stub_after_turns 1 Age grace before a chunk block becomes stub-eligible rich_stub_extract_max_tokens 150 Bound on extract size per cited chunk bare_stub_preview_chars 100 Preview length for uncited chunks refetch_budget_per_turn 2 Max stub re-fetches per request stub_store_backend sqlite sqlite / s3 / disk enable_prefix_cache_aware_ordering true Order stub passes so the cache-invalidated tail is minimized

5.6 Pseudocode: the per-request pruning pass

python
def prepare_request(history, turn, config, stub_store):
    # 1. Identify stub-eligible retrieval blocks (age grace, boundary-only)
    for block in retrieval_blocks(history):
        if turn - block.turn <= config.stub_after_turns:
            continue                                # too recent: keep full
        if block.turn == last_completed_turn(history):
            continue                                # boundary discipline

        # 2. Tiered stub: cited/used chunks get extract, rest get bare pointer
        stub = []
        for chunk in block.chunks:
            if chunk.id in cited_chunks(block.answer):
                stub.append(rich_stub(chunk, extract=chunk.key_facts))   # ~120 tok
            else:
                stub.append(bare_stub(chunk))                            # ~40 tok
        stub_store.put(block.chunks)                    # persist full text once
        history.replace(block, render_stub(block, stub))

    # 3. Promote-back dedupe: reinflate previously re-fetched chunks, dedupe IDs
    history = dedupe_and_promote(history, stub_store)
    return history

  1. Why the improved design pays less than maintaining a full prefix (recap)

Against the current implementation (full prefix, no stubbing), the improved design:

Dimension Current Improved stubbing Why Context size at turn 30 180k (cliff at turn 21) 12–14k Chunks evicted to stubs after 1 turn Cache reads per turn grows linearly with session flat (stub-sized prefix) Cached prefix is stubs + last turn, not full history Full-price prefill per turn new tokens only, but context grows unboundedly 1 turn of tail (bounded forever) Boundary stubbing bounds the invalidated region Total prefill (30 turns) 0.88 + forced compaction pass 0.75, no compaction pass Writes double, reads collapse 30×, no compaction LLM call Decode attention 60–90k avg context 8–14k Dominant long-term win: quadratic → linear Lossy compaction events forced none Reversible eviction replaces lossy summarization Vector DB load baseline baseline + rare re-fetches Tiered stubs answer most follow-ups in-context; re-fetch budget + promote-back cap the rest

Against the naive approach, the improvements add: (a) 10× fewer stub-triggered re-fetches (tiered stubs), (b) bounded, amortized cache invalidation (boundary discipline), (c) no vector-DB stampede (store + Redis index + promote-back), (d) no silent staleness (explicit invalidation), — while keeping the naive approach's entire prefill/decode/context win, at a stub payload cost of 150 extra tokens/turn of history.


  1. Alternatives considered

Alternative Why not LLM-based compaction of old turns Lossy, adds an LLM call + latency, rewrites structure into prose, discards original interaction. Keep as emergency fallback only (Atlassian's cascade principle: prune first, summarize last). Sliding-window truncation Dumb eviction: drops the original task statement and early decisions that remain authoritative all session. Also breaks citations mid-conversation. Sentence-level pruning at retrieval (e.g., Provence) Pre-hoc, complementary — shrinks what enters context. Does nothing for post-hoc accumulation across turns, which is the problem here. Worth stacking later. kapa.ai-style rubric grading at the front door Also pre-hoc/complementary. Good future addition for retrieval quality; orthogonal to cross-turn accumulation. Just raise the context window / use a bigger model Cost and latency scale with context anyway (attention is quadratic); decode slowdown and quality decay persist. Doesn't remove the cliff, delays it.


  1. Risks and open questions

  2. Distillation gaps. The answer may paraphrase a number without surrounding context a later multi-hop question needs. Mitigated by rich stubs + re-fetch path, but we should measure "unanswerable-from-context follow-up" rate in evals.

  3. Exact-quote follow-ups. "Quote the exact clause" requires verbatim text → re-fetch. Acceptable if rare; measure per-session re-fetch rate (target: <0.5/turn).

  4. Extract quality. Tiered stubs inherit extract quality. Cheap fallback: heuristic extract (first sentence + sentences containing query terms) if LLM extract proves flaky.

  5. Cache-behavior dependence. Savings assume the provider's prefix cache behaves as documented. Should log cache hit/miss ratio per request as a first-class metric.

  6. Doc updates during session. A stub promoted back must serve current text; invalidation hooks in re-ingestion are required before enabling promotion.

  7. Non-agentic chat. In a plain Q&A bot without tool access, "re-fetch" must be an internal retrieval call, invisible to the user. Same mechanics apply.


  1. Metrics / acceptance criteria
  • Context tokens at turn 30 of a standard eval session: <15k (vs 180k today)
  • Zero forced compaction events in 30-turn eval sessions
  • Per-session stub-triggered re-fetch rate: <0.5/turn; p95 added latency from re-fetch: <300ms
  • Cache hit ratio on stable prefix: >90% of prefix tokens
  • Answer-quality parity (or better) on multi-turn eval set vs. current implementation, especially follow-up-question suites
  • Prefill /session at 10× cache discount: ≤ current implementation, with decode/latency measurably lower

References

Source: jamwithai/production-agentic-rag-course