# Methodology This page is the canonical reference for what CompactBench measures and how. It describes scorer **3.0.0** (benchmark v2). Scores from earlier scorers are not comparable. ## The loop A case is a long conversation split into **cycles**. Cycle 0 is the opening conversation; every later cycle is only what happened *after* the previous compaction. 1. **Cycle 0.** The method receives the whole opening conversation and returns an artifact. 2. **Cycle n.** The method receives its previous artifact plus the turns since then — never the earlier turns. This is how compaction works in a real agent, and it is what makes drift measurable: whatever the method dropped is gone for good. 3. After every compaction, a **reader** model answers that cycle's probes using only the rendered artifact. The reader — model and reasoning effort — is fixed per run (and per season for ranked runs), so the method is what varies. Turn `tags` are generation metadata (some mark the turn that carries the answer). They are stripped before the method sees anything. ## What a case contains Cases are generated deterministically from a **family**, a **seed** and a **difficulty**. Each family is a kind of compaction failure: | Family | What breaks compactors | |---|---| | `buried_constraint` | Rules stated once, often indirectly or inside pasted notes and tool output, among look-alike rules for other projects, hypotheticals and rejected proposals. Later cycles add, lift and change rules. | | `decision_override` | Decisions changed, reverted (A → B → A) and given scoped exceptions; rejected proposals; who made the latest call. | | `entity_confusion` | Look-alike people (same first name, near-identical surnames), ownership handed back and forth between them, roles and outside companies. | | `reference_resolution` | Choices made by pointing ("the second quote", "the cheaper of the two EU-hosted options"), then changed by pointing again — which only resolves if the shortlist survived. | | `numeric_precision` | Exact figures — contract values, dates, versions, identifiers — first as estimates, then finalized and corrected, next to near-identical figures for sibling projects. | | `conditional_scope` | Rules that cover only some components or only until a date; the scope widens, narrows and ends across cycles, next to look-alike policies on sibling projects. | | `task_continuity` | A ticket board whose statuses, owners and blockers keep moving, with work that is "basically done" but only in review. | | `provenance_authority` | Team decisions contradicted by fetched documents and instructions aimed at the assistant — some later confirmed by the team, most not. | Ranked Elite and the public `practice` suite use **mixed sessions**: every family in one conversation, sharing the same people, components and token budget. A mixed case carries several times the state of a single-family case, so an artifact has to record state tersely to keep it all, and has to keep kinds of state apart (the same person decides things, owns components and holds tickets). Each probe is tagged with its family, so scores still break down per family. The `drills` suite keeps one family per case. Scores vary far more from case to case than from question to question, so ranked runs use many cases with a fixed, family-balanced subset of each case's probes: 48 mixed cases of 20 probes each (the same probes at every compaction, so drift is still measured on the same questions). At the same reader cost, that is far more stable than a few cases with every probe: one method scored on fresh samples moves by about 1.5–2 points (one standard deviation), which the reported 95% intervals cover. Conversations are padded with on-topic filler — source files, test runs, logs, API responses, git history, metrics — about the same project and people, so a method can't separate signal from noise by topic. Filler never states a rule, a decision or an ownership, so every probe stays answerable from the full conversation. Every update says what it changes in plain terms (a ticket "moves to In review", a policy "has ended"), so an answer never hinges on interpretation. Each case is set in a **world**: a vocabulary of people, projects, components, rules, decisions, facts and filler, plus the wording of every sentence the families write. The public suites use one public world. The ranked Elite suite uses private worlds with the same families, the same difficulty and the same structure, so the public Practice suite is a faithful rehearsal but can't be memorized into a ranked score. | Difficulty | Opening | Each later cycle | Drift cycles | Answer options | |---|---|---|---|---| | easy | ~1.5k tokens | ~0.6k | 2 | 4 | | medium | ~6k | ~2k | 3 | 5 | | hard | ~16k | ~5k | 4 | 6 | | elite | ~32k | ~8k | 4 | 7 | ## Probes Every probe has a mechanically checkable answer: | Format | The reader gives | Scored | |---|---|---| | single | one option letter | 1 if correct; picking several scores 0 | | multi | every letter that applies | `max(0, (right − wrong) / right answers)` | | value | one exact value | normalized by kind (money, date, number, version, identifier, text), then compared exactly | | list | every value in a set | same formula as multi | Wrong options are built from the case itself — superseded decisions, rules for other projects, look-alike people, the runner-up vendor — so a lossy summary picks them. Some wrong options are **traps**: answers that only a decoy supports, such as another project's rule, a rejected proposal, or a value injected by a fetched document. Single-choice probes always offer *"Not stated in the conversation"*, and some probes have it as the right answer: the conversation raised the question but never settled it. Select-all probes always have at least as many wrong options as right ones, so selecting everything can't pay, and always have at least one right answer. Each probe has a category (constraint recall, constraint application, decision state, entity attribution, reference resolution, fact recall, abstention) for the breakdowns. ## Metrics | Metric | Definition | |---|---| | **score** | Mean probe score per family, then the mean across families — every family counts equally. Reported with a 95% bootstrap interval that resamples whole cases (a mixed case brings all its families along). Abstention probes count only when missed: answering "not stated" correctly earns nothing, since an empty artifact would too, while inventing an answer counts as a wrong one. | | **normalized score** | With `--controls`: per family `(score − null) / (oracle − null)`, the share of the achievable range the method kept. | | **drift resistance** | Per case, the score at the last cycle over the score at the first, on the probes asked at both (excluding "never settled" probes); averaged over cases. 0 when unmeasurable. | | **decay** | The same probes' first-cycle score minus their last-cycle score. | | **stale-answer rate** | Of probes that offered a superseded answer, the share where the reader picked it. | | **trap rate** | Of probes that offered a trap, the share where the reader picked it. | | **hallucination rate** | Of "never settled" probes, the share where the reader gave a concrete answer. | | **artifact tokens / compression** | Rendered artifact size, and conversation-so-far tokens divided by it. | All token counts use `cl100k_base` on the rendered artifact — exactly what the reader sees. ## Controls `--controls` answers every probe twice more, on the same cases: from the **full conversation so far** (oracle — what losing nothing scores) and from **nothing** (null — what guessing scores). A method's score only means something between those two. Suites are calibrated so the oracle scores at least 0.90 and the null at most 0.10 in every family; a family that misses either bound is fixed before it ships. The same references exist as built-in methods (`oracle`, `null`, `truncate-last-n`) for standalone runs; they are published as reference rows and never ranked. Ranked seasons measure the controls once, on a calibration sample, and publish the ceiling and floor per family on the Seasons page, rather than on every run: the full conversation is long, so the controls are most of a run's reader cost. Locally, add `--controls` to any run to get them on your own cases. ## Token budget Every run has a token budget for the rendered artifact (default 2048; tiers are Tight 1024, Standard 2048, Roomy 4096). The method is told the budget. Anything beyond it is cut off before the reader sees it, and ranked runs reject any cycle over budget. Compression is therefore a constraint, not a bonus: methods compete on what they keep within the same budget. Ranked Season 1 uses the Tight tier. Compacting a ~32k-token session into 1,024 tokens is about 32x — roughly what production auto-compaction does — and a terse notes artifact holding everything the probes ask about still fits, so a near-perfect score stays reachable. The budget is a season setting: the leaderboard never compares rows across budgets. ## Ranking Within one suite, scorer, reader and budget, rows are ordered by **score**; ties break on drift resistance, then lower stale-answer rate, then earlier publication. A row's rank is one plus the number of rows whose whole 95% interval lies above its own, so methods whose intervals overlap share a rank. A run must: - complete every case and cycle (a results file without its final event is never ranked); - have at least one drift cycle and a token budget, with no cycle over budget; - have usable reader answers for at least 95% of probes; - use the reader on its provider's own endpoint; - match its season's pinned settings (suite, difficulty, cycles, cases, budget, reader and reader effort). Controls and maintainer baselines are shown as reference rows and never ranked. ## Reproducibility - Case generation is a pure function of family, seed, difficulty and drift cycles. - Model output is not deterministic — current models don't take sampling parameters — so results report confidence intervals, and `--traces` keeps every raw reader reply so any score can be re-checked exactly. - Results files record the suite and scorer versions, method and version, both models, where each model's calls went (`endpoint_kind`), the budget and the seed group. They hold scores only — no conversation text or questions — so they are safe to share. Published results from the hidden set are also redacted: each question's key (which names the private world's people and rules) becomes a salted hash, and the method's own warning text is dropped; scores are unchanged. --- # Submitting to the leaderboard Ranked scores come from a **hidden Elite set** that is generated fresh for every ranked run, at the same difficulty as the public `practice` suite: mixed sessions in private worlds. There is nothing fixed to memorize, and what you see in your own provider logs can't be reused on the next run. ## 1. Build and test locally A method is a Python class that subclasses `compactbench.compactors.Compactor` — see [Writing a compactor](/docs/writing-a-compactor). Develop against the public `practice` suite with any model you like: a hosted one, a local one through Ollama, or your own OpenAI-compatible server. ```bash compactbench run --method method.py:MyCompactor --suite practice --cases 4 \ --provider openrouter --model qwen/qwen3-235b \ --reader-provider anthropic --reader-model claude-haiku-5-5 \ --reader-effort high --controls --output results.jsonl compactbench qualify --results results.jsonl ``` `qualify` applies the same floors the leaderboard does and lists every reason a run would be rejected. ## 2. Submit on the website Go to [compactbench.com/submit](https://compactbench.com/submit), sign in with GitHub, and fill in: - **Your method:** `method.py`, the class name, a name and version, and any extra dependencies, pinned (`name==version`). - **The model it calls:** any of Anthropic, OpenAI, OpenRouter (hundreds of models), Google Gemini, Groq, DeepSeek, Mistral, Together, Fireworks or xAI — or **your own OpenAI-compatible endpoint**, with an optional display name for your model. Hosted models are shown by their model id; a custom endpoint's display name is shown with a "custom endpoint" label and your handle. - **Your API keys:** a key for that provider, and an Anthropic key that pays for grading (about $0.50 a run). If your method runs on Anthropic, one key covers both. Everything else — suite, difficulty, compactions, cases, token budget, and the reader model and its effort — is pinned by the season. **No method of your own? Benchmark a model.** Choose *A reference method on my model* instead of uploading code, pick one of the published built-ins (`sectioned-summary`, `hierarchical-summary`, `naive-summary` or `structured-state`), and give the model and keys as above. The built-in runs unchanged with its default settings, so rows differ only in the model; they appear on the leaderboard's **By model** board, ranked against other models on the same method, and are published under `submissions//----/`. This is how a lab or a provider can put a number for its model on the board, paid for by its own keys. **About your keys.** Create dedicated keys with spend limits, and revoke them after your run. A key is sent once over HTTPS and sealed immediately to the season's public key; only the evaluation's model proxy (for your method's key) and grader (for the reader key) can open it. Your method never sees a key. ## 3. Watch it run You get a status link. A run takes about an hour: 1. **Build.** Your method and its dependencies are built into a container image. Installing dependencies happens at build time, with network access but without any secret. 2. **Run.** The container runs under gVisor with **no network except a model proxy**, a read-only filesystem, no privileges and resource limits. It receives one compaction request at a time — the new turns and its own previous artifact, nothing else. The hidden generator, the questions, the reader and the other cases stay outside it. 3. **Proxy.** The proxy is the only thing holding your key. It forwards your method's calls only to your provider (or the one endpoint you declared), only for the model you named, without streaming, and stops at a token cap. Requests that would have the provider reach the internet for your method — server-side tools like web search or fetch, MCP servers, images or documents given by URL — are refused; client-side tools (function calling) are fine. It logs call metadata only, never request or response bodies. 4. **Publish.** When the run qualifies, it goes straight onto the leaderboard: your method's source, its public settings and its scores are published under `submissions///`. Full traces — including the hidden cases — are sealed to the maintainers' key and kept private; the public row carries a SHA-256 commitment to them, so any score can be audited later. ## Limits To keep runs fair and the queue moving: one run in progress per account, at most five ranked runs per account per week, and a daily cap across everyone. Ranked runs need a GitHub account at least 14 days old. A run that never starts doesn't count, and a run that stops reporting for 8 hours is closed so you can submit again. Resubmitting a method replaces its leaderboard row. ## Rules - Don't submit a method that has seen hidden content, or that was tuned on hidden results. - A method must not try to reach anything other than its model through the proxy, or to detect or fingerprint ranked cases. Attempts are grounds for removal. - Your method's source is published with its results — that is the audit trail. - See the [submission terms](/submission-terms) for what you agree to by submitting. --- # Failure families Each family generates one kind of compaction failure. Practice and ranked cases are mixed sessions: every family in one conversation, under one token budget. ## Buried constraints (`buried_constraint`) Rules stated once and buried among look-alike rules for other projects, hypotheticals and rejected proposals; later cycles add, lift and change rules. ## Decision overrides (`decision_override`) Decisions changed, reverted and given scoped exceptions across cycles, with rejected proposals and look-alike deciders. ## Entity confusion (`entity_confusion`) Look-alike people, ownership handed back and forth between them across cycles, and roles and companies that must stay with the right person. ## Reference resolution (`reference_resolution`) Choices made and changed by reference — ordinals, superlatives, who recommended it — that only resolve if the shortlist survives compaction. ## Numeric precision (`numeric_precision`) Exact amounts, limits, dates, versions and identifiers — estimated then finalized, corrected across cycles, and shadowed by look-alike values for sibling projects. ## Conditional scope (`conditional_scope`) Rules that cover only some components or only until a date, whose scope widens, narrows and ends across cycles, next to look-alike policies for sibling projects. ## Task continuity (`task_continuity`) A ticket board whose statuses, owners and blockers change across cycles, with work that is claimed done but is only in review. ## Provenance and authority (`provenance_authority`) Decisions contradicted or 'updated' by fetched documents, emails and instructions aimed at the assistant — some confirmed by the team, others not. ## Suites - `starter`: Short cases (~1.5k tokens) for smoke-testing a method end to end. - `practice`: Public twin of the ranked Elite set: mixed sessions with every family in one conversation, at Elite difficulty, in the public world (~32k-token openings, 4 drift cycles, 48 cases of 20 probes; use --cases for a quicker look). - `drills`: One family per case at Elite difficulty, for working on one failure mode at a time. - `elite` (hidden): the ranked set — mixed sessions in private worlds, sampled fresh per run. --- # Leaderboard — season s1 Suite elite 2.0.1, budget 1024 tokens, 5 compactions, reader claude-haiku-5-5 (effort high). Score = % of questions answered correctly from the method's artifact, family-balanced, with 95% interval. | Rank | Method | Kind | Model | Score | 95% CI | Drift | |---|---|---|---|---|---|---| | 1 | starter-template 0.1.0 | submission | claude-haiku-5-5 | 62.4 | 60.0–64.6 | 50 | | — | sectioned-summary 1.0.0 | baseline | claude-haiku-5-5 | 51.9 | 49.7–54.0 | 54 | | — | hierarchical-summary 2.0.0 | baseline | claude-haiku-5-5 | 50.2 | 47.1–53.4 | 91 | | — | naive-summary 2.0.0 | baseline | claude-haiku-5-5 | 45.1 | 42.4–47.9 | 38 | | — | structured-state 2.0.0 | baseline | claude-haiku-5-5 | 40.0 | 37.4–42.4 | 63 | | — | anthropic-compaction 1.0.0 | baseline | claude-haiku-5-5 | 28.7 | 24.7–32.7 | 26 | | — | hybrid-ledger 2.0.0 | baseline | claude-haiku-5-5 | 27.6 | 25.5–29.7 | 57 | | — | extractive 1.0.0 | baseline | claude-haiku-5-5 | 9.7 | 8.7–10.8 | 55 | | — | truncate-last-n 2.0.0 | control | claude-haiku-5-5 | 0.8 | 0.6–1.1 | 12 | ## By model The same published methods run unchanged on different models; rank is among models on that method. | Method | Rank | Model | Submitted by | Score | 95% CI | |---|---|---|---|---|---| | hierarchical-summary | 1 | claude-haiku-5-5 | compactbench | 50.2 | 47.1–53.4 | | naive-summary | 1 | claude-haiku-5-5 | compactbench | 45.1 | 42.4–47.9 | | sectioned-summary | 1 | claude-haiku-5-5 | compactbench | 51.9 | 49.7–54.0 | | structured-state | 1 | claude-haiku-5-5 | compactbench | 40.0 | 37.4–42.4 | --- # Datasheet A datasheet for CompactBench, following the questions in *Datasheets for Datasets* (Gebru et al.). It covers the generated conversations, the probes, and the results the leaderboard publishes. ## Motivation **Why was it created?** To measure how much state AI agents keep when their context is compacted — not once, but repeatedly, as in a long-running session — under a fixed token budget, with answers checked mechanically rather than by another model. **Who maintains it?** The CompactBench maintainers, in the open at [github.com/compactbench/compactbench](https://github.com/compactbench/compactbench). ## Composition **What does an instance look like?** A *case* is a generated working conversation (an opening of about 32k tokens, then about 8k new tokens before each later compaction) split into cycles, plus structured *probes* asked after each compaction. Probes are single-choice, select-all, exact-value or list questions with mechanically checkable answers, superseded ("stale") answers and decoy-only ("trap") answers marked. **What do conversations contain?** People, projects, components, rules, decisions, ownership, exact figures, ticket boards, scoped policies, shortlists chosen by reference, and fetched documents that try to change decisions — interleaved with on-topic filler: source files, logs, test runs, API responses, tickets, chat. Ranked and practice cases are *mixed sessions* with every family in one conversation. **Is any of it real?** No. Every name, company, project, figure and message is procedurally generated from vocabulary lists and sentence templates. Product and vendor names (databases, clouds, tools) appear as plausible options, not as claims about those products. No personal data is used. **How many instances?** The generator is unbounded: any seed gives a case. The public suites are fixed by seed (`starter`, `practice`, `drills`); the ranked Elite set is sampled fresh for every ranked run from a private generator. **Is anything held back?** The ranked generator's worlds — vocabulary, sentence wording and filler — are private, so ranked cases can't be memorized. The scenario families, scoring and public worlds are open source, and the public `practice` suite is built the same way at the same difficulty. **Are there known errors or noise?** Every family is calibrated before a season opens: a fixed reader answering from the full conversation must score at least 0.90 in every family, and answering from nothing at most 0.10. Items that fail are fixed in the generator, not patched by hand. Scores vary from case to case, so results carry 95% intervals and overlapping intervals share a rank. ## Collection and generation **How is the data produced?** By deterministic Python generators (`compactbench.scenarios`): a seed picks a world, a project and a cast, each family places its facts and later changes among filler, and probes are derived from the generator's own record of the truth. The same seed always gives the same case on every platform. **Who is involved?** No human annotators or crowdworkers. The answer key comes from the generator; a fixed reader model only answers questions during evaluation. ## Uses **Intended uses.** Comparing context-compaction methods (summarizers, structured state, memory systems, provider-native compaction) on how much state they keep across repeated compaction; diagnosing which kinds of state a method loses; regression-testing an agent's compaction. **Uses to avoid.** Treating a score as a general measure of model intelligence or of summarization quality outside agentic, state-heavy sessions. Training on the public suites and then reporting public-suite scores as if they were ranked results. **Known limitations.** Practice predicts Elite closely for model-based methods: Season 1's prompted baselines scored within 4 points of their Elite score on Practice (−3.7, +1.0 and −1.5 points). Methods that match surface wording rather than meaning can differ more, because Elite is written in private wording: a rule-based extractive baseline scored 6.5 points lower on Practice than on Elite. One method's score varies by about 1.6 points (standard deviation) between fresh Elite samples, which is why every row carries a 95% interval and rows whose intervals overlap share a rank. Grading uses one Claude reader; re-grading a Practice subsample (24 artifacts, about 480 questions) with a reader from another model family (gpt-oss-20b) ranked the baselines identically (Kendall's τ = 1.0) and scored 94% of questions the same, with no sign that the Claude reader favours Claude-written summaries. ## Distribution **How is it distributed?** As an Apache-2.0 Python package (`pip install compactbench`) that generates the public suites locally, plus the public leaderboard data (`/api/leaderboard.json`, `/llms.txt`, a remote MCP server). Results files hold scores and settings only, never conversation text; published hidden-set results also have their question keys hashed, so they reveal nothing of the private worlds. ## Maintenance **How is it updated?** In seasons. A season pins the suite and its version, difficulty, compactions, cases, token budget and reader, and its rows never change after it closes. Changes that could move scores ship as a new suite version and, for the ranked set, a new season. See [governance](/docs/elite-versions) and the changelog. **How do I report a problem?** Open an issue on GitHub. Questions about an item that looks wrong are especially welcome: every probe is supposed to be answerable from the full conversation. --- # Privacy > **Draft.** This policy covers the CompactBench repository, the leaderboard site and ranked evaluation. ## The site - The leaderboard is a static site. It has no accounts, no sign-in for visitors, and no advertising or tracking cookies. - Submitting a method needs GitHub sign-in. We read only your public profile (handle and id), keep it in a short-lived signed cookie, and never store your GitHub token. We keep your handle with your submission, for attribution and rate limits. - Our hosting provider keeps standard request logs (IP address, user agent, time, page) for security and abuse prevention. We use them only in aggregate. - The contact form sends your message, and your email address if you give one, by email to the maintainer. The site doesn't keep a copy. To stop one sender flooding the inbox it keeps a keyed hash of your IP address and the time for 24 hours, then deletes it. - Donations go through Ko-fi, on Ko-fi's own website. We never see your payment details. - For a daily summary, the site counts a few events in total (sign-ins, new runs, contact messages, MCP sessions and tool calls) per day, and reads aggregate traffic figures (visitors, page views, countries) from our hosting provider. No visitor, IP address or account is recorded for these counts. ## Running CompactBench yourself - The package makes no network calls of its own. Your runs talk only to the model providers you configure, using your keys. Nothing is sent to us. - Results files hold scores and settings, not conversation text. Traces hold everything and stay wherever you write them. ## Ranked submissions - What a submission publishes, and what is kept privately, is described in the [submission terms](/submission-terms). - Your API keys are sealed on arrival and opened only inside the evaluation; the plain keys are never stored. - Private traces are encrypted to the maintainers' key before they leave the evaluation run, and are kept for auditing and benchmark research. ## Contact To ask what we hold about you or to have it removed, use the [contact form](https://compactbench.com/contact), or send the maintainers a private report through [GitHub's private reporting form](https://github.com/compactbench/compactbench/security/advisories/new). --- # Submission terms > **Draft.** These terms take effect when ranked evaluation reopens. Until then they describe how the pipeline will treat submissions. By submitting a method on compactbench.com you agree to the following. ## Your code - When your run qualifies, your method's source, its pinned requirements and its public settings are published in the CompactBench repository under its license (Apache 2.0). - Submissions are evaluated automatically. The maintainers may remove any submission, or bar an account, for abuse or for breaking these terms. ## Your API key - You supply your own API keys: one for the model your method calls, and an Anthropic key for grading (one key can do both if your method uses Anthropic). They are sealed as soon as they arrive and opened only inside the evaluation, for the duration of your run. - You are responsible for your keys' spend limits and for revoking them after the run. The proxy stops at a token cap, but your providers bill you for the calls made with them. ## Evaluation outputs - Your run's scores and metadata (method name and version, model, provider, settings, per-family scores, timings and token counts) are published on the leaderboard and in the CompactBench repository. - Full traces — the hidden cases, your method's artifacts at every cycle, and the reader's answers — are kept privately by the maintainers. You grant the maintainers a perpetual license to keep and use these outputs to operate, audit and improve the benchmark, and to publish aggregate or anonymized statistics derived from them. - The hidden cases are not shared with you. Your own provider may log what your method sent it; that is between you and your provider. ## Fair play - Don't try to recover, fingerprint or store hidden cases, reach anything other than your model through the proxy, or tune on hidden results. - Submissions found doing so are removed, and the submitter may be barred. ## Withdrawal - You can ask for your row to be removed from the leaderboard at any time. Published pull request history and previously released aggregate statistics are not retracted. Questions: open an issue, or for anything private use [GitHub's private reporting form](https://github.com/compactbench/compactbench/security/advisories/new). --- # Getting started > **Zero-install Colab notebook.** Want to try CompactBench in your browser without any setup? Open [`notebooks/try_compactbench.ipynb`](https://colab.research.google.com/github/compactbench/compactbench/blob/main/notebooks/try_compactbench.ipynb) in Colab — it installs the package, runs the built-in methods and controls on Groq's free tier, and ends with writing your own compactor. ## Install ```bash pip install 'compactbench[providers]' ``` Or with [uv](https://github.com/astral-sh/uv): `uv pip install 'compactbench[providers]'`. The `providers` extra installs every provider SDK; without it only the offline `mock` provider works. ```bash compactbench --version compactbench suites list compactbench families list ``` ## Two models: the method's and the reader's A run involves two models, which can be the same: - **the method's model** (`--provider` / `--model`) — what your compactor calls, if it calls anything; - **the reader** (`--reader-provider` / `--reader-model`, defaulting to the method's) — the model that answers the questions from the compacted artifact. Hold the reader fixed when comparing methods. Ranked seasons pin it. ## Configure a provider | Provider | `--provider` key | Env var | |---|---|---| | Anthropic | `anthropic` | `COMPACTBENCH_ANTHROPIC_API_KEY` | | OpenAI | `openai` | `COMPACTBENCH_OPENAI_API_KEY` | | OpenAI-compatible (vLLM, llama.cpp, LM Studio, OpenRouter, …) | `openai` | `COMPACTBENCH_OPENAI_BASE_URL` (+ key if the server checks one) | | Groq | `groq` | `COMPACTBENCH_GROQ_API_KEY` | | Google AI Studio | `google-ai-studio` | `COMPACTBENCH_GOOGLE_AI_STUDIO_API_KEY` | | Ollama (local) | `ollama` | `COMPACTBENCH_OLLAMA_BASE_URL` (default `http://localhost:11434`) | | Mock (tests) | `mock` | none — canned responses, scores are meaningless | Put keys in a `.env` file at the project root (only `COMPACTBENCH_*` names are read) or export them. A real environment variable wins over `.env`. > **Custom endpoints are recorded.** Runs against a custom base URL are recorded as `endpoint_kind: "custom"` (the URL itself is never stored). Leaderboards segment on it, so a self-hosted model is never ranked against the hosted model whose name it was run under. ## Run your first benchmark ```bash compactbench run --method built-in:hybrid-ledger --suite starter \ --provider anthropic --model claude-haiku-5-5 --controls ``` Locally with Ollama: ```bash compactbench run --method built-in:hybrid-ledger --suite starter \ --provider ollama --model qwen2.5:7b-instruct --controls ``` Results go to `results.jsonl` (change with `--output`). Useful options: | Option | What it does | |---|---| | `--suite starter\|practice` | `starter` is a quick smoke test; `practice` matches the ranked Elite difficulty | | `--cases N` | cases per family (default: the suite's) | | `--drift-cycles N`, `--difficulty easy\|medium\|hard\|elite` | override the suite's profile | | `--budget N` | token budget for each artifact (default 2048; `0` disables) | | `--controls` | also score from the full conversation (ceiling) and from nothing (floor) | | `--traces FILE` | keep every artifact, question and raw reader reply | | `--estimate` | print projected calls, tokens and cost; makes no API calls | | `--resume` | skip cases already in `--output` | Always run `--estimate` before a large run. ## Read a case ```bash compactbench generate --family entity_confusion --seed 42 --difficulty easy --text ``` The same family, seed and difficulty always produce the same case, so this is the way to debug a method against one specific failure. ## Read the scores ```bash compactbench score --results results.jsonl ``` Shows the family-balanced score with its 95% interval, the score at every cycle, drift resistance, stale-answer and hallucination rates, and breakdowns by family and by probe category. With `--controls`, each family also shows its oracle and null scores and the normalized score between them. ```bash compactbench qualify --results results.jsonl ``` Runs the leaderboard's qualification floors locally and lists every reason a run would be rejected. ## Next steps - [Write your own compactor](/docs/writing-a-compactor) - [Methodology](/methodology) - [Submitting](/submitting) --- # Writing a compactor A compactor is one class with one async method. It receives a `CompactionRequest` and returns a `CompactionArtifact`. ```python from typing import ClassVar from compactbench.compactors import Compactor from compactbench.contracts import CompactionArtifact, CompactionRequest from compactbench.providers import CompletionRequest from compactbench.rendering import render_request class MyCompactor(Compactor): name: ClassVar[str] = "my-method" version: ClassVar[str] = "0.1.0" async def compact(self, request: CompactionRequest) -> CompactionArtifact: response = await self.provider.complete( CompletionRequest( model=self.model, prompt="Update the running summary:\n\n" + render_request(request), max_tokens=8_000, # room for thinking on reasoning models reasoning_effort="low", ) ) return CompactionArtifact(summaryText=response.text.strip()) ``` Run it: ```bash compactbench run --method path/to/my_compactor.py:MyCompactor \ --suite practice --provider anthropic --model claude-haiku-5-5 --controls ``` ## What the request holds | Field | Cycle 0 | Later cycles | |---|---|---| | `cycle` | `0` | `1, 2, …` | | `turns` | the whole opening conversation | **only** the turns since your last compaction | | `previous_artifact` | `None` | exactly what you returned last cycle | | `token_budget` | the run's budget (or `None`) | same | The earlier turns are never sent again. Anything your artifact dropped is gone — that is the point of the drift cycles. Turns have a `role` (`user`, `assistant`, `system`, `tool`), `content`, and for tool output a `name` (`read_file`, `run_tests`, …). `compactbench.rendering.render_request` renders a request as one prompt body; `render_artifact` shows exactly what the reader will see. ## The artifact ```python CompactionArtifact( summaryText="...", # free text structured_state=StructuredState( # optional sections immutable_facts=[...], locked_decisions=[...], forbidden_behaviors=[...], deferred_items=[...], unresolved_items=[...], entity_map={"Dana Whitfield": "owns the export job"}, ), methodMetadata={...}, # carried to your next cycle, never shown to the reader ) ``` The reader sees `render_artifact(artifact)`: the summary, then each non-empty section. The token budget is measured on that rendering, so moving text into `structured_state` doesn't avoid it. An over-budget artifact is cut before the reader sees it, and disqualifies a ranked run, so models that overshoot a word limit need a safety net: `compactbench.compactors.fit_to_budget(artifact, request.token_budget)` returns the artifact trimmed to fit (oldest structured entries first, then the end of the summary), as the built-in methods do. `methodMetadata` is a good place for state you want back next cycle (the `truncate-last-n` control keeps its turns there). ## The model your method uses `self.provider` and `self.model` are the method's own model — whatever `--provider` / `--model` the run was given. The reader that answers the probes is configured separately (`--reader-provider` / `--reader-model`, or pinned by a season), so your method can use any model you like, or none. Method-specific settings arrive as `self.config`: the JSON object you give with `--method-config` locally, or in the "Method config" field when you submit. ## Check before you submit ```bash compactbench run --method my_compactor.py:MyCompactor --suite practice \ --provider anthropic --model claude-haiku-5-5 \ --reader-provider anthropic --reader-model claude-haiku-5-5 \ --controls --traces traces.jsonl --output results.jsonl compactbench score --results results.jsonl compactbench qualify --results results.jsonl ``` `traces.jsonl` shows, per cycle, your artifact, the questions, and the reader's raw replies — the fastest way to see what your method loses. Use `--estimate` first to see the token cost. ## Migrating from 0.2 0.2 compactors implemented `compact(self, transcript, config=None, previous_artifact=None)` and received the **whole** transcript every cycle. In 0.3: - the signature is `compact(self, request: CompactionRequest)`; - after cycle 0 you receive only the new turns plus your previous artifact; - `config` moved to `self.config`; - there is a token budget (`request.token_budget`). A class with the old signature fails to load with a message pointing here. The usual port is: build your prompt from `render_request(request)` instead of the transcript, and stay under `request.token_budget`. --- # Forget less: what Season 1 says about compaction instructions When an agent compacts its context, it rewrites the conversation as a summary and carries on from that. Whatever the summary drops or gets wrong is gone. Season 1 measured eight ways of writing that summary on the same 48 hidden conversations, each compacted five times. This page turns the results into instructions you can paste into your agent. The numbers below come from the [Season 1 leaderboard](/leaderboard): Claude Haiku 5.5 writes the summary and answers the questions, every summary has a 1,024-token budget, and scores are on a 0-100 scale ([data](/api/leaderboard.json)). Per-family scores rest on fewer questions than the overall score, so read them as directions rather than exact figures. ## What the results show ### 1. Give the summary fixed sections The plain "summarize the conversation" baseline (`naive-summary`) scored **45.1**. The same single call with seven fixed headings (`sectioned-summary`) scored **51.9**, the best in Season 1; the two intervals don't overlap. The headings help most where a plain summary blurs details: | Family | Plain summary | Sectioned summary | |---|---:|---:| | Names and who they refer to (`entity_confusion`) | 20 | 65 | | Constraints stated once, early (`buried_constraint`) | 48 | 66 | | Rules with a scope or exception (`conditional_scope`) | 56 | 66 | ### 2. Replace what changed, and say what it replaced A summary rewritten from the previous summary drifts. `sectioned-summary` answered 73 after the first compaction and 39 after the fifth. When a question offered a value the conversation had since replaced, it picked the old value 17% of the time. `hierarchical-summary` held between 49 and 51 across all five compactions and picked the old value 4% of the time. Among other differences, its merge step tells the model: where a newer part of the conversation changes something, keep the newer version and note what it replaced. After five compactions it was ahead by 10 points. If your sessions compact many times, this is the property that matters most. ### 3. Track tasks with their status Keeping track of tasks (what is done, in progress or pending, and who owns it) was the hardest family for every summary: **10** for the sectioned summary, **5** for the plain one and **17** for the hierarchical one. `structured-state`, which keeps tasks as explicit records, scored **36**: the best on this family, although it was weaker overall (40.0). ### 4. Keep each name with its role `structured-state`'s entity map scored **81** on names and roles, the best in the season, against 65 for the sectioned summary. ## Instructions to paste This combines the four findings: the winning method's sections, the instruction from the method that didn't drift, and explicit task status and roles. > **Not yet scored as a combination.** Each part comes from a measured method, but this exact prompt has not been run through the benchmark yet. [Check it on your own setup](#measure-it-on-your-setup), and if you do, please share the result in an issue. ```text Your context is being compacted. Write the summary you will continue from; the original messages will not be available. Use these sections and keep each one current: 1. Primary request and intent 2. Decisions and constraints: each rule as it stands now, with its scope and exceptions 3. People and responsibilities: each name with its role and what they own 4. Facts and figures: exact numbers, dates, versions and identifiers, copied verbatim 5. Tasks: each one with its status (done, in progress, pending, blocked) and owner 6. Open questions 7. Current state and next step When something has changed since the earlier summary, write only the new version and add "(replaced: )". Drop what was cancelled or reverted. Keep rules that are still in force, however long ago they were stated. ``` ### Claude Code Add a `# Compact instructions` section to your project's `CLAUDE.md`, and Claude Code uses it when it compacts: ```markdown # Compact instructions When you compact, use these sections and keep each one current: 1. Primary request and intent ... ``` You can also pass instructions to a single manual compaction: `/compact `. ### Codex CLI Set `compact_prompt` in `~/.codex/config.toml` (or point `experimental_compact_prompt_file` at a file holding the prompt): ```toml compact_prompt = """ Your context is being compacted. Write the summary you will continue from; ... """ ``` ### LangChain `SummarizationMiddleware` takes the prompt as `summary_prompt`. It is a format string: keep the `{messages}` placeholder, and double any other braces. ```python from langchain.agents import create_agent from langchain.agents.middleware import SummarizationMiddleware FORGET_LESS = """Your context is being compacted. ... Messages to summarize: {messages} """ agent = create_agent( model="anthropic:claude-haiku-5-5", tools=[...], middleware=[ SummarizationMiddleware(model="anthropic:claude-haiku-5-5", summary_prompt=FORGET_LESS) ], ) ``` ### LlamaIndex `ChatSummaryMemoryBuffer.from_defaults(llm=..., token_limit=..., summarize_prompt=FORGET_LESS)`. LlamaIndex has deprecated this buffer in favour of its newer `Memory` class, so check the current LlamaIndex docs for where a summary prompt goes there. ## Measure it on your setup Your agent, model and conversations differ from Season 1's. To see whether a prompt helps, wrap it as a compactor and compare it with the built-in baseline on the same Practice cases: ```python # forget_less.py from typing import ClassVar from compactbench.compactors import Compactor, fit_to_budget from compactbench.contracts import CompactionArtifact, CompactionRequest from compactbench.providers import CompletionRequest from compactbench.rendering import render_request PROMPT = """...""" # the instructions above class ForgetLess(Compactor): name: ClassVar[str] = "forget-less" version: ClassVar[str] = "0.1.0" async def compact(self, request: CompactionRequest) -> CompactionArtifact: limit = f"Stay under {request.token_budget} tokens." if request.token_budget else "" response = await self.provider.complete( CompletionRequest( model=self.model, prompt=f"{PROMPT}\n{limit}\n\n{render_request(request)}\n\nSUMMARY:", max_tokens=8_000, # room for thinking on reasoning models reasoning_effort="low", ) ) artifact = CompactionArtifact(summaryText=response.text.strip()) fitted, _ = fit_to_budget(artifact, request.token_budget) return fitted ``` ```bash compactbench check --method built-in:sectioned-summary --cases 12 \ --baseline baseline.json --update-baseline compactbench check --method forget_less.py:ForgetLess --cases 12 --baseline baseline.json ``` The second command reports the change against the sectioned summary, overall and per family. If your agent uses Codex CLI's or LangChain's default compaction, compare against `built-in:codex-cli` or `built-in:langchain-summarization` instead: they reproduce those defaults from the agents' open-source code. See [checking in CI](/docs/ci) for the options and [writing a compactor](/docs/writing-a-compactor) for the rest of the interface. --- # Check your method in CI `compactbench check` runs a small, fixed sample of the public Practice suite on your compaction method and tells you whether it forgets more than it used to. Put it in CI and a pull request that makes your agent lose instructions, decisions or exact figures after compaction fails its build, with a report of what got worse. Every call uses **your own API keys**: your method's model and the reader that answers the questions. ## What it runs By default the check uses the Season 1 settings on a small sample: | Setting | Default | Option | |---|---|---| | Suite | `practice` (mixed sessions at Elite difficulty, ~32k-token openings) | `--suite` | | Cases | 4 | `--cases` | | Which cases | seed group `ci`, the same cases every run | `--seed-group` | | Compactions | 5 (the opening plus 4 drift cycles) | | | Budget | 1,024 tokens per artifact | `--budget` | | Method's model | `anthropic` / `claude-haiku-5-5` | `--provider`, `--model` | | Reader | `anthropic` / `claude-haiku-5-5`, high effort | `--reader-provider`, `--reader-model`, `--reader-effort` | Because the cases never change, a change in score comes from your method (and the run-to-run variation of the models), not from a different sample. See the cost of a run before making any calls: ```bash compactbench check --method my_compactor.py:MyCompactor --estimate ``` With Claude Haiku 5.5 as both the method's model and the reader, a default run of the `sectioned-summary` baseline made 80 calls and cost about $0.11, most of it the reader's thinking (which the estimate doesn't include). ## Run it locally ```bash pip install 'compactbench[providers]' export COMPACTBENCH_ANTHROPIC_API_KEY=... # Record a baseline once, and commit it. compactbench check --method my_compactor.py:MyCompactor \ --baseline .compactbench/baseline.json --update-baseline # Later: compare against it. Exits 1 on a regression. compactbench check --method my_compactor.py:MyCompactor \ --baseline .compactbench/baseline.json ``` The report shows the score with its 95% interval, the score after each compaction (how fast the method forgets) and the score per [failure family](/methodology), each against the baseline. `--summary FILE` appends the same report as Markdown, `--json FILE` writes the numbers and the verdict, and `--output` keeps the full results file for `compactbench score`. ## The gates | Gate | Default | Fails when | |---|---|---| | `--max-drop` | 5 points | the score is more than this many points (0-100 scale) below the baseline | | `--min-score` | off | the score is below this | A baseline only counts if it was recorded with the same suite version, cases, seed group, budget, reader and scorer. If any of them differ the check fails and asks you to record a new baseline, rather than reporting a change that means nothing. Changing the method or its model is fine: that is what you are comparing. ## GitHub Action ```yaml name: CompactBench on: pull_request: permissions: contents: read pull-requests: write # only needed for `comment: true` jobs: check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: compactbench/compactbench@main # pin a release tag or commit SHA with: method: my_compactor.py:MyCompactor baseline: .compactbench/baseline.json comment: true env: COMPACTBENCH_ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` The report goes to the job summary and, with `comment: true`, to one pull-request comment per method and model that later runs update. The action installs CompactBench in its own virtual environment; if your method needs other packages, list them in `install` (for example `install: -r requirements.txt` or `install: .`). | Input | Default | | |---|---|---| | `method` | required | `built-in:` or `:` | | `provider`, `model` | `anthropic`, `claude-haiku-5-5` | the method's model | | `reader-provider`, `reader-model`, `reader-effort` | `anthropic`, `claude-haiku-5-5`, `high` | the reader | | `suite`, `cases`, `seed-group`, `budget` | `practice`, `4`, `ci`, `1024` | the sample | | `method-config` | `{}` | JSON passed to the method as `self.config` | | `baseline`, `max-drop`, `min-score` | none, `5`, none | the gates | | `update-baseline` | `false` | write the run to `baseline` instead of comparing | | `comment`, `github-token` | `false`, the job's token | the pull-request comment | | `install` | none | extra `pip install` arguments for your method | | `version` | the action's own | a CompactBench version from PyPI | | `python-version`, `working-directory` | `3.12`, `.` | | Outputs: `score`, `change` (points against the baseline), `passed`, `report` (the JSON report) and `results` (the full results file — upload it with `actions/upload-artifact` to inspect a failing run). Pass each provider's key as an environment variable, as above (`COMPACTBENCH_OPENAI_API_KEY`, `COMPACTBENCH_GROQ_API_KEY`, ...; see [getting started](/docs/getting-started#configure-a-provider)). GitHub does not give repository secrets to workflows triggered from forks, so the check can only run on pull requests from branches in your repository. ## Choosing the sample size and the gate Four cases keep the check cheap. The cases are the same every run, so what varies between runs is the models' sampling. Two identical default runs of the `sectioned-summary` baseline scored 46.8 and 45.7 overall, while single families moved by up to 23 points: gate on the overall score, and read the family table as a pointer to where to look. The 95% interval in the report is wider than that (about ±10 points with four cases) because it also covers which cases were drawn; it tells you how far the score generalizes beyond these cases. To tighten it, raise `--cases` and record a new baseline. Either way the check measures your method on public cases: it is a development signal, not a leaderboard score. Ranked scores come from the hidden Elite set. --- # Integrations CompactBench's `Compactor` ABC works standalone, but most production code already lives inside a framework. The `compactbench.integrations` package ships thin adapters that let you benchmark what you already have. - [LangChain](#langchain) — wrap any callable that takes `list[BaseMessage]` - [LlamaIndex](#llamaindex) — wrap any callable that takes `list[ChatMessage]` Both adapters share the same return-shape contract (`str | list[messages] | dict`) and preserve turn provenance via `additional_kwargs` so filtered-message methods automatically populate `CompactionArtifact.selected_source_turn_ids`. **What your callable receives.** At the first compaction, the whole opening conversation. At every later compaction, a system message holding your previous artifact (`"Summary of the conversation so far: …"`, marked `compactbench_previous_artifact` in `additional_kwargs`) followed by only the turns since then — the same shape a framework app sees after its own summarisation step. Tool output arrives as user messages prefixed `TOOL[name]:`. **`provider` / `model`.** Your callable owns its own LLM, so these are only recorded as the method's model. The reader that answers the questions is set on the run (`--reader-provider` / `--reader-model`). ## LangChain `compactbench.integrations.langchain` wraps any LangChain-flavoured compaction callable as a CompactBench [`Compactor`](/docs/writing-a-compactor) so it can be scored against the Practice suite or the hidden Elite set. **Install:** ```bash pip install 'compactbench[langchain]' ``` That adds only `langchain-core>=0.3`. Bring your own `langchain`, `langchain-openai`, `langchain-anthropic`, etc. — they're all compatible. ### Wrap a summarisation chain ```python from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage from langchain_openai import ChatOpenAI from compactbench.integrations.langchain import LangChainCompactor from compactbench.providers import MockProvider summariser = ChatOpenAI(model="gpt-4o-mini", temperature=0) async def summarise(messages: list[BaseMessage]) -> str: response = await summariser.ainvoke( [ SystemMessage( content=( "Summarise the conversation, preserving every constraint, " "decision, and unresolved task. Reply with the summary only." ) ), *messages, ] ) return str(response.content) compactor = LangChainCompactor( # Your callable owns its LLM; provider/model are only recorded as the # method's model. The reader is configured on the run. provider=MockProvider(), model="gpt-4o-mini", compaction_fn=summarise, method_name="openai-mini-summary", method_version="0.1.0", ) ``` Hand `compactor` to `compactbench run --method …` (via a custom wrapper) or use the runner API directly. The full submission flow is the same as for any other method: see [submitting](/submitting). ### Return structured state If your method populates ledgers or extracted entities, return a dict instead of a string: ```python async def structured(messages: list[BaseMessage]) -> dict: # ... your pipeline ... return { "summary_text": prose_summary, "structured_state": { "locked_decisions": ["supplier list must be EU-only"], "forbidden_behaviors": ["recommending non-EU suppliers"], "immutable_facts": [...], "entity_map": {"Alice": "owner of task A", "Bob": "owner of task B"}, "unresolved_items": [...], }, "warnings": ["truncated two early turns"], "method_metadata": {"chain_type": "summary_memory", "calls": 3}, } ``` The dict keys are optional — missing keys fall back to sensible defaults. `summary` is accepted as an alias for `summary_text` so you can return `ConversationSummaryMemory.predict_new_summary(...)` output directly. ### Preserving turn provenance `request_to_messages` (via `transcript_to_messages`) stamps each LangChain message with `additional_kwargs["compactbench_turn_id"]`. If your callable returns a filtered `list[BaseMessage]`, the adapter reads those ids back and populates `CompactionArtifact.selected_source_turn_ids` automatically — useful for `trim_messages`-style retention methods and for the contradiction scorer. ```python from langchain_core.messages.utils import trim_messages def trim(messages: list[BaseMessage]) -> list[BaseMessage]: return trim_messages( messages, max_tokens=500, token_counter=len, # swap for a real tokenizer strategy="last", ) compactor = LangChainCompactor( provider=MockProvider(), model="none", compaction_fn=trim, method_name="trim-last-500", ) ``` ### Benchmarking legacy `ConversationSummaryMemory` The legacy `langchain.memory.ConversationSummaryMemory` API predates `langchain-core`'s message primitives but still works if you have it installed. Wrap it like this: ```python from langchain.memory import ConversationSummaryMemory from langchain_openai import ChatOpenAI from langchain_core.messages import BaseMessage memory = ConversationSummaryMemory(llm=ChatOpenAI(model="gpt-4o-mini")) def compact_with_legacy_memory(messages: list[BaseMessage]) -> str: # ConversationSummaryMemory consumes messages in (human, ai) pairs. human: str | None = None for message in messages: if message.type == "human": human = str(message.content) elif message.type == "ai" and human is not None: memory.save_context({"input": human}, {"output": str(message.content)}) human = None return memory.buffer # the running summary string ``` This is exactly the shape a production LangChain app uses — now it's a row on the CompactBench leaderboard. ## LlamaIndex `compactbench.integrations.llamaindex` mirrors the LangChain adapter — same three public symbols, same three supported return shapes (`str | list[ChatMessage] | dict`), same provenance-preserving `additional_kwargs`. Pick whichever framework you already have in production. **Install:** ```bash pip install 'compactbench[llamaindex]' ``` That adds only `llama-index-core>=0.11`. Your LLM binding (`llama-index-llms-openai`, `llama-index-llms-ollama`, etc.) stays your choice. ### Wrap a `ChatSummaryMemoryBuffer` ```python from llama_index.core.base.llms.types import ChatMessage from llama_index.core.memory import ChatSummaryMemoryBuffer from llama_index.llms.openai import OpenAI from compactbench.integrations.llamaindex import LlamaIndexCompactor from compactbench.providers import MockProvider summariser_llm = OpenAI(model="gpt-4o-mini", temperature=0) def summarise(messages: list[ChatMessage]) -> str: memory = ChatSummaryMemoryBuffer.from_defaults(llm=summariser_llm, token_limit=500) memory.set(messages) return "\n".join(str(m.content) for m in memory.get()) compactor = LlamaIndexCompactor( provider=MockProvider(), # unused: your callable owns its LLM model="gpt-4o-mini", compaction_fn=summarise, method_name="llamaindex-chat-summary-buffer", method_version="0.1.0", ) ``` ### Return structured state Same dict-shape contract as the LangChain adapter — return any of `summary_text`, `structured_state`, `selected_source_turn_ids`, `warnings`, `method_metadata`: ```python async def structured(messages: list[ChatMessage]) -> dict: # ... your pipeline ... return { "summary_text": prose_summary, "structured_state": { "locked_decisions": [...], "forbidden_behaviors": [...], "entity_map": {...}, }, "method_metadata": {"memory_type": "chat_summary_buffer", "calls": 3}, } ``` ### Preserving turn provenance `request_to_chat_messages` (via `transcript_to_chat_messages`) stamps `additional_kwargs["compactbench_turn_id"]` on every outgoing message. If your callable returns a filtered `list[ChatMessage]`, the adapter reads those ids back and populates `CompactionArtifact.selected_source_turn_ids` automatically. ```python def keep_last_n(messages: list[ChatMessage], n: int = 6) -> list[ChatMessage]: return messages[-n:] compactor = LlamaIndexCompactor( provider=MockProvider(), model="none", compaction_fn=lambda ms: keep_last_n(ms, 6), method_name="keep-last-6", ) ``` ## Other frameworks **CrewAI** and **Haystack** adapters follow the same shape (`result_to_artifact` + a subclass of `Compactor`). Open a [GitHub issue](https://github.com/compactbench/compactbench/issues/new) if you want a specific framework prioritised — or send a PR; the LangChain and LlamaIndex adapters at `src/compactbench/integrations/` are good reference templates. --- # Elite program Elite is CompactBench's ranked track: the hardest set we maintain, and the only one that produces leaderboard ranks. ## Tracks | Track | Visibility | Purpose | |---|---|---| | **Starter** | public | smoke-test a method end to end (~1.5k-token conversations) | | **Practice** | public | develop and debug at Elite difficulty (~32k-token openings, 4 drift cycles) | | **Elite** | hidden | ranked runs | Practice and Elite share the same families, difficulty profile, probe formats and scoring. Elite differs in what can't be learned from the public package: its cases are set in private worlds — their own people, projects, rules, decisions, facts and filler — and every sentence the families write uses private wording. ## Fresh samples, not a fixed test set Elite is a generator, not a list of cases. Every ranked run draws its own sample, so there is no answer key to memorize, and a run's cases — even if a submitter sees them in their own provider logs — tell them nothing reusable about the next run. Scores are comparable across samples because the generator is calibrated: one method scored on several fresh samples lands within a few points, and every reported score carries a confidence interval. ## What makes it hard - Rules stated once, indirectly, inside pasted notes or tool output, tens of thousands of tokens before they matter — among look-alike rules for other projects, hypotheticals and rejected proposals. - Decisions overridden, reverted and carved into scoped exceptions, across compactions. - Look-alike people trading ownership back and forth. - Choices made by reference that only resolve if the alternatives survived. - Exact figures that get estimated, finalized and corrected, next to near-identical figures for sibling projects. - Rules that cover only some components or only until a date, with scopes that keep changing. - A ticket board whose statuses, owners and blockers move between compactions. - Fetched documents and injected instructions that contradict what the team decided. - Questions about things that were raised but never settled, where any concrete answer is a hallucination. - Wrong answers built from the conversation itself, so a lossy summary picks them. - A fixed token budget for every artifact. ## Fairness Every item must be answerable from the full conversation and not guessable from nothing. Each Elite release is checked against both before it is used: items a reader gets wrong with the full conversation, or right with no context, are removed, and the families are balanced so no single family is easy. Runs with `--controls` measure the same ceiling and floor on their own cases. ## Seasons A season pins every setting that affects a score: suite and version, difficulty, drift cycles, cases per family, token budget, and the reader model and its reasoning effort. Season 1 is defined in [`seasons/s1.yaml`](https://github.com/compactbench/compactbench/blob/main/seasons/s1.yaml). Submitters choose only their method and the model it calls. Leaderboards are segmented by season, and a season's rows stay pinned to its versions permanently. See [governance](/docs/elite-versions) for versioning and retirement. --- # Elite governance ## Versioning - Every family has a version; every suite has a version; the scorer has a version. - A change that can move scores — new or changed families, filler, vocabulary, difficulty, probe formats or scoring — is a new suite or scorer version. - Results record all of them, and leaderboards segment on suite, scorer, reader and budget, so numbers from different versions never compete. | Scorer | Benchmark | Status | |---|---|---| | 3.0.0 | v2 — scenario families, true drift loop, structured probes | current | | 2.0.0 | v1 YAML templates, substring checks | retired; results archived in `docs/data/archive/` | | 1.0.0 | v1 | retired | ## Seasons A season fixes one Elite configuration for a period. Within a season, every ranked run uses the same settings and a fresh sample from the same generator. A new season can change any setting; its rows form a new board and earlier seasons stay as they were. ## Retirement A family, generator or season is retired when it is compromised (its private content leaks) or saturated (top methods score near the oracle ceiling). Retirement is announced in the changelog; retired content stays available for audit but no new ranked runs use it. ## Review of published runs Qualifying runs are published automatically. The maintainers may review any run afterwards — for example one whose family scores look implausible — against its sealed traces, and remove it if it breaks the submission rules. --- # FAQ ## How is this different from long-context benchmarks? Long-context benchmarks measure the *model* with everything in its window. CompactBench measures what happens when the window is replaced by a compacted artifact — repeatedly, as the conversation continues. You can have the strongest model available; if your compactor dropped a rule, kept a superseded decision, or swapped two people, the model will act on that. ## How is compaction different from summarization? Summarization is one strategy (`naive-summary` is the simplest baseline). Others are structured state extraction, hierarchical summarization, append-only ledgers, sliding windows, and provider-native compaction. The benchmark scores whatever artifact you return. ## Why a separate reader model? So the method is the only thing that varies. Your method can use any model it likes; the reader that answers the questions is fixed per run, and pinned per season for ranked runs. Hold the reader fixed whenever you compare methods. ## Why no LLM judge? Judges have biases, drift between versions, and cost money on every item. Every CompactBench answer is an option letter or an exact value, so scoring is free, deterministic and re-checkable from the traces. Wrong options are built from the conversation itself, so a structured format doesn't make the questions easier — a summary that kept the old decision picks the old decision. ## What do the controls tell me? `--controls` scores the same questions from the full conversation (oracle) and from nothing (null). The oracle shows what's achievable with that reader; the null shows what guessing gets. A method at 0.55 with an oracle of 0.90 and a null of 0.10 kept about 56% of the achievable range. ## Can I run this against my own model? Yes. Point the `openai` provider at any OpenAI-compatible server with `COMPACTBENCH_OPENAI_BASE_URL` (vLLM, llama.cpp, LM Studio, OpenRouter…), use `ollama` for local models, or subclass `Provider`. Custom endpoints are recorded as such. ## Why is there a hidden set if the generator code is public? The public families drive Starter and Practice. Ranked Elite cases come from private generators, vocabulary and filler, and every ranked run gets a fresh sample — so there's nothing fixed to memorize, and Practice is difficulty-matched so it still predicts your Elite score. ## Why Python? Open-source AI evaluation is overwhelmingly Python (`lm-evaluation-harness`, `inspect_ai`, SWE-bench). It keeps the bar to contributing a method low. ## How do I cite CompactBench? Cite the repository and pin the versions your numbers came from — `suite_version` and `scorer_version` are in every results file, and scores are not comparable across scorer major versions: ``` CompactBench: a benchmark for LLM context compaction. https://github.com/compactbench/compactbench ``` ## How do I get in touch? - Bugs and feature requests: [open an issue](https://github.com/compactbench/compactbench/issues/new) - Vulnerability reports: see [SECURITY.md](https://github.com/compactbench/compactbench/blob/main/SECURITY.md) - Everything else: PRs welcome --- # Related work Where CompactBench sits relative to everything else measuring context compaction, memory, and long-context retention — including the work that overlaps it, and the places where somebody else got there first. This page exists because a benchmark that only cites itself is not credible. If you are deciding whether to use CompactBench, you should be able to see what else exists and choose the right tool, which is sometimes not this one. > **Last surveyed 2026-11-01.** Corrections and additions are welcome — open a PR. If we have mischaracterised your work, that is a bug and we will fix it. ## The problem is no longer novel — the standing scoreboard is Between April and August 2026 the field converged on exactly the question CompactBench was built around, and published it. ### Governance Decay / ConstraintRot [arXiv:2606.22528](https://arxiv.org/abs/2606.22528) · June 2026 Introduces **Governance Decay**: in-context constraints an agent reliably obeys while visible are silently dropped by compaction, and the same agent then performs the prohibited action. ConstraintRot is a benchmark of long-horizon agent scenarios with deterministic tool-call grading, across seven model families. Headline result across 1,323 episodes: violation rises from **0% with the policy in full context to 30% after compaction**, reaching **59%** on some models. When the constraint survives the summary, violation stays at 0%; when it is dropped, violation reaches 38%. **Relationship to CompactBench.** This is the result CompactBench's `buried_constraint` family measures, published first and at greater scale, so it isn't an open question. ConstraintRot is a paper artifact rather than a live, versioned, submittable leaderboard. ### Lost in Compaction / COMPINT [arXiv:2608.11242](https://arxiv.org/abs/2608.11242) · July 2026 Evaluates how well compactors preserve **Session Constraints** — user instructions meant to govern behaviour for a whole session — across multi-turn chat, agentic trajectory, and long-horizon research settings. Systematically varies compactor, prompt, context length, constraint phrasing, and injection location. Headline result: current compactors retain only **17%** of injected session constraints on average. Their proposed SC-aware extractor reaches **90%+** without modifying the compactor or the model. **Relationship to CompactBench.** Close to what CompactBench measures, and thorough on constraint phrasing and injection position. Code is released; there is no leaderboard. ### Compact-Bench (coding agents) [arXiv:2610.31710](https://arxiv.org/abs/2610.31710) · October 2026 · [code](https://github.com/cai-jianfeng/compact-bench) Measures what compaction costs long-horizon **coding agents** by pairing full-history and summary-only continuations from a shared repository state, across SWE-bench repairs, agentic sessions and production compaction chains. Reports that LLM summaries retain at most 16% of recurring details, versus 79% for mechanical extraction. **Relationship to CompactBench.** Similar name, different artifact: a coding-agent study with a public dataset, where CompactBench is a domain-general, multi-cycle benchmark with a hidden ranked set and a standing leaderboard. Its mechanical-extraction finding is a useful baseline for anyone building a method here. ### Slipstream [arXiv:2605.08580](https://arxiv.org/pdf/2605.08580) · 2026 Trajectory-grounded compaction validation for long-horizon agents — validating compaction against the trajectory that produced it rather than against a reference summary. **Relationship to CompactBench.** Complementary. Slipstream is a validation technique; CompactBench is a scoreboard. A method built on Slipstream is exactly the kind of thing that should be submittable here. ### Letta Context-Bench [Blog](https://www.letta.com/blog/context-bench/) · [Leaderboard](https://leaderboard.letta.com/) · live Benchmarks agentic **context engineering** — chaining file operations, tracing entity relationships, multi-step retrieval, and discovering/loading skills — with a maintained public leaderboard. **Relationship to CompactBench.** Adjacent rather than overlapping: Context-Bench measures how well a model *manages* its context; CompactBench measures what survives when history is *replaced* by a compacted artifact. It is also evidence that a maintained leaderboard in this space is useful to people. ## Long-context benchmarks that are frequently confused with this These measure whether a model can *find* information in a long context. CompactBench measures what survives when that context is **deliberately destroyed and replaced**. If your question is "can the model use 200k tokens", these are the right tools and CompactBench is not. | Benchmark | Measures | Why it is not this | |---|---|---| | Needle-in-a-Haystack | Retrieval of a planted fact from long context | Full context is present; nothing is compacted | | RULER | Synthetic long-context tasks at controlled lengths | Same — context is intact | | LongBench / ∞Bench | Long-document understanding | Document comprehension, not conversational state | | BABILong | Reasoning over facts spread through long context | No compaction step | | HELMET | Long-context evaluation across task types | No compaction step | ## Where CompactBench is genuinely differentiated Being honest about this is more useful than overclaiming: **Multi-cycle drift.** Most work compacts once and measures what was lost. CompactBench compacts repeatedly — compact → continue → compact — and treats decay across cycles as a first-class metric. As of the 2026-08 survey we are not aware of another public benchmark that does this, and it is the failure mode production agents actually hit, because they compact many times over a long session. **Separating model limits from compaction losses.** With `--controls`, every run also scores the same questions from the full conversation (oracle) and from nothing (null), on the same cases. A method's score is read against that bracket rather than against 1.0, which separates what the reader can't do from what the method lost. **Real multi-cycle state.** After the first compaction a method only ever gets its previous artifact plus new turns, while later cycles change rules, override decisions and move ownership. Wrong answers are built from that history, so a stale artifact is measured as stale, not just incomplete. **A standing, versioned scoreboard.** Papers publish a number once. CompactBench pins `suite_version`, `scorer_version`, the reader model and the token budget, segments rankings on them, and keeps accepting submissions — ranked against a hidden set that is sampled fresh for every run. ## Where CompactBench is currently weaker Stated plainly, because you will find these out anyway: - **Synthetic content.** Conversations are procedurally generated from templates and vocabularies, not taken from real agent sessions. The filler is on-topic and adversarial, but it is not real. - **One setting.** Every case is a software-project conversation. Support, research and operations sessions fail differently. - **Scale.** The hardest public suite opens at ~32k tokens and grows by ~8k per cycle. Production agents often compact at 100k+. - **No validity study yet.** No human-agreement data and no demonstrated correlation with downstream task success. Nobody in this area has published one either, but that is not a defence. ## Citing There is no CompactBench paper yet. Cite the repository and pin the versions your numbers came from — `suite_version` and `scorer_version` are recorded in every `results.jsonl`, and scores are not comparable across scorer major versions.