读见

将我们的 Messages API 迁移到 Rust

原题Migrating our Messages API to Rust

约 18 分钟约 4,453 字原文英文已翻译

推荐理由核心接口迁移团队可以沿 Anthropic 的影子请求设计检查哪些行为足以比较新旧接口,以及怎样保留退路。

读前速览

5 个要点

Anthropic 将 Messages API 从 Python 迁移到 Rust,并把生产系统本身转化为验证器,借助检查点、指纹识别和多智能体验证循环,在零停机的情况下将 CPU 使用量降低 70%,响应速度提升 20%。

  1. 将 API 流量增长 1,800 倍(从 2024 年到 2026 年)作为背景,迁移从 Python 到 Rust 的主要动因是降低 CPU 开销并改善延迟。

    随着 Messages API 不断发展,每个请求都需要经过验证、提示词构建、分词和安全筛查,Python 在对象创建、内存管理和跨语言通信方面的开销逐渐成为瓶颈,因此提升效率对规模化至关重要。

  2. 传统测试方法难以胜任,因为测试与 Python 实现耦合,且无法完整覆盖生产环境中的边缘情况。

    现有的 700 项集成测试与 Python 的行为紧密耦合,无法覆盖 JSON 字符转义等细微差异;API 配置的组合数量又呈爆炸式增长,使得穷举测试并不现实。

  3. 团队构建了一套基于生产环境的验证系统,利用检查点和指纹识别定位并归类 Python 与 Rust 实现之间的差异。

    检查点会对比每个处理步骤(验证、提示词构建、分词),以定位差异出现的位置;指纹识别则记录差异的位置和规模,便于对错误进行分组并高效跟踪修复情况。

  4. 多智能体验证循环让团队能够快速迭代并部署修复方案,而无需让服务离线。

    内部循环用于在沙箱中测试拟议的修复方案,外部循环则在实时流量中验证变更;记忆循环会将修正记录为可复用规则,让智能体能够不断学习和改进。

  5. 迁移后 CPU 使用量降低 70%,首 token 中位时间缩短 20%,同时保持了功能开发速度。

    团队只运行一次模型,再将输出回放给两个版本,从而在不影响客户体验的情况下验证两者的一致性。这使他们能够完成全面迁移,在保留原有功能的同时大幅提升性能。

完整摘要

本文详细介绍了 Anthropic 如何将 Messages API 从 Python 迁移到 Rust,以及如何应对在实时、非确定性系统中验证正确性的挑战。团队制定了一套验证方案,将生产环境中的 API 视为预言机,通过检查点对比每个处理步骤,并使用指纹识别对特定错误进行分组和定位。他们还实现了嵌套验证循环:用于快速测试的内部沙箱循环、用于验证的外部生产循环,以及用于从错误中学习的记忆循环。这一方案让团队成功发布了基于 Rust 的 API:每个请求的 CPU 使用量降低 70%,首 token 中位时间缩短 20%,同时保持了功能开发速度,并避免了服务停机。

目录 · 13 节

查看原文

01为什么要迁移?01Why migrate?

许多问题都存在生成器与验证器之间的差距:验证一个解是否正确,往往比想出一个解容易得多。数独就是一个经典例子。检查答案很简单(只需数一数每行、每列和每个宫格中的数字),但找到答案可能要花很长时间。许多颇具雄心的 Claude 项目都利用了这一差距:无论是将数学证明形式化,还是迁移经过充分测试的大型代码库,只要 Claude 有可靠的方法验证自己的工作,就能承担这些任务。Many problems have a generator–verifier gap: it’s often far easier to verify that a solution is correct than to come up with one. Sudoku is a classic example. It’s simple to check the solution (just count the numbers in each row, column, and box), but finding that solution can take a long time. Many ambitious Claude projects have relied on this gap: formalizing proofs in mathematics or migrating large, well-tested codebases are tasks Claude can take on as long as it has a reliable way to verify its work.

但随着 Claude 的能力不断增强,它开始承担实际运行系统中的项目,而在这些系统里,生成代码比验证代码更容易。用户往往会依赖测试套件未涵盖的边界情况和各种特性,也很难写出一个面面俱到的“正确”定义。若没有可靠的方法来检查 Claude 的成果,就很难放心地迁移实际运行中的系统——无论 Claude 生成相关代码的速度有多快。But as Claude has become more capable, it’s begun to take on projects in live systems, where generating the work is easier than verifying it. In these systems, users often rely on edge cases and quirks that fall outside the test suite, and it’s hard to write a definition of “correct” that covers everything. Without a reliable way to check Claude’s work, the migration of a live system is hard to trust—however quickly Claude can generate the code for it.

我们在将 Messages API 从 Python 迁移到 Rust 时遇到了这个问题。这个 API 是客户以及我们自己的应用(如 Claude Code 和 Cowork)访问 Claude 的主要方式。从 2024 年初到 2026 年秋季,API 流量增长了约 1,800 倍。Rust 能让我们大幅降低每个请求的 CPU 使用量。Claude 在大约一周内编写了 API 核心请求路径的第一个版本。但要让我们对这次迁移建立信心,就必须找到一种方法,验证 Rust API 是否与生产环境中的 API 保持一致。事实证明,这很难,原因有几个:迁移期间 Python API 一直在变化,因此一致性的目标也在不断变化;Claude 对同一个请求可能会给出不确定的回复,因此两个输出之间的差异并不一定意味着存在 bug;而且我们无法读取客户的请求,所以很难弄清楚两个版本在哪些地方出现了差异。We ran into this problem when we migrated our Messages API from Python to Rust. This API is the primary way that customers—as well as our own apps, like Claude Code and Cowork—reach Claude. From early 2024 to fall 2026, API traffic grew roughly 1,800 times. Rust would allow us to use far less CPU per request. Claude wrote a first version of the API’s core request path in about a week. But building trust in the migration required us to find a way to verify that our Rust API was at parity with our production API. This proved hard for several reasons, including that the Python API continued changing throughout the migration, so parity was a moving target; Claude can reply nondeterministically to the same request, so a difference between two outputs didn’t necessarily mean a bug; and we couldn't read customer requests, so we weren't able to easily see where the two versions diverged.

在这篇文章中,我们将分享如何把生产环境中的 Messages API 本身变成验证器,以及这如何帮助我们在生产流量上测试新的 Rust 版本、找出两者的差异,并自动派发智能体来修复这些差异。借助这一做法,我们成功上线了 Rust API:每个请求的 CPU 使用量减少约 70%,首个令牌的中位耗时缩短约 20%,整个过程中既没有让服务下线,也没有暂停功能开发。In this post, we share how we turned the production Messages API itself into a verifier—and how that helped us test the new Rust version on production traffic, find where it differed, and automatically dispatch agents to fix those differences. This allowed us to ship an API on Rust that uses about 70% less CPU per request and cuts median time to first token by about 20% without ever taking the service offline or freezing feature development.

为什么要迁移?Why migrate?

我们于 2023 年构建了 Messages API,并使用 Python 编写,因为当时我们的许多研究代码都在内部广泛使用 Python。起初,它很简单:Messages API 将请求传递给模型,再把模型生成的内容返回。(当时有位工程师称它“基本上就是一个请求转发器”。)但随着 Messages API 的能力不断增强,并与我们的代码库深度集成,它也开始与研究团队和推理团队维护的 Python 库形成共享依赖,这让迁移变得困难。如果我们想改用其他语言,就意味着要从头重建日志记录、指标和工具。We built the Messages API in 2023 and wrote it in Python, which was widely used internally for much of our research code. At first, it was simple. The Messages API passed requests to the model and sent back what the model wrote. (One engineer at the time called it “basically a request forwarder.”) But as the Messages API became more capable and deeply integrated with our codebases, it also developed shared dependencies with Python libraries that were owned by our research and inference teams, which made it hard to move. If we ever wanted to move to another language, it would mean building logging, metrics, and tools all over again.

这种权衡逐渐开始发生变化。到 2025 年底,每个 Messages API 请求都必须经过验证、转换为提示词、分词,并由我们的安全分类器进行筛查。每当回复到达时,Token 流都必须被分类为文本、思考内容和工具调用;而每当 Python 创建对象、释放内存或将工作交给下一个任务时,都会为这些步骤增加额外开销。流量最终远远超出了最初构建该 Python 服务时的承载能力(图 1),我们很快就需要找到让服务效率大幅提升的方法。This calculus gradually began to change. By late 2025, every Messages API request had to be validated, converted into the prompt, tokenized, and screened by our safety classifiers. As each reply arrived, the stream of tokens had to be sorted into text, thinking, and tool calls, and Python added overhead to every one of those steps each time it created an object, freed memory, or handed its work to the next task. Traffic eventually grew far beyond what the initial Python service was built for (Figure 1), and we quickly needed to find a way to make the service much more efficient.

Bar chart of API requests per day by month, from January 2024 to October 2026. Bars are barely visible through 2024, rise gradually in 2025, and climb steeply in 2026 to their highest point in October.
The monthly average of API requests per day on our own platform, including our own use.

逐步进行,还是一次性完成?Incremental or all at once?

大型生产系统的全面重写通常会谨慎对待,至少有两个原因。首先,无法保证测试套件覆盖了生产代码行为的 100%,重写存在风险。其次,这类工作所需的投入实在太大,往往难以完成。(2024 年,在一位工程师建议迁移到 Go 或 Rust 后,另一位暂时为这个问题定了调:“我们不会用 go 或 rust 重写 API!”)Full rewrites of large production systems are often approached cautiously, for at least two reasons. First, there is no guarantee that test suites cover 100% of production code behavior, and rewriting it is risky. Second, the sheer effort required often makes such work intractable. (In 2024, after one of our engineers suggested migrating to Go or Rust, another temporarily settled the question: “We are not rewriting the API in go or rust!”)

因此,如果你想提升性能,通常的建议是只重写拖慢系统的部分,我们也正是从这里入手的。在 Rust 中,我们重写了解析模型输出的代码,并从 Python 中调用它。这使 API 的 CPU 使用率降低了约 8% 到 10%。然而,增量式方案往往会增加复杂性,因此务必确认增量改进带来的收益足以抵消这些成本。就我们的情况而言,这些收益不足以抵消新增的复杂性。现在,每个 token 都要在 Python 和 Rust 之间传递三次(图 2),带来了新的开销来源。The standard advice if you’re looking for performance gains is thus to rewrite only the parts that are slowing the system down, so that’s where we started. In Rust, we rewrote the code that parses a model’s output and called it from Python. This reduced the API’s CPU usage by about 8% to 10%. However, incremental solutions often incur added complexity, and it’s important to make sure that incremental improvements justify those costs. In our case, the gains didn’t justify the added complexity. Each token now crossed between Python and Rust three times (Figure 2), creating new sources of overhead.

Two diagrams of the request path. In the partial rewrite (March 2026), Rust receives and parses tokens while Python does the other steps, so each token crosses between languages three times. In the full rewrite (September 2026), Python hands over the request and Rust does every other step around the model.
After the incremental rewrite, each token of a reply crossed between Python and Rust three times.

随着 Claude 的能力不断增强,我们开始质疑,避免全面迁移的那些常见理由是否依然成立。开展这项工程所需的工作量正在迅速减少:到 2026 年 5 月,Anthropic 合并的代码中,超过 80% 是由 Claude 编写的。我们想知道,Claude 是否已经能够帮助我们编写代码,通过实证捕捉生产系统中的每一种行为和修复。但问题变成了:我们该如何验证迁移后的行为是否正确?瓶颈已经从代码生成转向了验证。As Claude became increasingly capable, we began to question whether the usual reasons to avoid a full migration still held. The effort required to undertake the project was dropping fast: by May 2026, Claude was writing more than 80% of the code Anthropic merged. We wondered if Claude could now help us write code that would empirically capture every behavior and fix in the production system. But the question became: how could we verify that the behavior of our migration was correct? Verification, not generation, had become the bottleneck.

我们如何验证迁移How we verified the migration

通用方法General approaches

为了验证迁移是否成功,我们首先需要定义“正确”意味着什么。这可以通过几种方式来实现(图 3)。如果运气好,你可以直接写一条规则。数学中的定理是一种精确的陈述,而证明助手(如 Lean)可以依据一组固定规则检查证明的每一步。另一些时候——在软件工程中更常见——你会通过一组示例(如测试)来定义“正确”。例如,Bun 从 Zig 迁移到 Rust 时,它的测试套件是用 TypeScript 编写的,因此同一套测试可以评判两个版本。就我们的情况而言,这两种方法都不够,因此我们在迁移过程中使用现有系统作为判定基准,以测试两者是否保持一致。不过,我们的现有系统(Messages API)一直在变化。我们定期发布新模型、推出新功能,这使得“正确”的定义也在不断变化。To verify the migration, we first needed to define what “correct” meant. You can do this in a few ways (Figure 3). If you’re lucky, you can simply write a rule. A theorem in mathematics is a precise statement, and a proof assistant (like Lean) can check each step of a proof against a fixed set of rules. Other times—and more frequently in software engineering—you define “correct” with a set of examples, like tests. For instance, when Bun moved from Zig to Rust, its test suite was written in TypeScript, so the same tests could judge both versions. In our case, neither approach was sufficient, so we used the existing system as an oracle to test parity during the migration. In this case, our existing system (the Messages API) kept changing. We were releasing new models and shipping new features regularly, which made the definition of “correct” a moving target.

Three rows, each sending a signal to a Claude agent. A rule, like Lean for proofs, is all written down and flags a step that doesn’t follow. Examples, like Bun’s test suite, are partly written down and flag a failing test. An existing system, like our Python service, has no answers written down, so you build a checker that flags where the two differ.
Three common sources of “correctness.”

测试Tests

测试是我们最容易着手的地方,因为我们已经有一套约 700 个集成测试。不过,有两个问题让我们无法信任这些测试能够验证如此高风险的迁移是否正确(图 4)。Tests were the easiest place for us to start, since we already had an existing set of about 700 integration tests. However, two problems limited our ability to trust them to verify the correctness of a migration as high stakes as this (Figure 4).

这些测试与 Python 实现耦合在一起。集成测试会发送请求,然后检查回复以及发送给其他服务的内容。我们的测试在测试进程内部运行 Python API,并在 Python 内存中模拟计费、限流等服务。代码变更时,测试也必须随之修改,而 Claude 两边都帮了忙。如今,“通过”可能意味着代码正确,也可能意味着测试被修改后放过了错误代码。我们确实发现了这种情况:审查移植后的测试时,我们发现有 100 多处断言被弱化。The tests were coupled to the Python implementation. An integration test sends a request, then checks the reply and what was sent to other services. Our tests ran the Python API inside the test’s process and mocked services, like billing and rate limiting, in Python’s memory. The tests had to change along with the code, and Claude helped with both. Now, a “pass” could mean that the code was right, or that the test had been changed in a way that let wrong code through. We saw this happen: when we audited the ported tests, we found more than 100 weakened assertions.

测试并不完整。Messages API 有几十项功能,而配置组合实在太多,无法逐一穷尽测试。仅 20 个二元选项就会产生超过一百万种组合——按每项测试一秒计算,一个模型就需要测试 12 天,而且这还没算调整其中的提示词。在实践中,工程师会测试一部分配置,尽量模拟生产环境,但这个过程不可避免地会遗漏一些情况。有些项目(如 Bun)拥有足够全面的独立测试套件,可用于评估重写是否正确。许多生产服务则没有这样的测试套件;正确与否,既取决于它们的实际行为,也取决于测试或文档中的描述。The tests were incomplete. The Messages API has dozens of features, and there are far too many configurations to test them exhaustively. Just 20 binary options make over a million combinations—that translates to 12 days of tests at a second each, for one model, before we even vary the prompts inside them. In practice, engineers test a subset that tries to approximate production, but that process inevitably misses cases. Some projects, like Bun, have an independent suite that’s extensive enough to judge a rewrite. Many production services don’t; what counts as correct depends as much on how they behave as on what’s in their tests or documentation.

Two panels. Left, tests coupled to the legacy implementation: a Python test is ported to a Rust test that Claude also wrote, which checks a smaller area and misses differences. Right, incomplete tests: a few small clusters of checked cases in a large grid of feature combinations, with many missed differences outside them.
A ported test may check less than the original (dashed), and tests cover only the combinations someone thought of.

检测与生产环境的一致性Detecting parity with production

生产数据有时是检验新代码是否与旧代码行为一致的“唯一可靠标准”。将请求分别交给新旧代码处理,再比较结果,这通常称为影子测试。要了解我们需要比较什么,可以看看一条请求在 Messages API 中的处理过程(图 5)。API 会验证每条请求,将其转换成模型可读的提示词(用于推理的提示词),对其进行分词,并通过安全分类器检查。随后,模型逐个生成 token 来撰写回复。在输出端,API 会将这些 token 分类为文本、思考内容和工具调用,流式传输给客户,并统计用量,以便执行限额和计费。Production data is sometimes “the only true test” that new code behaves like the old code. Running requests through old and new code and comparing the results is often called shadowing. To understand what we needed to compare, it helps to walk through what happens to a single request on the Messages API (Figure 5). The API validates each request, converts it into a prompt a model can read (the prompt for inference), tokenizes it, and runs it through safety classifiers. A model then writes a reply, one token at a time. On the output side, the API sorts those tokens into text, thinking, and tool calls, streams them to the customer, and counts usage for limits and billing.

Flow diagram of a request. The input path accepts or rejects it, resolves settings, and builds the prompt; about a quarter of inputs matched at first. Claude runs once. The output path sorts the reply, streams it, and counts usage. Examples of differences include a rejected field, a 1M limit read as 200K, a missing tool description, stripped newlines, and missing usage fields. The risk designed against is a copy counted twice.
The Messages API’s input and output paths. Filled dots are examples of differences we found between Python and Rust. The hollow dot is a risk we had to prevent.

此次迁移涵盖了输入和输出路径。某些差异显而易见,例如 Rust API 拒绝了 Python API 曾接受的请求。但许多差异则很微妙。比如,如果 Rust API 漏掉了提示词的一部分,请求仍会成功,模型也仍会作答,只是有时答案会略有不同。The migration covered both the input and output paths. Some differences were obvious, such as when the Rust API rejected a request that Python had accepted. But many were subtle. For instance, if the Rust API left out part of a prompt, the request would still succeed and the model would still answer, though sometimes with minor differences.

我们的 Rust API 在 4 月通过了约 98% 的测试,但在生产流量中,只有约四分之一的输入匹配(图 6)。差距部分源于生产流量中的一些情况未被测试覆盖。例如,Python 写入 JSON 工具调用时,会将某些字符(如表情符号)转义为文本编码。Rust 则原样写入这些字符,因此两个提示相差了几个字节。生产环境对 bug 的影响也有不同的加权方式。在测试套件中,每个用例只计一次;而在实时流量中,某个 bug 会出现在每个触发它的请求中,这意味着一个常见的 bug 就可能造成大量不匹配。Our Rust API passed about 98% of its tests in April, yet only about a quarter of inputs matched on production traffic (Figure 6). The gap came partly from cases in production traffic that our tests didn’t cover. For example, when Python writes JSON tool calls, it escapes certain characters (e.g., an emoji) by replacing them with text codes. Rust wrote those characters as is, so the two prompts differed by a few bytes. Production also weighted bugs differently. In a test suite, each case counts once, but in live traffic, a bug will show up in each request where it’s triggered, which means a single common bug can cause many mismatches.

Line chart of the share of inputs that matched, from late April to August. It starts at 24%, drops to 6.5% in early May, then rises sharply as fixes roll out, with two falls from changes on the Rust side, and ends at 99.6%. The comparison began on our own traffic and then moved to a wider sample.
How often Rust’s input matched Python’s on the requests we compared. Replies were compared separately. Each dot is a day, and the line is a seven-day median. What we compared changed over time, and six misleading days are left out.

常见的流量镜像工具通常假设请求可以安全地运行两次,或者服务具有确定性。但这些假设并不适用于我们的情况。我们必须确保每个请求在计算客户的使用限额和账单时只计入一次。此外,Claude 具有非确定性,也就是说,相同的输入可能得到不同的回复(图 7)。为此,我们只运行一次模型,然后将模型输出回放给 Rust。Common tools for shadowing often assume that a request can safely run twice, or that a service is deterministic. These assumptions didn’t apply in our case. We had to ensure that a request only counted once toward a customer’s limits and bill. In addition, Claude is nondeterministic, meaning that replies can differ for the same input (Figure 7). To address this, we ran the model once and replayed the model output to Rust.

即使两个版本使用的是相同的模型输出,我们仍必须比较模型调用前后的每个阶段,并确保结果完全一致。在许多系统中,错误输入会导致调用链下游某处报错。但由于 Claude 几乎接受任何提示词,即使是细微的偏差也可能改变它的回复,却不会触发错误。我们比较了模型调用前后的每一步,以便找出任何可能改变客户收到内容的偏差。With both versions working from the same model output, we still had to compare every stage before and after the model call, and the results had to match exactly. In many systems, bad input causes an error somewhere down the stack. But since Claude accepts almost any prompt, even a small deviation can change its reply without triggering an error. We compared each step before and after the model call, so that we could pin down any deviation that might change what a customer received.

Two comparisons. In a typical service, two old copies and a new one match on ID, the new copy shows a bug in the total, and the time varies, so it is ignored as noise. In an inference API, two Python copies and Rust each word the answer to “Is 91 prime?” differently, so the whole reply would count as noise and go unchecked.
Diff tools often run the old code twice to learn what varies on its own, then ignore it. Claude's replies vary, so those tools would ignore them, along with any bugs in them.

对我们来说,重要的是以保护用户隐私的方式完成这项工作。为此,我们必须在不读取用户请求或 Claude 回复的情况下开展工作,这意味着我们很难直接看出 API 的 Rust 版本和 Python 版本之间有哪些差异。因此,我们没有查看文本,而是记录每项差异的特征,例如差异出现在服务的哪个位置,以及差异有多大。我们采用了几种不同的方法来做到这一点:It was important to us to do this in a way that protected user privacy. To do that we had to work without reading user requests or Claude’s replies to them, which means we couldn’t easily see where the Rust and Python versions of the API differed. 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. We did this using a few different approaches:

  • 检查点。两个 API 版本都通过相同的步骤处理请求:接受或拒绝请求、解析其设置、构建提示。每个步骤都会产生一些结果,例如错误或提示的组成部分,我们可以逐步比较这些结果,也可以逐块比较提示内容。它们首次出现差异的位置,大致表明了迁移代码与生产代码的差异所在(图 8)。
    Checkpointing. Both API versions handle a request using the same steps: accept or reject it, resolve its settings, build the prompt. Every step produces some result, such as an error or the pieces of the prompt, that we could compare step by step, and within the prompt, piece by piece. The first place they differed indicated roughly where the migration code differed from production code (Figure 8).
Python and Rust compared at each step, with the model called once and its output replayed to Rust. Building the prompt is the first step to differ: in piece 2, two keys are in a different order from byte 17. The record passed to a Claude agent lists the step, piece, both lengths of 190 bytes, and first differing byte, but no text.
Comparing at checkpoints, simplified, with made-up values. The first step to differ shows where to look. The record gives the piece, the lengths, and where they first differ, but not the text.
  • 指纹。大致确定每处差异所在的位置后,我们仍需要一种方法来区分不同的 bug。我们记录了每处差异在提示词中的起始位置,以及两个版本之间的长度差异。结合检查点机制中隔离出的提示词步骤和片段,我们发现 bug 会呈现出特定的指纹。也就是说,同一个 bug 往往会在它影响的每个请求中留下相同的指纹(图 9)。这样,我们就可以按指纹对错误进行归类,从而帮助我们确定修复工作的优先级。
    Fingerprint. Once we knew roughly where each diff resided, we still needed a way to distinguish one bug from another. We recorded where each difference began in the prompt, as well as the length difference between the two versions. Combined with the step and piece of the prompt isolated in checkpointing, we found that bugs presented with a specific fingerprint. That is, one bug tends to leave the same fingerprint on every request it affects (Figure 9). We could then group errors by fingerprint, which helped us triage the fixes.
Four dot grids show mismatches being counted, grouped by fingerprint, split by build, and regrouped after a fix. Fingerprint A accounts for nearly all mismatches; fixing it reveals two older groups, B and C. A table below distinguishes the three by piece and position in the prompt, length gap, and hash.
Fingerprints from one kind of request. A, at the start of the prompt, hid older differences. Once it was fixed, they appeared as B and C. Dots are illustrative.

最终我们构建了一个影子系统,用来记录 Rust 和 Python API 之间的每一处差异。下面是一个示例,数值均为虚构:The result was a shadowing system that produced a small record of each difference between our Rust and Python APIs. Here is an example, with made-up values:

step:        build prompt     ← where in the code
piece:       2                ← where in the prompt
first diff:  byte 17          ← fingerprint
python:      190 bytes        ← fingerprint
rust:        190 bytes        ← fingerprint

然后,我们可以把这条记录交给智能体修复。We could then pass this record to an agent to fix it.

验证循环Verification loops

每个存在差异的请求都会在我们的日志中留下一条记录。单个 bug 就可能产生数十万条几乎相同的差异记录。我们没有把每条记录都发送给一个代理,而是每隔 10 到 30 分钟运行一次脚本,按差异字段对记录进行分组;只有发现新类型的记录时,才会通知负责协调的 Claude 代理。这个协调代理会为每种新类型的记录分配一个负责处理它的工作代理。它还会在共享的 Slack 频道中创建一个新话题,方便人类工程师跟进,并在必要时引导处理流程。Each request that differed left a record in our logs. A single bug could produce hundreds of thousands of nearly identical diff records. Rather than send each to an agent, we ran a script every 10 to 30 minutes that grouped them by which fields differed, then alerted a coordinating Claude agent only when it saw a new kind of record. This coordinator assigned a worker agent to own each new kind of record. It also created a new thread in a shared Slack channel where human engineers could follow along and steer it when necessary.

为解决大量 bug,我们建立了一系列验证闭环。快速的内层循环为智能体提供了一个沙盒,让它们可以在其中测试想法并提出修复方案。随后,较慢的外层循环会在生产环境中验证这些修复。此外,记忆循环会记录过程中出现的错误并保存下来,让智能体能够随着时间推移不断学习(图 10)。To tackle the many bugs, we set up a series of verification loops. A fast inner loop gave agents a sandbox in which they could test ideas and propose fixes. A slower outer loop then validated fixes in production. In addition, a memory loop recorded any mistakes along the way, saving them so that agents could learn over time (Figure 10).

Three nested loops. The inner loop asks whether an edit fixes the difference, using local checks that take under a second to compare. The outer loop asks whether it is gone in production, using shadowed live traffic over hours or days. The memory loop asks why it keeps happening, and turns people’s corrections into new rules.
Verification loops. An edit is checked in a sandbox, and then on shadowed live traffic. People’s corrections become rules. Each loop can catch what the one inside it misses.

内层循环Inner loop

4 月刚开始测试时,我们给每个智能体一份记录,说明 Rust 和 Python 版本之间的差异。智能体会根据代码猜测根本原因,并提交拉取请求。修复经过审核并合并后,他们会将其部署到 staging 环境——这是 Rust API 的预生产副本,我们会在其中对测试流量运行相同的影子比较。智能体会检查差异是否已消除。由于每个假设都需要经过审核和部署,反馈往往要等上几小时甚至几天。When we first started testing this in April, we gave each agent a record that showed where the Rust and Python versions differed. Agents would guess the root cause from the code and open a pull request. Once the fix was reviewed and merged, they deployed it to staging, a preproduction copy of the Rust API where we ran the same shadow comparison on test traffic. The agents checked whether the difference was eliminated. Since every hypothesis needed a review and a deployment, feedback was taking hours or days.

我们需要让代理更早从验证中获得反馈,因此将它们移到了各自独立的工作区。我们重新设计了内循环,让代理能够快速测试想法,并在安全的环境中失败。每个代理都在云端沙箱中运行,其中包含两个代码库,以及用于检查模型调用前后行为的快速本地检查。输入检查会接收一个请求,构建各个版本将发送给模型的提示,并展示它们之间的差异。由于这项检查实际上不会调用模型,比较各个版本只需不到一秒。之后我们又添加了输出检查,用模拟模型分别运行两个版本。输出检查会将一条脚本化回复(例如工具调用)交给各个版本处理,然后比较结果。We needed agents to get a signal from verification much sooner, so we moved them into their own workspace. We redesigned the inner loop so that agents could have a place to test ideas quickly and fail safely. Each agent ran in a cloud sandbox with both codebases and fast, local checks for what happens before and after the model call. The input check took a request, built the prompt that each version would send to the model, and showed what differed. Because this check never actually called the model, comparing the versions took under a second. We later added an output check, which ran both versions against a fake model. The output check passed a scripted reply, such as a tool call, through each version and compared the results.

主要的限制是,智能体只能看到指纹,看不到每条记录背后的请求。因此,智能体会推测造成差异的原因,然后自行编写请求或模型回复,尝试复现这种差异。由于请求和回复都是由智能体自己编写的,它可以完整读取两边的结果。如果结果一致,就说明它猜错了,智能体便会再次尝试。如果结果以记录所描述的相同方式出现差异,智能体就会修改 Rust 代码,直到两个版本的结果一致,然后添加一个在旧代码上失败、在新代码上通过的测试(图 11)。The main limitation was that agents could only see the fingerprint, not the request behind each record. So an agent would hypothesize what had caused the difference, then write its own request or model reply to try to reproduce the difference. Since each agent was writing these itself, it could read both results in full. If the results matched, its guess was wrong and the agent tried again. If they differed the same way the record described, the agent edited the Rust until the two versions matched, then added a test that failed on the old code and passed on the new (Figure 11).

The inner loop, highlighted. From a fingerprint, the agent guesses the cause and writes a triggering request or reply. Input and output checks run it through both versions. If they match, it guesses again; if they differ as the record did, it edits the Rust and rechecks. Once they match after the edit, it opens a PR with a fix and a test.
Inner loop. From a fingerprint, an agent guesses the cause and writes a request or reply that should trigger it. Local checks run it through both versions until an edit makes them match.

内循环与外循环之间的分界,是人工审核的一个良好检查点。在沙盒中,猜错一次只会让智能体损失几秒钟,也不会影响用户。智能体可以自行迭代。只有经过 PR 审核后,我们才允许修复方案进入外循环;这样,工程师就能把注意力放在提议的修复方案(而不是猜测)以及验证器无法回答的问题上,例如 Rust API 与 Python API 之间的差异究竟是 bug 所致,还是有意为之。The seam between the inner and outer loops was a good checkpoint for human review. Inside the sandbox, a wrong guess cost an agent only a few seconds and had no impact on users. Agents could iterate on their own. We allowed a fix to cross into the outer loop only after it had undergone PR review; this allowed engineers to focus their attention on proposed fixes (rather than on guesses) and on the questions the verifiers couldn’t answer, such as whether a difference between the Rust and Python APIs was the result of a bug or a deliberate change.

智能体将修复方案和证据发布到各自的 Slack 讨论串中,供工程师审查。5 月中旬,Rust API 与 Python API 之间最大的剩余差异之一来自网页搜索。生产环境中的 API 会从内部服务获取网页搜索工具的描述,而 Rust API 尚未调用该服务,因此提示中缺少工具描述。一名智能体提出了一个权宜之计:将文本复制到 Rust 可以读取的文件中。这样一来,提示就匹配了,修复也通过了本地验证器的检查。但一名工程师否决了这个方案,因为它并未解决问题:Rust 仍需在上线前调用该服务,到那时,这个权宜之计就会被弃用(图 12)。Agents posted their fixes and evidence to their Slack threads for engineers to review. In mid-May, one of the largest remaining differences between the Rust and Python APIs came from web search. The production API retrieved the web search tool’s description from an internal service. The Rust API didn’t call this service yet, so the tool description was missing from the prompts. An agent proposed a shortcut to copy the text into files that would be readable by Rust. The prompts then matched, and the fix passed the local verifier. But an engineer turned it down because it didn’t solve the problem: Rust would still need to call the service before launch, at which point the workaround would be thrown out (Figure 12).

但验证器会奖励输出匹配,而智能体也找到了生成这些输出的最廉价方式。验证器可以告诉智能体输出是否匹配,却无法判断修复是否足以达到发布标准。因此,人工审核是一道重要的关卡。But the verifier rewarded matching outputs, and the agent found the cheapest way to produce them. A verifier can tell an agent whether the outputs matched, but not whether the fix is good enough to ship. That’s why human review was an important gate.

A Slack channel, #rust-migration. An engineer asks a coordinating Claude agent to explain its next target. Claude agents trace the mismatch to web search, find it is already tracked, and open a fix that loads the description from text files. A second engineer replies: “We know we have to fetch that text before we ship, so this seems like throwaway code. Abandon that PR.”
Agents trace a mismatch to the web search tool across four Slack threads and propose a fix, which an engineer rejects as throwaway code. We shortened and reworded the messages and added the thread names and agent labels.

外层循环Outer loop

在内环中,智能体排查差异并提出修复方案。在内环与外环的衔接处,工程师审查这些修复方案、提供反馈,并批准部署。随后,外环对比了应用每项修复前后的 Rust API 部署效果。In the inner loop, agents debugged differences and proposed fixes. At the seam between the inner loop and the outer loop, engineers reviewed the proposed fixes, gave feedback, and approved them to deploy. The outer loop then compared Rust API deployments with and without each fix.

为了确保这种比较公平,我们记录了每个被比较请求的相关信息,但不记录其文本,包括请求使用的模型和 API 功能,例如提示缓存、工具或扩展思考。这些信息让代理能够比较同类请求(图 13),并了解在包含修复和未包含修复的构建版本中,出现该错误特征的频率。这样,代理就能监控新构建版本中是否出现该错误。To make that comparison fair, we logged facts about each request we compared, but not its text, including which model and API features it used—for example, prompt caching, tools, or extended thinking. These details let agents compare requests of the same kind (Figure 13) and ask how often the bug’s fingerprint appeared on builds with and without the fix. This way, agents could monitor the new builds for the bug.

The outer loop, highlighted. An engineer reviews the PR, which merges and deploys to a test environment, then production. Shadowed live traffic is watched for the fingerprint. If it remains, work returns to the inner loop. If repeated checks find it gone, the task closes, and the thread reopens if it returns.
Outer loop. An engineer reviews the fix, it deploys, and shadowed traffic shows whether its fingerprint is gone. If not, the task returns to the inner loop.

我们设计外层循环,用来发现内层循环遗漏的问题。内层循环能够快速但并不完美地模拟生产环境:智能体可以在几秒钟内测试一个假设,但只能针对自己编写的请求进行测试,而且使用的本地验证器配置也不总是与生产环境完全一致。We designed the outer loop to catch problems that the inner loop missed. The inner loop simulated production quickly but imperfectly: agents could test a hypothesis in seconds, but only on requests they had written, and with a local verifier that wasn’t always configured exactly like production.

这意味着,有时修复在沙箱中通过了,但生产环境仍然存在差异。负责该 bug 的智能体会在新构建的记录中发现这一差异,或者收到协调智能体的提醒。随后,它会回到内循环,并利用这些证据提出新的假设。This means that sometimes a fix passed in the sandbox and production still showed the difference. The agent assigned to the bug would either see the difference in the new build’s records, or be alerted by the coordinating agent. It then went back to the inner loop and used that evidence to form a new hypothesis.

记忆循环Memory loop

内外循环每次只修正一个差异。记忆循环则改进了智能体进行这些修正的方式。我们不希望工程师不得不重复做同样的修正,因此记录了评审和智能体自身工作中总结出的经验,并将其应用到后续的每个智能体。The inner and outer loops fixed one difference at a time. The memory loop improved how agents made those fixes. We didn’t want engineers to have to make the same correction twice, so we recorded what came out of reviews and agents’ own work and applied it to every agent that followed.

例如,当一名工程师否决了网络搜索快捷方式(图 12)时,智能体将一条备注保存到记忆中,说明了这一决定、作出决定的原因以及正确的修复方案:让 Rust 调用提供工具描述的服务。For example, when an engineer turned down the web search shortcut (Figure 12), the agent saved a note to memory explaining the decision, the reason for it, and the correct fix, which was to have Rust call the service that supplies tool descriptions.

构建那个调用耗费了团队数周时间,而在此期间,这个 bug 仍不断产生记录。有些记录有新的指纹,因为缺失的文本出现在提示中的其他位置,或者属于使用同一服务的另一种工具。代理查看了记忆笔记,认出了这个已知 bug,并将这些记录关联到该 bug,而不是再编写一个变通方案(图 14)。Building that call took our team weeks, and in the meantime the bug kept producing records. Some had new fingerprints, because the missing text fell at other positions in the prompt or belonged to another tool that used the same service. Agents checked the memory note, recognized the known bug, and linked those records to it, instead of writing another workaround (Figure 14).

其他经验教训则成为移植代码和编写 Rust 的通用规则。在一名代理猜测 Python 的行为后,一位工程师规定,移植时必须严格遵循 Python 的实际行为。随后,一名代理按照这条规则检查现有代码,发现还有七处移植代码依赖了猜测。Other lessons became general rules for porting and writing Rust. After one agent guessed at Python’s behavior, an engineer made it a rule to port exactly what Python did. An agent then compared the existing code with that rule and found seven more places where the port had relied on a guess.

6月,某个代理还梳理了团队约60条评审意见,将反复出现的问题归类并提出规则,随后由一名工程师编辑并批准,纳入 CLAUDE.md(图14)。In June, an agent also went through about 60 of the team’s review comments, grouped the recurring problems and proposed rules, which an engineer edited and approved for CLAUDE.md (Figure 14).

这个记忆循环还将一些经验教训固化为永久检查。其中包括:当 Rust 与 Python 的实现出现偏差时就会失败的新测试;禁止审查者反复指出的问题模式的 lint 规则;以及后来新增的一项合并检查,要求任何修改 Python 代码的人都必须在 Rust 中做出相应修改,或申请豁免。The memory loop also encoded some lessons in permanent checks. This included new tests that failed when Rust drifted from Python, lints that banned patterns reviewers kept flagging, and later a merge check that required anyone changing the Python code to make a matching change in Rust or request an exemption.

The memory loop, highlighted. A repeated mistake prompts an engineer’s correction, “Did you make that up yourself?” It becomes a rule each new agent reads first, a search by another agent that finds the same mistake in seven places, and a test that fails if the versions drift. A daily read of merged changes flags what Rust might need to mirror.
Memory loop. An engineer’s correction becomes three things: a rule that each new agent reads, a search for the same mistake, and a test.

展望未来Looking ahead

借助 Claude 迁移生产系统正变得越来越可行,无论是为了提升性能还是增强安全性,都无需让 API 下线或拖慢功能开发。如今,编写新代码已不再是最难的部分,我们需要对新系统的行为与旧系统一致建立足够的信心。It’s increasingly feasible to migrate production systems with Claude, either for better performance or security, without taking an API offline or slowing feature development. Now that the hard part is no longer writing new code, we need to build sufficient confidence that the new system behaves like the old one.

迁移的常见做法有点像重建忒修斯之船:旧船的木板一块一块地被替换。通常可以在船仍航行时更换木板,但如果一次更换太多,就得进港。把这个比喻再延伸一步,如今 Claude 让我们能够在第一艘船继续航行、木板不断被替换的同时,在旁边造出一艘功能完全相同的新船。智能体让新船随着旧船的变化同步跟进,我们也不断检查两艘船的表现是否一致。确认它们确实一致后,我们便一次转移少量乘客。新船比旧船航行得更快,也更高效。The usual approach to migration is a bit like rebuilding the Ship of Theseus, in which the old ship was replaced plank by plank. Generally it’s been possible to replace planks while the ship still sails, but changing too many planks at once requires coming into dock. To fully stretch the metaphor, Claude now makes it possible to build an identically functioning ship alongside the first—even as the first keeps sailing and having its planks replaced. Agents kept the new ship in step as the old one changed, and we kept checking that the two behaved the same. Once we trusted that they did, we moved the passengers over a few at a time. The new ship sails faster and more efficiently than the old one.

经验教训Lessons learned

验证正成为新的瓶颈。过去,迁移这类大型软件项目很难证明其合理性,因为它们需要投入太多精力,风险也太高。但如果编写代码不再是瓶颈,主要限制就变成了你能多快验证结果。总的来说,只要有办法让 Claude 验证正确性,就可以设定更高的目标。Verification is the new bottleneck. Previously, large software projects like migrations were hard to justify because they took too much effort and carried too much risk. But if writing code is no longer the bottleneck, the main constraint becomes how quickly you can verify results. In general, ambition can be increased as long as there’s a way for Claude to verify correctness.

验证是建立信心的方式。在数学中,我们会使用证明助手来验证 Claude 写出的证明中的每一步是否有效。对于软件,测试或形式化验证也能帮助我们获得类似的信心。但如果这些检查还不够,生产系统本身也可以充当验证器。Verification is how you earn confidence. In math, we use a proof assistant to verify that each step of a proof Claude wrote is valid. For software, tests or formal verification can help us gain similar confidence. But when these checks aren’t enough, a production system itself can also be a verifier.

仔细设计验证信号。验证器会提供一个 Claude 可以据此采取行动的信号。我们可以校准这个信号,让 Claude 知道问题出在哪里。证明助手会指出失败的步骤,测试会标明失败的用例,而生产系统通常不会默认提供这样的信号。我们在这个项目上投入了大量精力来构建这样的信号。在这个案例中,检查点定位了代码中的每处差异,指纹则帮助区分不同的 bug。Carefully design the verification signal. A verifier provides a signal that Claude can act on. We can calibrate this signal to show Claude where things went wrong. Where a proof assistant points to the failing step or a test names the failing case, a production system often offers no such signal by default. Much of our effort for this project went to building such a signal. In this case, checkpoints located each difference in the code and fingerprints helped tell one bug from another.

构建循环,让 Claude 能够根据该信号自主采取行动。我们的内层循环速度很快,并在沙箱中本地运行。智能体使用自己编写的请求,在几秒内测试假设。外层循环较慢,会在镜像的生产流量上检查修复效果。最外层循环则只是文字说明,修正内容会以规则的形式保存到记忆中,供后续流程中的所有智能体读取。这些循环协同运作,使我们得以将 Messages API 迁移到 Rust;迁移后,每个请求的 CPU 使用量减少了约 70%,首个 token 的中位耗时缩短了约 20%(图 15)。Build loops that let Claude autonomously act on the signal. Our inner loop was fast and ran locally in a sandbox. Agents tested hypotheses in seconds using requests they wrote themselves. The outer loop was slower and checked fixes on shadowed production traffic. The outermost loop was just prose, with corrections saved as rules in memory that could be read by every agent later in the process. Together, these loops allowed us to migrate the Messages API to Rust, which uses about 70% less CPU per request and reduces median time to first token by about 20% (Figure 15).

Three charts of the move from Python to Rust. CPU used per request falls by about 70% and memory used per request by more than 80%, both from August to October. Median time to first token falls by about 20% between roughly September 7 and 21.
CPU and memory used per request, and median time to first token, as requests moved from Python (gray) to Rust (blue). Lines are seven-day averages, 100 is about the level just before the move, and each arrow shows the change from the first dot to the second. CPU is one region, memory is all of production, and time to first token is customers' Claude Code requests over a shorter period. In the third panel, the fall before the first dot came while almost all of those requests were still on Python.

让循环保持简单,以便随着 Claude 能力的提升而扩展。我们尽量只在人类判断“什么才算正确”这件事上介入;除此之外,如何达成目标都交由 Claude 自行决定。智能体自行选择要测试哪些假设、如何复现每个 bug,以及如何修复。验证器负责评判结果。围绕强大的验证器构建简单的循环,让我们能够随着时间推移持续高效推进(图 16)。Keep the loops simple, so they scale with Claude’s capability. We tried to put human judgment only into what counted as correct; otherwise we left it up to Claude how to get there. Agents chose which hypotheses to test, how to reproduce each bug, and how to fix it. The verifiers judged the result. Simple loops around strong verifiers allowed us to move productively over time (Figure 16).

Bar chart of changes merged per two-week period, April 6 to September 7, 2026. Changes climb from under 100 to roughly 1,000 by late June, level off through July, then jump to more than 3,000 in the period starting August 10 and stay above 2,500 for the next two periods.
Changes merged to our API's Rust code in each two-week period, from April until public traffic moved to Rust in September 2026. Not all of them are migration work.

转向外层循环。起初,我们让工程师在内层循环中工作,运行 Claude 并自行排查差异。后来,他们转移到了循环之间的衔接处,帮助引导代理,并在 Slack 中审核修复方案。但随着系统日趋成熟,他们越来越多地转向边缘位置,在那里他们能发挥最大的杠杆作用,为代理设定规则和检查。随着 Claude 变得更加智能(而我们与它协作的能力也不断提升),我们的工作方式从指挥 Claude 演进为由 Claude 自主指挥,主要在重要的判断决策上依赖人类。Move toward outer loops. At first, we had our engineers working inside the inner loop, running Claude and chasing differences themselves. Later, they moved to the seam between loops, helping to steer agents and reviewing fixes in Slack. But as the system matured, they increasingly moved to the edge, where they could provide the highest leverage, writing the rules and checks that agents worked within. As Claude grew more intelligent (and as we grew more intelligent at working with it), we evolved from directing Claude to Claude directing itself, relying on humans mainly for important judgment calls.

值得记下

  1. 验证,而非生成,已经成为瓶颈。
  2. 我们将生产环境中的 Messages API 本身变成了一个验证器。
  3. 最终,我们构建了一个影子运行系统,用简短记录呈现 Rust API 与 Python API 之间的每处差异。
  4. 这让我们能够发布基于 Rust 的 API:每个请求的 CPU 使用量降低约 70%,首 token 中位时间缩短约 20%,整个过程中服务从未停机,功能开发也从未停滞。

← 回到本期 · 第 12 条