# The 90% Prefix-Cache Trap: Why Context Pruning Often Raises Agent Costs (7 Benchmarks)

> 💡 **AI Labo Benchmark Cluster Synthesis — Experiments `E62, E63, E70, E71, E72, E87, E95` (Prefix-Cache Economics)**
>
> Synthesizing 7 controlled A/B experiments (`N=3` counterbalanced `AB/BA` trials per study, `temperature=0.7`, 3-UID isolation, `gemini-3.8-flash LOW`) executed inside zero-NIC Debian Proxmox sandboxes with 90% implicit prefix-cache cost accounting.
> * 🚀 **[Master Benchmark Hub & Pattern Index](https://tappers.hashnode.dev/ai-agent-harness-patterns-benchmark)**
> * 🛡️ **[Anti-Cheating Proxmox & systemd Sandbox Architecture](https://tappers.hashnode.dev/air-gapped-proxmox-systemd-agent-sandbox)**

When pricing coding agents on paper, cutting peak prompt tokens looks like an automatic win. Replace a growing ReAct chat log with stage-reset DAG nodes, run periodic context compaction every 3 turns, or hot-swap learned rules into the system prompt mid-flight, and your list-price input tokens plummet by 20% to 84%.

Across **7 isolated Proxmox benchmarks (`E62`, `E63`, `E70`, `E71`, `E72`, `E87`, `E95`)**, we tested that intuition under modern **90% implicit prefix caching**—and repeatedly watched **"token-saving" optimizations raise real API bills by `+4.5%` to `+155.1%`**. Under modern provider KV-cache pricing, *cached tokens cost 1/10th as much as uncached tokens*, meaning any edit that shifts a single byte inside the warm prefix resets cache reuse to zero and multiplies effective spend.

---

## TL;DR — Key Empirical Findings Across 7 Benchmarks

* **1. Prefix-Breaking "Optimizations" Trigger Cost Reversals (`E62`, `E63`, `E70`, `E95`):** Cutting list tokens via stage-reset DAGs (`-84.2%` peak prompt in `E62`), serial cache-forked subagents (evicting parent KV cache leaves in `E63`), mid-task system rule injection (`E70`), or unconditional periodic compaction (`E95`) dropped cache hit rates sharply and **increased effective cached cost by `+4.5%`, `+17.5%`, `+155.1%`, and `+9.5%`**.
* **2. Tail-Preserving Offloading & Rule Re-Pinning Beat In-Window Summarization (`E71`, `E72`):** Keeping the prefix append-only and querying archived turns outside the context window (`get_session_events` in `E71`) boosted hidden-suite accuracy by **`+23.95pt` (`22.33/32` ➔ `30.00/32`)** and cut effective cost by **`-16.1%`**. Re-pinning immutable constraints in the tail after compaction plus a pre-write hook (`E72`) cut calls by **`-14.3%`** and cost by **`-7.4%`**.
* **3. Flat Tool Schemas Win at `<=24` Tools (`E87`):** Under vague prompts with 24 category-prefixed tools, lazy `search_tools` saved `-13.3%` list-price cost on Turn 1 but added a discovery turn (`8 -> 9` calls) and reduced prefix cache hits (`36.2% -> 21.4%`), yielding a net **`+0.2%` effective cost tie (`$0.0216` vs. `$0.0216`)**. Save progressive tool search for `30+` tools (`E14`).

| Exp | Harness Contrast (Mode A vs. Mode B, `N=3`) | Hidden Suite | Structural / Cache Impact | Effective Cached Cost (A ➔ B) | Verdict |
| :--- | :--- | :---: | :--- | :---: | :--- |
| **`E62`** | ReAct Loop vs. Program-Governed DAG (`VM267`) | `31.33` vs. `31.00/32` | Peak prompt `-84.2%`, list `-40.9%`, cache `69.3% -> 8.2%` | `` `$0.0771` `` ➔ `` `$0.0806` `` (**`+4.5%`**) | **Reversal** (cache loss > list savings) |
| **`E63`** | Cold-Start Subagent vs. Cache-Forked Subagent (`VM268`) | `32/32` vs. `32/32` | Worker cache `+123.3%`, parent cache `72.6% -> 35.6%` | `` `$0.1530` `` ➔ `` `$0.1797` `` (**`+17.5%`**) | **Reversal** (leaf eviction hurts parent) |
| **`E70`** | Static Rules vs. Mid-Task Prefix Rule Edit (`VM275`) | `32/32` vs. `32/32` | Prefix edit reset `cached=0`; calls `6.33 -> 12.33` | `` `$0.0305` `` ➔ `` `$0.0779` `` (**`+155.1%`**) | **Severe Trap** (never mutate head) |
| **`E71`** | In-Window Compaction vs. `get_session_events` (`VM276`) | `22.33` ➔ **`30.00/32`** | Accuracy **`+23.95pt`** via external slice lookup | `` `$0.0420` `` ➔ **`` `$0.0352` `` (`-16.1%`)** | **Win** (externalize, don't compress) |
| **`E72`** | In-Summary Rules vs. Tail Re-Pin + Hook (`VM277`) | `32/32` vs. `32/32` | Calls `9.33 -> 8.00` (`-14.3%`), time `-13.8%` | `` `$0.0329` `` ➔ **`` `$0.0305` `` (`-7.4%`)** | **Win** (re-pin + deterministic guard) |
| **`E87`** | 24 Flat Category Tools vs. `search_tools` (`VM292`) | `32.00` vs. `31.67/32` | List `-13.3%`, cache `36.2% -> 21.4%`, calls `8 -> 9` | `` `$0.0216` `` vs. `` `$0.0216` `` (`+0.2%`) | **Tie** (keep flat schema `<=24` tools) |
| **`E95`** | Append-Only vs. Periodic Compaction (`VM300`) | `27/28` vs. `27/28` | Peak `-23.0%`, list `-5.8%`, cache `57.5% -> 41.9%` | `` `$0.0497` `` ➔ `` `$0.0544` `` (**`+9.5%`**) | **Reversal** (compact on threshold only) |

---

## 1. The Economics Behind Prefix-Cache Reversals

Why did `E62`, `E63`, `E70`, `E87`, and `E95` all invert list-price intuition? Under 90% implicit caching, a model API bills uncached tokens at `1.0x` and warm prefix tokens at `0.1x`. Even if a clean rewrite cuts your total prompt size by 25%, resetting the prefix forces you to pay `1.0x` on the remaining 75%—which costs **7.5x more per token** than reading 100% of an append-only history at `0.1x`.

```text
+-------------------------------------------------------------------------+
| The 90% Implicit Prefix-Cache Cost Equation (E62, E63, E70, E95)        |
|                                                                         |
|  [A] Append-Only Loop (Warm KV Prefix Preserved)                        |
|   [Sys Rules + Tools][Turn 1..4][Turn 5 tail] --> Cache Hit: 57%..69%   |
|   Effective bill: (Cached * 0.1x) + (New Tail * 1.0x)  ==> CHEAPER      |
|                                                                         |
|  [B] Mid-Task Prefix Edit / Unconditional Compaction / DAG Reset        |
|   [Sys Rules*MUTATED* or Summary Rewrite] --> Cache Hit: 0%..42%        |
|   Re-pays 1.0x on entire rewritten body + extra discovery calls         |
|   ==> E70: +155.1% | E63: +17.5% | E95: +9.5% | E62: +4.5% cost spike   |
+-------------------------------------------------------------------------+
```

Three distinct failure mechanisms emerged across the 7 runs:

1. **Head Mutation Penalty (`E70`):** Editing the system prompt mid-run with "Propose-Probe-Compose" rule discovery zeroed the KV prefix on Turn 2 (`cached=0`) and doubled calls (`6.33 -> 12.33`), spiking cost `+155.1%`.
2. **Premature History Destruction (`E71`, `E95`):** In `E95` (proposed by reader Kürşat Yılmaz), periodic compaction every fixed turn cadence reduced peak prompt by `-23.0%` and list price by `-5.8%`, yet dropped cache reuse (`57.5% -> 41.9%`), raising effective spend `+9.5%`. Worse, in `E71`, irreversible in-window summarization discarded symbol details needed on later turns, crashing accuracy to `22.33/32` (`69.8%`).
3. **Cache Leaf Eviction in Subagent Forks (`E63`):** Forking worker subagents serially onto the parent's KV prefix boosted worker cache hits by `+123.3%`, but evicted the parent's own active branch leaves (`72.6% -> 35.6%` cache hit) and raised total spend `+17.5%`. Meanwhile, keeping schemas static up to `24` tools (`E87`) preserved prefix stability far better than dynamic `search_tools` round-trips, whereas lazy search shines once schemas cross ~`30+` tools as seen in [`E14`](https://tappers.hashnode.dev/e14-progressive-tool-search) or when pairing with tail-only updates from [`E25`](https://tappers.hashnode.dev/e25-prefix-stable-prompt-caching) and avoiding blind mid-run elision traps from [`E61`](https://tappers.hashnode.dev/e61-staged-rule-based-elision).

---

## 2. Drop-In Implementation Recipe: Prefix-Safe Compaction & Slice Lookup (`E71` + `E72` + `E95`)

Instead of rewriting the prompt prefix or scheduling periodic summaries on a fixed clock, preserve an **append-only warm head**, compact **only when context utilization crosses a hard threshold** (e.g., `>=75%` of working budget or repeated stall loops), store verbatim full turns in an external JSONL log queryable via `get_session_events` (`E71`), and re-pin immutable rules at the tail alongside deterministic hooks (`E72`).

```python
import json
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class PrefixSafeCompactionController:
    """Append-only context manager preserving 90% KV cache reuse (E71/E72/E95)."""

    archive_path: Path
    pinned_rules: list[str]
    token_budget: int = 26_000
    compact_threshold: float = 0.75
    turns: list[dict[str, str]] = field(default_factory=list)
    _seq: int = 0

    def append_turn(self, role: str, content: str, est_tokens: int) -> None:
        self._seq += 1
        record = {"seq": self._seq, "role": role, "content": content, "tokens": est_tokens}
        self.turns.append(record)
        with self.archive_path.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(record, ensure_ascii=False) + "\n")

    def maybe_compact(self, current_prompt_tokens: int, repeated_failures: int = 0) -> bool:
        """Threshold-gated compaction only; avoids E95 periodic cache-busting."""
        ratio = current_prompt_tokens / max(1, self.token_budget)
        if ratio < self.compact_threshold and repeated_failures < 2:
            return False  # Keep append-only tail warm for 90% cache discount

        # Summarize middle window, keep latest 2 turns, and re-pin rules in tail (E72)
        archived_upto = max(0, len(self.turns) - 2)
        rule_banner = "\n".join(f"- [PINNED] {r}" for r in self.pinned_rules)
        summary = (
            f"[COMPACTED seq 1..{archived_upto}: call get_session_events(start, end) "
            f"if exact line/trace recall is needed]\n{rule_banner}"
        )
        self.turns = [{"seq": 0, "role": "user", "content": summary, "tokens": 180}, *self.turns[-2:]]
        return True

    def get_session_events(self, start_seq: int, end_seq: int) -> list[dict[str, str]]:
        """Out-of-band slice interrogation (E71) prevents irreversible detail loss."""
        events = [json.loads(line) for line in self.archive_path.read_text(encoding="utf-8").splitlines()]
        return [ev for ev in events if start_seq <= int(ev["seq"]) <= end_seq]
```

**Why this works:**
* **Zero periodic cache destruction (`E95`):** Turns `1..N` remain strictly append-only until `current_prompt_tokens` genuinely nears the `compact_threshold` or error loops stall progress.
* **No Mid-Task System Edits (`E70`):** Learned or critical constraints are injected at the **tail** during compaction (`E72`) and paired with deterministic pre-write hooks rather than invalidating Turn-0 system prefixes.
* **Lossless Recovery (`E71`):** When an agent needs an exact error line from Turn 2 after compaction, `get_session_events(2, 3)` fetches only that slice instead of forcing blind re-reads or hallucinations.

---

## 3. Threats to Validity & When NOT to Use This

1. **Task Horizon & Token-Scale Boundary:** All 7 studies ran on `gemini-3.8-flash (LOW)` across 5–13 turn Python engineering tasks inside a `32,768`-token output window. On ultra-long `100k+`-token agent trajectories where raw history genuinely hits context-window limits or triggers Lost-in-the-Middle recall failure, threshold-triggered compaction (`E95` + `E71`) remains essential—just trigger on token utilization (`>=75%`), never on a fixed low-turn cadence.
2. **Multi-Turn vs. Single-Shot Ratio:** Prefix-cache dominance shrinks if your workflow averages only 1–2 LLM calls per isolated worker, or if your schema exceeds `30+` heavy MCP tools (`E14` still saves `-92.7%` input tokens at `32` tools when prompts explicitly require discovery).
3. **Cross-Layer Integration Caution:** Preserving KV cache is only layer 1 of a stable harness; pairing append-only contexts with deterministic zero-token guards prevents silent drift after edits—covered next in **[Cluster 2: Zero-Cost Brownfield Agent Guards](https://tappers.hashnode.dev/e68-e94-brownfield-zero-cost-defense-cluster)**.

<details>
<summary>📋 Experiment Metadata & Reproducibility (E62, E63, E70, E71, E72, E87, E95)</summary>

* **Experiment Cluster:** `E62` (`VM267`), `E63` (`VM268`), `E70` (`VM275`), `E71` (`VM276`), `E72` (`VM277`), `E87` (`VM292`), `E95` (`VM300`)
* **Protocol:** Benchmark v2.1 (`N=3` counterbalanced `AB/BA` trials per experiment, `temperature=0.7`)
* **Sandbox:** Zero-NIC Debian Proxmox VMs (`PrivateNetwork=yes`, 3-UID isolation separating agent, runner, and hidden grader)
* **Model & Pricing:** `gemini-3.8-flash` (`thinkingLevel="LOW"`, `max_output_tokens=32768`), evaluating effective cached spend (`90%` prefix-cache discount) alongside uncached list price upper bounds.
* **Community Attribution:** `E95` periodic clean compaction vs. append-only prefix caching was proposed by reader Kürşat Yılmaz.

</details>

---

**Discussion:** Have you caught a "token-saving" optimization in production that actually increased your monthly API bill once prompt-cache hit rates were included? Share your cache-ratio numbers or compaction thresholds below!

<!-- PUBLIC_DATASET_LINKS_START -->
### 📦 Raw Benchmark Telemetry & Interactive Trial Explorer

* 🔍 **[Interactive Trial Explorer (CLUSTER1)](https://tappers-labo.github.io/ai-labo-benchmark-data/#cluster=CLUSTER1)** — Filter all 104 benchmarks and inspect per-trial `effective_cached_usd`, token breakdowns, and hidden-test outcomes.
* 💾 **[Sanitized Open Dataset Repo](https://github.com/tappers-labo/ai-labo-benchmark-data)** — Download `experiments_master.csv/.jsonl`, Block 5 Bill of Design, plus sanitized `usage.json`, `independent-tests.json`, and `actions.json` traces.
* 🎥 **[YouTube Channel (Tappers AI Labo)](https://www.youtube.com/@tappers-labo-en)** — Plain-English Lv.1 video walkthroughs of our isolated AI benchmark lab & key findings.
<!-- PUBLIC_DATASET_LINKS_END -->

### 🔗 Continue Reading the Series
* 🚀 **Master Benchmark Hub:** [AI Agent Harness Patterns Benchmark](https://tappers.hashnode.dev/ai-agent-harness-patterns-benchmark)
* 🛡️ **Methodology & Sandbox Architecture:** [How to Benchmark AI Agents Without Eval Cheating or API Key Leaks](https://tappers.hashnode.dev/air-gapped-proxmox-systemd-agent-sandbox)
* 🛡️ **Cluster 2 (`E68`–`E94`):** [Zero-Cost Brownfield Agent Guards: Full-Dir Locks, AST Hooks & Early Stop](https://tappers.hashnode.dev/e68-e94-brownfield-zero-cost-defense-cluster)
* 🔗 **Foundational Caching Study (`E25`):** [Prefix-Stable Prompt Caching](https://tappers.hashnode.dev/e25-prefix-stable-prompt-caching)
* 🔗 **Related Elision Trap (`E61`):** [Why Blind Tool-Output Elision Backfires (+40.1% Cost)](https://tappers.hashnode.dev/e61-staged-rule-based-elision)
