compression with a quality contract

Research & Frontier

The proof artifacts no competitor publishes: a savings-vs-quality curve where every point carries a certification verdict, a distribution-free risk certificate on the decision-change rate, a never-regressing self-distilling loop, and savings telemetry you can verify yourself.

Proof harness & paper. For a non-circular evaluation, Distil grades real agent traces (τ-bench / SWE-bench) with a real model — no planted markers — via benchmarks/prove.py: E1 frontier, E2 out-of-sample certification coverage, E3 distribution shift, E4 downstream task-success, and an E5 head-to-head vs. the real llmlingua packages (now running on Apple-silicon / MPS), with an optional --expand recovery loop. The headline run is the full real SWE-bench_Lite edit-localization (n=300 instances, 600 decisions, Claude grader): the certified reversible engine holds 98.8% out-of-sample certificate coverage at a mean realized decision-change rate of 8.0% for 15.7% mean certified savings (E2; α=0.15, δ=0.05, 500 splits). On the 100-trajectory E5 subset, LLMLingua-2 certifies at 11.6% savings / 7.0% decision-change and LongLLMLingua at 5.7% / 3.5% (a fixed adapter no-op bug) — a frontier illustration, not a dominance claim. De-confounding (v0.24): re-running E5 with the gold hunk randomly repositioned (seed 1729) shows the gold-last position confound is real but not load-bearing — recency's decision-change rises 5.5%→8.5% yet still certifies, distil's aggressive levels still don't, and E2 still holds (100% coverage). With honest calibration/test operating-point selection, distil does certify 14.0% test savings / 4.0% decision-change, but the certified point is plain head-truncation — on this single-turn task the win is the certificate that selects safe operating points, not a compressor that beats truncation. Get real τ-bench data with benchmarks/fetch_real.py tau --src tau:gpt-4o-airline (no HuggingFace needed). See benchmarks/PROVE.md, the protocol in docs/PAPER_PLAN.md, the compiled paper (PDF) with arXiv-ready LaTeX source in docs/paper/, and the first-timer publishing guide in docs/PUBLISHING.md.

E14: provider-native context manipulation (the instrument turned outward)

Harness: distil certify-provider · Numbers: benchmarks/results/provider-compaction/ · Full study: Provider Compaction

E1–E13 point the decision-equivalence contract at distil’s own compressor. E14 points the same instrument at the two features that now rewrite the context window by default, server-side: Anthropic context editing and OpenAI server-side compaction. Neither vendor publishes what its feature does to an agent’s decisions — a structural conflict of interest, since no vendor ships a tool that measures its own degradation. Same protocol as everywhere else: pre-registered (protocol.json hashed before the first API call), majority-of-3 decisions per arm, an A/A arm for the self-agreement floor, SIG v3 signatures, live calls hard-capped, Hoeffding–Bentkus upper bound.

Provider manipulationConfigA/B changeA/A floorAdjusted95% boundCertified at α=0.1
Anthropic context editing — default policy, run 2keep=3, trigger 3k100.0%2.5%100.0%100.0%No
Anthropic context editing — default policy, run 1keep=3, trigger 3k95.0%2.5%94.9%99.5%No
Anthropic context editing — aggressivekeep=0, trigger 50092.5%7.5%91.9%98.6%No
OpenAI server-side compactionthreshold 3k20.0%2.5%17.9%36.7%No
OpenAI server-side compactionthreshold 1k12.5%0.0%12.5%27.8%No

The finding is the mechanism, not the rate. Anthropic’s default retention (keep=3) did not reduce the decision-change rate versus deleting everything — 92.5% → 95–100%. It changed the failure mode. Under keep=0 the agent lost the load-bearing facts and stopped acting: 37 of 40 flips were tool→text. Under the default, stalls nearly vanish and 29–31 of 40 flips become tool→wrong tool — the three retained results are the routine ones (inventory, shipping, promotions), enough to keep the agent confidently acting while the records its policy depends on are gone. It refunds where it should escalate fraud. A stalled agent is a visible incident; a wrong one is a silent write.

Why retention counted in recency cannot help. The load-bearing facts in an agent trajectory are gathered early, then buried under routine calls. A policy that keeps the most recent N tool uses cannot protect a decision that depends on relevance. That ordering is the normal shape of agentic work, not an adversarial construction — and it is why the default is the dangerous setting rather than the safe one.

The contrast. Summarization preserved decisions roughly 5–7× better than deletion, at both the aggressive and default configs. Neither feature certifies decision-safe at α=0.1, and per the house rule (see E7) both numbers are published either way. The pre-registered protocol was executed twice against Anthropic and both runs are published — selecting the kinder or crueler one after the fact is the practice this experiment exists to refuse.

Honest scope. Synthetic decision-bearing corpora, deliberately ordered so that keep=3 retains only routine rounds: this measures what the policy’s mechanism does when load-bearing facts age out, not how often that arises in your traffic. The trigger is lowered to 3k (from the 100k default) so 40 cases fit a budget; the retention rule is the real default. Decision-equivalence is the measured invariant, not task success — E7 showed those can diverge. Point-in-time, 2026-07-26, on the models named. Reproduce, don’t extrapolate — the commands are published.


E7: SWE-bench Verified end-to-end task-success

Harness: benchmarks/swe_bench_e2e/ (official swebench 4.1.0) · Numbers: docs/paper/results/swe_bench_verified_e2e.json · Source: PR #8

E1–E5 measure decision-equivalence on edit-localization — a proxy. E7 is the first non-proxy test: does the certified operating point survive real execution? A real agent (aider + claude-sonnet-4-6, temp 0, diff edit format) is run end-to-end on SWE-bench Verified (n=50, seed 1729) and scored by the official swebench harness, across three conditions sharing the identical agent: (A) full context, (B) distil at its certified trunc@500 operating point, and (C) LLMLingua-2.

ConditionResolvedpass@1
A — full context26 / 5052.0%
B — distil trunc@500 (certified)8 / 5016.0%
C — LLMLingua-213 / 5026.0%

distil's certified point loses to full context by 36 points (paired McNemar p<0.001) and does not beat LLMLingua-2. At trunc@500 it strips 86% of agentic context (vs LLMLingua-2's 48%), so its lower score is partly aggression, not purely method.

The honest verdict. The localization decision-equivalence certificate does not transfer to end-to-end task success once compression is aggressive — trunc@500 was certified at 4.0% decision-change yet collapses pass@1 by 36 points. The contract (decision-equivalence) is right; the certified rate, not the chosen compressor, is the contribution. The certificate is the contribution, not the compressor. Total spend $33.66.

E8: long-horizon agent task-success

Harness: benchmarks/swe_bench_e2e/ (official swebench) · Numbers: docs/paper/results/swe_e2e_longhorizon/reports/ (per-condition resolved-instance reports)

E7 flagged relevance-gated reversible compression as an untested path on real long-horizon execution. E8 runs that test across six conditions, including a Headroom competitor and LLMLingua-2. A custom multi-turn ReAct coding agent (read / search / edit_file / run_tests tools, up to 30 turns, claude-haiku-4-5, temp 0) is run end-to-end on the full 500-instance SWE-bench Verified set, scored by the official swebench harness (hidden tests, per-instance Docker). Runs average ~27 turns — read-file and tool outputs accumulate into large peripheral context behind a small active working set, which is exactly the regime the relevance gate was designed for. Six conditions share the identical agent; only the compressor differs.

ConditionCtx reductionResolvedpass@195% CI (Wilson)
A — full context (no compression)196 / 50039.2%[35.0%, 43.5%]
E — distil reversible, relevance-gated53%184 / 50036.8%[32.7%, 41.1%]
F — Headroom (lossy competitor)163 / 50032.6%[28.6%, 36.8%]
D — distil reversible + skeleton digest (+distil_expand, ungated)162 / 50032.4%[28.4%, 36.6%]
B — distil trunc@500 (aggressive lossy)28 / 5005.6%[3.9%, 8.0%]
C — LLMLingua-2 (lossy competitor)12 / 5002.4%[1.4%, 4.2%]

All six conditions score the same 500 instances (paired McNemar). Gate vs full context: difference = −2.4 pp, 95% CI [−5.7, +0.9], McNemar p=0.19 — non-inferior to full at a 6 pp margin (borderline at a strict 5 pp margin; p=0.19 means no significant difference was detected, not that the two are equivalent). Gate vs Headroom: +4.2 pp, McNemar p=0.035 — distil's relevance-gated tier beats Headroom with statistical significance. Lossy truncation (B) vs full context: p<0.001. Gate vs LLMLingua-2: 174 instances the gate solved that LLMLingua-2 did not, 2 the reverse — McNemar p<0.001. Recovery round-trips tell the mechanism: ungated (D) issues 9.6 distil_expand calls per instance (skeleton digested the whole history, must keep recovering the working set); gated (E) issues only 0.58 per instance (digests only aged-out periphery, keeping the working set full). An honest ablation: applying the skeleton digest to the gated tier (E) — which uses head-truncation in its passive path — regressed pass@1 from 36.8% to 5.6%, matching condition B. The navigable digest makes the agent over-trust the summary and stop re-reading; head-truncation is the correct digest for the passive tier.

The positive resolution to E7 — and the cleanest possible evidence for selective compression. On the axis that defines the field — certified decision-equivalence plus real task success — distil leads. The relevance-gated tier (E) achieves the highest pass@1 of any compressor tested: 36.8%, +4.2 pp over Headroom (p=0.035), and is the only condition statistically non-inferior to full context (difference −2.4 pp, 95% CI [−5.7, +0.9]; McNemar p=0.19). It is also the only reversible and certified compressor in the comparison. Lossy competitors are cheaper or simpler but offer no guarantee: Headroom reaches 32.6% (uncertified, lossy), LLMLingua-2 reaches 2.4% (same ~52% context reduction as distil's gate, yet 34 points lower on task success). Distil does not claim cost-domination — Headroom is cheaper. The claim is certified accuracy with a guarantee, at leading real-task performance.

New techniques in E8: skeleton digest and sticky expansion

Two new techniques were introduced and ablated in E8:

Certificate scope on long-horizon trajectories

The skeleton digest is 100% byte-exact reversible — its decision-equivalence rate with recovery is 0% (96% raw, like all lossy methods; safety comes from reversibility). The E9 trajectory-composition bound extends the per-turn certificate to multi-turn trajectories: across ~27-turn runs, the naive composition bound becomes vacuous (only ~1.8 turns are outcome-determining), so the per-turn certificate's integrity on full trajectories is tighter than a naive product would suggest, though the formal bound for arbitrary trajectories remains an open problem. The honest position: reversibility is the safety guarantee for the active-recovery tier; non-inferiority to full context is the empirical result for the relevance-gated tier.

E10: trajectory-level decision-equivalence certificate

E2 gave a per-turn guarantee. E7 showed that guarantee does not naively transfer to task success under aggressive compression. E8 showed relevance-gated compression is empirically non-inferior to full context. E10 closes the loop with a real statistical guarantee at the trajectory (task) level — lifting the per-turn certificate all the way to whole-run outcomes.

E10 is the first trajectory-level, distribution-free decision-equivalence certificate for agent context compression (to our knowledge). It runs the same Learn-Then-Test / Hoeffding–Bentkus engine as E2 (distil.conformal.certified_risk_bound), but inverted to a (1−δ) upper confidence bound on per-trajectory 0/1 loss, over the full 500-instance SWE-bench Verified set used in E8. Two loss functions are measured:

Results — relevance-gated (passive) tier, 500 instances, δ=0.05

Loss Empirical Certified ≤ (95% CI) Out-of-sample coverage
Divergence (outcome ≠ full) 14.4% 18.0% 95.4%
Harm (full solved, gated did not) 8.4% 11.4% 96.7%
Plain-language guarantee. With 95% confidence, the relevance-gated compressor changes a run’s outcome on ≤18.0% of exchangeable tasks and costs a solvable task on ≤11.4% — about 1 in 9, certified.

Out-of-sample proof (the bound actually holds)

Like E2, E10 is proven out-of-sample, not merely asserted. Over 1000 random calibration/test splits of the 500 instances: the bound β is certified on the calibration half, then the disjoint test half’s realized rate is measured. Coverage lands at 95.4% (divergence) and 96.7% (harm), both at or above the 95% target. The bound holds on held-out data.

Honest scope: ungated reversible tier

The ungated reversible tier (skeleton digest, condition D in E8) also certifies under E10: divergence ≤23.2%, out-of-sample coverage 93.9%. Coverage is marginally below the 95% target — a borderline result, reported here without softening. The relevance gate is the tier with a clean certificate.

Honest scope: exchangeability

The guarantee holds for traffic exchangeable with the calibration distribution (SWE-bench Verified, this agent + model combination). It is not a universal bound. Changing the agent, the model, or the task distribution requires re-certification. Reproducible via benchmarks/trajectory_certificate.py; numbers trace to docs/paper/results/swe_e2e_longhorizon/trajectory_certificate.json.


E11: cross-model generality (five models, three vendors)

Reproducible: benchmarks/long_horizon/run.py --backend openai (DeepSeek-V3, OpenAI) · results in docs/paper/results/swe_e2e_longhorizon_deepseek/, docs/paper/results/swe_e2e_longhorizon_sonnet/, docs/paper/results/swe_e2e_longhorizon_gpt4omini/, docs/paper/results/swe_e2e_longhorizon_gpt41/

E7–E10 use claude-haiku-4-5. To test whether the gate's non-inferiority generalizes, the long-horizon harness was re-run on four more models spanning three vendors: DeepSeek-V3 (deepseek-chat, n=200), Claude Sonnet 4.6 (n=50), gpt-4o-mini (OpenAI, n=50), and gpt-4.1 (OpenAI, n=50). Full-context strength spans a wide range — gpt-4o-mini 12.0%, gpt-4.1 26.0%, Haiku 39.2%, Sonnet 54.0%, DeepSeek-V3 60.0% — letting us separate capability from compression aggressiveness.

model (vendor)full (pass@1)gate@12vs fullrealized
gpt-4o-mini (OpenAI, n=50)12.0%12.0%+0.0 pp, p=1.0 (n.s.)29%
gpt-4.1 (OpenAI, n=50)26.0%20.0%−6.0 pp, p=0.45 (n.s., CI [−16.2,+4.2])32%
Haiku 4.5 (Anthropic, n=500)39.2%36.8%−2.4 pp
Sonnet 4.6 (Anthropic, n=50)54.0%54.0%+0.0 pp, p=1.0 (n.s.)18%
DeepSeek-V3 (n=200)60.0%55.5%−4.5 pp, p=0.15 (n.s.)31%

gate@6 (aggressive setting): held on Haiku (−2.4 pp), Sonnet (−2.0 pp), and gpt-4o-mini (+0.0 pp, realized 58%); broke on DeepSeek (−31 pp, realized 60%); gpt-4.1 gate@6 partial — OpenAI account credit exhausted mid-run (32/50 instances scored), not reported.

Honest scope: 3 of 5 runs are n=50 (wide CIs, directional not powered). gpt-4.1 full 26% is modest — the ReAct harness is tuned for Claude/DeepSeek (harness-fit caveat, not a distil result). The certificate itself (E2/E10) is model-agnostic by construction.

gate@12 shows no statistically significant degradation on any of the five models across three vendors. The two well-powered runs (Haiku n=500, DeepSeek n=200) confirm non-inferiority; the three n=50 runs (Sonnet, gpt-4o-mini, gpt-4.1) are directionally consistent with wide CIs (not powered). The earlier “aggressiveness must scale with model capability” story is refuted by the wider sweep. gate@6 broke only on DeepSeek (−31 pp) and held everywhere else. Two facts dissolve the capability story: (i) gpt-4o-mini held at gate@6 despite the highest realized compression of all (58%, above DeepSeek’s breaking 60%) — because a weak agent never used that periphery; (ii) Sonnet, also strong, held because its gate@6 realized only 34% compression on these runs (the same gate_recent digests different fractions depending on workload conversation shape). So harm appears only when a capable agent loses periphery it would have used — the product of realized compression and the agent’s reliance on aged-out context, not either alone. A fixed gate_recent cannot predict this (it is a workload×model interaction), which is exactly why distil calibrates on outcomes per deployment with a fail-safe to full context.

Operationalized: auto-calibration of the operating point

A workload-dependent operating point is a deployment hazard only if it is hand-tuned — point distil at a new model or task distribution and it could silently ship a lossy setting. distil removes the hazard with the operating-point analogue of the certificate: just as conformal risk control selects the most aggressive compression level whose decision-change rate is provably controlled, distil calibrate (distil/calibrate.py) selects the most aggressive working-set size whose task-success loss is non-inferior to full context (same paired McNemar test), over a small calibration run. If no candidate certifies non-inferior, it fails safe to full context — absence of evidence degrades to no compression, never to silent loss. On the E11 data the procedure recovers the manual choice automatically (selects gate@12, rejects gate@6 on DeepSeek-V3). The relevance gate itself is now a shippable library primitive (distil/gate.py), not benchmark-only. Production status: docs/GA_READINESS.md.

distil calibrate \
  --baseline scores/full.json \
  --candidate gate@6=scores/gate6.json:6 \
  --candidate gate@12=scores/gate12.json:12 \
  --margin 0.05
# → ✔ SELECTED 'gate@12' → DISTIL_E7_GATE_RECENT=12  (gate@6 ✘ too aggressive)

E12: the cost frontier under the motto

No cost-domination claim. An uncertified lossy method can always be cheaper because it is allowed to change decisions. These techniques cut cost inside the certified envelope only — they never trade the decision-equivalence guarantee for dollars. “Best in class” holds on the motto’s axis (certified decision-equivalence + task success), not raw cost.

Five techniques are shipped or in-progress; status is reported honestly for each.

# Technique Status Where
1 Cache-monotone gate — deterministic, append-only digests keep the digested prefix byte-stable across turns so prompt-cache/KV reuse captures it; cache read ≈10× cheaper than fresh input; lossless relative to the plain gate Shipped + tested distil/gate.py:monotone_gate; tests/test_cost_frontier.py
2 Graded gate — per-distance compression tiers crush the far periphery harder while keeping near-periphery at plain fidelity; introduces a graded (non-binary) loss Shipped + tested distil/gate.py:graded_gate; distil/conformal.py:tight_risk_bound
3 Tighter conformal (empirical-Bernstein, Maurer–Pontil) — tighter than Hoeffding–Bentkus in the low-variance regime that graded losses live in; certifies more savings at the same confidence; coverage Monte-Carlo–validated Shipped + coverage-tested distil/conformal.py:empirical_bernstein_bound; tests/test_conformal_bounds.py
4 Speculative expansion — pay for full context only when a certified divergence trigger fires; escalates to the cheapest threshold whose certified miss rate ≤ α; fail-safe to full context Framework shipped + tested; end-to-end savings need a live calibration run — not a shipped default yet distil/speculative.py
5 Constrained-bandit operating-point search — online successive-elimination under the non-inferiority constraint, fail-safe; full constrained-RL keep-policy needs training data Shipped + tested; RL keep-policy is research (not shipped) distil/calibrate.py:bandit_select_operating_point

Honest caveat on #1 (cache-monotone gate). On content that is already fully cacheable, caching alone can be cheaper than any compression — compressing rewrites cached bytes as fresh. The cache-monotone gate’s win is over a cache-hostile gate, not over no-compression; the gate’s primary payoff remains accuracy (E8/E11).

Honest caveat on #3 (empirical-Bernstein). For binary decision-change losses, Bentkus is already near-optimal. Empirical-Bernstein applies to the graded losses introduced by the graded gate (#2), which live in the low-variance regime where EB tightens.

Full details and production status: docs/GA_READINESS.md.


E13: continuous assurance under drift

The certificate is valid under exchangeability, so its standing operational risk is silent drift — a new model or workload pushes the true decision-change rate above the budget α the operating point was certified at. Three shipped pieces close it:

First of its kind. To our knowledge this is the first anytime-valid drift monitor for a context-compression decision-equivalence certificate — you can watch the guarantee hold (or break) in production, continuously, with a provably bounded false-alarm rate.

Certified compression frontier

Module: distil/eval.py · Command: distil eval [--corpus --runner --out]

Most compression tools publish a headline savings number. Distil publishes the full curve: a sweep of compression aggressiveness levels where every point is tagged with (token savings, decision-equivalence, certified/not). This locates the cliff past which lossy compression starts dropping agent decisions — and proves that distil sits safely inside the certified region.

The proof artifact. The FrontierReport produced by distil eval is the artifact no competitor publishes: a curve where every point carries a TOST non-inferiority verdict. The certified ceiling is the highest savings level the gate accepts; beyond it, lossy strategies start changing agent decisions and are rejected. Distil operates below the cliff.

How the sweep works

distil/eval.py defines frontier(), which measures two reference operating points (tier-0 lossless and distil (cache-aware)) and then sweeps a range of truncation limits ([4000, 2000, 1200, 700, 450, 300, 220, 160, 120, 90] chars) across the corpus. For each point it measures:

Results are sorted by savings ascending and printed as the frontier table. Run offline with the deterministic runner (structural decision-equivalence). For real task-accuracy on a benchmark (tau-bench, SWE-bench, GSM8K) ingest its traces and run with --runner anthropic.

$ distil eval
certified compression frontier  (runner=deterministic)

level                   savings   equiv  certified  curve
--------------------------------------------------------------------------
distil (cache-aware)       8.4%    100%    ✔ PASS   ██
truncate@1200              7.2%     79%       ✘ —    ██
truncate@700              20.0%     36%       ✘ —    ████
truncate@300              41.3%      0%       ✘ —    █████████
--------------------------------------------------------------------------

distil: 8.4% savings @ 100% decision-equivalence — certified.
certified ceiling: 8.4% savings (beyond this, lossy compression drops decisions and the gate rejects it).

The raw curve can be written to JSONL with --out <dir> for CI integration or archiving.

Offline mode

Deterministic runner

Uses structural decision-equivalence (ground-truth DECISION: markers). Runs fully offline, no API key required. Results are reproducible bit-for-bit across machines.

Live mode

--runner anthropic

Grade the curve with a live model. Use this when evaluating against real benchmarks (tau-bench / SWE-bench / GSM8K) — ingest their traces first with distil ingest.

Flags

FlagDefaultDescription
--corpusbundled corpusCustom corpus dir (e.g. from distil ingest on benchmark traces)
--runnerdeterministicdeterministic (offline) or anthropic (live model, requires API key)
--outoffWrite the raw curve as timestamped JSONL to this directory

Decision-Equivalence Risk Certificate (DERC)

Module: distil/conformal.py · Command: distil conformal [--alpha --delta --method --corpus --runner]

The frontier above tells you where the cliff is. The DERC turns that into an operational guarantee: you pick a risk budget — a maximum tolerable decision-change rate α — and Distil certifies the most aggressive compression level whose risk is provably below it, distribution-free and finite-sample, calibrated on your own traffic. This is conformal risk control, not a heuristic threshold.

The guarantee. For the certified level λ̂, Learn-Then-Test gives P( R(λ̂) ≤ α ) ≥ 1 − δ — with no distributional assumptions and valid at finite n. The loss on each calibration turn is 1 iff the agent's decision flips versus the uncompressed context, graded by the same runner as the gate. R is the decision-change rate.

How it certifies

Distil calibrates a ladder of compression levels (byte-exact → lossless → a truncation sweep), measures the decision-change rate at each, and selects the most aggressive controlled level via one of two procedures:

$ distil conformal --corpus ./mycorpus --alpha 0.05 --delta 0.05
Decision-Equivalence Risk Certificate (DERC)

  method      : LTT  (Learn-Then-Test)
  risk target : α = 0.05  (max allowed decision-change rate)
  confidence  : 95%  (1 − δ)
  calibration : n = 320 turns,  runner = deterministic
----------------------------------------------------------------
  ✔ CERTIFIED  'lossless'  →  57.4% token savings

  the decision-change rate vs. uncompressed context is ≤ 5.0%
  with 95% confidence (Learn-Then-Test, n=320 calibration turns).

Why this is novel

Conformal prediction is established theory, but applying it to context compression with the loss defined as agent decision-equivalence is, to our reading of the literature, open white space. The nearest neighbour (arXiv:2511.17908, ECIR 2026) applies conformal guarantees to RAG retrieval recall — a different task (which documents to fetch), not how far you can crush the context an agent already holds while it keeps acting identically.

The one honest caveat (load-bearing). Conformal guarantees require exchangeability: your calibration traffic must resemble your live traffic. Under distribution shift (new agent, prompt change, workload drift) the bound can silently weaken — recalibrate on a rolling window. The guarantee is marginal over the calibration distribution (an average rate, not a per-prompt promise). And it is honestly conservative: on a small corpus it will refuse to certify a tight α rather than over-claim — more calibration turns certify the same α (double-validated: 320 turns certify lossless at α=2%, 640 turns at α=1%).

Flags

FlagDefaultDescription
--alpha0.05Risk target: max tolerable decision-change rate
--delta0.05LTT failure probability; confidence is 1−δ (ignored by CRC)
--methodlttltt (high-probability bound) or crc (expected-rate bound)
--corpusbundled corpusCalibration corpus (use your own traffic via distil ingest)
--runnerdeterministicdeterministic (offline) or anthropic (live model)

Salience protection — keep the needle, crush the haystack

Module: distil/compress/salience.py · Composes with: the certificate (it shifts the frontier)

The certificate tells you how far you can compress safely. Salience protection makes "far" go further: before a lossy level crushes a block, it guarantees the decision-bearing lines survive — so aggressive compression stops dropping load-bearing identifiers and directives. It is model-free (a few hundred microseconds, no transformer in the path), and unlike syntactic entity protectors it blends three signals and works at line granularity so the decision unit (verb + target) stays intact.

Signal 1 — pattern

Identifier shapes

UUIDs, git SHAs, PREFIX-NNN IDs, emails, IPs, semver — the obvious load-bearing tokens.

Signal 2 — entropy

Novel IDs no regex anticipates

High-information mixed-alnum tokens caught by Shannon entropy + character diversity, so an unfamiliar key format is still protected.

Signal 3 — reference

Cross-block anchors

A token that recurs across blocks (a tool name in the schema and in an output) is something the agent navigates by — load-bearing, not noise.

Composition

A frontier shifter, not a heuristic

Protection lowers the decision-change rate, so the conformal certificate can certify a more aggressive level. The guarantee still comes from the gate; this just moves where the gate says “safe.”

Measured. On the realistic corpus, wrapping blind truncate@200 with protect(…) took its load-bearing-target survival from 0/120 → 120/120, at a cost of only 2.4 points of savings (73.9% → 71.5%) — and ~0.4 ms per turn, no model. The needle survives; the haystack still compresses. Distil's distil conformal ladder includes protect+truncate levels, so the certificate can pick a protected-aggressive operating point automatically.

Shadow-mode — live decision-equivalence on real traffic

Module: distil/shadow.py · Command: distil proxy --shadow RATE · distil shadow-stats

The certificate proves decision-equivalence offline, on a calibration corpus. Shadow mode closes the loop online. Cost is free to measure live (token deltas); equivalence is not — it needs the counterfactual, the decision the agent would have made on the uncompressed context. So shadow mode samples a fraction of live requests and runs each one both ways, comparing the agent's chosen next action.

How it stays production-safe. The second (uncompressed) call runs in a background thread — the client gets the compressed response immediately, never blocked. Only RATE of requests are sampled, so the overhead is RATE (e.g. 5%), not 2×. And it is content-free: the ledger stores a decision signature and an equivalent bool — never prompt or response text.

The "decision" is the agent's next action — the first tool_use (Anthropic), tool_call (OpenAI), or functionCall (Gemini). Two responses are equivalent iff that action matches, exactly the {action, target} fingerprint the certificate uses. It is streaming-aware: the decision is reconstructed from SSE, so shadow-mode works on real agent sessions (Claude Code, Codex, Gemini CLI) that stream — not just non-streaming SDK calls. The result is a rolling, live decision-change rate on your traffic:

$ distil proxy --shadow 0.05 --upstream https://api.anthropic.com
  → shadow-mode live decision-equivalence: sampling 5%

$ distil shadow-stats
  shadowed requests : 412
  decision changes  : 2
  decision-change rate (rolling): 0.49%
  decision-equivalence          : 99.51%

This complements periodic re-certification (distil ingestdistil conformal) under the exchangeability caveat: shadow mode is the continuous monitor, the certificate is the guarantee. Together they make decision-equivalence observable in production, not just in eval.


Cache-delta context coding — cross-version delta, decision-equivalent

Module: distil/cachedelta.py · Command: distil proxy --session-delta · For: coding agents (Claude Code / Codex / Gemini CLI)

The coding-agent hot path is read → edit → re-read. The re-read file is not byte-identical to the first read — one hunk changed — so exact-duplicate dedup (the state of the art elsewhere, e.g. Headroom's dedup_identical_items) misses it and re-sends the whole file as fresh tokens. Cache-delta coding instead sends only the diff against the previously-delivered version, referencing the rest.

Why it is decision-equivalent (the motto). The prior version is still present earlier in the (cached) conversation, so prior-version + diff carries exactly the information the agent needs for its next action — the decision is unchanged. It is reversible (the full current version is kept locally; distil_expand recovers it byte-exact) and measurable (shadow mode records the live decision-change rate), so the equivalence is proven, not asserted.
Win 1 — exact re-send

Back-reference

Content delivered earlier this session is replaced by a compact handle reference. Table stakes — competitors do this too.

Win 2 — near-duplicate

Cross-version delta

A re-read-after-edit is replaced by a reference plus a unified diff. The leap exact-only dedup can't make — and it's the most common coding pattern.

Cache-monotonic

Never bust the prefix

Only the volatile suffix is touched; the stable, already-cached prefix is left byte-identical, so prompt-cache hits survive. Optimising the real bill (cached·0.1 + writes·1.25 + new·1.0), not raw tokens.

Measured (honest)

The digest is the lever; cache-delta is the verbatim lever

On the 256-turn coding benchmark, the Tier-1 digest already wins (~91% cache-aware, reversible), so cache-delta adds little on top of it. Its real niche is verbatim/interactive mode (digest disallowed): there it turns a 0% floor into 43.8% cache-aware savings, reversible. See the coding-agent benchmark.

AST-structural delta (distil/astdelta.py, stdlib ast, model-free) is the deepest layer: for Python it diffs files by parsed structure, fingerprinting each top-level definition with ast.dump — invariant to whitespace, comments, and import order. A reformat-only re-read is recognised as no definition changed and referenced; only definitions whose AST actually changed are sent in full. Textual diff explodes on reformatting; the structural delta isolates exactly what changed. Non-Python or mid-edit (unparseable) source falls back to the textual delta — it never fails a request, it just does less.


Self-distilling keep-model

Module: distil/online.py · Command: distil online [--corpus --promote-to]

Most learned compressors train a keep-model on a generic judge applied to synthetic data. Distil trains on causal labels — certified-safe drops discovered by the ablation engine running on your own real traffic. The label source is the moat: a model that learns what actually changed a decision, not what a judge guessed.

The never-regressing loop

The loop has four steps, each grounded in the source:

  1. Collect causal labels (collect_causal_labels()) — run counterfactual ablation (discover()) on every trajectory. Blocks that never changed a decision are PRUNABLE (label=0). Blocks that changed at least one decision are KEPT (label=1). Only VOLATILE blocks are scanned; the stable cacheable prefix is out of scope. Conflict resolution: keep wins (label=1 is never overridden to 0).
  2. Retrain (retrain()) — featurize the labeled lines (9 features, same as the built-in logistic model) and train logistic regression with full-batch gradient descent, L2 regularization, and a deterministic SHA-256 train/test split. No random seed dependency.
  3. Certify promotion (certify_promotion()) — wrap the new weights as a compression strategy, run the TOST non-inferiority gate on every single corpus trajectory. A single regression anywhere blocks the promotion.
  4. Persist iff certified (online_round()) — write the new weights to --promote-to only if step 3 passed. A cycle that would degrade quality is silently discarded.
Never-regressing by construction. Because step 3 requires non-inferior TOST on every trajectory before weights are touched, the loop can only improve the keep-model. A candidate that regresses on any trajectory is discarded without modifying production weights.

Illustrative output — your numbers depend on your corpus

Example from one distil online round on a bundled corpus; the flywheel is real and gated, but exact figures vary by traffic.

286
Causal labels collected
0.873
Accuracy (held-out)
0.932
F1 (held-out)
PASS
Certified (gate)
$ distil online --corpus ./mycorpus --promote-to ./weights/keep_model.json
self-distilling round — keep-model learns from causal labels, gated by non-inferiority

  n_labels: 286
  accuracy: 0.873
  f1: 0.932
  certified: True
  promoted: True

If the gate fails (a regression anywhere in the corpus), promotion is blocked and the output will show certified: False and promoted: False with a message that the candidate failed the non-inferiority gate.

Flags

FlagDefaultDescription
--corpusbundled corpusCorpus directory of traffic to learn from. Use distil ingest to convert real logs first.
--promote-tooff (dry run)If certified, persist the new weights as a LogisticKeepModel-compatible JSON file at this path.

Verifiable federated telemetry

Module: distil/telemetry.py · Command: distil federated-leaderboard --dir <dir> [--keys <keys.json> --html <out.html>]

Each opt-in instance contributes a signed, content-free savings aggregate with its certification verdict attached. The leaderboard aggregates only verified submissions — every number on the board is tamper-evident. No prompt text, no response content, no tool outputs ever leave the machine: only (instance_id, tokens_saved, dollars_saved, runs, certified, timestamp).

How signing works

Signing uses HMAC-SHA256 (symmetric: both sides share a per-instance key). The canonical form of the aggregate is json.dumps(fields, sort_keys=True, separators=(',', ':')) — deterministic across Python versions and dict orderings. Verification uses hmac.compare_digest for constant-time comparison.

ed25519 is the documented upgrade. The module docstring in distil/telemetry.py documents the natural upgrade: if you want a leaderboard anyone can verify without sharing keys, swap HMAC-SHA256 for ed25519. The instance keeps the signing key, publishes the verify key, and the aggregator uses the public key only. The swap is a drop-in change at the sign/verify boundary — nothing else in the module changes.

Leaderboard rules

$ distil federated-leaderboard \
    --dir ./submissions \
    --keys ./instance-keys.json \
    --html ./leaderboard.html
verifiable savings — 3 verified instance(s), 0 rejected

  totals (certified only): {'tokens_saved': 142816, 'dollars_saved': 0.071408, 'runs': 47, 'instances': 3}

The --html flag writes a self-contained dark HTML page (the same style as the gateway dashboard) showing per-instance verified savings. The page is served inline — no CDN, no external assets.

Content-free

Zero prompt leakage

The SavingsAggregate dataclass contains only numeric fields. No text from your prompts, tool results, or model responses is ever included in a submission.

Tamper-evident

Savings you can verify

Every number on the leaderboard was produced by a verified submission. Tampered or unsigned entries are counted in rejected and excluded from totals.

Flags

FlagDefaultDescription
--dirrequiredDirectory containing submissions.jsonl (one signed aggregate per line)
--keysoffPath to a JSON file mapping instance_id → HMAC key. Submissions with no matching key are rejected.
--htmloffWrite a self-contained leaderboard HTML page to this path