ctx-compact: What I Learned Trying to Fit Long Conversations into a Token Budget as a ml researcher

Three charts of held-out LoCoMo results: evidence recall versus budget for every compaction method, recall by question type, and the gain from neighbour smoothing per ranker
Held-out results on LoCoMo: hybrid ranking with neighbour smoothing keeps 78% of the answer-bearing turns at 500 words, against 2% for keeping the last N messages.

Every chat app and every agent eventually hits the same wall. The conversation gets longer than the context window, or just too expensive to prefill on every turn, and something has to go. The usual answer is to keep the last N messages, or to summarise the old ones. Both are blind to the question being asked next, and both fail in the same predictable way: the early turn that holds the answer is the first thing thrown away.

I wanted to know how much that actually costs, and whether a smarter but still cheap selector could fix it. So I built ctx-compact (ctxc for short), ran it against a synthetic suite and a real long-conversation benchmark, and wrote the results up as a short paper. This post is the story of that experiment: what I set out to build, what worked, and the part that did not work at all, which turned out to be the most interesting result.

Everything runs offline. No API keys, no hosted models. The dense retrieval and the answer-accuracy check use local models through Ollama, and CI runs the tests and the synthetic evaluation on every push.

The problem, stated narrowly

Memory systems like MemGPT, Mem0 and MemoryBank bundle a lot together: retrieval, LLM-written summaries, extraction, memory management. That makes it hard to say which part of the pipeline decided what the model gets to see. I wanted to isolate just one step.

A compactor gets three things: the full conversation, the next question, and a budget in words. It returns a subset of turns that fits the budget. That is it.

To score it I used evidence recall: the share of the turns that actually contain the answer that are still there after compaction. There is no model in the loop, so the number measures what the context keeps, not how well some particular LLM happens to read it. Later I added an answer-accuracy check on top, to make sure recall differences really turn into answer differences.

The idea I started with: turns depend on each other

My first design was built around one failure I kept seeing in agent logs. Early in a session someone states a rule: "hard limit of 12 tokens per tool call". Forty turns later they ask "what was that limit again?". Keep-the-last-N has long since dropped the rule. A plain relevance ranker might find the question but not the rule, because "that limit" shares no words with "12 tokens per tool call".

So ctxc builds a dependency graph between turns, which I called dy:

  • An edge goes from the turn that first introduced an entity to every later turn that reuses it.
  • Back-reference cues like "as I said", "that limit" or "remind me" link a turn to the earlier constraint-like turns.
  • Speaker names and entities that appear in too many turns (a document-frequency cap, max_df) are ignored, so filler words do not wire the whole conversation together.

The selector then runs one greedy loop:

  1. Charge the pinned system prompt against the budget first.
  2. Score every turn.
  3. Take the best remaining turn, plus its parents in dy up to max_depth levels.
  4. If the parents do not fit whole, fold each one into a one-line pin instead of dropping it.
  5. Repeat until the budget is spent. Kept turns are shown in their original order.

Here is the graph for one of the held-out synthetic dialogues. The red node is the constraint stated early, the teal node is the late question, and the edges are what the selector follows to keep the rule alive:

Dependency graph for one synthetic dialogue: turns laid out in order, a red constraint-like anchor turn near the start, a teal probe question at the end, and red depends-on edges linking later turns back to earlier ones
The dependency graph dy for one held-out synthetic dialogue. Red: the constraint-like anchor. Teal: the late question that depends on it.

Experiment 1: a synthetic suite built for the failure

I started with something I could control: 24 template dialogues, 12 used for tuning and 12 held out. In each one a rule is stated early and asked about many turns later. Entities are extracted automatically, so nothing on the evaluation path is hand-labelled, and a dialogue counts as passed if the rule survives compaction.

At a 55-token budget on the held-out dialogues:

method rule survives
ctxc (with dependency graph) 100%
ctxc with the dependency graph switched off 33%
keep the last N messages 17%
similarity eviction 17%
extractive summary baseline 100%
Six panels from the synthetic held-out sweep: accuracy versus token budget for each method, an ablation panel showing the dependency graph matters, tokens kept, compaction time, estimated prefill time, and accuracy at a 55-token budget
Synthetic held-out sweep (12 dialogues). The ablation panel is the interesting one: turning off the dependency graph drops accuracy from 100% to 33% at 55 tokens.

The ablation was exactly what I hoped to see. Same scorer, same budget, and switching off the dependency graph drops survival from 100% to 33%.

But I want to be honest about that table, because it is easy to oversell. The summary baseline also scores 100%, only because its keyword filter happens to match words like "limit" and "rule" that I wrote into these dialogues. And the whole suite was built around the failure my method targets. It shows the mechanism works when dependencies are real and sparse. It does not show that it generalises. For that I needed real conversations.

Experiment 2: real conversations on LoCoMo

LoCoMo has 10 long two-person conversations, 369 to 689 turns each (9k to 19k words), and about 2,000 questions. Every question is labelled with the turns that hold its answer, which is exactly what evidence recall needs.

I kept the protocol strict, because with only 10 conversations it is very easy to fool yourself:

  • Conversations 1 to 5 are the dev split. Every setting (neighbour weight, BM25 share of the hybrid score, the entity frequency cap, parent depth) was picked there by best mean recall over all budgets.
  • Conversations 6 to 10 are held out: 776 questions (423 single-hop, 140 multi-hop, 165 temporal, 48 open-domain), scored once with the settings frozen.
  • Adversarial (unanswerable) questions are excluded.

The first run was humbling. My original overlap-plus-recency scorer, the one that looked perfect on the synthetic suite, kept 5.6% of the evidence at 500 words. Keep-the-last-N kept 2%. Real conversations do not look like my templates: the answer to a question is usually many sessions old, and the question rarely reuses the exact words of the answer.

So I spent the next round of commits on the ranker, and that is where the real gains came from.

What the rankers do

  • BM25: the standard lexical ranker. Then BM25-stem: the same with stopwords removed and common English suffixes stripped.
  • Dense: cosine similarity with nomic-embed-text, run locally in Ollama.
  • Hybrid: 0.3 × min-max-normalised BM25-stem plus 0.7 × min-max-normalised dense score.

Neighbour smoothing: the one-line change that worked

Reading the misses, the same pattern kept coming up. In a conversation the answer is usually the reply to the turn that matches the question. Someone asks "What breed is he?". The turn that matches is "I got a new dog!". The answer is in the next turn: "Biscuit is a corgi."

So each turn inherits part of the score of its best neighbour in the same session:

s'(t_i) = s(t_i) + α · max( s(t_i-1), s(t_i+1) )

Neighbours from a different session count as zero. Dev tuning picked α = 0.5 for BM25-stem and the hybrid, and 0.25 for dense. In code it is about this small:

def smooth(scores, session, alpha=0.5):
    out = list(scores)
    for i, s in enumerate(scores):
        nb = [scores[j] for j in (i - 1, i + 1)
              if 0 <= j < len(scores) and session[j] == session[i]]
        out[i] = s + alpha * max(nb, default=0.0)
    return out

The results

Here is the held-out evidence recall, in percent, at four word budgets, plus the multi-hop subset at 4,000 words:

method 500 1000 2000 4000 multi-hop @ 4000
hybrid + neighbour 77.9 84.0 88.7 94.1 85.3
hybrid 75.9 82.8 88.6 93.2 85.3
dense + neighbour 71.7 79.7 86.9 92.1 82.5
dense 71.4 78.6 85.3 91.3 82.6
BM25-stem + neighbour 70.4 77.1 83.0 87.2 69.1
BM25-stem 63.4 70.0 76.3 82.3 62.9
BM25 55.0 62.2 70.3 77.4 57.0
original overlap scorer 5.6 9.8 19.3 37.5 —
keep last N 2.0 5.2 10.9 24.7 —
summary-style keyword drop 1.6 5.0 10.6 24.2 —

The chart at the top of this post is the same data: recall versus budget on the left, recall by question type at 1,000 words in the middle, and how much neighbour smoothing adds for each ranker on the right.

What I take from it:

  • Truncation fails badly on real chat. Anything that keeps recent or keyword-flagged turns finds under 25% of the evidence, even at 4,000 words.
  • The ranker does most of the work. Plain dense retrieval beats every lexical variant, and is far ahead on multi-hop questions (82.6 vs 69.1 at 4,000 words). The hybrid adds another 1.9 to 4.5 points on top of dense.
  • Neighbour smoothing helps, but less the better your ranker is. It adds 4.9 to 7.2 points to stemmed BM25, 0.3 to 1.6 to dense, and 0.1 to 2.1 to the hybrid. A good embedder already scores the reply as related to the question even when they share no words.

Checking which differences are real

With five held-out conversations, a one-point difference can easily be noise. So I ran a paired bootstrap over the 776 questions (10,000 resamples) for the key comparisons:

difference 500 1000 2000 4000
hybrid + neighbour − hybrid +2.1 [0.3, 3.9] +1.2 [−0.3, 2.7] +0.1 [−1.2, 1.3] +0.9 [−0.2, 2.0]
BM25-stem + neighbour − BM25-stem +7.0 [5.0, 9.0] +7.2 [5.1, 9.2] +6.7 [4.9, 8.5] +4.9 [3.3, 6.7]
hybrid − dense +4.5 [2.3, 6.7] +4.2 [2.3, 6.1] +3.3 [2.0, 4.7] +1.9 [0.8, 3.0]

Bold means the 95% interval excludes zero. On the hybrid, only the 500-word gain from smoothing is clearly real. From 1,000 words up, hybrid with and without smoothing are statistically indistinguishable on this data.

It is also not a uniform win. On the hybrid, the gain comes entirely from single-hop questions (+6.2 points at 500 words). Smoothing loses 7 of the 16 question-type-by-budget cells, mostly multi-hop and open-domain at small budgets. When the evidence is spread across several distant turns, budget spent on a neighbour is budget not spent on the next distant hit.

The negative result: the dependency graph does not transfer

This is the part I did not expect, and the reason the repo is named after a mechanism that ended up switched off.

On LoCoMo, wherever neighbour smoothing is used, dev tuning picked an entity frequency cap of 0.002. With 369 to 689 turns per conversation, that only admits entities that appear in at most one turn, so no turn can link to another. The dependency graph has zero edges in all 10 conversations. Tuning, in effect, chose to turn my main idea off, and recall is identical to the no-graph ablation to the last reported digit.

Where the graph is active (plain BM25 with looser caps, 0 to 543 edges per conversation) it is a trade-off: about the same overall, +4.6 points on multi-hop at 4,000 words with two levels of parents, and about −5 points at 500 words.

The reason is simple once you see it. In casual conversation the entities are things like "work", "family" and "trip". They come back constantly, so reusing one says nothing about whether a later turn depends on an earlier one. In my agent-style synthetic dialogues, entities like "12 tokens per tool call" are rare and specific, so reuse really does mean dependence. The mechanism works when dependencies are real and sparse, and real open-domain chat is neither.

I left this in the paper as a negative result rather than quietly dropping it. A method that only helps on the benchmark you wrote for it is worth knowing about.

Does better recall mean better answers?

Recall is a proxy, so I checked it against real answers. Each method's 1,000-word context went to Qwen2.5-7B (local, temperature 0), which answers in a few words. The same model then judges each answer CORRECT or WRONG against the gold answer, next to SQuAD-style token F1. The oracle sees only the gold evidence turns (63 words on average).

method recall F1 judge accuracy multi-hop temporal
oracle (gold turns only) 100.0 57.0 70.9 75.0 49.1
hybrid + neighbour 84.0 52.5 62.4 55.0 35.8
hybrid 82.8 52.0 62.4 55.0 35.8
BM25-stem + neighbour 77.1 50.3 59.0 49.3 31.5
BM25 62.2 41.9 50.9 40.7 27.3
keep last N 5.2 5.3 6.4 10.0 4.2

The recall ordering carries over. Hybrid ranking is 11.5 judge points above BM25 (95% interval +8.1 to +14.8). Neighbour smoothing on top of the hybrid changes nothing at this budget: 53 questions are answered correctly only with smoothing and 53 only without it.

Compaction still costs something. The best compactor keeps 84% of the evidence and still trails the oracle by 8.5 judge points. Part of that is missing evidence, and part is distraction: the oracle's 63 words contain nothing unrelated, while a 1,000-word context is mostly unrelated turns. Temporal questions are hard even for the oracle (49.1%), because the gold answers are absolute dates the model has to work out from "last Tuesday" and the session date.

It is cheap

With turn embeddings computed once per conversation and cached, the hybrid selector with smoothing takes about 6 ms per question on a CPU, and BM25 about 3 ms. The lexical selectors need no model at all. That matters, because a compactor runs on every single turn.

Limits, stated plainly

  • Answer accuracy is one 7B model at one budget, and the same model is the judge. The judge is lenient on lists ("rock climbing" passes for "rock climbing, fishing, camping"), though equally for every method.
  • LoCoMo has only 10 conversations, written by LLM agents and edited by humans rather than collected from real users. Read one- or two-point differences through the intervals above.
  • Budgets are counted in words. A real deployment should count with the serving model's tokenizer.
  • I compare selection policies only, not full memory systems that extract or summarise with an LLM.
  • GPU inference is not bit-exact even at temperature 0: an accidental double run changed the wording of 135 of 2,302 answers, which moved aggregate scores by at most 0.5 points.

What I learned

The thing I set out to build, dependency tracking between turns, works in the setting I designed it for and does not transfer to open-domain chat. The thing that actually moved the numbers was boring: a better ranker, and a one-line rule that a reply belongs with the turn it answers. If you are compacting long chats today, the practical advice is short:

  1. Never just keep the last N messages. On LoCoMo it keeps 2% of the evidence at 500 words.
  2. Rank turns against the next question, with a hybrid of BM25 and a small embedding model.
  3. Add neighbour smoothing. It is free, and it helps a lot if your ranker is lexical.
  4. Keep dependency tracking for agent-style sessions with rare, specific constraints, where it does help.

Try it yourself

The code, every result CSV, the plots and the paper draft are on GitHub: Viraj-rana/ctx-compact. There is also a Colab notebook that runs the tests and the synthetic sweep.

pip install -e ".[dev]"
python -m pytest -v

python scripts/get_locomo.py                                       # LoCoMo, CC BY-NC 4.0, downloaded not vendored
python -m ctxc.eval.locomo --out results/locomo_sweep.csv          # lexical methods only
python -m ctxc.eval.locomo --dense --out results/locomo_sweep.csv  # + dense/hybrid (Ollama, nomic-embed-text)
python scripts/bootstrap_locomo.py                                 # 95% intervals
python -m ctxc.eval.qa --budget 1000                               # answer accuracy (Ollama, qwen2.5:7b)

If you work on long-context RAG, I wrote about the production side of the same problem in The Dark Art of Context Truncation & Dynamic Prompt Compaction in Production RAG, and about running all of this locally in Architecting a Zero-Cloud Agent Memory Lab.