Бизнес и продуктивность

Миграция Messages API на Rust: как Anthropic автоматизировала проверку кода с помощью Claude

Anthropic переписала основной API с Python на Rust, снизив потребление CPU примерно на 70%. Для проверки сгенерированного ИИ кода компания использовала реальный производственный трафик.

Обновлено:
5 мин чтения
Миграция Messages API на Rust: как Anthropic автоматизировала проверку кода с помощью Claude

Главное за 30 секунд

При переписывании сложных систем с помощью ИИ главной сложностью становится не генерация кода, а автоматизация его проверки на реальных данных.

  • Трафик API вырос примерно в 1800 раз с начала 2024 до осени 2026 года.
  • Claude написал первую версию ядра API примерно за неделю.
  • Rust-версия снизила потребление CPU примерно на 70% на запрос.
  • Медианное время до первого токена сократилось примерно на 20%.

Неочевидное: Успешное прохождение 98% тестов не гарантирует работоспособность кода: на ранних этапах тестирования лишь около 25% результатов новой системы совпадали с реальным трафиком из-за мелких различий в обработке данных.

Суть

Компания Anthropic завершила перевод своего основного шлюза для клиентов — Messages API — с языка Python на Rust. В результате миграции потребление ресурсов процессора (CPU) на каждый запрос снизилось примерно на 70%, а медианное время до генерации первого токена сократилось примерно на 20%. Проект был реализован без остановки сервиса и заморозки разработки новых функций, при этом основную часть кода сгенерировала модель Claude.

Контекст

Изначально Messages API был написан на Python в 2023 году. На первых этапах он работал просто как маршрутизатор запросов. Однако по мере усложнения системы каждый запрос стал требовать валидации, преобразования, токенизации и проверки фильтрами безопасности. Python добавлял накладные расходы на каждом этапе выделения памяти и передачи задач.

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.

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.

С начала 2024 года до осени 2026 года трафик API вырос примерно в 1800 раз. Попытка частичного переписывания (только парсинга вывода) на Rust дала снижение использования CPU примерно на 8-10%, но усложнила архитектуру: каждый токен стал пересекать границу между Python и Rust три раза.

Детали

К маю 2026 года модель Claude писала более 80% кода, который принимали инженеры Anthropic. Первую версию ядра нового API модель написала примерно за неделю. Однако главной проблемой стала не генерация кода, а его проверка — так называемый разрыв между генератором и верификатором (generator-verifier gap).

Интеграционные тесты оказались недостаточными. В апреле Rust-версия API проходила около 98% тестов, однако при проверке на производственном трафике лишь около четверти запросов совпадали с результатами старой системы. Различия скрывались в пограничных случаях, например, в том, как разные языки обрабатывают экранирование символов в JSON-вызовах инструментов.

Также по темеКак Clay использует модели OpenAI для автоматизации продаж
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.

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.

Анализ

Чтобы решить проблему верификации, инженеры использовали старый Python API в качестве «оракула». Они применили метод теневого копирования (shadowing), пропуская реальные производственные запросы через обе версии системы и сравнивая результаты.

Этот подход показал, что при масштабном рефакторинге сложных систем с помощью больших языковых моделей (LLM) традиционные наборы тестов теряют свою абсолютную надежность. Тесты часто привязаны к особенностям старой реализации и не способны охватить все возможные комбинации параметров реального мира.

Перспектива

Опыт Anthropic демонстрирует сдвиг в разработке программного обеспечения: создание кода перестает быть главным узким местом благодаря возможностям ИИ. На первый план выходит задача построения надежных систем верификации. Использование существующих производственных систем для автоматической проверки сгенерированного ИИ кода может стать стандартом индустрии при модернизации устаревшей инфраструктуры.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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 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.

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.

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.

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.

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.

Источник:Anthropic

Читать дальше