Why Passing Tests Don't Prove a Python-to-Rust API Rewrite Is Safe

Why Passing Tests Don't Prove a Python-to-Rust API Rewrite Is Safe

pr0h0••26 min read•coding
AI Usage (87%)
On this page

A Passing Test Suite Is Not Proof That a Python-to-Rust API Rewrite Is Safe

Passing tests after a Python-to-Rust API rewrite prove that the new code satisfies its assertions. They do not prove the API is safe for existing clients. This post uses the supplied reporting on a Claude-assisted migration of the Anthropic Messages API as a case study, separates what those reports establish from what they leave out, and builds a locally runnable differential lab—Python reference gateway, Rust candidate, deterministic upstream stub, and comparator—that demonstrates a compatibility bug a green suite can miss. The production evidence that matters is differential testing, staged traffic, observability, and rollback planning.

What the Supplied Reporting Claims About the Rewrite

The supplied reporting makes two related claims. On 25 November 2026, Unite.AI, Crypto Briefing, and Digg ran headlines about a Claude-assisted migration of the Messages API from Python to Rust. Digg went further: the tests weren't enough. InfoWorld followed on 26 November 2026, reporting that Anthropic had moved its Claude API from Python to Rust with no downtime.

Those are headline claims from secondary sources. I haven't seen an Anthropic engineering report on the migration, and I couldn't confirm one exists. So when I say "what Anthropic did" below, I mean "what the reports say." When I talk about how to prove a rewrite safe, that part is mine.

My position is simple: a green test suite after a language rewrite proves very little. It shows the new code satisfies assertions written mostly by the same people—or, increasingly, the same model—that wrote the new code. Production compatibility is a stronger claim: every client that relied on the old wire behavior still gets behavior it can use. Those are different evidence problems. Treating them as the same is how a rewrite ships "successfully" while quietly breaking a group of SDKs.

Scope of This Walkthrough: A Reproducible Differential Lab

I'll do two things. First, look at what the supplied reporting actually establishes—and what it leaves out. Second, build a small, complete, locally runnable differential lab: a Python reference gateway, a Rust candidate gateway, a deterministic upstream stub, and a comparator. It demonstrates a compatibility bug you can introduce in an afternoon.

The lab is illustrative. The pinned versions below are not meant to match Anthropic's stack, and the fixtures are not reconstructions of anyone's production traffic.

What the Reporting Establishes About the Python-to-Rust Rewrite—and What It Does Not

The Supplied Timeline of Migration Reports

Date (UTC)PublisherClaim in the headline/summary
2026-11-25 16:26DiggClaude helped rewrite the Messages API in Rust; "the tests weren't enough"
2026-11-25 16:30Crypto BriefingMessages API moved from Python to Rust with Claude's help
2026-11-25 17:19Unite.AIClaude-assisted Rust migration of the Messages API
2026-11-26 02:27InfoWorldClaude API moved from Python to Rust with no downtime

Attribute the Claims Carefully: Messages API vs. Claude API

The reports don't even agree on what was rewritten. Three say Messages API. InfoWorld says Claude API. The Messages API is the surface most client SDKs hit, but it isn't the whole API—a rewrite scoped to /v1/messages says nothing about admin endpoints, file uploads, batch jobs, or token counting.

Resolve that before citing this in an internal review. I can't do it from headlines, and neither can you.

"Zero downtime" is undefined in the supplied material too. It could mean no increase in 5xx, no failed health checks, no dropped streams, or no customer-visible incident. Those are different measurements with different blind spots.

What the Reporting Does Not Establish About Safety

The reporting doesn't tell us:

  • which endpoints were rewritten, or whether the rewrite happened endpoint by endpoint
  • how long the two implementations coexisted
  • what percentage of traffic was ever served by Rust before the cutover completed
  • any performance result, with or without methodology
  • what the test suite covered, or how the assertions were derived
  • whether shadow traffic was used, and if so what the sink looked like
  • how rollback was exercised, or whether it was
  • how "zero downtime" was measured and over what window

That list is long, and that's the point. A migration write-up that answers none of these is a press release, not a safety case. Without the details, the useful thing I can do is describe the evidence I'd want.

Why a Python-to-Rust API Rewrite Can Pass Tests and Still Break Clients

The Oracle Problem: Assertions Derived From the Old Implementation

A test asserts that code produces an expected value. Where did the expected value come from? In a rewrite, usually from reading the old implementation. If the old implementation has a quirk—and every mature service does—the test encodes the quirk. That's fine when the quirk is intentional. It's not fine when the quirk is an accident clients now depend on, because nobody can tell you which is which.

AI-assisted rewrites make this worse. The implementation, fixtures, and assertions often come from the same prompt describing the same mental model. Errors become correlated instead of independent. A test generated alongside the bug will keep passing, confidently, forever.

Concretely, this assertion passes for both of these wire responses:

## passes whether metadata.user_id was sent as null or omitted entirely
assert response.json()["metadata"] in ({}, {"user_id": None})

A test like that looks like coverage. It's really a test that the rewrite didn't crash. Compatibility testing needs an assertion derived from the wire contract—"given these exact request bytes, the upstream must receive {"metadata":{"user_id":null}}." That's a fact the old implementation's source can't supply by itself.

Independently derived contracts and real production observations break the correlation. Everything else is the team grading its own homework.

Rust's Guarantees Stop at the API Boundary, Not the Wire Contract

Rust gives you memory safety, no data races in safe code, sum types instead of null, and exhaustiveness checking. All of that is valuable. None of it is API compatibility.

Rust gives youRust does not give you
no use-after-freethe same input validation rules
no null dereferencethe same treatment of null on the wire
thread safety in safe codethe same authorization decisions
exhaustive match on enumsthe same error taxonomy and status codes
compile-time type checksthe same streaming and cancellation semantics

That second row isn't hypothetical. Option<T> is a good type, and #[serde(default)] correctly maps both null and absent to None. The type system does exactly what you asked. The problem is that JSON has three states—present with a value, present as null, absent—and a plain Option<T> has two. If your Python handler passed dictionaries through untouched, that asymmetry never came up. The rewrite introduces it silently.

Availability Is Not Correctness for Small Client Cohorts

Here's arithmetic, not measurement—I have no data on Anthropic's traffic. Suppose 0.4% of requests include metadata: {"user_id": null}, which is plausible for clients that clear a user identifier conditionally. Suppose the rewrite turns null into absent and the upstream model doesn't care.

Aggregate error rate: unchanged. Uptime: unchanged. p99 latency: unchanged. One client library, one customer's logging pipeline, one billing reconciliation job: broken. Dashboards average over the whole fleet, so a total break for a 0.4% cohort is invisible at two significant figures. You only see it by breaking metrics down by client cohort and request shape, which almost nobody does until after the incident.

Define the API Compatibility Boundary Before Comparing Implementations

Build a Contract Matrix Before Diffing Implementations

Before writing a line of the candidate, write down what "compatible" means. The classic mistake is starting with a diff of the two implementations. Then you test whatever they happen to differ on, which isn't the same set as what clients depend on.

DimensionContract questionComparison class
Status codessame code for same condition?exact
Missing required fieldwhich code, which body?exact
Explicit null vs absentpreserved distinctly?exact
Defaults for omitted fieldssame effective value?exact
Numeric boundariesmax_tokens: 0, negative, 2**31exact
UnicodeNFC/NFD, astral plane, lone surrogatesexact
Unknown fieldsrejected, or forwarded, or dropped?needs a decision
Error envelopetype and error.type taxonomyexact
Contract headerscontent-type, request-id presencesemantic
Header values that always differdate, server, content-lengthapproved difference
JSON key ordernot part of the contractsemantic

Fill in the "needs a decision" rows before you run anything. If you make the decision while staring at a failing diff, you'll rationalize the candidate's behavior instead of choosing a contract.

Pin the Streaming Contract to Documentation, Not the Python Implementation

For Messages-style streaming, take the protocol from the API docs, not from whatever the Python process happened to emit. The documented shape is server-sent events where each event has a data: line containing a JSON object named by its type field: message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop, plus keepalive ping events and mid-stream error events. The terminal message_delta carries stop reason and usage.

What isn't contract:

  • how many bytes arrive per TCP read, and therefore where event boundaries land in a given buffer
  • whether a keepalive ping appears between two specific deltas
  • TLS record boundaries, Transfer-Encoding chunk framing, connection reuse

A comparator that flags chunk boundaries will produce so much noise you'll start ignoring it. An ignored comparator is worse than none. Compare decoded event sequences; treat framing as an approved difference with a written justification.

Classify Every Expected Difference Explicitly

Three buckets, and every difference has to land in one:

  1. Exact — status codes, error type strings, absent versus null.
  2. Semantic — parsed-JSON equality where key order and number formatting don't matter.
  3. Approved difference — an intentional change with a ticket, a documented client impact, and a communication plan.

Here's the rule people push back on: the Python implementation is a behavioral reference, not an authority. If the old handler accepts max_tokens: 0 because it's missing a bounds check, fix the contract in both implementations, record it as an approved difference, and tell clients. Copying a bug for byte-equality isn't safety; it preserves a defect. Any divergence from the reference must be chosen and written down, not discovered later in a diff.

Build a Reproducible Python-to-Rust Differential Testing Lab

Lab Environment and Pinned Versions

ComponentVersionNote
Python3.12.7reference gateway + comparator, stdlib only
rustc / cargo1.83.0pinned in rust-toolchain.toml
axum0.7.9candidate HTTP layer
tokio1.41.1runtime
serde / serde_json1.0.215 / 1.0.133JSON
reqwest0.12.9candidate upstream client
Ports8787 / 8788 / 8789reference / stub / candidate, loopback only

None of this matches Anthropic's stack, and it isn't supposed to. The point is that every number is written down, so a result can be reproduced.

Lab Artifacts and Process Layout

lab/
  stub_echo.py            # deterministic upstream stub, echoes the parsed request
  reference/gateway.py    # Python reference handler
  candidate/              # Rust candidate (axum)
  fixtures/*.json         # named request fixtures
  compare.py              # differential runner
## terminal 1 — deterministic upstream stub
$ python3.12 lab/stub_echo.py
stub listening on 127.0.0.1:8788

## terminal 2 — Python reference gateway
$ python3.12 lab/reference/gateway.py
reference listening on 127.0.0.1:8787

## terminal 3 — Rust candidate
$ cargo run --release --manifest-path lab/candidate/Cargo.toml
candidate listening on 127.0.0.1:8789

## terminal 4 — compare every fixture
$ python3.12 lab/compare.py lab/fixtures/*.json

The stub matters more than it looks. It makes the upstream deterministic, so the only variable is the gateway. It also echoes the parsed JSON it received, so any field the gateway drops or rewrites shows up in the response body and can be attributed to the gateway.

⚠️

Transcripts in this post are expected output derived from the code shown, not captured results from a run I performed, and certainly not output from any Anthropic system. Run the lab yourself before quoting any of it.

The Python Reference Gateway as a Behavioral Oracle

lab/reference/gateway.py
# Python 3.12.7, stdlib only


from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

UPSTREAM = "http://127.0.0.1:8788/v1/messages"

def forward(payload: dict) -> tuple[int, dict]:
  req = urllib.request.Request(
      UPSTREAM,
      data=json.dumps(payload).encode(),
      headers={"content-type": "application/json"},
      method="POST",
  )
  with urllib.request.urlopen(req) as resp:
      return resp.status, json.loads(resp.read())

class Gateway(BaseHTTPRequestHandler):
  def do_POST(self):
      n = int(self.headers.get("content-length", "0"))
      payload = json.loads(self.rfile.read(n) or b"{}")
      if "messages" not in payload:
          self._send(400, {"type": "error", "error": {
              "type": "invalid_request_error",
              "message": "messages: field required",
          }})
          return
      status, body = forward(payload)
      self._send(status, body)

  def _send(self, status, body):
      raw = json.dumps(body).encode()
      self.send_response(status)
      self.send_header("content-type", "application/json")
      self.send_header("x-lab-impl", "python-reference")
      self.send_header("content-length", str(len(raw)))
      self.end_headers()
      self.wfile.write(raw)

  def log_message(self, *args):
      pass

if __name__ == "__main__":
  ThreadingHTTPServer(("127.0.0.1", 8787), Gateway).serve_forever()

The reference handler does the one thing that makes it a trustworthy oracle: it forwards the parsed payload verbatim. It checks that messages is present, returns an error envelope if it isn't, and otherwise leaves the body alone.

The Rust Candidate Gateway, With a Deliberate Compatibility Bug

lab/candidate/src/main.rs (trimmed)
use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::post, Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

const UPSTREAM: &str = "http://127.0.0.1:8788/v1/messages";

#[derive(Debug, Deserialize, Serialize)]
struct Metadata {
  // BUG: absent and null both deserialize to None, and None is then skipped
  // during serialization, so an explicit null is silently deleted.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  user_id: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
struct MessagesRequest {
  messages: Vec<Value>,
  #[serde(default, skip_serializing_if = "Option::is_none")]
  metadata: Option<Metadata>,
}

#[derive(Clone)]
struct AppState {
  client: reqwest::Client,
}

async fn create_message(
  State(state): State<AppState>,
  Json(req): Json<MessagesRequest>,
) -> impl IntoResponse {
  match state.client.post(UPSTREAM).json(&req).send().await {
      Ok(resp) => {
          let status = resp.status();
          let body: Value = resp.json().await.unwrap_or_else(|_| json!({}));
          (status, Json(body)).into_response()
      }
      // trimmed for brevity — retry/timeout mapping omitted
      Err(_) => (
          StatusCode::BAD_GATEWAY,
          Json(json!({"type": "error", "error": {
              "type": "api_error", "message": "upstream unavailable"
          }})),
      ).into_response(),
  }
}

#[tokio::main]
async fn main() {
  let app = Router::new()
      .route("/v1/messages", post(create_message))
      .with_state(AppState { client: reqwest::Client::new() });

  let listener = tokio::net::TcpListener::bind("127.0.0.1:8789").await.unwrap();
  axum::serve(listener, app).await.unwrap();
}

This code is idiomatic. A reviewer would approve it. It also has two compatibility defects no type checker will catch.

Defect one. metadata: {"user_id": null} becomes metadata: {} on the way upstream. The type system guaranteed memory safety while the wire format changed.

Defect two surprises people. The handler takes Json<MessagesRequest> as an extractor. When deserialization fails, axum's default rejection maps a data error to 422 Unprocessable Entity with a plain-text body. The Python reference returns 400 with a JSON error envelope. Different status code, different content type, different body shape—for the most common client mistake. Replacing the extractor with Result<Json<T>, JsonRejection> and mapping to the reference's envelope is a prerequisite, not a nicety.

The Fixture That Catches Null-vs-Absent Metadata

lab/fixtures/null-vs-absent-metadata-user-id.json
{
"name": "null-vs-absent-metadata-user-id",
"request": {
  "model": "lab-fixture-model",
  "max_tokens": 64,
  "messages": [{ "role": "user", "content": "ping" }],
  "metadata": { "user_id": null }
}
}

lab-fixture-model is deliberately fake; the stub ignores it. A real-looking model id would imply the fixture exercises a real endpoint.

The Differential Comparator

lab/compare.py (trimmed)
import json, sys, urllib.error, urllib.request

REF  = "http://127.0.0.1:8787/v1/messages"
CAND = "http://127.0.0.1:8789/v1/messages"

## documented-volatile: present, but the value is not part of the contract
VOLATILE = {"date", "server", "content-length", "x-lab-impl"}

def call(url, payload):
  req = urllib.request.Request(
      url, data=json.dumps(payload).encode(),
      headers={"content-type": "application/json"}, method="POST")
  try:
      with urllib.request.urlopen(req) as r:
          return r.status, dict(r.headers), json.loads(r.read() or b"null")
  except urllib.error.HTTPError as e:
      body = e.read()
      try:
          return e.code, dict(e.headers), json.loads(body)
      except json.JSONDecodeError:
          return e.code, dict(e.headers), body.decode("utf-8", "replace")

def diff(a, b, path="$"):
  if type(a) is not type(b):
      return [(path, a, b)]
  if isinstance(a, dict):
      out = []
      for k in sorted(set(a) | set(b)):
          if k not in a:
              out.append((path + "." + k, "<absent>", b[k]))
          elif k not in b:
              out.append((path + "." + k, a[k], "<absent>"))
          else:
              out.extend(diff(a[k], b[k], path + "." + k))
      return out
  if isinstance(a, list):
      out = [] if len(a) == len(b) else [(path, "len=" + str(len(a)), "len=" + str(len(b)))]
      for i, (x, y) in enumerate(zip(a, b)):
          out.extend(diff(x, y, path + "[" + str(i) + "]"))
      return out
  return [] if a == b else [(path, a, b)]

fails = 0
for path in sys.argv[1:]:
  fixture = json.load(open(path))
  rs, rh, rb = call(REF,  fixture["request"])
  cs, ch, cb = call(CAND, fixture["request"])
  problems = []
  if rs != cs:
      problems.append(("status", rs, cs))
  for h in ("content-type",):
      if rh.get(h) != ch.get(h):
          problems.append(("header " + h, rh.get(h), ch.get(h)))
  problems.extend(diff(rb, cb))
  if problems:
      fails += 1
      print("FAIL  " + fixture["name"])
      for p, x, y in problems:
          print("      " + p.ljust(28) + " reference=" + repr(x) + "  candidate=" + repr(y))
  else:
      print("PASS  " + fixture["name"])
print(str(fails) + " of " + str(len(sys.argv) - 1) + " fixtures differ")

Two deliberate choices: x-lab-impl is in VOLATILE because it differs by construction and isn't part of the contract, and request-id is not ignored—it should be checked for presence and format even though the value always differs. That distinction, present-but-not-equal, gets lost when you normalize by header name instead of by property.

Expected Comparator Output

$ python3.12 lab/compare.py lab/fixtures/*.json
PASS  messages-empty-array
PASS  unicode-astral-plane-content
FAIL  missing-messages-field
      status                       reference=400  candidate=422
      header content-type          reference='application/json'  candidate='text/plain; charset=utf-8'
FAIL  null-vs-absent-metadata-user-id
      $.metadata.user_id           reference=None  candidate=<absent>
2 of 4 fixtures differ

The second failure line is the core lesson. Nothing crashed. Both services returned 200. Both had comparable latency. One of them deleted a field the client explicitly sent. The only reason anyone knows is that the harness compares parsed structures field by field instead of comparing hashes or eyeballing responses.

The Fix: Preserve Wire Semantics Instead of Re-Modeling Payloads

The minimal patch is to stop re-modeling the payload:

#[derive(Debug, Deserialize, Serialize)]
struct MessagesRequest {
    messages: Vec<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    metadata: Option<Value>,   // forwarded verbatim: absent stays absent, null stays null
}

Validate metadata in a separate function that reads it and returns a Result, but never rewrites it. Pair that with a rejection handler that maps JsonRejection to the 400 plus JSON envelope the reference emits, and both failures clear. The remaining question—what the gateway should do with an unknown top-level field—is a contract decision, not a bug fix.

That patch is the most transferable idea in this post: every field you re-model in the new language is a field you can get wrong, and the safest serialization strategy for a compatibility rewrite is to touch as little of the payload as possible.

Make the Differential Comparator Strict Without Making It Noisy

Compare Structure, Status Codes, and Contract Headers, Not Bytes

Compare status codes exactly. Compare contract-relevant headers by property: content-type value, request-id presence and format. Compare parsed JSON recursively. Normalize only fields documented as volatile, and keep that list in version control next to the comparator, not in someone's head.

Don't Use Live Model Output as a Deterministic Oracle

Two independent generations from the same prompt will differ, usually at the first token. Comparing them byte-for-byte guarantees noise; comparing them semantically gives you a fuzzy judgment call that isn't a test. Point both gateways at the deterministic stub and compare gateway behavior. Live upstream calls belong in a separate smoke test that asserts properties—a valid event sequence, a terminal message_stop, usage present—not equality.

Compare Streaming Responses Incrementally Across Chunk Sizes

lab/sse.py
def iter_sse(chunks):
  """Consume arbitrary byte chunks, yield decoded SSE events.
  Framing is normalised; event order and payload are not."""
  buf, event, data = "", None, []
  for chunk in chunks:
      buf += chunk.decode("utf-8", "replace")
      while "
" in buf:
          line, buf = buf.split("
", 1)
          line = line.rstrip("
")
          if line == "":
              if data:
                  yield {"event": event, "data": "
".join(data)}
              event, data = None, []
          elif line.startswith("event:"):
              event = line[6:].strip()
          elif line.startswith("data:"):
              data.append(line[5:].lstrip())

Then drive both implementations with the same recorded SSE byte stream, split at chunk sizes [1, 7, 64, 4096, whole], and assert the decoded event list is identical in every case. Chunk size must be irrelevant; event sequence must not be. This one test catches the classic Rust rewrite bug where a stream is re-emitted per read instead of per event, producing the right bytes in the right order but with boundaries that break a client's incremental parser.

Beyond the happy path, the streaming suite needs cases for: missing message_stop, an error event mid-stream, a delta before content_block_start, a duplicate message_start, and a client that disconnects after the first delta. Each has an observable expected behavior. "The process didn't panic" isn't it.

Expand Fixture Coverage Beyond Happy-Path Requests

Boundary Cases and Generated Inputs

Hand-written fixtures cover what you thought of. Add:

  • omitted vs empty collections (metadata: {} vs no metadata)
  • max_tokens at 0, 1, and the documented maximum, plus one above it
  • negative and non-integer numerics
  • Unicode: NFC vs NFD, astral-plane characters, an unpaired surrogate
  • unknown top-level and nested keys
  • malformed JSON, truncated JSON, and a body with content-length larger than the payload
  • request bodies over the size limit — and the exact status and body returned when they're rejected

Then generate. proptest in Rust and hypothesis in Python both shrink failing cases automatically. Commit the shrinker's minimal output as a permanent named fixture. That conversion step turns a one-off investigation into regression coverage.

Be honest about the limit: in a differential lab, the oracle is the reference implementation, so generated cases only find where the two differ. They can't find where both are wrong. For that you need the contract matrix and, eventually, client-side tests.

Test Timeouts, Retries, Disconnects, and Backpressure

This is where rewrites break in ways response comparison never sees. Have the stub record the active upstream request count and expose it on a /debug/inflight route. Then:

  1. Start a request and abort the client connection mid-flight.
  2. Assert the stub's in-flight count returns to zero within a bounded time.

A candidate that returns the right response and leaves the upstream call running has passed the equality test and failed the resource test. Same for retries: make the stub fail once with 503 and assert the retry count and deadline match the contract, not whatever the framework's default middleware chose.

Measure Resource Behavior Separately From Response Equality

Response equivalence and resource behavior are different experiments and should have different write-ups. For a local load run, state the tool, the rate, and the duration:

$ oha --duration 60s --qps 50 -m POST -T application/json \
      -d lab/fixtures/null-vs-absent-metadata-user-id.json \
      http://127.0.0.1:8787/v1/messages

If I ran that, I'd report machine specs, the exact command, the latency distribution, error counts, and peak RSS for both processes. I haven't run it, so there's no number in this post to quote. A latency claim without the method isn't a result, and a rewrite benchmark with a stub upstream measures your HTTP framework, not your service.

Use Shadow Traffic Without Duplicating Production Effects

Shadow Traffic Is a Proposed Technique, Not Reported Practice

Nothing in the supplied coverage says Anthropic used shadow traffic. I'm proposing it because a hand-written corpus covers what the authors imagined, while representative traffic covers what clients actually send—including the 0.4% cohort.

Establish the Shadow-Traffic Safety Boundary First

Mirroring a request can bill a customer, write a record, consume quota, or trigger a downstream action. Before you duplicate any traffic:

  • point the candidate's upstream client at a replay server serving recorded responses, or at a sandbox credential with hard quotas
  • strip or replace authorization headers so the mirror cannot act as the customer
  • deny outbound writes at the network layer, not in application code
  • record the mirror's side effects on the reference path and assert zero

The invariant: a mirrored request must be observationally free. If you can't state that, don't mirror.

Protect Request Data Without Destroying the Edge Cases

Request bodies contain prompts, and prompts contain personal data. Access controls, sampling, short retention, and field-level redaction are non-negotiable. The trap is that aggressive sanitization removes the edge cases you're hunting—the Unicode long tail, the odd nesting, the null you didn't expect. Redact by replacing values with type-preserving surrogates, not by deleting keys, and keep a small, tightly restricted, short-retention raw sample for mismatches only.

Shift Traffic in Stages with Explicit Promotion and Stop Conditions

Staged Traffic Progression With Promotion Evidence

StageTraffic to candidateEvidence required to promote
Offline replay0% livezero unexplained diffs on the corpus
Isolated shadow0% live, 100% mirroredshadow diff rate at or below the offline baseline
Internal requestsinternal onlyno unexplained diffs, on-call sign-off
Canary~1%diff rate, SLOs, stream completion within gates
Wider~5%, ~25%, ~50%, ~100%same gates at each step

Every percentage and window in that table is illustrative. Real numbers come from your error budget and traffic volume. A 1% canary on low volume produces so few samples that a 1% failure rate is statistically invisible. Treating sparse canary data as proof is how promotions get rubber-stamped.

Promotion and Stop Gates

Pick thresholds from your baseline and SLOs, not from a template:

  • unexplained compatibility diffs: zero, or each one individually triaged with a written decision
  • error-budget consumption attributable to the canary: within the current burn allowance
  • tail latency: within the budget defined for the endpoint
  • stream completion rate: at or above baseline
  • cancellation cleanup: in-flight upstream count returns to zero after aborts
  • resource saturation: no headroom regression that would break the next stage

Route Client Cohorts, Not Individual Requests

Pin a client to one implementation for the duration of a session or stream. Otherwise a long-lived stream can start in Python and resume in Rust, which is a different experiment. Expand by cohort—SDK version, region, account type—not uniformly, so the data is readable. If the canary only ever contains the happy-path cohort, it will always look clean.

Instrument the Differences That Aggregate Dashboards Hide

Fields Both Implementations Must Emit

FieldTypeWhy
impl_versionlabelattribute every diff to a build
routelabeldivergence is rarely uniform across endpoints
status_classlabel4xx/5xx shifts at cohort granularity
error_typelabelthe error taxonomy must not drift
ttfe_mshistogramtime to first SSE event, not total time
termination_reasonlabelcompleted / client_disconnect / upstream_error / cancelled
cancel_cleanup_mshistogramdid abandoned work actually stop
upstream_latency_mshistogramcontrols for workload drift

Notice what's absent: request bodies, prompt text, user identifiers. Correlation belongs in logs and traces with restricted access, not metric labels—and never at high cardinality, or you'll spend the migration budget on the metrics bill.

Separate Regression From Workload Change

If p99 rose after promotion, ask first whether the workload changed. Matched cohorts and a shared upstream latency distribution tell the two apart. A 1% canary isn't a random sample of 1% of behavior; it's whatever your routing rule selected.

Investigate One Discrepancy End to End

  1. The comparator fails a shadow fixture at $.metadata.user_id.
  2. Pull the trace by request id and compare both spans: same upstream latency, different serialized body length.
  3. Reduce it to a two-line fixture and add it to lab/fixtures/.
  4. Confirm the candidate drops None on serialization—observed.
  5. Hypothesis: other Option-typed fields in the same struct behave the same way. Unconfirmed until you grep the struct and run the new fixtures, which then surface a second and third affected field.

Keeping steps 4 and 5 separate is the discipline. "I found the cause" and "I found one confirmed symptom and suspect three more" are different statements. Merging them is how a fix ships that closes one hole and leaves two open.

Make Rollback a Tested Capability, Not a Routing Promise

Routing Back Is Not Rollback

If the rewrite changed a shared schema, cache key format, retry policy, or accounting table, flipping traffic back re-exposes the reference implementation to state it doesn't understand. Coexistence requires backward-compatible state for the whole overlap window: new fields optional, old fields still written, cache formats versioned or dual-read, retry semantics unchanged, usage records reconcilable.

Rehearse the Rollback With Client-Facing Signals

A rollback runbook that has never been executed is a wish. Rehearse:

  1. Halt promotion—freeze the routing table change, don't just "intend" to.
  2. Route new requests to the reference implementation.
  3. Drain existing streams instead of cutting them; a truncated message_stop is an incident.
  4. Reconcile side effects: usage counters, writes, queued jobs.
  5. Confirm recovery with the same client-facing signals you used to detect the problem—not a proxy metric that stayed green the whole time.

Step 5 is where rehearsals usually fail. If the trigger was a cohort-level diff rate, the all-clear must also be cohort-level diff rate.

Keep the Old Implementation Operable Until Retirement Criteria Are Met

Retire Python only when the agreed observation window closes. Write down in advance who can stop the rollout, what evidence triggers a stop, and what evidence justifies retirement. An observation period with no defined end becomes permanent, and permanent dual-operation is its own outage waiting to happen.

Conclusion: AI Assistance Changes Implementation Speed, Not the Acceptance Bar for a Safe Rewrite

Back to the Supplied Reporting

The supplied coverage describes a Claude-assisted Python-to-Rust rewrite of the Messages API, and InfoWorld reports the move happened without downtime. That's a notable claim and, if accurate, a real engineering result. It's also not a validation methodology. The sources don't say which endpoints moved, how much traffic ran on Rust before completion, what the tests covered, whether shadowing was used, or how downtime was defined. Digg's headline—"the tests weren't enough"—points at the right question, even though a headline isn't evidence of anything.

Acceptance Checklist for a Safe Python-to-Rust API Rewrite

Before you call a rewrite safe, you should be able to produce:

  • an explicit contract matrix, with every difference classified as exact, semantic, or approved
  • a differential fixture corpus that runs in CI against a deterministic upstream
  • streaming comparison across fragmented reads, missing terminals, mid-stream errors, and client disconnects
  • boundary and property-based coverage, with shrunk failures committed as fixtures
  • representative traffic validated through an observationally-free shadow sink
  • cohort-level telemetry that separates regression from workload change
  • a rehearsed rollback with backward-compatible state across the coexistence window

A green test suite isn't on that list because it isn't evidence by itself. It's the starting condition. And if an AI wrote both the rewrite and the tests, you have less independent evidence than usual, not more. The review burden moves to the contract, the fixtures, and the traffic—where it should have been all along.

Further Reading and Verification

Secondary Reporting and Headline-Level Claims

These are the supplied sources. They're news summaries and headlines, not engineering reports. I haven't been able to locate a primary Anthropic write-up describing the migration or its validation process.

Primary Protocol References

These are the documents the streaming and error-shape claims rest on. Verify against them rather than any implementation, including the one you're migrating from.

Share this post

More posts

Loading comments…