Skip to content
Preserved Thinking: Build a Prefix-Drift Guard in Python — ContentBuffer guide

Preserved Thinking: Build a Prefix-Drift Guard in Python

K
Kodetra Technologies··13 min read Intermediate

Summary

Claude now 400s agents that edit history. Catch the edit before the API does.

On October 12, Anthropic published its new distillation defenses and the numbers got a lot of attention: reasoning tokens extracted by distillers down 10 to 100 times, tens of thousands of accounts banned. Buried in the middle is the part that can break your code today. On Claude Fable 5.1, Opus 5.5, Sonnet 5.5 and Haiku 5.5, the API now checks that nothing before a returned thinking block has changed. If your account was created on or after August 31, 2026, a mismatch is a hard 400.

Plenty of ordinary agent code does exactly that kind of editing without anyone deciding to. A system prompt that includes the current time. A helper that shrinks old tool results to save tokens. A compaction routine that drops the middle of the history. Each one worked fine last month and now fails, usually with an error that says a block is 'bound to a different conversation' and nothing about which line of your code did it.

This guide builds a small, dependency-free guard that sits in front of your Messages API calls. It remembers what you sent last time, tells you the exact path of the first thing that changed, and names the documented replacement. You will also see the four most common ways agents trip this, each reproduced and fixed. Everything below was run; the output blocks are real.

What the API actually checks

Per the preserved thinking docs, every thinking or redacted_thinking block you send back is validated through its signature. There are two separate checks, and they fail differently.

CheckWhat must holdOn failure
Model readabilityThe model you call must be allowed to read the block (Fable 5.1 blocks are only readable by Fable 5.1 and Mythos 5.1, and so on down the family)Block silently dropped, request succeeds
Prefix integritysystem, tools and every earlier message are byte-identical to when the block was produced400 invalid_request_error by default on accounts created on or after Aug 31, 2026
Account binding (Sonnet 5.5, Haiku 5.5)Block was produced by your account or a linked oneDropped with reason organization_binding_mismatch, request succeeds

The expensive failure is the quiet one. If you opt into drop_block to keep requests alive, the model has to regenerate its reasoning each turn. Anthropic's own testing in the docs saw output tokens rise 67.1% at max effort when dropping on every turn. So the goal is not to catch the 400. It is to never rebuild the prefix at all.

Not affected: Claude Code, Cowork and claude.ai, which manage thinking blocks for you. This matters for anyone running their own agent loop on the API, Bedrock, Vertex AI or Foundry.

Prerequisites

  • Python 3.10+. The guard itself has no dependencies.
  • pip install anthropic only if you want to run the wrapper against the real API. The demo below uses a stub client so you can run it anywhere.
  • An API model that does preserved thinking, e.g. claude-opus-5-5 or claude-fable-5-1.

Step 1: Find the first byte that changed

Hashing the whole request tells you something changed, which you already know because you got a 400. What you need is the path. We convert SDK objects to plain data, then walk two structures in lockstep and return the first path where they differ. Paths use the same messages.1.content.0 style the API uses in its own error messages, so you can compare them directly.

"""prefix_guard.py - catch the edit that breaks Claude's preserved thinking."""
import copy
import json
from dataclasses import dataclass


def plain(x):
    """SDK objects -> plain JSON-able data, so we can hash and diff them."""
    if hasattr(x, "model_dump"):
        return x.model_dump(mode="json")
    if isinstance(x, dict):
        return {k: plain(v) for k, v in x.items()}
    if isinstance(x, (list, tuple)):
        return [plain(v) for v in x]
    return x


def canon(x) -> str:
    return json.dumps(plain(x), sort_keys=True, separators=(",", ":"))


def first_diff(a, b, path):
    """Return the deepest-first path where a and b differ, or None."""
    if type(a) is not type(b):
        return path
    if isinstance(a, dict):
        for k in sorted(set(a) | set(b)):
            if k not in a or k not in b:
                return f"{path}.{k}"
            d = first_diff(a[k], b[k], f"{path}.{k}")
            if d:
                return d
        return None
    if isinstance(a, list):
        if len(a) != len(b):
            return f"{path}.length"
        for i, (x, y) in enumerate(zip(a, b)):
            d = first_diff(x, y, f"{path}.{i}")
            if d:
                return d
        return None
    return None if a == b else path

Note canon() sorts keys. Dict ordering in your own code should not matter for the diff, but remember the API cares about bytes, so avoid anything that reorders blocks or fields on the way back out.

Step 2: The PrefixGuard class

The guard stores a deep copy of the last request's system, tools and messages. On the next call, the old messages must be a prefix of the new ones. It reports at most one message edit, because once one block is invalid every later one is too, and a wall of errors is no help.

It also lints thinking blocks, because two of the most common bugs are not edits at all: an assistant turn saved as a plain string, and a streaming parser that produces a thinking block with an empty signature.

@dataclass
class Drift:
    path: str
    kind: str
    hint: str

    def __str__(self):
        return f"[{self.kind}] {self.path}: {self.hint}"


class PrefixGuard:
    """Call check() right before every request. Empty list = append-only."""

    def __init__(self):
        self.prev = None  # deep copy of the last request's prefix

    def check(self, system, tools, messages, commit=True):
        now = {"system": plain(system), "tools": plain(tools),
               "messages": plain(messages)}
        drifts = []
        if self.prev is not None:
            if canon(now["system"]) != canon(self.prev["system"]):
                drifts.append(Drift("system", "system_rebuilt",
                    "Use a mid-conversation system message instead of rewriting `system`."))
            if canon(now["tools"]) != canon(self.prev["tools"]):
                drifts.append(Drift("tools", "tools_changed",
                    "Keep `tools` as first sent; use tool_addition / tool_removal blocks."))
            old = self.prev["messages"]
            if len(now["messages"]) < len(old):
                drifts.append(Drift("messages", "history_shortened",
                    f"{len(old)} messages last request, {len(now['messages'])} now. "
                    "Compact server-side, or summarize into ONE fresh user message."))
            else:
                for i, m in enumerate(old):
                    d = first_diff(m, now["messages"][i], f"messages.{i}")
                    if d:
                        drifts.append(Drift(d, "message_edited",
                            "An earlier turn changed. Everything after it loses its thinking."))
                        break  # later blocks are already invalid, one report is enough
        drifts += self.lint_thinking(now["messages"])
        self._pending = copy.deepcopy(now)
        if commit:
            self.commit()
        return drifts

    def commit(self):
        """Remember this request's prefix. Call it once the request was sent."""
        self.prev = self._pending

    @staticmethod
    def lint_thinking(messages):
        out, saw_thinking = [], False
        for i, m in enumerate(messages):
            if m.get("role") != "assistant":
                continue
            c = m.get("content")
            if isinstance(c, str):
                if saw_thinking:
                    out.append(Drift(f"messages.{i}", "content_collapsed",
                        "Assistant content stored as a plain string; thinking blocks were lost."))
                continue
            for j, b in enumerate(c):
                if b.get("type") == "thinking":
                    saw_thinking = True
                    if not b.get("signature"):
                        out.append(Drift(f"messages.{i}.content.{j}", "empty_signature",
                            "A thinking block with an empty signature is rejected. "
                            "Check your streaming accumulator and serializer."))
        return out

One design detail worth copying: check() takes commit=False. If you stage a request, find drift and decide not to send it, you do not want the guard to remember a prefix that never went out. Otherwise the second attempt sails through, which is exactly the false comfort you built this to avoid.

Step 3: A chat wrapper that refuses to send a drifting prefix

The wrapper uses the request shape from the docs: client.beta.messages.create with thinking={"type": "adaptive", "block_binding": {...}} and the beta header thinking-binding-controls-2026-08-01. That header is what makes input_transformations appear on the response, which tells you after the fact whether the API dropped anything.

"""chat.py - a thin Claude chat loop that refuses to send a drifting prefix."""
import logging
from prefix_guard import PrefixGuard, plain

log = logging.getLogger("chat")
BETA = "thinking-binding-controls-2026-08-01"


class PrefixDriftError(RuntimeError):
    pass


class GuardedChat:
    def __init__(self, client, model, system, tools=None, on_drift="raise"):
        self.client, self.model = client, model
        self.system, self.tools = system, tools or []
        self.messages, self.guard = [], PrefixGuard()
        self.on_drift = on_drift  # "raise" (default) or "drop"

    def ask(self, text):
        self.messages.append({"role": "user", "content": text})
        drifts = self.guard.check(self.system, self.tools, self.messages, commit=False)
        behavior = "error"
        if drifts:
            for d in drifts:
                log.warning("prefix drift: %s", d)
            if self.on_drift == "raise":
                self.messages.pop()
                raise PrefixDriftError("; ".join(map(str, drifts)))
            behavior = "drop_block"  # stopgap: costs extra output tokens

        kwargs = dict(
            model=self.model, max_tokens=16000, system=self.system,
            messages=self.messages,
            thinking={"type": "adaptive",
                      "block_binding": {"prefix_mismatch_behavior": behavior}},
            betas=[BETA],
        )
        if self.tools:
            kwargs["tools"] = self.tools
        resp = self.client.beta.messages.create(**kwargs)
        self.guard.commit()  # only remember the prefix once the request went out

        for t in (getattr(resp, "input_transformations", None) or []):
            t = plain(t)
            if t.get("reason") == "prefix_binding_mismatch":
                log.error("API dropped thinking at %s", t.get("path"))
            else:
                log.info("transformation: %s", t)

        # Store the content EXACTLY as returned. No filtering, no re-serializing.
        self.messages.append({"role": "assistant", "content": resp.content})
        return "".join(b.text for b in resp.content if b.type == "text")

Two rules in there are not negotiable. First, assistant content is stored as resp.content, untouched, because the docs say to keep the array exactly as returned, including thinking blocks whose thinking text is empty. Second, the default is to raise. on_drift="drop" exists as the documented stopgap, and it logs a warning every time so it cannot become permanent by accident.

Step 4: Run it

The demo uses a stub client that returns a thinking block plus a text block, so you can see the guard's behavior without an account. It then reproduces four bugs.

import datetime, logging
from types import SimpleNamespace as NS
from prefix_guard import PrefixGuard
from chat import GuardedChat, PrefixDriftError

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")

def fake_resp(i):
    return NS(content=[NS(type="thinking", thinking="", signature=f"sig{i}",
                          model_dump=lambda mode=None, i=i: {"type":"thinking","thinking":"","signature":f"sig{i}"}),
                       NS(type="text", text=f"answer {i}",
                          model_dump=lambda mode=None, i=i: {"type":"text","text":f"answer {i}"})],
              input_transformations=[])

class FakeClient:
    def __init__(self): self.n = 0; self.beta = NS(messages=NS(create=self.create))
    def create(self, **kw): self.n += 1; return fake_resp(self.n)

c = GuardedChat(FakeClient(), "claude-opus-5-5", "You are a release bot.")
print(c.ask("Plan the release."))
print(c.ask("Now list the risks."))

print("\n-- bug 1: timestamp injected into system prompt each turn")
c.system = f"You are a release bot. Now: {datetime.datetime(2026,10,13,20,5)}"
try: c.ask("Anything else?")
except PrefixDriftError as e: print("BLOCKED:", e)
try: c.ask("Anything else?")   # retry: still blocked, drift is not forgotten
except PrefixDriftError: print("BLOCKED again (drift not swallowed)")

print("\n-- bug 2: old tool_result shrunk in place")
g = PrefixGuard()
msgs = [{"role":"user","content":"run it"},
        {"role":"assistant","content":[{"type":"thinking","thinking":"","signature":"s1"},
            {"type":"tool_use","id":"t1","name":"sh","input":{"cmd":"ls"}}]},
        {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"x"*5000}]}]
print(g.check("sys", [], msgs))
msgs[2]["content"][0]["content"] = "x"*200 + " [trimmed]"
msgs.append({"role":"assistant","content":[{"type":"text","text":"ok"}]})
print([str(d) for d in g.check("sys", [], msgs)])

print("\n-- bug 3: assistant turn saved as plain text")
g = PrefixGuard()
m = [{"role":"user","content":"hi"},
     {"role":"assistant","content":[{"type":"thinking","thinking":"","signature":"s1"},{"type":"text","text":"yo"}]},
     {"role":"user","content":"more"},
     {"role":"assistant","content":"yo again"}]
print([str(d) for d in g.check("sys", [], m)])

print("\n-- bug 4: empty signature from a lossy stream parser")
g = PrefixGuard()
m = [{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":""}]}]
print([str(d) for d in g.check("sys", [], m)])

print("\n-- on_drift=drop")
c2 = GuardedChat(FakeClient(), "claude-opus-5-5", "base", on_drift="drop")
c2.ask("a"); c2.system = "changed"; print(c2.ask("b"))

Output:

answer 1
answer 2

-- bug 1: timestamp injected into system prompt each turn
WARNING prefix drift: [system_rebuilt] system: Use a mid-conversation system message instead of rewriting `system`.
BLOCKED: [system_rebuilt] system: Use a mid-conversation system message instead of rewriting `system`.
WARNING prefix drift: [system_rebuilt] system: Use a mid-conversation system message instead of rewriting `system`.
BLOCKED again (drift not swallowed)

-- bug 2: old tool_result shrunk in place
[]
['[message_edited] messages.2.content.0.content: An earlier turn changed. Everything after it loses its thinking.']

-- bug 3: assistant turn saved as plain text
['[content_collapsed] messages.3: Assistant content stored as a plain string; thinking blocks were lost.']

-- bug 4: empty signature from a lossy stream parser
['[empty_signature] messages.1.content.0: A thinking block with an empty signature is rejected. Check your streaming accumulator and serializer.']

-- on_drift=drop
WARNING prefix drift: [system_rebuilt] system: Use a mid-conversation system message instead of rewriting `system`.
answer 2

Look at the second bug. The first check() returns an empty list, because a fresh conversation has nothing to drift from. After the tool result is trimmed from 5,000 characters to roughly 200, the path comes back as messages.2.content.0.content. That is the exact field. You would not get that from the API's error text, which names the block that failed (messages.1.content.0), not the edit that caused it.

Worked example: four bugs and their documented fixes

These are the patterns the docs list as breaking the prefix, paired with what to do instead. Each fix keeps earlier bytes untouched.

Bug 1: a timestamp in the system prompt

The classic. system=f"... Now: {datetime.now()}" rebuilds the prefix on every request. Render the system prompt once and send changes as a mid-conversation system message, placed after the tool_result user message and never between a tool_use and its result:

{
  "role": "system",
  "content": "The user switched the workspace to read-only mode. Do not write files until told otherwise."
}

Leave it in place on later requests. If the note is only relevant for one turn, add "clear_at": "next_user_message" and the earlier copy costs no input tokens while staying in the array so later thinking stays valid. That one needs the mid-conversation-system-clear-at-2026-08-21 beta header.

Bug 2: shrinking old tool results in place

Long agent runs bloat with tool output, so people trim it. Trimming an earlier tool_result in the stored list is an edit. Either shorten it before the first send, or let the server do it with context editing (clear_tool_uses_20250919, beta header context-management-2025-06-27).

Bug 3: changing tools mid-session

Permission prompts that turn tools off, or plugins that register a new one after login, tend to mutate the tools list. Keep tools as first sent and use system-message blocks instead:

{
  "role": "system",
  "content": [
    { "type": "tool_removal", "tool": { "type": "tool_reference", "name": "delete_branch" } },
    { "type": "text", "text": "Branch deletion is disabled for the rest of this session." }
  ]
}

Adding a tool you declared up front with defer_loading: true works the same way with tool_addition. The docs recommend keeping at least one tool without defer_loading in the list. These need inline-tools-2026-09-15 (or the older mid-conversation-tool-changes-2026-07-01).

Bug 4: client-side compaction that keeps the tail

Summarize the old half, keep the last few turns, send both. It looks reasonable and it fails: the kept assistant turns carry thinking that was produced after the original turns, not after your summary. Two safe options. Use server-side compaction (compact-2026-09-04), or do the simple version the docs recommend: summarize the whole session into one user message and send only that plus the next instruction. Nothing earlier is replayed, so there is no stale thinking to reject.

If you must keep a tail with a hand-written summary, the docs show drop_block as the way through, and say plainly it is a stopgap:

response = client.beta.messages.create(
    model="claude-fable-5-1",
    max_tokens=16000,
    thinking={
        "type": "adaptive",
        "block_binding": {"prefix_mismatch_behavior": "drop_block"},
    },
    messages=compacted_messages,
    betas=["thinking-binding-controls-2026-08-01"],
)
print(response.input_transformations)

A dropped block shows up like this, and it is the entry worth alerting on:

{
  "input_transformations": [
    {
      "type": "thinking_dropped",
      "path": "messages.1.content.0",
      "reason": "prefix_binding_mismatch"
    }
  ]
}

Wiring it into a tool-use loop

The wrapper above does one turn per call. In a real agent, call guard.check() inside the loop, right before each create(), with the full list including the latest tool_result message. If you stream and assemble blocks yourself, the thinking block opens, receives its signature in a signature_delta event, and closes. Only append the assistant message after the stream ends, and run the guard once more before the next call. If empty_signature fires, your accumulator is dropping that event.

A cheap production setup: run the guard in every environment, raise in staging and CI, and in production log the drift and fall back to drop_block only for the sessions that need it. Store that choice with the session so a retry does not flip back.

Common pitfalls

  • Serializers that tidy up. Dropping unknown block types, omitting empty fields, or reordering blocks all change bytes. A pydantic model with exclude_none=True on the way back out is a frequent culprit. Store the SDK's content array as returned.
  • Failover across platforms. Sonnet 5.5 and Haiku 5.5 thinking is bound to the producing account. Switching from the Claude API to Bedrock mid-session drops it silently and the next response is slower and costs more. Accounts under the same Claude Platform parent organization or Google Cloud organization are linked automatically. Otherwise ask your account team to link them.
  • Changing model mid-conversation. Opus 5.5 cannot read Fable blocks. The request succeeds, but the blocks are dropped with model_binding_mismatch. Not an error, which is why it hides.
  • Older accounts feel safe. Enforcement is by default only for accounts created on or after Aug 31, 2026. Anthropic says it will expand with upcoming model launches, and the docs recommend staying append-only regardless of account age. Treat the guard as a migration you are doing early.
  • Cache effects. A stable prefix also lets prompt caching hit more often. Fixing drift can lower cost, not only remove errors.
  • Parameters are free. Changing max_tokens, tool_choice, metadata or top-level effort does not break the prefix, and moving cache_control markers is fine. The guard only watches system, tools and messages, matching that.
  • The guard compares against your last request, not the server's idea of it. If you restart your process and rehydrate history from a database, call check() on the rehydrated list first and compare against what you stored. Persist the raw content array, not a text rendering.
  • Not documented. The preserved thinking page does not say what a safeguard-blocked request returns or whether it is billed. Anthropic's post says that since September 24 it charges for requests its safeguards block before Claude responds. Check the refusals and fallback docs before building billing logic on that.

Quick reference

You want to...Do thisBeta header
Change instructions mid-sessionMid-conversation system messagenone
One-turn reminderSystem message with clear_at: next_user_messagemid-conversation-system-clear-at-2026-08-21
Disable or add a tooltool_removal / tool_addition blocksinline-tools-2026-09-15
Trim old tool outputclear_tool_uses_20250919 on the servercontext-management-2025-06-27
Compact historyServer-side compaction, or one fresh summary messagecompact-2026-09-04
Change effortPer-message output_configmid-conversation-output-config-2026-07-01
Keep going despite drift (stopgap)prefix_mismatch_behavior: drop_blockthinking-binding-controls-2026-08-01
See what was droppedRead response.input_transformationsthinking-binding-controls-2026-08-01

Next steps

  • Add the guard to your CI replay tests: record a real session, replay it through check(), and fail the build on any drift.
  • Emit Drift.kind as a metric. A spike in message_edited after a deploy points at a new helper rewriting history.
  • Alert on prefix_binding_mismatch in input_transformations. It is the signal that you are paying for regenerated reasoning.
  • Read Anthropic's earlier distillation post to understand why the API cares: the defenses are built on the idea that nobody legitimate needs to replay or rewrite a model's reasoning.

The honest caveat on this guide: I ran the guard and wrapper against synthetic transcripts and a stub client, not a live Fable or Opus account, so the request shape follows the docs rather than a captured response. The diffing logic is the part you can trust from the output above. Test the live path in staging before relying on it.


Sources: Anthropic, Strengthening our defenses against distillation attacks; Claude Platform Docs, Preserved thinking; Claude Help Center, Preserved thinking.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,617 newsletter subscribers.

Also get