DEV Community

Cover image for The Tests Pass. Does the New Kotlin Code Behave Like the Old Java?
Prikshit
Prikshit

Posted on Originally published at Medium

The Tests Pass. Does the New Kotlin Code Behave Like the Old Java?

How to Prove an AI-Written Migration Is Correct: Shadow Runs, Diffs and Staged Rollouts

A week to write, a lot longer to trust

Headline "A week to write, a lot longer to trust" with trust highlighted in a green pill. Body text: "Claude wrote core API code in about a week, but verification, not generation, became the bottleneck." A cyan calendar card says "Write 1 week" with a check mark. A green calendar card says "Trust Much longer" with a clock. A laptop showing code sits behind a green shield with a check mark.

On 25 November, Anthropic published a write-up about migrating its Messages API from Python to Rust.

The Rust API uses "about 70% less CPU per request" and "cuts median time to first token by about 20%". They completed the migration "without ever taking the service offline or freezing feature development."

There are some limitations to these numbers. The CPU figure comes from one region, while the time to first token figure covers Claude Code requests over a shorter period.

One thing I found interesting in the article was how quickly Claude wrote the initial implementation.

"Claude wrote a first version of the API's core request path in about a week."

Most of the article explains why writing that initial implementation was the easier part. Anthropic describes the problem in one sentence:

"Verification, not generation, had become the bottleneck."

An AI assistant might be able to convert a module from Java to Kotlin or from Objective-C to Swift in an afternoon. But how do we verify that the new code behaves exactly like the old code, including behavior that nobody documented?

Anthropic's article is about migrating a Python service to Rust. It doesn't discuss Android or iOS.

I want to look at how we can apply the same verification method to mobile and backend migrations. The technical claims about Kotlin, Swift, Envoy and app rollouts come from their respective documentation. The engineering recommendations are my judgment.

Why green tests aren't enough

Headline "Why green tests aren't enough" with enough highlighted in a green pill. Body text: "Tests can pass and still miss behavior changes, hidden edge cases, and input differences." Three icon cards read Changed Tests, Limited Coverage, and Input Differences. A laptop shows a Tests Passed checklist, and a magnifying glass over it reads Hidden Differences with a warning icon.

Anthropic started with about 700 integration tests. They found two problems with using those tests to verify the migration.

The first problem was that the tests depended on the existing Python implementation. They ran the Python API inside the test process and mocked other services in Python memory.

This meant the tests also needed to change during the migration, and Claude helped change both the implementation and the tests.

As Anthropic explains, "a 'pass' could mean that the code was right, or that the test had been changed in a way that let wrong code through."

When they reviewed the migrated tests, they found "more than 100 weakened assertions."

The second problem was test coverage. With just 20 binary options, you already have over a million possible combinations.

Anthropic shared these numbers:

"Our Rust API passed about 98% of its tests in April, yet only about a quarter of inputs matched on production traffic."

One reason for the difference was how Python and Rust handled JSON tool calls. Python escaped certain characters, such as an emoji, into text codes. Rust kept the original characters.

This meant the two prompts differed by a few bytes.

We have similar problems when migrating mobile applications.

Android's documentation says Android Studio's converter "produces functionally-equivalent Kotlin code that compiles and runs," but also says "it's likely that you need to make additional optimizations to the converted code."

Nullability is a good example. According to the documentation, Android Studio "defaults to the non-null assertion."

Kotlin's own docs explain what happens when you assign a value from Java to a non-nullable Kotlin type and "the value is actually null at runtime, Kotlin throws a NullPointerException."

The original Java code might have been passing a null value around without crashing. After converting it to Kotlin, the same value can cause a crash.

If your tests never pass that null value, all your tests can still pass.

Kotlin's converter docs also mention that the converter "is not fool-proof."

There's a similar concern when migrating Objective-C to Swift. Apple's migration guide says that if your Objective-C code doesn't have nullability annotations, "now's the time to add them."

The reason is that those annotations control how declarations are imported into Swift.

Android's Kotlin interop guide recommends the same for public Java APIs.

Keep the old code alive as the oracle

Headline "Keep the old code alive as the oracle" with oracle highlighted in a green pill. A cyan document labeled Legacy behavior connects to a center card that says Compare both, with a check mark, and then to a green document labeled Candidate behavior. A bottom banner with a wrench reads Apply fixes to both.

Anthropic used the existing implementation as another way to verify the migration.

In their words, "we used the existing system as an oracle to test parity during the migration."

I think this is a useful approach for mobile migrations as well. Tests tell us what someone expected the code to do. The existing implementation gives us a reference for how the code actually behaves today, including its quirks.

Apple recommends migrating per file, one class at a time. Its documentation also says "Don't delete the .m and .h files immediately; use them to troubleshoot."

Android Studio also converts one file at a time.

Migrating smaller parts of the application makes verification easier. If you find a difference in a single class, there are fewer places you need to investigate.

There's another problem to consider. The existing implementation might still be changing while you're migrating it.

Anthropic's Python API "continued changing throughout the migration, so parity was a moving target."

They later introduced a merge check. Anyone changing the Python code had to make the corresponding change in Rust or request an exemption.

I'd follow the same rule in an app. If someone fixes a bug in a Java class that already has a Kotlin implementation, apply the fix to both.

Shadow the function inside the app

Headline "Shadow the function inside the app" with Shadow highlighted in a green pill. Body text: "Run old and new code together, compare results, and return the legacy result." Two glowing windows sit behind a magnifying glass with a check mark. A phone lists three steps: Old Code Use, New Code Try, and Return Legacy Result.

Anthropic explains shadowing like this:

"Running requests through old and new code and comparing the results is often called shadowing."

In a mobile application, we can do this inside the app process without involving a server.

GitHub's Scientist README provides a useful example of this pattern.

You put the existing implementation inside a use block and the new implementation inside a try block. The caller always receives the result from use.

The experiment can also run the new block, randomize the execution order, compare the results, handle exceptions from the new implementation and publish the findings.

Scientist is a Ruby library. We're only borrowing the pattern here.

Below is a minimal Kotlin implementation. The candidate runs on an executor with a timeout. The shadowRun function returns the legacy result right away, so a slow or hanging candidate doesn't block or delay the caller.

import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger

fun interface Step {
    fun run(input: String): String
}

fun interface Reporter {
    fun report(record: DiffRecord)
}

data class DiffRecord(
    val step: String,
    val firstDiff: Int,
    val legacyLength: Int,
    val candidateLength: Int,
)

fun compareStep(step: String, legacy: String, candidate: String): DiffRecord? {
    if (legacy == candidate) return null
    val shared = minOf(legacy.length, candidate.length)
    val first = (0 until shared).firstOrNull { legacy[it] != candidate[it] } ?: shared
    return DiffRecord(step, first, legacy.length, candidate.length)
}

fun newShadowExecutor(): ExecutorService {
    val n = AtomicInteger()
    return Executors.newCachedThreadPool(object : java.util.concurrent.ThreadFactory {
        override fun newThread(r: Runnable): Thread {
            return Thread(r, "shadow-${n.incrementAndGet()}").apply { isDaemon = true }
        }
    })
}

fun shadowRun(
    name: String,
    input: String,
    legacy: Step,
    candidate: Step,
    reporter: Reporter,
    executor: ExecutorService,
    timeoutMs: Long = 1_000,
): String {
    val expected = legacy.run(input)
    val task: Future<String> = executor.submit(Callable { candidate.run(input) })
    executor.execute(Runnable {
        try {
            val candidateOut = task.get(timeoutMs, TimeUnit.MILLISECONDS)
            compareStep(name, expected, candidateOut)?.let { reporter.report(it) }
        } catch (e: Exception) {
            task.cancel(true)
            try {
                reporter.report(DiffRecord(name, -1, expected.length, -1))
            } catch (_: Exception) {
                // The caller already has the legacy result.
            }
        }
    })
    return expected
}
Enter fullscreen mode Exit fullscreen mode

The report can arrive after shadowRun has returned. Remember to shut down the executor when the screen or process that created it ends.

Notice that the record contains the position of the difference and the lengths of both results. It doesn't contain the actual text.

Anthropic couldn't read customer requests or replies, so "instead of looking at text, we recorded the shape of each difference, such as where it happened in the service and how big it was."

In a mobile app, those strings could contain a user's address, message or search query. We shouldn't send that information to analytics just to identify a difference.

Another useful part of this approach is comparing the output at each step.

Anthropic compared each stage before and after the model call, and "the first place they differed indicated roughly where the migration code differed from production code."

If your implementation parses data, maps it and then formats it, call shadowRun separately for each stage.

Comparing only the final output tells you that something went wrong, but you still need to find out where.

Be careful about which functions you shadow. Parsing, mapping, validation and price or date arithmetic are good candidates because they can be run twice safely.

Don't do this with functions that write to a database or call a payment endpoint.

Anthropic faced the same problem on the server. As they explain, "Common tools for shadowing often assume that a request can safely run twice, or that a service is deterministic," and their API needed to ensure that a request counted only once toward a customer's limits and bill.

Scientist's README also warns that the two blocks run one after the other in random order. The data they depend on might change between executions, producing a mismatch even when there's no bug.

Start by running an experiment where both blocks call the existing implementation. The mismatch rate from that experiment gives you your noise floor.

Mirror traffic when the backend is what's moving

Headline "Mirror traffic when the backend is what's moving" with Mirror highlighted in a green pill. Body text: "Send the same requests to both versions, compare responses, and keep users on the old one." A phone sends the same requests through a Compare Responses scale card to two server racks labeled Old Backend and New Backend.

If you're migrating a Java backend service to Kotlin, you can shadow entire requests instead of individual functions.

Envoy's route configuration provides a request mirror policy for this.

The documentation describes a router that "is capable of shadowing traffic from one cluster to another," using a "fire and forget" approach.

Envoy "will not wait for the shadow cluster to respond before returning the response from the primary cluster."

route:
  cluster: api_legacy
  request_mirror_policies:
    - cluster: api_candidate
      runtime_fraction:
        default_value:
          numerator: 5
          denominator: HUNDRED
Enter fullscreen mode Exit fullscreen mode

This configuration copies five percent of requests to the candidate service. Users continue receiving responses from the legacy service.

Envoy also appends -shadow to the incoming Host header. For example, it becomes api.example.com-shadow, so the candidate service must accept that host.

One thing to keep in mind is that Envoy's mirror documentation explains how to copy the requests. It doesn't explain how to compare the responses.

You'll need to implement that part yourself. You can log both responses using the same correlation ID or store the candidate's output somewhere you can join it with the original output.

Anthropic's recommendation was "Carefully design the verification signal."

If you want to know which step produced a different result in production, you need to build that into your verification process.

You also need to account for nondeterminism before enabling mirroring.

Claude can return different answers for the same request. To handle this, Anthropic "ran the model once and replayed the model output to Rust."

Both implementations received identical model output, and every stage had to match exactly.

Your backend might not call an AI model, but it probably uses a clock, a random number generator or an ID generator.

Pin or replay those values during verification. Otherwise, you might spend time investigating differences caused by the environment rather than the migration.

Group the diffs by fingerprint

Headline "Group the diffs by fingerprint" with fingerprint highlighted in a green pill. Body text: "Use a stable fingerprint to group similar differences and find the real issues faster." A stack of documents flows into a Fingerprint icon, then splits into three grouped result cards. A large fingerprint icon sits on a pedestal at the right.

Once you start shadowing production traffic, you'll have a lot of difference records to review.

Anthropic recorded where the difference appeared in the code, which part of the prompt was affected, the byte where the difference started and the length of each result.

They used this information as a fingerprint because "one bug tends to leave the same fingerprint on every request it affects."

The problem is that a single bug "could produce hundreds of thousands of nearly identical diff records," which makes reviewing individual records impractical.

Anthropic ran a script every 10 to 30 minutes. It grouped the records according to which fields differed and raised an alert only when it found a new kind of record.

I'd use the same idea with the Kotlin example above.

Group the records by step, the position of the first difference and the two lengths. A thousand mismatches can usually be reduced to a handful of causes.

Start by fixing the largest group.

Don't let the checker be edited by the thing being checked

Headline "Don't let the checker be edited by the thing being checked" with checked highlighted in a green pill. Body text: "Keep your verification and test suite independent so the tests stay a fair judge." A laptop shows a Test Suite with green check marks and a locked shield. A robot hand reaching for an edit card is blocked by a red X.

Anthropic shared an example of an agent proposing a fix that passed verification but still wasn't suitable for production.

The agent found that the Rust API was missing the description of a web search tool. It proposed copying the description into files that Rust could read.

The prompts matched after the change, and the local verification passed.

An engineer rejected the fix because the Rust implementation would need to call the actual service before launch anyway.

Anthropic explains the limitation well:

"A verifier can tell an agent whether the outputs matched, but not whether the fix is good enough to ship."

I think this example, along with the more than 100 weakened assertions, gives us a useful rule for AI-assisted migrations.

The comparator, recorded inputs and existing tests are what we use to judge whether the migration is correct.

The person or agent doing the migration shouldn't change those checks in the same pull request without a human reviewing that part first.

It's the cheapest control available. A pull request that changes both the implementation and its tests deserves closer review than one that only changes the implementation.

Roll out in steps, and shadow before the store

Headline "Roll out in steps, and shadow before the store" with store highlighted in a green pill. Body text: "Verify with shadow runs, then enable for a small percentage, and roll out to everyone." Three connected stages labeled Shadow Run, Small Percentage, and Everyone lead to a phone with an App Store download icon.

Anthropic describes the migration as building a second ship alongside the first while it continues sailing.

Once they were confident that both implementations behaved the same way, "we moved the passengers over a few at a time."

We can do something similar with mobile app releases, but there are limitations.

Google Play's staged rollouts distribute an update to a percentage of randomly selected users.

That percentage "won't increase automatically," so someone needs to increase it manually.

You can halt the rollout, but users who have already received the update "will remain on that version."

App Store Connect's phased release distributes an update over 7 days to users who have automatic updates enabled.

You can pause the phased release for up to 30 days in total. However, anyone can still download the update manually at any time.

The important thing to understand is that stopping a rollout prevents further distribution. It doesn't remove the version from devices that already have it.

For a mobile app, I'd include shadowing in a release before switching to the new implementation.

Release N contains both implementations. It returns the legacy result and reports fingerprints whenever the results differ.

Release N+1 switches to the new implementation using a staged rollout. Do this only after the fingerprint counts for each step have stayed at zero for a period you decided on in advance.

A backend service can often be rolled back quickly. We don't have that same option with an application binary that's already installed on a phone.

So more of the verification needs to happen before we switch the implementation.

Where this lands

Headline "Where this lands" with lands highlighted in a green pill. Body text: "A safer way to replace old code with confidence by comparing results, reducing risk, and keeping users stable." Three icon cards read Replace Old Code, Reduce Risk, and Keep Users Stable. A phone on the right shows a large green check mark.

Anthropic describes how the engineering work shifted toward writing "the rules and checks that agents worked within."

I agree with that approach.

If an AI agent can generate the implementation in a week, spending only an afternoon planning how to verify it isn't enough.

Decide how much time and effort you can spend on verification before starting the conversion. Use that budget to decide how much code you can safely migrate at once.

Sources

Top comments (2)

Collapse
 
remycalder profile image
Remy Calder •

one thing that carries over from the anthropic write-up pretty directly on android: since kotlin and java interop, you can leave the old java test files untouched and point them at the converted kotlin class. then the tests can't be edited in the same change as the code, which is how their 100+ weakened assertions got in. you'll usually need a few annotations for it to compile, like @JvmStatic on companion functions, @JvmOverloads where kotlin uses default args, and calling properties as getX(). if a test really needs changing, it's worth doing in its own commit so someone reads it on its own.

on the shadowRun code, the catch block reports a timeout and a candidate exception the same way (firstDiff = -1). since the nullability NPE is the main risk you describe, I'd add a kind field (mismatch, exception, timeout) plus the exception class name, still no input text. otherwise a !! crash from the converter looks the same as a slow call.

and a small one for the date and price arithmetic you suggest shadowing: legacy and candidate now run at the same time on different threads, so if the java side shares a static SimpleDateFormat, the two runs can mess up each other's parsing and show diffs that aren't migration bugs. running your both-legacy noise floor experiment with the same threading setup should show it if it's there.

(disclosure: drafted with AI help, and I'm building something in the "did the agent's change actually behave" space)

Collapse
 
prikshit profile image
Prikshit •

I'd replace the shared firstDiff value for both failures with a sealed outcome using Mismatch, Threw with the exception class, and TimedOut. This separates a !! crash from a slow call without recording user text. The legacy execution finishes before the candidate is submitted, so there's no race within one call. However, the candidate can overlap the next call's legacy execution, where a shared static SimpleDateFormat would break.