# Why Blind Tool-Output Elision Backfires: Cache Busting & +40.1% Cost (N=3)

> 💡 **AI Labo Benchmark Series — Experiment `E61` (Staged Rule-Based Elision vs. Recoverable Summarization)**
>
> Part of our controlled benchmark series testing AI coding agent harnesses inside network-isolated Proxmox VMs (`N=3` counterbalanced `AB`/`BA`/`AB` trials, `temperature=0.7`, 3-UID grading, 90% prefix-cache cost accounting).
> * 🚀 **[Master Benchmark Hub & All Pattern Rankings](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)**

Fan et al. (`arXiv:2609.20804`) proposed a two-stage context compactor: first deterministically elide old `>= 600`-char tool outputs into non-recoverable stubs (`M1` at soft threshold `B1`), and only invoke LLM summarization (`M3`) at hard threshold `B2`—promising lower summarization spend with equal or better accuracy.

We tested **Staged `M1 ➔ M3` Elision** against **Recoverable `M3 + M2` Summarization** under a `26,000`-token window on `models/gemini-3.8-flash` (`LOW`, `N=3`). Under real implicit prefix caching, **blind `M1` elision backfired on both accuracy (`-33.3%`) and cost (`+40.1%`)**.

---

## TL;DR — Key Empirical Findings

* **1. Accuracy Collapsed in Trial 2 (`31.00 / 32` vs. `20.67 ± 17.90 / 32`):** `Baseline (M3 Summarization + M2 recall_event)` hit **`31.00 ± 0.00 / 32` (`96.88%`)** and submitted cleanly in `3/3` trials (missing only `inv_15` `cap=True` bool check). `Candidate (Staged M1 ➔ M3 Elision)` tied at `31/32` in Trials 1 & 3, but crashed to **`0/32` (`24`-turn limit)** in Trial 2 after `M1` twice erased `metering_contracts.py`—inducing hallucinated symbols (`MAX_EVENT_QUANTITY`, `min_val=0`).
* **2. `+40.14%` Higher Effective Cost Despite `-53.92%` Cheaper `M3`:** While `M1` trimmed `M3` summary spend from `` `$0.0102` `` to `` `$0.0047` `` (`-53.92%`), deleting spec/contract reads triggered a **`+192.86%` re-read spiral** (`inspect_workspace`: `4.67` ➔ `13.67` calls) and **Implicit Prefix Cache Busting**: mutating `msgs[2], msgs[4]...` in-place every 1–2 turns crashed cache hits to **`3.4%–8.1%`**, raising uncached input **`+92.88%`** and effective cost from `` `$0.1532 ± $0.0100` `` to **`` `$0.2147 ± $0.0198` `` (`+40.14%`)**.
* **3. Exact Boundary (`rehearsal-02` vs. Production `N=3`):** In `rehearsal-02` (cramped `W=18,000` with no anti-thrashing guard), `Baseline` thrashed `M3` `8` times and `Candidate` won **`-40.55%`** (`` `$0.2072` `` ➔ `` `$0.1232` ``). Adding `MIN_M3_FOLDABLE_TOKENS=1500` and a healthy `W=26,000` stabilized `Baseline` and exposed `M1`'s cache-busting penalty.

| Metric (`N=3` Trials, `Mean ± SD`) | Baseline: `M3 + M2` (`B2=20.8k`) | Candidate: `M1 ➔ M3` (`B1=15.6k`) | Delta / Effect |
| :--- | :---: | :---: | :--- |
| **Hidden Grading Suite (`32` Cases)** | **`31.00 ± 0.00`** (`96.88%`) | `20.67 ± 17.90` (`[0–31]`, `64.59%`) | **`-10.33` (`-33.33%`, T2 `0/32`)** |
| **Clean Submissions (`3` Trials)** | **`3 / 3`** | `2 / 3` (T2 hit `24`-turn cap) | Trial 2 contract hallucination |
| **Total Model Calls (incl. `M3`)** | **`17.33 ± 0.58`** | `25.00 ± 1.00` | **`+44.23%`** (`+7.67` calls) |
| **`inspect_workspace` Re-Reads** | **`4.67 ± 0.58`** (`[4–5]`) | `13.67 ± 2.08` (`[12–16]`) | **`+192.86%` re-read spiral** |
| **`M3` Summary Calls / Cost** | `2.67` / `` `$0.0102 ± $0.0021` `` | **`1.67` / `` `$0.0047 ± $0.0019` ``** | `-53.92%` summary cost (`` `-$0.0055` ``) |
| **Implicit Cache Hit Rate (%)** | **`53.14 ± 7.57%`** | `40.75 ± 11.58%` (`3.4–8.1%` post-`M1`) | **`-12.38 pt` cache busting** |
| **Uncached Input Tokens** | **`84,080.7`** | `162,171.3` | **`+92.88%`** (`+78,090.7` tokens) |
| **Total Tokens (`total_tokens`)** | **`203,849.7 ± 19,739.4`** | `299,231.3 ± 30,269.4` | **`+46.79%`** (`+95,381.7`) |
| **Effective Cached Cost (90% OFF)** | **`` `$0.1532 ± $0.0100` ``** | `` `$0.2147 ± $0.0198` `` | **`+$0.0615` (`+40.14%` worse)** |
| **List-Price Upper Bound (No Cache)** | **`` `$0.2191 ± $0.0085` ``** | `` `$0.2920 ± $0.0235` `` | `+33.27%` (`` `+$0.0729` ``) |
| **`MAX_TOKENS` Hits (`32768` cap)** | `0 / 3` | `0 / 3` | Zero output truncation |

---

## 1. Experiment Design & Cache-Busting Mechanism

```text
+-----------------------------------------------------------------------+
| Proxmox VM266 (0 NICs, 3.8-flash LOW, W=26k, N=3 AB/BA, 32 Tests)     |
|                                                                       |
| Baseline (M3 Summary at B2=20,800 + MIN_M3_FOLDABLE=1500):            |
|   Compacts only 2-3x at milestones -> preserves 62-84% cache hits     |
|   between summaries -> 4.67 inspects | $0.1532 eff. | 31/32 (3/3)     |
|                                                                       |
| Candidate (Indiscriminate M1 Elision at B1=15,600 -> M3 at 20,800):   |
|   M1 stubs msgs[2], msgs[4]... every 1-2 turns (incl. SPEC/contracts) |
|   --> Re-read loop (13.67 inspects) + Prefix Cache drops to 3.4-8.1%  |
|   --> Uncached input +92.9% | $0.2147 eff. (+40.1%) | T2 0/32 crash   |
+-----------------------------------------------------------------------+
```

Notice the pricing asymmetry: saving `` `$0.0055` `` on `M3` summarization backfired by triggering **`+$0.0670`** of extra agent turns and uncached input charges—confirming Fan et al.'s own Appendix 8.4 warning on prefix-cache invalidation.

---

## 2. Drop-In Implementation Recipe: Volatile-Only Batch Compaction

Never apply `M1` blindly to specification/contract reads, and never mutate early messages turn-by-turn. Elide **volatile tool outputs only** (`pytest`, `grep`) and batch-compact at milestone boundaries:

```python
VOLATILE_TOOLS = {"run_public_checks", "grep_search", "list_dir"}


def selective_batch_compaction(
    history: list[dict],
    est_tokens: int,
    soft_b1: int = 15600,
    hard_b2: int = 20800,
    min_foldable: int = 1500,
) -> tuple[list[dict], str]:
    """Protects durable specs/contracts and batches compaction to preserve KV prefix cache."""
    if est_tokens < soft_b1:
        return history, "NO_OP_KEEP_KV_CACHE"
    if est_tokens < hard_b2:
        # Elide ONLY volatile noisy outputs (never inspect_workspace spec/contract reads)
        elided_chars = 0
        for turn in history[:-4]:
            if turn.get("tool") in VOLATILE_TOOLS and len(turn.get("output", "")) >= 600:
                elided_chars += len(turn["output"])
                turn["output"] = "[volatile log elided]"
        return history, f"VOLATILE_ONLY_ELISION:{elided_chars}"
    foldable_est = sum(len(t.get("output", "")) // 3 for t in history[:-4])
    if foldable_est < min_foldable:
        return history, "SKIP_M3_ANTI_THRASH"
    return history, "TRIGGER_BATCH_M3_SUMMARY"
```

* **Why this works:** Protecting `inspect_workspace` spec/contract reads stops the `+192.86%` re-read spiral, batching at `B2` preserves `60%–84%` KV cache streaks, and `min_foldable` prevents `M3` thrashing.

---

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

1. **Repo Horizon (`14` Files, `14–24` Turns) vs. `50–100`-Turn Log Exploration:** In long debugging sessions filled with huge one-off `grep` or build dumps that never need re-reading, `M1` elision aligns with `arXiv:2609.20804`. Our falsification applies specifically to **10–30 turn multi-file implementation tasks referencing durable specs**.
2. **Literal Algorithm 1 vs. Tool-Aware Elision:** We faithfully implemented Fan et al.'s tool-agnostic `>= 600`-char `M1` rule; tool-aware elision (like the recipe above) resolves the re-read bug.
3. **Timer Initialization Note:** Because `run_guest.py` stamped `started_ts` in `__init__`, guest `elapsed_seconds` (`474.3s`) reflects combined process time; actual wall-clock pacing is reflected by total calls (`17.33` vs. `25.00`).

<details>
<summary>📋 Experiment Metadata & Reproducibility</summary>

* **Experiment ID:** `E61` (`C057` / Fan et al. `arXiv:2609.20804` / Benchmark v2.1)
* **Run ID:** `e61-20261124-vm266-01` (`N=3` trials: `AB` ➔ `BA` ➔ `AB`, `temperature=0.7`)
* **Sandbox Environment:** Proxmox Isolated VM `VM266` (0 NICs, Debian 13, 3-UID isolation: `labexp61` / `labrunner61` / `labjudge61`)
* **Model Tier:** `tier1_flash_low` — `models/gemini-3.8-flash` (`LOW`, `max_output_tokens=32768`, `M3: 4096`, `W=26,000`)
* **Cost Accounting:** Google 90% implicit prefix-cache discount (`effective_cached_micro_usd`) as primary metric; list-price upper bound reported alongside.

</details>

---

**Discussion:** When compacting agent history, do you protect `read_file` spec/contract turns from deletion—or how do you keep prefix-cache hit rates from collapsing?

### 🔗 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: Designing a Proxmox & systemd Sandbox](https://tappers.hashnode.dev/air-gapped-proxmox-systemd-agent-sandbox)
* ⬅️ **Previous Post (`E60`):** [Benchmarking Procedural Graphs on Flash: -77% Token Variance, +1.9% Cost (N=3)](https://tappers.hashnode.dev/e60-self-evolving-procedural-graph)
* ⚡ **Related Prefix Caching (`E25`):** [Stop Invalidating Your Coding Agent's KV Cache: Dynamic System Prompt Mutation vs. Append-Only Prefix-Stable Prompt Caching (2.63x Faster)](https://tappers.hashnode.dev/e25-prefix-stable-prompt-caching)
* 🗜️ **Related Milestone Compaction (`E12`):** [How Save-Game Context Compaction Fixes Spec Drift in Multi-Step Coding Agents (-91.9% Input Tokens)](https://tappers.hashnode.dev/e12-milestone-context-compaction)
