Claude Context Management: Compaction, Pruning and Fresh Sessions

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D6 Context Management for Long-Running Sessions

👋 In plain words: Long chats and agents keep adding text to every request: old messages, tool outputs, logs. After a while the request gets slow, expensive, and Claude starts to lose track of the original instructions. This lesson shows you how to spot that early and which technique to use to fix it, one step at a time.

Advertisement

Context bloat is the slow failure of long-running Claude apps: costs creep up, answers drift away from the instructions, and eventually requests fail. The CCDV-F exam asks you to read the symptoms and pick the right fix. In this lesson you will measure how history grows, prune old tool output, use Anthropic’s context editing and compaction, isolate noisy work in subagents, and decide when a fresh session with a summary is the right call.

📖 What You’ll Learn: You will be able to measure context growth, choose between pruning, context editing, compaction, subagent isolation and fresh sessions, and implement each in Python.

🔑 Key terms

  • Context bloat: the history grows with content that no longer helps, such as old tool outputs.
  • Drift: the model’s behaviour moves away from its instructions as they get buried under newer content.
  • Pruning: your code removes or shortens old content before sending.
  • Context editing: an API feature (beta) that clears old tool results or thinking blocks for you.
  • Compaction: an API feature (beta) that summarises earlier context server-side when the input grows past a threshold.

🪜 Step 1: Measure the growth

You cannot manage what you do not measure. Count the tokens of the history before each call and log them:

📄 growth.py

import anthropic

client = anthropic.Anthropic()
history = []
log_chunk = "FAILED test_checkout_total - AssertionError: expected 90.00 got 100.00\n" * 40

for turn in range(1, 5):
    history.append({"role": "user", "content": f"Here is build log {turn}:\n{log_chunk}\nAnything new?"})
    tokens = client.messages.count_tokens(model="claude-opus-5-5", messages=history).input_tokens
    print(f"turn {turn}: history = {tokens:,} input tokens")
    history.append({"role": "assistant", "content": "Same checkout total failure as before."})

⌨️ Terminal

python growth.py

🖥️ Output (sample run)

turn 1: history = 784 input tokens
turn 2: history = 1,581 input tokens
turn 3: history = 2,377 input tokens
turn 4: history = 3,173 input tokens

Each turn adds a full log, so every request is bigger than the last, and you pay for the whole history again on each call. In an agent that reads files or runs tests, tool outputs grow even faster.

🪜 Step 2: Recognise the symptoms

Symptom in traces Likely cause Fix to choose
Input tokens climb every turn, mostly old tool results Stale tool output Prune tool results or use context editing
Model forgets early instructions or constraints in a long chat Instructions buried, drift Re-state rules with a mid-conversation system message; consider compaction
Requests approach the context window Very long session Compaction, or a fresh session with a summary
One subtask (a big search, a log scan) floods the main conversation Noisy exploration in the main context Subagent isolation: do it elsewhere and return a short result
The task changed completely Old context is irrelevant Start a fresh session
🎯 Exam focus: This table is the “Context Management for Long-Running Sessions” skill in one place: read the symptom, pick compaction, tool-output pruning, subagent isolation or a fresh session. Raising max_tokens or switching to a bigger model does not fix bloat.
Advertisement

🪜 Step 3: Prune old tool results yourself

The simplest technique works on any model and platform: before each call, replace the content of old tool results with a short stub, and keep the most recent ones:

📄 prune.py

import copy
import json


def prune_tool_results(messages: list, keep_last: int = 2, stub: str = "[old tool output removed]") -> list:
    """Return a copy where all but the last `keep_last` tool_result blocks are replaced by a stub."""
    pruned = copy.deepcopy(messages)
    positions = [(i, j) for i, m in enumerate(pruned) if isinstance(m["content"], list)
                 for j, b in enumerate(m["content"]) if b.get("type") == "tool_result"]
    for i, j in positions[:-keep_last] if keep_last else positions:
        pruned[i]["content"][j]["content"] = stub
    return pruned


history = []
for n in range(1, 5):
    history.append({"role": "assistant", "content": [{"type": "tool_use", "id": f"t{n}", "name": "run_tests", "input": {}}]})
    history.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"t{n}", "content": f"run {n}: " + "x" * 2000}]})

before = len(json.dumps(history))
after = len(json.dumps(prune_tool_results(history)))
print(f"characters before: {before:,}  after: {after:,}")
for m in prune_tool_results(history)[1::2]:
    print(m["content"][0]["tool_use_id"], "->", m["content"][0]["content"][:30])

⌨️ Terminal

python prune.py

🖥️ Output

characters before: 8,812  after: 4,848
t1 -> [old tool output removed]
t2 -> [old tool output removed]
t3 -> run 3: xxxxxxxxxxxxxxxxxxxxxxx
t4 -> run 4: xxxxxxxxxxxxxxxxxxxxxxx
  • The tool_use / tool_result pairs stay in place (the API needs every tool_use to have its result); only the bulky content is replaced.
  • Prune on a copy and keep the full history in your own logs for debugging.
⚠️ Watch out: Editing history changes the request prefix, which breaks prompt caching from that point on (Lesson 43), and on current models it can invalidate earlier thinking blocks (Lesson 16). Prune in big, rare steps rather than a little on every turn, or use the server-side features below, which Anthropic designed for this.
Advertisement

🪜 Step 4: Use context editing and compaction (beta)

Anthropic offers two server-side features on current models. Both are beta:

  1. Context editing clears old tool results (strategy clear_tool_uses_20250919) or thinking blocks (clear_thinking_20251015) before the model sees the request. Beta header: context-management-2025-06-27.
  2. Compaction summarises earlier context automatically when input reaches a trigger (150K tokens by default). Beta header: compact-2026-01-12, edit type compact_20260112. The response carries a compaction block that you must keep in the history.

📄 compaction.py

import anthropic

client = anthropic.Anthropic()
messages = []


def chat(text: str) -> str:
    messages.append({"role": "user", "content": text})
    r = client.beta.messages.create(
        betas=["compact-2026-01-12"],
        model="claude-opus-5-5",
        max_tokens=4000,
        messages=messages,
        context_management={"edits": [{"type": "compact_20260112"}]},
    )
    messages.append({"role": "assistant", "content": r.content})  # keep ALL blocks, including compaction
    return next(b.text for b in r.content if b.type == "text")


print(chat("We are triaging last night's 40 failures. Start with the checkout ones."))
print(chat("Now the login failures."))
print("turns kept:", len(messages))

⌨️ Terminal

python compaction.py

🖥️ Output (sample run)

The 6 checkout failures share one cause: the discount is not applied to the total.
The 3 login failures are lockouts from a shared test account used by parallel workers.
turns kept: 4
  • Append r.content, not just the text. If you keep only the text, the compaction state is lost.
  • Compaction and context editing are different: compaction summarises, context editing clears. Do not mix up their beta names.
  • These are beta features: check model and platform support in Anthropic’s documentation before relying on them.

🪜 Step 5: Isolate noisy work in a subagent

When one step needs lots of reading (scan 200 log files, search a large repo), do it in a separate call or subagent with its own context, and return only a short result to the main conversation:

📄 isolate.py

import anthropic

client = anthropic.Anthropic()


def scan_logs_in_isolation(logs: list[str]) -> str:
    """A separate conversation reads everything; only its short summary comes back."""
    joined = "\n".join(f"<log>{l}</log>" for l in logs)
    r = client.messages.create(
        model="claude-haiku-5-5", max_tokens=300, output_config={"effort": "low"},
        system="Summarise the distinct failure causes in at most 3 bullet points.",
        messages=[{"role": "user", "content": joined}],
    )
    return r.content[0].text


summary = scan_logs_in_isolation([f"worker {i}: TimeoutError waiting for #pay-button" for i in range(200)])
main_history = [{"role": "user", "content": f"<log_summary>\n{summary}\n</log_summary>\nWhat should we fix first?"}]
print("summary returned to the main conversation:\n" + summary)
print("main conversation size (chars):", len(str(main_history)))

⌨️ Terminal

python isolate.py

🖥️ Output (sample run)

summary returned to the main conversation:
- All 200 workers time out waiting for #pay-button: one shared cause, likely the payment iframe not loading on the test environment.
main conversation size (chars): 223

The main conversation receives a few hundred characters instead of 200 logs. Lesson 34 shows the same idea with Agent SDK subagents.

Advertisement

🪜 Step 6: Know when to start fresh

Start a new session (with a short handover summary) when:

  1. The task has changed: yesterday’s debugging has nothing to do with today’s feature.
  2. Drift persists after re-stating instructions.
  3. The session is near the context limit and a summary would lose little.

A good handover is short and structured: goal, decisions made, open items, key facts (IDs, file names). Generate it with Claude, then begin the new session with it as the first user message.

🌍 Real-world example: Ravi’s day-long triage chat

Ravi’s triage assistant ran in one conversation all day. By afternoon each request was over 300K tokens, mostly old test output, and the assistant had stopped following the “one-line answer” rule. He added pruning of tool results older than the last three, moved the log scan to an isolated Haiku call, and started a fresh session each morning from the previous day’s summary. Requests stayed under 30K tokens and the format rule held.

🧪 Practice Questions

Question 1. An agent’s traces show input tokens doubling every few turns, and 80% of the input is test-run output from earlier turns. Which fix targets the cause?

  • A. Switch to a model with a larger context window
  • B. Prune or clear old tool results (client-side pruning or context editing)
  • C. Raise max_tokens
  • D. Add more instructions to the system prompt
Show answer

Answer: B. The bloat comes from stale tool output. Removing it reduces cost and keeps the relevant context visible.

Question 2. A team enables compaction but appends only the response text to the history on each turn. What goes wrong?

  • A. Nothing; compaction is fully server-side
  • B. The compaction block is lost, so the summarised state is not carried forward
  • C. Every request returns 429
  • D. Thinking is disabled
Show answer

Answer: B. The compaction block in response.content must be passed back on later requests.

Question 3. A coding assistant must search 500 files to answer one question. Which approach keeps the main conversation small?

  • A. Paste all 500 files into the conversation
  • B. Run the search in an isolated subagent or separate call and return a short result
  • C. Use compaction on the main conversation after the search
  • D. Start a fresh session for every file
Show answer

Answer: B. Subagent isolation keeps exploration noise out of the main context; only the result is returned.

Question 4. Which two are good reasons to start a fresh session with a handover summary? (Choose 2.)

  • A. The user switched to an unrelated task
  • B. The last answer was short
  • C. Drift persists even after re-stating the instructions
  • D. The API returned one 529 error
Show answer

Answer: A and C. A new task or persistent drift means the old context hurts more than it helps. A transient error is not a context problem.

📝 Assignment

  1. Task 1: Add token counting before each call in one of your multi-turn scripts and plot (or print) growth over 10 turns.
    ✅ Done when: you can say which content type dominates the growth.
  2. Task 2: Write pytest tests for prune_tool_results: the last two results are untouched, earlier ones are stubbed, and every tool_use still has a matching tool_result.
    ✅ Done when: all three tests pass.
  3. Stretch: Write a handover_summary(messages) function that asks Claude for goal, decisions, open items and key facts as structured output, and start a new session with it.
    ✅ Done when: the new session answers a follow-up question correctly using only the summary.
Advertisement

❓ Frequently Asked Questions

🤔 What is context compaction in Claude?

A beta API feature that automatically summarises earlier parts of a long conversation when the input grows past a threshold, so the session can continue within the context window.

🤔 What is the difference between compaction and context editing?

Compaction summarises earlier context. Context editing clears specific content, such as old tool results or thinking blocks, without summarising.

🤔 Why does Claude forget instructions in long conversations?

As history grows, early instructions get buried among newer content. Re-state key rules with a mid-conversation system message, prune noise, or compact.

🤔 Does pruning history affect prompt caching?

Yes. Changing earlier content changes the request prefix, so the cache is invalidated from that point. Prune rarely and in larger steps.

🏁 Summary

  • Measure context growth with token counting before you optimise.
  • Stale tool output → prune or context editing; buried instructions → re-state or compact; huge exploration → isolate in a subagent.
  • Compaction and context editing are beta, server-side features; keep compaction blocks in the history.
  • Start fresh with a structured handover when the task changes or drift persists.
  • Editing history breaks caching and can invalidate thinking blocks; change it rarely.
📝 Test yourself: D6 Prompt and Context Engineering practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Citations: Ground Answers in Documents and Return Not Found.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.