Practical technical guides / AI engineering: context management and cost

Mask Old Tool Observations Before Paying for Summaries: Agent Context Management Measured

arXiv 2508.21433 found masking old tool outputs halved cost and matched LLM summaries. A cost model of both on a 44-turn run, and how to mask safely.

By Sandeep Belgavi · Published 2026-11-07

arXiv 2508.21433 found masking old tool outputs halved cost and matched LLM summaries. A cost model of both on a 44-turn run, and how to mask safely.

Where the tokens in an agent run go

An agent that works through a task one tool call at a time sends its whole history back to the model on every turn: the system prompt, the task, and for each earlier turn the model's reasoning, the action it took and the observation the tool returned. Observations dominate. A file read, a directory listing or a test log can be thousands of tokens, while the reasoning and action around it are a few hundred. In the paper discussed below, observation tokens made up around 84 percent of an average SWE-agent turn in the authors' preliminary experiments.

Because every turn resends everything before it, input tokens grow roughly with the square of the number of turns. The usual answer is context management: shrink the history before each call. Two families dominate. LLM summarization asks a model to condense older turns into a running summary and keeps the most recent turns in full, as OpenHands does. Observation masking keeps every reasoning step and action but replaces observations older than a window with a short placeholder, as SWE-agent does. Summarization sounds smarter. This guide looks at what the evidence says, then measures both on a synthetic run with a cost model you can rerun.

What arXiv 2508.21433 found

Lindenbauer and colleagues, "The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management" (v1 29 August 2025, v3 27 October 2025, a DL4C workshop paper at NeurIPS 2025), compared the two within SWE-agent on SWE-bench Verified across five model configurations, with an OpenHands probe added in v3. Their findings, in their words and numbers:

  • Observation masking "halves cost relative to the raw agent while matching, and sometimes slightly exceeding, the solve rate of LLM summarization". For Qwen3-Coder 480B, masking moved the solve rate from 53.8 percent (raw agent) to 54.8 percent.
  • Masking used a rolling window of the last 10 turns; performance peaked at M=10 and fell again at M=20.
  • Summaries lengthened runs. For Gemini 2.5 Flash the mean trajectory with LLM summaries was 52 turns, 15 percent longer than masking's 44 turns. The authors read this as summaries "encouraging the agent to keep going", which eats the saving.
  • A hybrid of the two reduced cost a further 7 percent against masking and 11 percent against summarization.

Their scope is narrow and they say so: one benchmark family of software-engineering tasks, mostly one scaffold, and a 250-turn limit. It is evidence that the simple method is a strong baseline, not proof that it wins everywhere.

A cost model you can rerun

The companion example builds a synthetic 44-turn run with deterministic sizes: a 1,500-token system prompt, a 400-token task, 150 tokens of reasoning and 60 of action per turn, and observations between 300 and 2,500 tokens with a 6,000-token file or log every seventh turn. It then counts the input tokens of every model call under three strategies:

  • raw: the whole history every time;
  • mask: observations older than the last 10 turns become a 12-token placeholder;
  • summary: once 21 turns fall out of the 10-turn tail, a summarizer call reads them and produces a 700-token summary that replaces them.
def context_for_call(obs, t, strategy, m, n):
    base = SYSTEM + TASK
    if strategy == 'raw':
        return base + sum(REASON + ACTION + o for o in obs[:t])
    if strategy == 'mask':
        return base + sum(REASON + ACTION + (o if i >= t - m else PLACEHOLDER)
                          for i, o in enumerate(obs[:t]))
    if strategy == 'summary':
        done = (max(0, t - m) // n) * n
        return base + (SUMMARY_OUT if done else 0) + sum(REASON + ACTION + o for o in obs[done:t])
StrategyTurnsTotal input tokensRelative to rawLargest single context
raw442,151,0641.000101,292
mask, M=10441,081,6440.50335,840
summary, N=21, M=10441,601,3000.74469,817
summary, run 15 percent longer522,105,6280.97971,475

These are calculations over invented sizes, not measurements of any model. They show the mechanism. Masking cuts every call after turn 10 because old observations stop being resent. Summarization only cuts calls after the first summary, which in this run happens at turn 31, and it pays for an extra summarizer call that reads 48,197 tokens. If summaries make the run 15 percent longer, as the paper saw for one model, the saving almost vanishes. The window matters too: in this model masking costs 383,458 tokens at M=1, 711,967 at M=5, 1,081,644 at M=10 and 1,648,488 at M=20. A smaller window is cheaper; the paper found M=10 solved more tasks than M=5 or M=20 for their setup, so the cheapest window is not automatically the best.

Implementing masking without breaking the agent

The placeholder must tell the model that something was there. SWE-agent and the paper replace old observations with a fixed short string; a useful version says what was omitted and how to get it back:

def mask_history(turns, window=10):
    out = []
    for i, turn in enumerate(turns):
        if i < len(turns) - window and turn['observation_tokens'] > 50:
            turn = dict(turn, observation=f"[output of {turn['tool']} omitted; rerun the call to see it again]")
        out.append(turn)
    return out

A few rules keep it safe:

  • Never mask the reasoning or the action. The model needs to know what it already tried. Masking only the tool output preserves the plan.
  • Pin observations the task depends on. If an early tool call returned the order details for BK-1001, keep that result or copy the key facts into a short pinned note. Everything else can go.
  • Keep the masked content retrievable. Store full observations outside the context, so the agent can call the tool again or a debugger can see what happened.
  • Mask deterministically. The same history must produce the same masked prompt, or prompt caching stops working and debugging becomes guesswork.

Provider features follow the same idea. Anthropic's context editing, for example, has a clear_tool_uses_20250919 strategy that clears the oldest tool results server-side once the prompt passes a configured threshold, keeps a configured number of recent tool uses, and can exclude named tools from clearing; the client keeps the full history. Whether you use a provider feature or your own function, measure it the same way.

When summarization is worth it

Masking throws information away; summarization compresses it. Summaries help when the useful content of old observations cannot be recovered by calling the tool again (a page that has since changed, a long conversation with a person) or when the task spans more turns than any sensible window. They hurt when the summary loses a detail the agent later needs, when the summarizer call is expensive, and, as the paper observed, when summaries make the agent run longer. A hybrid that masks first and summarises only when the masked history still exceeds a budget captures most of both.

Failure modes to test for

  • Re-fetch loops. An agent that sees a placeholder may call the same tool again on every turn. Count repeated identical tool calls before and after enabling masking.
  • Lost constraints. A requirement that appeared only in an old observation disappears. Pin it or move it into the task.
  • Cache breakage. Changing the masked prefix on every turn defeats prefix caching. Masking that only changes turns as they leave the window keeps most of the prefix stable.
  • Comparing at different lengths. Report cost per solved task and turns per run, not only tokens per call; a strategy that makes runs longer can look cheap per call and expensive per task.

How to evaluate it on your own agent

Pick 50 to 100 tasks your agent already runs, run each under raw history, masking at two window sizes and your current summarizer, and record solve rate, total input tokens, turns per run and repeated tool calls. Run each configuration more than once if the agent is nondeterministic. Then compare cost per solved task. If masking matches your summarizer's solve rate at lower cost, as it did in the paper's setting, you can delete a model call from every long run. If it does not, the comparison tells you which information your agent actually needed from its past.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/observation_masking. Views are my own and do not represent any employer, past or present.