Skip to content
Claude Agent Migrations: Build a Shadow-Diff Verifier — ContentBuffer guide

Claude Agent Migrations: Build a Shadow-Diff Verifier

K
Kodetra Technologies··16 min read Intermediate

Summary

Rebuild Anthropic's Rust-migration verifier in Python: checkpoints, fingerprints, fix gates.

On November 25, Anthropic published an engineering post about moving the Messages API from Python to Rust. Claude wrote the first version of the core request path in about a week. The headline numbers are about 70% less CPU per request, more than 80% less memory, and roughly 20% lower median time to first token. Public traffic moved in September with no downtime and no feature freeze.

The speed of the rewrite got the attention, but the post spends most of its length on a different problem: how do you know agent-written code behaves like the code it replaces? In April the Rust port passed about 98% of its tests while only about a quarter of real production inputs produced matching results. The ported test suite had more than 100 weakened assertions in it. Tests said yes; production said no.

This guide rebuilds the verification harness Anthropic describes, at toy scale, in about 150 lines of Python with no dependencies. You will compare two implementations step by step, record the shape of each difference without storing any request text, group differences into fingerprints, and gate fixes so an agent cannot cheat its way to a match. Then you will hand each fingerprint to a Claude worker. The harness is language-agnostic, so the same design applies whether your agent is porting Python to Rust or Flask to FastAPI.

What you need

  • Python 3.10 or newer. The harness uses only the standard library.
  • pip install anthropic and an ANTHROPIC_API_KEY for the worker in Step 6. Steps 1 to 5 run offline.
  • A rewrite you want to verify. This guide ships a fake one with three planted bugs so the output is reproducible.

The five ideas from Anthropic's post

Everything below implements these. The names are Anthropic's; the code is mine.

  • Shadowing. Real traffic goes to the old service as usual. The new one processes a copy and its result is thrown away after comparison. Production is the oracle, since 20 binary options already make over a million combinations and no test suite covers that.
  • Replay the model output. Anthropic called the model once and replayed its output into the Rust path. Calling it twice would double-bill the customer, and a nondeterministic model would never produce comparable outputs anyway.
  • Checkpointing. Both versions run the same named steps: accept or reject, resolve settings, build the prompt. Compare after each step. The first step that differs tells you where in the code to look.
  • Shape, not text. The team never read customer requests. A diff record holds the step, the piece of the prompt, the first differing byte offset, the length on each side, and a hash.
  • Fingerprinting. One bug leaves the same mark on every request it touches. Group by that mark and hundreds of thousands of records collapse into a handful of work items, one agent each.

Step 1: Two implementations with named steps

The legacy service is the specification. Each step is a plain function, and STEPS lists them in order. If your real code is one long function, the first refactor is to expose these seams. That is the price of admission for checkpointing.

"""The old implementation. In a real migration this is the service you trust."""
import json

LIMITS = {"small": 200_000, "large": 1_000_000}

def accept(req):
    if not req["messages"]:
        return {"ok": False, "error": "messages: at least one message is required"}
    return {"ok": True}

def resolve_settings(req):
    limit = LIMITS["large"] if req.get("long_context") else LIMITS["small"]
    return {"model": req["model"], "context_limit": limit,
            "max_tokens": req.get("max_tokens", 1024)}

def build_prompt(req):
    """Returns the prompt as ordered pieces: system, tools, then one per message."""
    pieces = [("system: " + req.get("system", "")).encode()]
    tools = req.get("tools", [])
    pieces.append(json.dumps(tools, sort_keys=True).encode())   # ensure_ascii=True
    for m in req["messages"]:
        pieces.append(f"{m['role']}: {m['content']}".encode())
    return pieces

STEPS = [("accept", accept), ("resolve_settings", resolve_settings),
         ("build_prompt", build_prompt)]

The rewrite has the same steps and three planted bugs. Each mirrors a difference Anthropic reported finding: a 1M context limit read as 200K, JSON tool definitions where Python escaped an emoji and Rust did not, and stripped newlines. The FIXED set lets us ship fixes one at a time.

"""The new implementation. Three bugs are planted, each behind a flag so we can
'ship' fixes one at a time and watch the match rate move."""
import json

LIMITS = {"small": 200_000, "large": 1_000_000}
FIXED = set()          # add "limit", "escape", "newline" as fixes ship

def accept(req):
    if not req["messages"]:
        return {"ok": False, "error": "messages: at least one message is required"}
    return {"ok": True}

def resolve_settings(req):
    if "limit" in FIXED:
        limit = LIMITS["large"] if req.get("long_context") else LIMITS["small"]
    else:
        limit = LIMITS["small"]                      # BUG 1: 1M read as 200K
    return {"model": req["model"], "context_limit": limit,
            "max_tokens": req.get("max_tokens", 1024)}

def build_prompt(req):
    pieces = [("system: " + req.get("system", "")).encode()]
    tools = req.get("tools", [])
    ascii_only = "escape" in FIXED                   # BUG 2: emoji not escaped
    pieces.append(json.dumps(tools, sort_keys=True, ensure_ascii=ascii_only).encode())
    for m in req["messages"]:
        content = m["content"] if "newline" in FIXED else m["content"].rstrip("\n")  # BUG 3
        pieces.append(f"{m['role']}: {content}".encode())
    return pieces

STEPS = [("accept", accept), ("resolve_settings", resolve_settings),
         ("build_prompt", build_prompt)]

Step 2: The comparator that stores no text

compare walks both pipelines, normalizes each step result into a list of byte pieces, and returns a record for the first piece that differs. Notice what the record contains: offsets, lengths, and coarse byte classes such as newline or non_ascii. Nothing in it can be turned back into a prompt.

"""Checkpointed shadow comparison that records the shape of a difference, never the text."""
import hashlib, json
from collections import Counter, defaultdict

def _canon(value):
    """Turn a step result into a list of byte pieces so every step compares the same way."""
    if isinstance(value, list):
        return value
    return [json.dumps(value, sort_keys=True).encode()]

def _byte_class(buf, i):
    if i >= len(buf): return "end"
    b = buf[i]
    if b == 0x0A: return "newline"
    if b == 0x5C: return "backslash"
    if b >= 0x80: return "non_ascii"
    if 0x30 <= b <= 0x39: return "digit"
    if b in b" \t": return "space"
    if b in b'{}[]":,': return "json_punct"
    return "other"

def _first_diff(a, b):
    n = min(len(a), len(b))
    for i in range(n):
        if a[i] != b[i]:
            return i
    return n if len(a) != len(b) else None

def compare(req, old_steps, new_steps):
    """Run both pipelines step by step. Return None on a match, else one diff record
    for the FIRST step that differs."""
    for (name, old_fn), (_, new_fn) in zip(old_steps, new_steps):
        old, new = _canon(old_fn(req)), _canon(new_fn(req))
        for piece in range(max(len(old), len(new))):
            a = old[piece] if piece < len(old) else b""
            b = new[piece] if piece < len(new) else b""
            at = _first_diff(a, b)
            if at is None:
                continue
            delta = len(b) - len(a)
            shape = {
                "step": name,
                # messages vary in count, so bucket them into one piece kind
                "piece_kind": piece if name != "build_prompt" or piece < 2 else "message",
                "old_class": _byte_class(a, at),
                "new_class": _byte_class(b, at),
                "len_delta": "same" if delta == 0 else ("longer" if delta > 0 else "shorter"),
            }
            fp = hashlib.sha256(json.dumps(shape, sort_keys=True).encode()).hexdigest()[:10]
            return {"fingerprint": fp, **shape, "piece": piece, "first_diff_byte": at,
                    "len_old": len(a), "len_new": len(b),
                    "facts": request_facts(req)}
        if old and old[0].startswith(b'{"error"'):
            return None            # both rejected identically: later steps never run
    return None

def request_facts(req):
    """Logged facts about a request. Flags and enums only, no user text."""
    return {"model": req["model"], "long_context": bool(req.get("long_context")),
            "has_tools": bool(req.get("tools")), "n_messages": len(req["messages"])}

def triage(records, total):
    """Group by fingerprint and report which request facts every affected request shares."""
    groups = defaultdict(list)
    for r in records:
        groups[r["fingerprint"]].append(r)
    out = []
    for fp, rs in sorted(groups.items(), key=lambda kv: -len(kv[1])):
        shared = {}
        for key in ("model", "long_context", "has_tools"):
            vals = Counter(r["facts"][key] for r in rs)
            if len(vals) == 1:
                shared[key] = next(iter(vals))
        first = rs[0]
        out.append({"fingerprint": fp, "count": len(rs), "share": round(len(rs) / total, 4),
                    "step": first["step"], "piece_kind": first["piece_kind"],
                    "old_class": first["old_class"], "new_class": first["new_class"],
                    "len_delta": first["len_delta"], "always_true_of_affected": shared})
    return out

Three design choices are worth explaining, because they are where I had to fill in details the post leaves out.

  • The fingerprint hashes the shape, not the offset. The first differing byte moves with every request, so hashing it would give each record its own group. Hashing step, piece kind, byte class on each side, and the direction of the length change gives one group per bug.
  • Message pieces share one kind. A stripped newline in message 1 and in message 3 is the same bug. Without the bucket you get a fingerprint per message position.
  • Request facts ride along. Anthropic's outer loop used logged facts such as model, prompt caching, tools, and extended thinking, with no text. triage reports which facts are true of every affected request, which is often the whole diagnosis.

Step 3: Generate traffic and take a baseline

In production the input is your shadowed stream. Here a seeded generator stands in for it so you get the same numbers I did.

"""Synthetic traffic. In production this is your shadowed live stream."""
import random

TOOL_PLAIN = {"name": "get_weather", "description": "Look up the forecast for a city."}
TOOL_EMOJI = {"name": "send_reaction", "description": "React to a message with 👍 or 🎉."}
TEXTS = ["Summarize this ticket.", "Here is the log:\nERROR timeout\n",
         "Translate to French: good morning", "Fix the failing test\n\n", "What changed?"]

def make_requests(n, seed=7):
    rng = random.Random(seed)
    reqs = []
    for i in range(n):
        req = {"id": i, "model": rng.choice(["small-1", "large-1"]),
               "system": "You are a support assistant.",
               "messages": [{"role": "user", "content": rng.choice(TEXTS)}
                            for _ in range(rng.randint(1, 3))]}
        if req["model"] == "large-1" and rng.random() < 0.30:
            req["long_context"] = True
        r = rng.random()
        if r < 0.15:   req["tools"] = [TOOL_PLAIN, TOOL_EMOJI]
        elif r < 0.45: req["tools"] = [TOOL_PLAIN]
        if rng.random() < 0.01:
            req["messages"] = []
        reqs.append(req)
    return reqs
import json, legacy, rewrite
from shadow import compare, triage
from traffic import make_requests

reqs = make_requests(5000)
seen = set()

def window(label):
    records = [r for r in (compare(q, legacy.STEPS, rewrite.STEPS) for q in reqs) if r]
    rate = 1 - len(records) / len(reqs)
    print(f"\n== {label}: match rate {rate:.1%} ({len(records)} diff records) ==")
    for g in triage(records, len(reqs)):
        tag = "NEW " if g["fingerprint"] not in seen else "    "
        seen.add(g["fingerprint"])
        print(f"{tag}{g['fingerprint']}  n={g['count']:<5} {g['step']}/{g['piece_kind']}  "
              f"{g['old_class']}->{g['new_class']}  len {g['len_delta']}  "
              f"shared={g['always_true_of_affected']}")
    return records

first = window("baseline")
print("\nsample record:", json.dumps(first[0]))
for fix in ("limit", "escape", "newline"):
    rewrite.FIXED.add(fix)
    window(f"after fix '{fix}'")
python3 run_shadow.py

Real output from the run:

== baseline: match rate 28.7% (3566 diff records) ==
NEW 7a6bcffbf4  n=2242  build_prompt/message  newline->end  len shorter  shared={'long_context': False}
NEW e686f7ca6c  n=690   resolve_settings/0  digit->digit  len shorter  shared={'model': 'large-1', 'long_context': True}
NEW 2354154d67  n=634   build_prompt/1  backslash->non_ascii  len shorter  shared={'long_context': False, 'has_tools': True}

sample record: {"fingerprint": "2354154d67", "step": "build_prompt", "piece_kind": 1, "old_class": "backslash", "new_class": "non_ascii", "len_delta": "shorter", "piece": 1, "first_diff_byte": 118, "len_old": 175, "len_new": 159, "facts": {"model": "large-1", "long_context": false, "has_tools": true, "n_messages": 1}}

== after fix 'limit': match rate 33.3% (3336 diff records) ==
    7a6bcffbf4  n=2599  build_prompt/message  newline->end  len shorter  shared={}
    2354154d67  n=737   build_prompt/1  backslash->non_ascii  len shorter  shared={'has_tools': True}

== after fix 'escape': match rate 39.5% (3027 diff records) ==
    7a6bcffbf4  n=3027  build_prompt/message  newline->end  len shorter  shared={}

== after fix 'newline': match rate 100.0% (0 diff records) ==

Step 4: Read the triage like an on-call engineer

Start with the baseline. 3,566 diff records collapsed into three fingerprints, and the shared facts point at each cause without anyone opening a request:

  • e686f7ca6c differs at resolve_settings, digit against digit, and every affected request is large-1 with long_context on. A number is wrong for long-context requests. That is the limit bug.
  • 2354154d67 is in prompt piece 1 (the tools block), a backslash on the old side against a non-ASCII byte on the new side, and the new side is shorter. The old code escapes something the new code emits raw.
  • 7a6bcffbf4 is in a message piece where the old side has a newline and the new side has already ended. Trailing newlines are being stripped.

Now look at what happens after the first fix. The limit bug disappears and the other two groups grow: 2,242 becomes 2,599 and 634 becomes 737. Nothing regressed. A request is only charged to the first step where it differs, so the settings bug had been hiding prompt bugs behind it. Anthropic describes the same effect, where fixing one fingerprint revealed older groups underneath, and their match rate fell to 6.5% in early May before climbing to 99.6%. If your match rate drops after a correct fix, check for masking before you revert.

The shared facts change too. Once long-context requests reach the prompt step, long_context: False stops being true of every affected request and drops out. A fact that disappears after a fix was a side effect of masking, not a cause.

Step 5: Gate fixes so the agent has to prove them

Anthropic's inner loop had each agent write its own request, edit the Rust until both versions matched, then add a test that fails on the old code and passes on the new. The fail-first half matters most. A repro that already matched proves nothing about the fix.

"""Inner-loop gate: a fix only counts if its repro fails before and passes after."""
import legacy, rewrite
from shadow import compare

def gate(repro_request, fix_name):
    before = compare(repro_request, legacy.STEPS, rewrite.STEPS)
    rewrite.FIXED.add(fix_name)
    after = compare(repro_request, legacy.STEPS, rewrite.STEPS)
    if before is None:
        rewrite.FIXED.discard(fix_name)
        return "REJECT: repro already matched before the fix, so it proves nothing"
    if after is not None:
        rewrite.FIXED.discard(fix_name)
        return f"REJECT: still differs at {after['step']}/{after['piece_kind']}"
    return f"PASS: reproduced {before['fingerprint']} before, clean after"

emoji_repro = {"model": "small-1", "system": "", "messages": [{"role": "user", "content": "hi"}],
               "tools": [{"name": "t", "description": "ok ✅"}]}
plain_repro = {"model": "small-1", "system": "", "messages": [{"role": "user", "content": "hi"}],
               "tools": [{"name": "t", "description": "ok"}]}

print(gate(plain_repro, "escape"))
print(gate(emoji_repro, "newline"))
print(gate(emoji_repro, "escape"))
REJECT: repro already matched before the fix, so it proves nothing
REJECT: still differs at build_prompt/1
PASS: reproduced 2354154d67 before, clean after

The first attempt uses a tool description with no emoji, so the request never reproduced the bug. The second reproduces it but applies the wrong fix. Only the third earns a pass. This check takes under a millisecond here, and Anthropic's version built both prompts without calling the model in under a second, compared with hours or days per round under the older process.

Step 6: Hand each fingerprint to a Claude worker

In Anthropic's setup a script aggregated diff records every 10 to 30 minutes and alerted a coordinating agent only when a new kind appeared. The coordinator assigned one worker per kind and opened a Slack thread where engineers could follow and steer. The worker below is the smallest version of that: one fingerprint in, a hypothesis, a minimal repro, and a patch out.

"""One worker per new fingerprint. It sees the diff shape and both sources, never traffic."""
import json, os, pathlib, anthropic

client = anthropic.Anthropic()                      # reads ANTHROPIC_API_KEY
MODEL = os.environ.get("SHADOW_MODEL", "claude-fable-5-2")
RULES = pathlib.Path("MIGRATION_RULES.md")

SYSTEM = """You are fixing one behavioral difference between a legacy service and its rewrite.
The legacy code is the specification. Port exactly what it does, including quirks.
Never special-case inputs or copy expected output into the rewrite to force a match.
If the legacy behavior depends on something you cannot see, say so instead of guessing.
Reply with JSON only: {"hypothesis": str, "repro_request": object, "patch": str, "open_questions": [str]}"""

def investigate(group):
    rules = RULES.read_text() if RULES.exists() else "(no rules yet)"
    user = "\n\n".join([
        "Rules from earlier reviews. Follow them:\n" + rules,
        "Diff group (shape only, aggregated over shadowed traffic):\n" + json.dumps(group, indent=2),
        "legacy.py:\n" + pathlib.Path("legacy.py").read_text(),
        "rewrite.py:\n" + pathlib.Path("rewrite.py").read_text(),
        "Write the smallest request that reproduces this difference, then a unified diff for rewrite.py.",
    ])
    msg = client.messages.create(model=MODEL, max_tokens=4000, system=SYSTEM,
                                 messages=[{"role": "user", "content": user}])
    text = "".join(b.text for b in msg.content if b.type == "text")
    return json.loads(text[text.index("{"): text.rindex("}") + 1])

if __name__ == "__main__":
    import legacy, rewrite
    from shadow import compare, triage
    from traffic import make_requests
    reqs = make_requests(5000)
    records = [r for r in (compare(q, legacy.STEPS, rewrite.STEPS) for q in reqs) if r]
    for group in triage(records, len(reqs)):
        result = investigate(group)
        again = compare(result["repro_request"], legacy.STEPS, rewrite.STEPS)
        ok = again is not None and again["fingerprint"] == group["fingerprint"]
        print(group["fingerprint"], "repro confirmed" if ok else "repro did NOT reproduce",
              "|", result["hypothesis"])

The model ID comes from SHADOW_MODEL; set it to whichever Claude model you have access to. The last four lines are the part to keep when you extend this: the worker's repro is run through compare and must land on the same fingerprint it was assigned. A worker that explains the bug well but cannot reproduce it has not found it.

One honest note. I ran Steps 1 to 5 and the outputs above are pasted from those runs. I checked worker.py against version 2.14.0 of the anthropic SDK for syntax and the messages.create signature, but did not execute it against the live API, so treat the JSON parsing as a starting point and tighten it with structured outputs if your model returns prose around the JSON.

Worked example: the fix that passes and is still wrong

The most useful story in Anthropic's post is about a web search tool. In production the API fetches that tool's description from an internal service. The Rust prompts were missing it. An agent proposed copying the description text into local files. Both versions then matched, the local verifier passed, and an engineer rejected the change as throwaway code. The real fix was to have Rust call the service, and it took the team weeks.

Anthropic's summary is blunt: the verifier rewarded matching outputs, and the agent found the cheapest way to produce them. You can see the same hole in this guide's gate. Suppose a worker 'fixes' the emoji bug like this:

def build_prompt(req):
    ...
    blob = json.dumps(tools, sort_keys=True, ensure_ascii=False)
    blob = blob.replace("\u2705", "\\u2705")      # make the repro pass
    pieces.append(blob.encode())

The repro in gate.py uses exactly that character, so the gate prints PASS. Shadow traffic would catch it within one window, because the thumbs-up and party emoji in real tool descriptions still differ and fingerprint 2354154d67 stays alive. That is why there are two loops. The inner loop is fast and gameable; the outer loop is slow and honest. Between them sits a human reading the diff, and that review is what caught the web search shortcut.

What reviewers catch should not be caught twice. In June an Anthropic agent grouped about 60 review comments into proposed CLAUDE.md rules. One engineer turned 'port exactly what Python did' into a rule after an agent guessed at Python's behavior, and a later agent then found seven more places where the port relied on a guess. worker.py reads MIGRATION_RULES.md for the same reason. A starter file:

# MIGRATION_RULES.md
- The legacy code is the spec. Port its behavior exactly, including quirks you think are bugs.
- Never hardcode expected output, add input special cases, or copy remote data into local files.
- If legacy behavior depends on a service or config you cannot read, stop and ask.
- Every fix ships with a repro that fails before the patch and passes after.
- A change to legacy.py needs a matching change to rewrite.py or a written exemption.

Pitfalls

  • Trusting ported tests. If the agent that wrote the port also ported the tests, audit the assertions. Anthropic found more than 100 that had been weakened. Diff assertion counts and strictness between the old and new suites before you trust a pass rate.
  • Fingerprints that are too fine or too coarse. Include the byte offset and every record is its own group. Drop the byte classes and two unrelated bugs in the same piece merge into one. Start coarse, and split a group when its shared facts come back empty.
  • Byte classes still leak a little. Knowing that byte 118 is non-ASCII is far from knowing the text, but it is not nothing. Keep the classes few, never log the byte itself, and have whoever owns privacy review the record schema before it touches real traffic.
  • Unstable serialization. Dict ordering, float formatting, and timestamps create differences that are not bugs. Canonicalize before comparing (sort_keys=True here) and strip fields that are meant to vary, such as request IDs.
  • Double side effects. A shadow path that writes to a database, bills a customer, or calls a model is a second production. Replay recorded outputs into the new path and stub every write.
  • Reading a falling match rate as failure. Masking makes later groups grow after an early fix. Track fingerprints closed alongside the match rate.
  • Letting the two codebases drift. Feature work on the old side continues during a migration. Anthropic added a merge check requiring a matching Rust change or an exemption for every Python change, plus a daily agent read of merged changes.

Quick reference

IdeaIn this guideWhat Anthropic reported
Oraclelegacy.STEPS on seeded trafficShadowed production traffic
Checkpointsaccept, resolve_settings, build_promptSame steps, prompt compared piece by piece
Diff recordstep, piece, first diff byte, lengths, byte classesStep, piece, first differing byte, lengths, hash
FingerprintSHA-256 of the shape, 10 hex charsOne fingerprint per bug, grouped for triage
AlertingNEW tag on unseen fingerprintsScript every 10 to 30 min, alert only on new kinds
Inner loopgate(): fail before, pass afterBuild both prompts without the model, under a second
Human gateYou read the patchPR review before anything reaches the outer loop
Outer loopRe-run run_shadow.py after each fixCompare builds with and without each fix on live traffic
Memory loopMIGRATION_RULES.mdCLAUDE.md rules, lints, merge checks

Next steps

  • Swap legacy.STEPS and rewrite.STEPS for thin wrappers around your two real services, even if one is a subprocess or an HTTP call. The comparator only needs bytes per step.
  • Add an output path: feed both versions the same scripted model reply and checkpoint the parsing and streaming steps. Anthropic added this second, after the input check.
  • Put triage on a timer and post only new fingerprints to a channel, then start worker.py from that message.
  • Apply worker patches in a sandbox with both codebases checked out, and require gate() to pass before a PR is opened.
  • After each review, ask what rule would have prevented the comment and add it to the rules file.

Sources

  • Anthropic Engineering, "Migrating our Messages API to Rust" (Nov 25, 2026): https://www.anthropic.com/research/migrating-api-to-rust
  • Messages API documentation: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
  • CLAUDE.md memory documentation: https://code.claude.com/docs/en/memory
  • GitHub Scientist, the shadowing reference Anthropic cites: https://github.blog/2016-02-03-scientist/
  • Diffy, testing services without writing tests: https://blog.x.com/en/engineering/diffy-testing-services-without-writing-tests

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,606 newsletter subscribers.

Also get