Introduction
AI coding agents can work on a task for much longer than a traditional chat assistant. They inspect repositories, read source files, execute commands, analyze test failures, modify code, and repeat the process until the task is complete.
The problem is that every interaction adds more information to the agent's working context.
Eventually, the agent has to decide what historical information should remain available and what can be compressed or removed. This process is generally called context compaction.
Compaction sounds straightforward: make the context smaller.
In practice, the strategy used to reduce context can significantly affect agent quality, latency, tool usage, and the amount of work the model has to repeat.
For example, an agent could compact:
After every fixed number of tool calls
When the context reaches a token threshold
Only when the model reports context pressure
At natural task boundaries
By summarizing everything
By preserving structured state and discarding raw history
These approaches are not equivalent.
This article presents a practical framework for benchmarking context compaction strategies in AI coding agents and explains how to measure whether a strategy actually improves the overall workload.
Why Context Compaction Matters
Consider an agent working on a moderately complex .NET application.
During one task, it might produce:
User request
|
+--> Repository search
|
+--> Project structure
|
+--> Read source files
|
+--> Read tests
|
+--> Modify implementation
|
+--> Build
|
+--> Test
|
+--> Analyze failure
|
+--> Modify again
|
+--> Test again
Every step can add context.
A long session may eventually contain:
Task
+ Conversation
+ Source snippets
+ Tool calls
+ Tool results
+ Compiler output
+ Test output
+ Failed approaches
+ Architectural decisions
+ Generated code
Keeping all of this indefinitely is expensive and can make the context difficult to manage.
But removing too much information creates another problem.
The agent may forget:
Why a design decision was made
Which files were already modified
Which approach failed
What tests are still failing
Which repository constraints matter
What the user originally requested
Therefore, context compaction is an optimization problem rather than a simple token-reduction exercise.
What Is Context Compaction?
Context compaction transforms a large conversation or agent history into a smaller representation.
For example:
Before:
Task
|
+-- User request
+-- Search results
+-- File A
+-- File B
+-- Build output
+-- Test output
+-- Failed implementation
+-- New implementation
+-- Final test output
After:
Task
|
+-- Objective
+-- Modified files
+-- Important decisions
+-- Known failures
+-- Current state
+-- Remaining work
The second representation is smaller, but ideally it retains the information necessary to continue the task.
A successful compaction strategy should reduce unnecessary context without forcing the agent to rediscover important information.
The Main Compaction Strategies
There are several strategies worth benchmarking.
Fixed-Interval Compaction
The simplest approach is to compact after a fixed number of model or tool calls.
For example:
Every 20 tool calls
|
v
Compact context
|
v
Continue task
This is easy to implement but does not consider the actual content of the context.
A task may need compaction after 8 large tool results while another task may remain efficient after 30 small interactions.
Token-Threshold Compaction
Another approach is to compact when context reaches a configured size.
Context size
|
v
Threshold reached?
|
Yes
|
v
Compact
This is more adaptive than a fixed call count.
However, token count alone does not tell you how valuable the information is.
Two contexts with the same number of tokens can have very different information density.
Event-Driven Compaction
A more intelligent strategy is to compact when the agent reaches a meaningful workflow event.
For example:
Implementation complete
|
v
Run tests
|
v
Compaction checkpoint
|
v
Analyze failures
This can preserve important boundaries between phases of work.
Structured-State Compaction
Instead of asking the model to summarize the entire conversation, the system maintains explicit task state.
For example:
{
"objective": "Add retry support to PaymentService",
"modifiedFiles": [
"PaymentService.cs",
"PaymentServiceTests.cs"
],
"decisions": [
"Use bounded exponential backoff"
],
"knownFailures": [
"Timeout test still fails"
],
"remainingWork": [
"Fix timeout handling"
]
}
This approach can be more deterministic because important information does not depend entirely on a free-form summary.
A Benchmark Should Compare Strategies, Not Just Token Counts
A common mistake is to define success as:
Smaller context = Better strategy
That is incomplete.
Suppose Strategy A reduces context by 60% but causes the agent to reread files repeatedly.
Strategy B reduces context by only 35% but allows the agent to complete the task with fewer tool calls.
Strategy B may be better overall.
A useful benchmark therefore measures:
| Metric | What it tells you |
|---|---|
| Context tokens | How much context is processed |
| Compaction count | How frequently compaction occurs |
| Tool calls | How much additional work the agent performs |
| Model calls | Overall inference activity |
| Task success | Whether the agent actually completes the task |
| Rediscovery rate | How often information must be obtained again |
| Latency | End-to-end completion time |
| Cache reuse | How much prior context remains reusable |
| Error rate | Whether compaction causes incorrect decisions |
| Cost estimate | Relative resource consumption |
The benchmark should evaluate the complete workload.
Designing a Representative Task Set
Do not benchmark compaction using only one coding task.
A useful test suite should contain several workload categories.
Small Tasks
Examples:
Rename a method
Add a validation rule
Fix a simple unit test
These determine whether compaction is unnecessary overhead.
Medium Tasks
Examples:
Add a service
Modify an API endpoint
Update persistence logic
Add integration tests
These create enough history for compaction to matter.
Large Tasks
Examples:
Refactor a subsystem
Migrate an API
Debug multiple test failures
Implement a cross-layer feature
These are useful for measuring long-session behavior.
Failure-Heavy Tasks
Include tasks where the first implementation does not work.
For example:
Implement
|
v
Build fails
|
v
Fix
|
v
Tests fail
|
v
Investigate
|
v
Fix again
These workloads are particularly useful because the agent needs to remember previous failures and decisions.
Establishing a Baseline
Before testing compaction, create a baseline with no intentional compaction.
Strategy 0
---------
No compaction
Full available history
Record:
Total context tokens
Total model calls
Total tool calls
Completion time
Task success
This baseline provides a reference point.
Without it, you cannot determine whether compaction actually improved the workload.
Building a Simple Benchmark Harness
A benchmark runner can represent each strategy explicitly.
public interface ICompactionStrategy
{
bool ShouldCompact(AgentContext context);
AgentContext Compact(AgentContext context);
}
A token-based strategy could look like:
public sealed class TokenThresholdStrategy
: ICompactionStrategy
{
private readonly int _threshold;
public TokenThresholdStrategy(int threshold)
{
_threshold = threshold;
}
public bool ShouldCompact(AgentContext context)
{
return context.TokenCount >= _threshold;
}
public AgentContext Compact(AgentContext context)
{
return context.CreateSummary();
}
}
A fixed-call strategy could use tool-call count instead:
public sealed class ToolCallStrategy
: ICompactionStrategy
{
private readonly int _interval;
public ToolCallStrategy(int interval)
{
_interval = interval;
}
public bool ShouldCompact(AgentContext context)
{
return context.ToolCallCount > 0 &&
context.ToolCallCount % _interval == 0;
}
public AgentContext Compact(AgentContext context)
{
return context.CreateSummary();
}
}
The important part is not the implementation itself.
It is the ability to run the same task workload against different strategies.
Keep the Benchmark Controlled
A useful benchmark needs to control variables that could otherwise distort the result.
Keep the following consistent where possible:
Same repository snapshot
Same task description
Same tool catalog
Same model configuration
Same temperature or generation settings where applicable
Same test environment
Same maximum execution time
Same tool permissions
Same initial agent state
Join the conversation! Your thoughts help the community grow.