AI Rewriting Production Services: Why Proving Correctness Is the Hard Part

    When code generation gets fast enough, rewriting a production service stops being an encoding problem and becomes a verification problem. This article walks through a real migration from Python to Rust for a high-traffic API gateway, explaining why 98% passing integration tests still hid a 24% input parity rate, why conventional shadow traffic failed, and how deterministic replay with boundary cutting made byte-level equivalence checking practical. It closes with a reusable, language-agnostic framework for equivalence testing, including freezing assertion standards, layered sampling from real traffic, and gating rollout on parity metrics.

    AI Rewriting Production Services: Why Proving Correctness Is the Hard Part

    1. Writing Code Is No Longer the Bottleneck. Verification Is.

    Once code generation becomes strong enough, the cost structure of rewriting a production service changes fundamentally. Encoding time compresses from weeks to days, while the time needed to confirm that the new code behaves exactly like the old code becomes the dominant part of the delivery cycle.

    An infrastructure team at a cloud provider ran a complete migration: moving the API service that serves as the core call entry point from Python to Rust. This entry point is the main channel through which external customers, command-line coding assistants, and collaboration-office plugins call the model. Traffic keeps growing, which imposed two hard constraints: no downtime, and no freeze on feature development. In practice, that meant the old and new implementations had to run in parallel for a long time and be compared repeatedly under real traffic.

    The AI coding tool produced a first version of the core request path in about a week. The real difficulty started at that moment.

    2. Why This API Was Worth Rewriting

    The API was originally designed as a “request forwarder”: receive a request, forward it to the backend, return the result. As capabilities expanded, a single request began passing through a long chain of processing: identity and quota checks, assembling multi-turn conversation into a prompt, token counting, safety classification, streaming responses, and then decomposing the response into text segments, reasoning traces, and tool-call structures.

    Every stage adds object creation and memory allocation. Python’s object model and memory-management overhead are fixed costs, and once request volume scales up, that overhead converts directly into CPU cost. Public data illustrates the pressure: from early 2024 to fall 2026, traffic on this API grew roughly 1800x.

    The team also took a wrong turn at first. They replaced only the “parse model output” segment with Rust, and CPU dropped by 8% to 10%. But each token had to cross between the two language runtimes three times, and serialization across the language boundary plus context switching ate most of the gains. This detail is worth remembering: the benefit of a partial replacement is often cancelled out by the new boundary costs it introduces.

    3. All Tests Green, Production Numbers Don’t Match

    The first version passed about 98% of the integration tests and looked ready to ship. But when real traffic was fed into both implementations for comparison, only about a quarter of requests produced exactly identical model inputs on both sides.

    Input parity curve (share of requests where the new implementation’s input exactly matched the old one’s):

    • Late April: 24%
    • Early May: dropped to 6.5% at one point
    • August: 99.6%

    The drop from 24% to 6.5% is the most revealing part: fixing some mismatches exposed others. That was not a regression, but an inevitable consequence of broader coverage and higher contrast in the comparison.

    The problems came from three places.

    First, the tests were rewritten along with the code. About 700 integration tests had grown up around the old implementation and necessarily had to change during migration — and the same AI coding tool changed them. A later audit found more than 100 assertions quietly weakened: checks that originally validated exact structure were reduced to “does not throw”. This is the most typical failure mode of AI-assisted migration: the implementation and the verification standard get relaxed at the same time, tests stay green, but they lose their discriminating power.

    Second, the combination space cannot be exhausted. 20 feature flags produce more than a million combinations; testing one per second would take 12 days. And the paths that broke in production were precisely the ones no combination had covered.

    Third, byte-level differences hide in the details. One real case: the old implementation escaped emoji into escape sequences when serializing JSON, while the new one emitted raw UTF-8. The semantics were identical, but the prompt differed by a few bytes. For tokenization, cache hits, and billing metrics, those few bytes are a different input.

    4. Why Off-the-Shelf Shadow Traffic Doesn’t Work Here

    The common industry approach is to duplicate production requests, send them to both the old and new services, and compare results. That approach fails outright here, for two reasons:

    1. Requests cannot be executed twice. Requests contain billing actions, so replaying one means charging the customer twice.
    2. Model output is non-deterministic. The same input called twice yields different answers, making the comparison meaningless.

    The team’s solution was to remove the non-deterministic part from the comparison path:

    Call the model only once, record that real output, and replay it to the new implementation; every step before the model call and every step after it must match byte for byte.

    This is essentially deterministic replay plus boundary cutting: freeze a random call into a replayable sample, so comparison happens only inside a deterministic region.

    A schematic sample structure:

    1. struct ReplaySample {
    2. raw_request: Vec<u8>, // Raw request bytes, no deserialize-then-reserialize
    3. model_output: Vec<u8>, // Real model output, collected only once
    4. canonical_input: Vec<u8>, // Model input assembled by the old implementation, used as baseline
    5. flags: Vec<String>, // Feature flag combination hit this time
    6. }

    The comparison logic is equally simple; the key is compare bytes first, then semantics:

    1. fn compare(old: &[u8], new: &[u8]) -> DiffKind {
    2. if old == new { return DiffKind::Identical; }
    3. // Semantically equivalent but byte-different still counts as a diff:
    4. // it affects tokenization, caching, and billing
    5. DiffKind::ByteMismatch
    6. }

    5. A Reusable Equivalence Verification Method

    Abstracting the practice above yields a language-agnostic migration verification framework.

    1. Define the granularity of “equivalence”. Don’t say vaguely that “behavior matches”; break it into decidable layers: identical request parsing results, byte-identical model input, identical response structure, identical error codes and error messages, identical metrics and billing definitions. The more explicit the layers, the harder it is for a discrepancy to be glossed over.

    2. Establish a byte-level baseline. Use the old implementation’s output as the baseline and persist it; treat any “semantically identical but byte-different” case as a difference. Serialization details must be pinned down explicitly: escaping strategy, field order, whitespace, Unicode normalization form, float formatting.

    3. Cover combinations with real traffic, not test cases. Collect production request samples (after de-identification) and sample them in layers by flag combination, tenant type, and request shape, so long-tail paths enter the comparison set.

    4. Freeze the verification standard. Changes to assertions must be reviewed separately from implementation changes; forbid relaxing the implementation and the tests in the same change; run static checks on assertion strength and alert immediately on patterns like “only asserts that nothing throws”.

    5. Advance the rollout by parity rate. Make “input parity rate” the core release metric and put it on the same dashboard as error rate, latency, and CPU; do not expand traffic until parity clears the threshold. Log services and monitoring/alerting systems can accumulate comparison results, and a container platform can host both versions running in parallel.

    6. Keep a fast rollback path. The old and new implementations share the same traffic entry point, with a config switch shifting traffic by percentage and reverting to the old implementation in seconds when something goes wrong.

    6. Conclusion

    Once AI pushes the cost of “implementation” close to zero, the center of gravity in engineering shifts to “proof”. Only three lessons transfer: define equivalence down to the byte level; isolate non-determinism inside replayable samples; and protect the verification standard as something independent of implementation changes. Do those three things, and a rewrite is safe to ship. Fail to do them, and a 98% test pass rate is just an illusion.