A response contains a compaction block, so your persistence code deletes earlier messages. But the block’s content is null: there is no replacement summary. On the next request, the application has discarded the very history it still needs. Handling Claude API compaction blocks correctly begins with this distinction between a returned block and a usable summary.

Consider an implementation that is almost finished. The assistant has changed a database migration and discovered a failing rollback fixture. If the persistence boundary loses that unresolved check, a later continuation may propose deployment before the work is ready.

For a product built on the native Messages API, Claude API compaction is an application continuity problem. The model needs a useful account of earlier work. Your application needs an accurate account of what happened, what remains unresolved, and what it is authorized to do next. Those records overlap, but they serve different purposes.

The architecture decision in this article is to keep the application’s task record outside the model summary and preserve returned content blocks as structured data. Start with an append-only conversation representation. Make history reduction a later, independently tested change. This gives a long-running implementation task a recoverable boundary without asking a summary to become a database, test runner, or approval system.

The migration scenario is illustrative. The code below is an offline storage test; no paid compaction request or production result is being reported.

Define the boundary you are implementing

This article covers threshold compaction in the native Claude Messages API. The relevant controls are context_management.edits, the compact_20260112 edit, and beta compact-2026-01-12. The threshold guide documents a default trigger of 150,000 input tokens, a minimum of 50,000, and optional pause_after_compaction. Custom instructions replace the default summary prompt.

These settings identify the feature; they are not a reason to generate a huge request for a demonstration. First prove that the application can save and recover the necessary structures. Request sizing belongs in the separate Claude API token counting guide.

The Messages API reference describes stateless multi-turn conversation input. In this design, the application owns the conversation it sends. That makes persistence an explicit responsibility: a successful previous response is useful only if the next worker can reconstruct the intended continuation.

If you are operating a terminal session instead of building this API boundary, use the separate Claude Code `/compact` guide. A command inside a coding product does not specify your service’s database schema or recovery policy.

Keep the task ledger authoritative

Imagine a task called import-retry-migration. A developer asked the assistant to add retry handling while keeping an existing import interface stable. During implementation, the assistant found that a rollback migration deletes a field too early. Another engineer is reviewing the interface change. A test process is still running.

A fluent summary could say that the migration is ready except for final checks. That wording leaves several operational questions unanswered. Which revision was tested? Is the running process checking the newest files? Did the reviewer approve the current interface or an earlier draft? Is a deployment allowed, or was the assistant only asked to prepare a patch?

Give those questions explicit application records:

RecordExample contentOwner of the truth
Task contractPreserve import compatibility; prepare a reviewable patchApproved task brief
Workspace revisionCommit or content revision associated with the patchRepository and workspace service
EvidenceRollback test failed against revision R17Test runner and stored output
Open decisionReviewer has not accepted the interface adjustmentReview workflow
Action statusDeployment has not been requestedApplication permission state
Next checkpointInspect failing rollback fixture before proposing completionTask coordinator

This is a proposed schema, not a set of Claude fields. The summary can point to these records and explain why they matter. It should not silently update them. For example, the phrase “tests look good” must not change a failed test row into a passed test row. Only a recorded execution against the relevant revision can do that.

The same separation helps when work moves between engineers or agents. A new worker can read the task contract, load the current revision, and inspect unresolved evidence even if the conversational explanation is incomplete. You preserve task state after Claude compaction by keeping the state inspectable outside the prose that describes it.

Preserve the compaction block as a protocol object

The beta Messages schema includes compaction blocks and encrypted_content. It specifies round-tripping these blocks and treating null-content blocks as no-ops. Treat opaque fields as provider-owned data: preserve them without decoding, recreating, or editing them.

Build two consumers of a response. The renderer extracts appropriate user-visible text. The conversation store retains the full returned content array, including ordering and block types. A helper called get_text() may be appropriate for a chat bubble. It is an unsafe foundation for saving the next request’s conversation.

In the migration example, a response might contain a compaction block followed by text describing the next investigation. Saving only the text loses the protocol object. Saving only the summary loses the subsequent turn. Reconstructing a new “equivalent” summary creates an application-authored message with a different provenance. All three failures can be introduced by an innocent display-layer convenience function.

The initial implementation should therefore append the assistant role and its complete content array to the existing message sequence. Keep response-level diagnostics separately. Do not put the entire response envelope into a message’s content; message content and response metadata occupy different places in the application model.

For a Python SDK integration, choose the documented beta message surface and serialize according to the current SDK. The official SDK overview distinguishes direct API clients from higher-level agent runtimes. Record the installed SDK version in the pilot because a client upgrade belongs to the tested configuration. Our offline example uses plain JSON dictionaries, so it isolates storage behavior from SDK conversion behavior.

Treat a null summary as retained history

A compaction block with content: null does not establish a replacement summary. Keep the earlier messages. The threshold guide also notes that blocked summaries can return a different stop reason; inspect the block instead of using one stop-reason string as proof of successful compaction. With a usable block, earlier content is ignored by the API; retaining it locally is supported.

This makes an append-only policy attractive for the first release. Both the usable-summary path and the null-summary path retain a complete local record. Your service does not need to decide which old rows to delete while also handling a newly introduced beta response shape. Database retention and the request representation can evolve separately later.

There is a subtle UI consequence. A null result is not a completed implementation, and it is not evidence that the earlier instructions vanished. The task remains at its last verified checkpoint. Show the task’s real status, such as “rollback check pending,” instead of deriving a progress milestone from the word compaction.

Avoid an automatic loop that keeps requesting compaction until a summary appears. Decide how a paused or blocked task returns to its coordinator, with an explicit continuation limit. The policy for tool-driven pause_turn belongs to the separate server-tool continuation guide; it should not be folded into this persistence function.

Prepare a native request without inventing a block

This request template is for a route whose native support has already been confirmed. Supply the exact agreed base URL, model ID, and key through environment variables. It is shown for integration and was not executed. The Python SDK documentation documents base_url, max_retries=0, and to_dict(); betas sets the beta header. Keep the SDK’s API version in the recorded configuration.

import os
from anthropic import Anthropic


def request_next(history):
    with Anthropic(
        api_key=os.environ["CLAUDE_API_KEY"],
        base_url=os.environ["CLAUDE_BASE_URL"],
        max_retries=0,
    ) as client:
        response = client.beta.messages.create(
            model=os.environ["CLAUDE_MODEL_ID"],
            max_tokens=1024,
            betas=["compact-2026-01-12"],
            messages=history,
            context_management={
                "edits": [{"type": "compact_20260112"}]
            },
        )
        raw = response.to_dict()
    return append_response(history, raw), raw

Here, history must come from the application’s real conversation store. The append_response helper appears below. The returned pair separates the next message sequence from the response envelope you may retain for diagnostics. No synthetic compaction content is inserted into the request. A short history will not demonstrate threshold compaction; this template defines the request contract, not a forced-compaction test.

Prove the storage boundary offline

The following standard-library test uses deliberately synthetic storage fixtures. They are not valid captured provider responses and must never be sent as substitute compaction blocks. It manufactures neither signatures nor encrypted payloads. The null encrypted_content field tests whether JSON null survives a save and reload.

from copy import deepcopy
import json


def append_response(history, response):
    if response["role"] != "assistant":
        raise ValueError("Expected an assistant response")
    updated = deepcopy(history)
    updated.append({
        "role": "assistant",
        "content": deepcopy(response["content"]),
    })
    return updated


def storage_round_trip(value):
    return json.loads(json.dumps(value, ensure_ascii=False))


original = [{"role": "user", "content": "Keep migration 017 reversible."}]
original_snapshot = deepcopy(original)
for reason in ("compaction", "refusal"):
    response = {
        "role": "assistant",
        "stop_reason": reason,
        "content": [{
            "type": "compaction",
            "content": None,
            "encrypted_content": None,
        }],
    }
    saved = storage_round_trip(append_response(original, response))
    assert saved[:-1] == original_snapshot
    assert saved[-1]["content"] == response["content"]
    assert saved[-1]["content"][0]["content"] is None

# Synthetic summary for local storage testing only.
response = {
    "role": "assistant",
    "stop_reason": "end_turn",
    "content": [
        {"type": "compaction", "content": "Migration 017 awaits rollback test."},
        {"type": "text", "text": "Next, inspect the rollback fixture."},
    ],
}
saved = storage_round_trip(append_response(original, response))
assert saved[-1]["content"] == response["content"]
assert saved[:-1] == original_snapshot
response["content"][1]["text"] = "Mutated after saving"
assert saved[-1]["content"][1]["text"] == "Next, inspect the rollback fixture."
assert original == original_snapshot
print("PASS: null histories, block order, restart serialization, copy isolation")

This fixture was run locally and passed. It checks retained history for both stop reasons, complete ordered content, JSON round-trip behavior, and isolation from later mutation. It does not prove model recall, gateway support, acceptance of a live compaction block, or recovery from an interrupted network stream.

Use the same assertions around your real persistence adapter. In particular, test the database column, queue envelope, and reload path used by a fresh worker. A successful in-memory copy does not tell you whether an ORM drops null fields or a queue consumer flattens content arrays. Keep the raw response available in a controlled diagnostic record while developing that boundary, subject to your application’s existing data policy.

Make recovery a task transaction

The next failure to consider is a process crash. Suppose the service receives a compaction response, displays the next step, and exits before saving the message. A replacement worker then reloads the earlier conversation. The user has seen progress that the durable task record cannot explain.

Commit the response record and the task’s next checkpoint together, or use a durable event that allows both to be reconstructed consistently. Give the received response an application-level deduplication key. If the same event is delivered twice, the second delivery should not append a duplicate assistant turn or schedule the next job twice.

This is an application design recommendation, not an Anthropic exactly-once guarantee. The useful invariant is straightforward: either the next worker sees the saved boundary and its checkpoint, or it sees neither and can recover from the previous durable state. A transport retry policy cannot establish that invariant on its own.

Keep task evidence versioned as work continues. If a new patch changes the rollback function, an earlier passing test becomes historical evidence rather than current acceptance. Rehydrating a summary must not make old evidence look new. The coordinator should ask for the missing check against the current revision before marking the migration complete.

Confirm the gateway contract before a selected-model pilot

For a TreeRouter deployment, native beta compaction support is unverified here. Confirm support for the exact account, selected model, and native Messages route before planning a live test. An ordinary text response does not establish preservation of beta controls or nontext blocks.

The beta-header documentation specifies the anthropic-beta opt-in mechanism. The API-version documentation separately describes anthropic-version. Record both in the route contract; a beta name and an API version are different configuration values.

Ask the route owner to confirm that context_management reaches the intended provider, that the selected edit is supported, and that returned compaction blocks retain all fields on subsequent requests. Also confirm what happens when a field is unsupported: an explicit rejection is actionable, while silent omission leaves the application believing a feature is active when it is not.

Then choose one real implementation task with written acceptance criteria and a limited test budget. Capture the confirmed model identifier, base URL, authentication method, SDK version, and headers in a private configuration record. Keep keys out of logs. Use naturally accumulated history appropriate to the task rather than padding a request merely to cross a threshold.

The pilot should answer a product question: after the boundary and a worker restart, does the assistant identify the unresolved rollback check, retrieve the correct revision, and continue from the actual checkpoint? Have an evaluator compare its next action with the task ledger. A polished continuation that ignores the failed check is a failed trial.

Save transport evidence as well. The official error guide documents error types and request identifiers. Connect those diagnostics to your application task ID so a route problem can be separated from an acceptance failure. For incomplete answers, follow the existing truncated-response diagnosis.

If native support is confirmed, get started with TreeRouter and run this one-task continuity pilot before expanding the workflow. Evaluate the recovered task and its evidence, then decide whether the route belongs in the application.

Frequently asked questions

Does a good summary replace the task database?

No. A summary explains prior work. Your application still needs independent records of revisions, test outcomes, unresolved reviews, and authorized actions. A summary can help the model find those records, but it should not be allowed to manufacture a passed check or an approval.

Should we delete old history immediately?

For the initial design, retain it and test continuation first. Later pruning needs separate recovery, audit, and schema tests. Never treat a null compaction result as a deletion boundary. The potential storage saving does not justify losing the only record of an unresolved requirement.

Can we validate this with a tiny API request?

A small request can check ordinary connectivity and some request validation. It cannot prove that threshold compaction occurred or that a resumed implementation remains correct. Separate offline persistence checks from a confirmed, bounded live pilot, and label the evidence from each accurately.

What if the task also uses many tools?

Keep the compaction persistence boundary independent of tool catalog design and tool-result repair. Use the existing Claude tool search guide for catalog decisions and the tool-result contract guide for identifiers and ordering. Combining these changes in the first pilot makes failures harder to locate.

References

Official technical references checked on November 16, 2026:

  1. Compaction at a token threshold
  2. Beta Messages schema
  3. Create a Message
  4. Beta headers
  5. API versions
  6. Claude API errors
  7. Official SDKs, CLI, and libraries
  8. Python SDK configuration and serialization