Agent engineering · Advanced

Comparing Context-Management Strategies for AI Agents

Сравнение стратегий управления контекстом AI-агента
Temporary fallback cover; replace in editorial pass.

Keeping the full conversation is easy to reason about, but it becomes expensive and slow. Compacting too aggressively reduces those costs while risking the loss of facts the agent still needs. This article defines a reproducible experiment for comparing full history, periodic compaction, and per-action compaction by cost, context size, latency, and task quality.

35-minute read Updated 29 November 2026 Agent Lab Journal

The difficult part of an agent’s long-running task is rarely producing one more response. It is deciding which earlier information must remain available when the next action is selected. A full transcript preserves everything but sends an ever-growing payload. A compact summary sends less, but its omissions can be silent: a filename, constraint, failed attempt, or user preference may disappear without causing an immediate error.

This is a measurement problem, not a matter of choosing the most elegant prompt. The useful question is: for this workload, how much cost and latency can be removed before task quality becomes unacceptable? The answer depends on the model, provider, tool outputs, task length, compaction prompt, and evaluation set. No universal ranking is established here. Instead, this article provides a controlled comparison that you can run against your own agent.

1. The problem: useful memory has a price

An agent repeatedly receives a request, its prior state, tool results, and instructions before producing either a final answer or another tool call. The accumulated material is the agent’s working context. The model can only attend to material that fits inside its context window, and every provider may charge differently for input tokens, output tokens, cached tokens, and reasoning.

Let a run contain actions a1 ... an. For action i, define:

The simplest total-input measure is:

TotalInputTokens = Σ Ii

If an API publishes separate rates, an approximate run cost can be calculated as:

Cost = Σ (
  input_tokens × input_rate
  + output_tokens × output_rate
  + cached_input_tokens × cached_input_rate
)

Use the rates that apply to the selected provider and account. Do not substitute a remembered price: provider pricing and cache rules can change, and some systems report usage differently from the payload sent by the client.

2. Three strategies to compare

The experiment compares the same agent and workload under three state policies. The model, tools, instructions, temperature settings, retry policy, and stopping criteria must remain constant.

2.1 Full history

Full history appends every user message, assistant message, tool request, and tool result to the next request. It is the reference condition because it makes the fewest information-selection decisions.

context(i) =
  system_instructions
  + user_request
  + messages[1:i-1]

This strategy is not necessarily optimal. Large tool outputs may dominate the context even when only one line was useful. Repeated instructions may also consume input tokens without adding new information. Still, full history is a valuable baseline: a compacting policy should reduce resource use without materially reducing quality on the same tasks.

2.2 Periodic compaction

Compaction replaces older messages with a shorter representation. Under periodic compaction, the agent allows the context to grow until a threshold is reached, then creates a summary and continues from that summary plus a protected recent tail.

if estimated_tokens(context) >= COMPACTION_THRESHOLD:
    summary = compact(
        protected_facts,
        older_messages,
        compaction_instructions
    )
    context = [system_instructions, summary, recent_tail]

Periodic compaction is easy to reason about operationally. It limits how often the summarizer runs and creates relatively stable segments of history. Its weakness is timing: information may be compressed only after the context has already become large, and the compaction boundary may occur immediately before a fact is needed.

2.3 Per-action compaction

Under per-action compaction, the agent constructs a fresh action context for every model call. It selects the current objective, persistent facts, relevant prior results, and the minimum recent trace needed to explain the next action.

context(i) =
  system_instructions
  + task_state
  + relevant_facts(i)
  + recent_trace(i)
  + current_tool_observation(i)

This is closer to explicit state management than transcript management. It can keep the context small even during long runs, but the selector becomes a new source of failure. If relevance detection is wrong, the agent may lose information that full history would have preserved.

3. A concrete case: repairing a small repository

Use a task with several dependent actions rather than a one-shot question. For example:

Inspect a repository, identify why a test fails, make the smallest safe change, run the relevant checks, and report the files changed, commands run, and any remaining uncertainty.

This case creates the conditions that make context management meaningful:

For a reproducible run, create a fixture repository with a known failing test and a documented expected fix. Keep the fixture free of credentials and personal data. Do not use a production repository for the initial comparison: accidental writes, changing dependencies, and unrelated files make quality scores difficult to interpret.

4. Define the workload before measuring

Write the task set before running any strategy. A useful set contains short, medium, and long traces, plus tasks that stress different memory properties.

Suggested workload categories
Category What it tests Example requirement
Recent fact Retention of the latest observation Use the error from the most recent test run.
Early constraint Retention of an initial instruction Do not modify the public API.
Negative evidence Retention of failed attempts Do not repeat the already-rejected fix.
Cross-step dependency Connecting a discovery to a later action Use the configuration file identified during inspection.
Final reporting Accurate provenance and verification Report only checks actually executed.

Keep each task’s expected outcome in a separate evaluator file. The agent must not receive the answer key. Include both positive requirements and forbidden behavior. A task that asks only for a final text answer may hide state-loss failures that would be obvious in an execution trace.

5. Make the state policies explicit

Before the first run, record the exact policy parameters. At minimum, capture:

A compact configuration can look like this:

{
  "model": "REPLACE_WITH_MODEL_ID",
  "temperature": 0,
  "max_steps": 24,
  "state_policy": "periodic",
  "compaction": {
    "trigger_input_tokens": 12000,
    "recent_tail_messages": 8,
    "preserve": [
      "original acceptance criteria",
      "user constraints",
      "files changed",
      "commands executed",
      "test failures and successful checks",
      "unresolved questions"
    ]
  }
}

The values above are configuration examples, not measured recommendations. Choose a threshold that fits the model’s supported context and then keep it fixed across repeated runs of the same condition.

6. Instrument every model action

Do not infer context size from the number of messages. Tool output can be large, and tokenization differs by model. Record the usage fields returned by the API whenever available. Also record the serialized request size and a hash of the state, so that two runs can be compared without storing sensitive content.

{
  "run_id": "opaque-run-id",
  "task_id": "fixture-03",
  "strategy": "periodic",
  "step": 7,
  "input_tokens": 0,
  "output_tokens": 0,
  "cached_input_tokens": 0,
  "request_bytes": 0,
  "latency_ms": 0,
  "compaction_count": 0,
  "context_message_count": 0,
  "state_hash": "sha256:...",
  "tool_name": "test_runner",
  "tool_exit_code": 0
}

Use zero or an explicit null only as a placeholder in the schema. A real run should populate the value from the provider response or a local tokenizer. If a provider does not return a usage field, label the measurement as unavailable rather than presenting an estimate as an observed result.

For latency, record at least:

Separating these values matters. A strategy can reduce the main prompt while adding enough compaction work to make the total run slower.

7. Reference pseudocode

The following pseudocode shows the control flow. It deliberately leaves provider-specific calls abstract.

for task in workload:
    for strategy in ["full", "periodic", "per_action"]:
        state = initial_state(task)
        trace = []

        for step in range(MAX_STEPS):
            if strategy == "full":
                action_context = full_history(state)

            elif strategy == "periodic":
                if estimate_tokens(state.context) >= THRESHOLD:
                    state.context = compact_context(
                        state.context,
                        preserve=PRESERVE_RULES
                    )
                action_context = state.context

            elif strategy == "per_action":
                action_context = build_action_context(
                    task=state.task,
                    facts=state.facts,
                    recent_trace=state.recent_trace,
                    current_observation=state.observation
                )

            response = model_call(action_context)
            usage = read_usage(response)
            trace.append(record_step(state, response, usage))

            if response.is_final:
                break

            observation = execute_tool(response.tool_call)
            state = update_state(state, response, observation)

        save_trace(task, strategy, trace)

In a real implementation, make state transitions explicit. A hidden mutation inside the message list can cause one strategy to receive data that another strategy does not. Keep the raw trace for auditing, but construct the next request from the strategy’s state policy.

8. Compaction instructions should preserve facts, not prose

A summary that merely “captures the conversation” may sound coherent while omitting operational details. Use a structured output with fields that an evaluator can inspect.

Summarize the working state for a later agent action.

Return valid JSON with these fields:
{
  "task_goal": "...",
  "hard_constraints": ["..."],
  "facts": [
    {"fact": "...", "source_step": 0, "confidence": "observed|inferred"}
  ],
  "files_and_artifacts": [
    {"path": "...", "status": "unchanged|changed|created|deleted"}
  ],
  "commands_run": [
    {"command": "...", "exit_code": 0, "result": "..."}
  ],
  "failed_attempts": [
    {"attempt": "...", "why_it_failed": "..."}
  ],
  "open_questions": ["..."],
  "next_action": "..."
}

Do not invent values. Preserve exact paths, identifiers, constraints,
exit codes, and quoted error tokens when they affect the next action.
If a field is unknown, use null or an empty array.

Structured summaries are easier to validate than free-form summaries, but they are not automatically correct. The compactor can still omit a fact, misclassify an inference as an observation, or report a command that was proposed rather than executed. Treat the summary as an artifact that needs tests.

9. Per-action selection needs a relevance contract

Per-action compaction is often described as “include only what is relevant.” That phrase is too vague to reproduce. Define relevance as a contract for each action type.

Example action-context contract
Action Must include May omit
Inspect files Goal, path constraints, repository root Old tool output unrelated to the path
Apply change Acceptance criteria, target file, observed cause Exploratory output not supporting the change
Run tests Files changed, test command, prior failed commands Unrelated discovery logs
Report result Actual changes, executed commands, exit codes, uncertainty Internal reasoning not needed by the reader

The evaluator should test both inclusion and exclusion. A small context is not a success if it omits a hard constraint. Conversely, retaining every old message means the selector is not achieving its intended purpose.

10. Quality must be scored independently of token usage

Cost and context size are not quality metrics. Use a fixed rubric and score each completed run without looking at the strategy label where practical.

A useful rubric has binary gates and graded dimensions:

  1. Task completion: did the agent reach the expected end state?
  2. Constraint adherence: did it respect all hard constraints?
  3. Change correctness: is the resulting artifact correct?
  4. Verification accuracy: did it run and report the required checks?
  5. State fidelity: did it retain required facts and distinguish observations from assumptions?
  6. Recovery behavior: after a failed attempt, did it adapt rather than repeat the same action?

Define failure severity before running the experiment. For example, losing a cosmetic preference may be minor, while violating a “do not modify” constraint is a critical failure. Report both the aggregate score and the count of critical failures. A high average can hide a dangerous failure mode.

11. Compare distributions, not one lucky run

Agent responses can vary even when the prompt is unchanged. Run each task under each strategy multiple times when the system permits it. Keep the workload and configuration fixed, and record the run identifier for every result.

For each strategy, calculate:

mean_input_tokens
median_input_tokens
p95_input_tokens
mean_total_cost
median_total_latency
p95_total_latency
compaction_overhead
quality_score
critical_failure_rate
completion_rate

Use medians and upper percentiles for operational planning. A strategy with a low average but occasional extremely large contexts may still create unacceptable latency or context-limit failures.

Do not compare raw token totals across different model tokenizers without qualification. Within one controlled experiment, the same tokenizer makes relative comparisons useful. Across providers, report the tokenizer and usage definition alongside the number.

12. The result table should make missing evidence visible

Populate a table like the following only after the runs are complete:

Measured comparison template
Strategy Median input tokens P95 input tokens Median latency Quality Critical failures
Full history Not measured Not measured Not measured Not measured Not measured
Periodic compaction Not measured Not measured Not measured Not measured Not measured
Per-action compaction Not measured Not measured Not measured Not measured Not measured

Leaving cells marked “Not measured” is preferable to filling them with plausible-looking values. Once you have real traces, include the workload version, model identifier, tokenizer, number of runs, and scoring rubric next to the table.

13. Verification checklist

Before interpreting the comparison, verify the experiment itself.

A practical verification command can validate the trace schema before any quality analysis:

jq -e '
  type == "array" and
  all(.[]; has("run_id") and
        has("task_id") and
        has("strategy") and
        has("step") and
        has("latency_ms"))
' traces/*.json

This checks only the shape of the files. It does not prove that the values are correct. Add separate checks for non-negative durations, valid strategy names, unique step numbers, and consistency between the recorded tool exit code and the actual tool result.

14. Failure cases to test deliberately

Fact dropped during compaction

Place a hard constraint early in the conversation, trigger compaction, and require the later action to respect it. The evaluator should mark a violation as a critical failure even if the final artifact otherwise looks correct.

Summary confuses an intention with an executed action

Have the agent propose a command but make the tool call fail or never execute. The final report must not claim that the command ran. This tests whether the state representation preserves provenance.

Large tool output overwhelms the policy

Return a long log with one relevant error near the end. Compare whether each strategy keeps the error, records its location, and avoids copying the entire log into every future action.

Repeated failure is forgotten

Make an initial fix fail for a known reason. A later action should use that evidence to choose a different approach. If the agent repeats the same failed action, record the failure as a state-fidelity or recovery defect.

Compaction itself becomes the bottleneck

Measure compaction calls as first-class model requests. A policy can lower the action context while increasing total input tokens because it repeatedly sends the same history to a summarizer.

Context selection leaks stale state

Change a fact during the task, such as the current file path or test status. The evaluator should check that the latest authoritative observation wins and that the old value is not reused merely because it remains in a cached summary.

15. Limitations and interpretation

This comparison cannot establish a strategy that is best for all agents. The result is workload-dependent. A coding agent with expensive tool output has different pressures from a customer-support agent with short turns and stable account facts. The model’s instruction-following behavior also affects whether a structured summary is reliable.

There are additional limitations:

For these reasons, report the boundary of the claim. A defensible conclusion looks like: “Under workload version X, model configuration Y, and the stated scoring rubric, strategy Z reduced the measured input-token distribution while maintaining the observed quality threshold.” It should not become: “Strategy Z is universally best.”

16. A practical decision rule

After measuring, choose a policy according to an explicit constraint:

Choose the least expensive strategy such that:
  quality_score >= minimum_quality
  critical_failure_rate <= maximum_failure_rate
  p95_latency_ms <= latency_budget
  context_limit_failures == 0

If full history meets the budget and has materially better quality, its simplicity may be worth the extra tokens. If the history grows beyond the context limit, periodic compaction is a reasonable intermediate policy. If long runs require predictable action contexts and the selector can be verified, per-action compaction may be appropriate.

Many production systems use a hybrid: preserve a small set of durable facts, retain a recent trace, compact older material at a threshold, and construct a task-specific action context. That design is not a fourth experimental result unless you measure it. Treat it as a candidate policy and include it in the same comparison if it is under consideration.

Conclusion

Context management is a trade-off between retained evidence and request overhead. Full history gives the agent maximum access to prior material but can increase cost, latency, and context-limit risk. Periodic compaction controls growth with a relatively simple policy but introduces summary loss at discrete boundaries. Per-action compaction can keep requests small and targeted, but its relevance selector becomes part of the system that must be tested.

The reproducible path is straightforward: define a multi-step workload, freeze the model and tools, instrument every action and compaction call, score quality independently, run repeated trials, and publish only values traceable to recorded runs. Until those runs exist, the correct result is an experiment plan—not an invented winner.

For related implementation patterns, continue with the Agent Lab Journal guides or look up terms in the glossary.

We publish what works for us—and implement the same solutions for your business. We design AI automation, Telegram bots, chats, and AI agents for real-world processes. Discuss your project →