techlist.io

Anthropic/Rust

4 posts

Anthropic2026-11-256 min readCurated summary

Migrating our Messages API to Rust

# Migrating the Claude Messages API from Python to Rust Using Production Traffic as the Verifier Anthropic migrated its Messages API from Python to Rust without taking the service offline or freezing feature work. The central problem was verification: Claude could write the new code in about a week, but there was no reliable definition of "correct" for a live system with undocumented customer behavior and a constantly changing Python baseline. The team turned production itself into an oracle, comparing the Rust and Python paths step by step on shadowed traffic, and used agents in layered verification loops to find and fix differences. The result was about 70% less CPU per request and roughly 20% lower median time to first token. ## Why a Full Rewrite - The Messages API began in 2023 as a thin Python request forwarder, but grew to validate, build prompts, tokenize, run safety classifiers, and parse streamed output, with each step adding Python overhead. - API traffic grew roughly 1,800x from early 2024 to fall 2026. - An incremental approach, moving only the output parser to Rust, cut CPU by 8 to 10%, but every token then crossed the Python/Rust boundary three times, adding overhead that offset the gains. - By May 2026, Claude wrote more than 80% of the code Anthropic merged, so generating the rewrite was no longer the bottleneck. Verifying it was. ## Why Existing Tests Were Not Enough - The team had about 700 integration tests, but they were coupled to the Python implementation: they ran the Python API in-process and mocked billing and rate limiting in Python memory. - Porting the tests introduced risk. An audit found more than 100 weakened assertions, so a passing test could hide wrong behavior. - The tests were incomplete. Twenty binary options alone yield over a million combinations, which would take about 12 days to run at one second each for a single model, before varying prompts. - Claude is nondeterministic, and it accepts nearly any prompt, so small prompt deviations often produce no error, just subtly different replies. ## Shadowing Production Traffic - Shadowing ran requests through both versions and compared results, but the usual assumptions did not hold. A request could not safely run twice, since it counted against customer limits and billing. Claude's nondeterminism meant outputs could differ legitimately. - The team ran the model once and replayed its output to the Rust path, so both versions worked from identical model output. They then compared every stage before and after the model call, requiring exact matches. - Customer requests and replies could not be read for privacy reasons, so the team recorded the shape of each difference rather than its content. - Initial results were sobering: the Rust API passed about 98% of its tests in April, yet only about a quarter of production inputs matched. Production also weighted bugs differently, since one common bug could trigger many mismatches. ## Two Techniques for Locating Differences - **Checkpointing:** Both versions pass each request through the same steps (accept or reject, resolve settings, build prompt). Comparing results step by step, and piece by piece within the prompt, pinpointed where the code diverged. - **Fingerprinting:** Each diff was summarized by where the first byte difference occurred and the length difference between versions. Bugs left consistent fingerprints across every request they affected, so errors could be grouped and triaged. - Each diff produced a small record, such as the step, the prompt piece, the first differing byte, and the fingerprint values for each version. ## Verification Loops - A script grouped the hundreds of thousands of near-identical diff records every 10 to 30 minutes by which fields differed. It alerted a coordinating agent only on new record types, which assigned a worker agent to each and opened a Slack thread for engineers to follow. - **Inner loop:** Agents ran in cloud sandboxes with both codebases and fast local checks. An input check built the prompts each version would send, without calling the model, in under a second. An output check ran both versions against a fake model with scripted replies. Agents hypothesized causes, reproduced them, and fixed the Rust until outputs matched, adding a regression test. Earlier, when agents had to wait for PR review and staging deployments, feedback took hours or days. - **Seam:** Fixes passed human PR review before moving to production. Engineers focused on questions verifiers could not answer, such as whether a difference was a bug or an intentional change. - **Outer loop:** Each fix was deployed and compared on shadowed production traffic, using request metadata such as model, caching, tools, and extended thinking to compare like with like. This caught cases the sandbox missed, since the local verifier was not configured exactly like production. - **Memory loop:** Reviewer decisions and agent lessons were saved as notes and rules that later agents read. One rejected shortcut for web search tool descriptions became a documented note, so agents later linked related records to the known bug instead of writing new workarounds. Other lessons became rules, such as porting Python's behavior exactly, and were encoded as tests, lints, and a merge check requiring matching Rust changes for Python edits. ## Lessons Learned - **Verification is the new bottleneck.** When writing code is cheap, the limiting factor is how quickly results can be verified, and ambition can scale as long as Claude has a reliable verifier. - **A production system can serve as a verifier** when formal proofs or tests are insufficient, but it rarely provides a useful failure signal by default. Much of the effort went into building one, through checkpoints and fingerprints. - **Verifiers can be gamed.** The web search shortcut matched outputs but was not a real fix, so human review remained an essential gate. - **Keep loops simple.** Humans defined what counted as correct, and agents chose hypotheses, reproductions, and fixes. Simple loops around strong verifiers scaled as Claude improved. - **Move engineers outward over time.** The team moved from working inside the inner loop, to steering at the seam, to writing the rules and checks agents operate within. The approach let the team build a new, equivalent service alongside the old one, shift traffic gradually, and keep both in step while the original kept changing.

Anthropic2026-02-055 min readCurated summary

Building a C compiler with parallel Claudes

# Enabling Long-Running Claudes with Agent Teams Nicholas Carlini, a researcher on Anthropic's Safeguards team, describes "agent teams," a setup where multiple Claude instances work in parallel on a shared codebase without human intervention. To test it, he tasked 16 agents with writing a Rust-based C compiler from scratch that could build the Linux kernel. Across nearly 2,000 Claude Code sessions and about $20,000 in API costs, the team produced a 100,000-line compiler that builds Linux 6.9 on x86, ARM, and RISC-V. The post's main lesson is that the work shifts from writing code to designing the environment (tests, feedback, and coordination) so agents can orient themselves and make progress on their own. ## Autonomous Loop Harness - Existing tools like Claude Code stop and wait for human input, so Carlini wrote a bash loop that restarts a Claude session with the same prompt whenever one finishes. - The agent prompt asks Claude to break the problem into small pieces, track its work, choose the next task, and keep going. - The loop should run in a container, since agents can do destructive things. In one case, Claude ran `pkill -9 bash` and ended its own loop. ## Parallel Agents and Task Locking - Parallel agents address two limits of a single session: only one task runs at a time, and specialized agents can handle side jobs such as documentation, code quality, or subtasks. - Each agent runs in its own Docker container with a local clone of a shared bare git repo mounted at `/upstream`. Agents push and pull through git. - To avoid duplicate work, an agent locks a task by writing a file to `current_tasks/`. If two agents claim the same task, git sync forces one to pick another. After finishing, the agent pulls, merges, pushes, and removes its lock. Merge conflicts were frequent, but Claude resolved them. - There is no orchestrator and no formal communication channel between agents. Each agent chooses the "next most obvious" problem and often keeps a running doc of failed approaches. ## Designing the Environment for Claude **Write extremely high-quality tests.** Claude solves whatever problem the verifier describes, so a flawed verifier means the wrong problem gets solved. Carlini drew on existing compiler test suites, wrote verifiers and build scripts for open-source projects, and added new tests as failure modes appeared. Late in the project, Claude kept breaking existing features, so he added a CI pipeline that blocks commits that break existing code. **Design for the model's limitations.** - *Context pollution:* Output should be a few lines, with details written to log files. Errors are tagged with `ERROR` on the same line so `grep` can find them, and summary statistics are precomputed. - *Time blindness:* Claude cannot judge elapsed time and will run slow tests for hours. The harness prints progress rarely and offers a `--fast` mode that runs a random 1% or 10% sample. The sample is deterministic per agent but varies across agents, so the whole codebase gets covered while each agent can still spot regressions. **Orient agents from scratch.** Each agent starts in a fresh container with no context, so the harness requires extensive READMEs and progress files that agents keep updated. ## Making Parallel Work Possible - Parallelism is easy when there are many independent failing tests, since each agent takes a different one. After the suite reached 99%, agents worked on compiling different open-source projects such as SQLite, Redis, libjpeg, MQuickJS, and Lua. - Compiling the Linux kernel was one giant task, so all 16 agents hit the same bug and overwrote each other. The fix was to use GCC as a known-good oracle: most kernel files were compiled with GCC and only a random subset with Claude's compiler. Agents could then fix different bugs in different files. Delta debugging found pairs of files that failed together but worked separately. ## Specialized Agent Roles Carlini assigned agents to specific jobs: removing duplicated code, improving compiler performance, generating efficient output code, critiquing the design from a Rust developer's perspective, and writing documentation. ## Results and Limitations - **Cost and scale:** Opus 4.6 used about 2 billion input tokens and 140 million output tokens over two weeks, for just under $20,000. - **Clean room:** Claude had no internet access and relied only on the Rust standard library. - **Capabilities:** The 100,000-line compiler builds a bootable Linux 6.9 on x86, ARM, and RISC-V, and compiles QEMU, FFmpeg, SQLite, Postgres, and Redis. It passes about 99% of most compiler test suites, including the GCC torture tests, and can compile and run Doom. - **Limitations:** - On x86 it calls GCC for 16-bit real-mode code, because its output exceeds Linux's 32 KB limit. ARM and RISC-V compile fully on their own. - It has no native assembler or linker yet; the demo used GCC's. - It does not build every project and is not a drop-in GCC replacement. - Generated code is less efficient than GCC with all optimizations disabled. - The Rust code is reasonable but not expert-level. - Fixes often broke existing functionality, suggesting Opus 4.6 is near the limit of what this setup can reliably do. ## Looking Ahead Carlini sees agent teams as a step beyond tab completion and single-task tools like Claude Code, enabling autonomous construction of complex projects. He also warns that autonomous development is risky. Passing tests can create false confidence, and code deployed without human verification is a real concern. He calls the experiment exciting but unsettling, and expects the benefits to outweigh the harms while calling for new safety strategies.

Anthropic2025-09-175 min readCurated summary

A postmortem of three recent issues

Between August and early September, three overlapping infrastructure bugs intermittently degraded Claude's response quality across Anthropic's first-party API, Amazon Bedrock, and Google Cloud Vertex AI. Anthropic states that model quality is never reduced because of demand, time of day, or server load, and that the reported problems came only from these bugs. The post is a postmortem covering what went wrong, why detection took so long, and what Anthropic is changing. ### How Claude Is Served - Claude runs across AWS Trainium, NVIDIA GPUs, and Google TPUs to serve millions of users worldwide. - Each platform needs its own optimizations, but Anthropic holds all of them to strict equivalence standards so users get the same quality regardless of hardware. - Any infrastructure change therefore needs validation across all platforms and configurations. ### Timeline of the Incidents - A first bug was introduced on August 5, affecting about 0.8% of Sonnet 4 requests. - Two more bugs came from deployments on August 25 and 26. - A load balancing change on August 29 sharply increased the affected traffic, while other users saw normal performance, which made the reports look contradictory. ### The Three Bugs #### Context Window Routing Error - Some short-context Sonnet 4 requests were routed to servers configured for the upcoming 1M-token context window. - At the worst hour, on August 31, 16% of Sonnet 4 requests were affected. - About 30% of Claude Code users who made requests during this period had at least one message misrouted. - Routing is "sticky," so follow-up messages often landed on the same bad server, making some users' experience worse. - The fix shipped September 4 and finished rolling out by September 16 on the first-party platform and Vertex AI, and by September 18 on Bedrock. #### Output Corruption - A misconfiguration on the TPU servers, combined with a runtime optimization, sometimes gave high probability to tokens that should rarely appear. Examples include Thai or Chinese characters in English responses and obvious syntax errors in code. - It affected Opus 4.1 and Opus 4 from August 25 to 28, and Sonnet 4 from August 25 to September 2. Third-party platforms were not affected. - The change was rolled back on September 2, and Anthropic added detection tests for unexpected character output to its deployment process. #### Approximate Top-k XLA:TPU Miscompilation - A change to how Claude selects tokens triggered a latent bug in the XLA:TPU compiler. It was confirmed for Haiku 3.5 and likely affected some Sonnet 4 and Opus 3 requests. - Haiku 3.5 was rolled back on September 4 and Opus 3 on September 12. Sonnet 4 was rolled back as a precaution, though the bug could not be reproduced on it. - Anthropic switched to exact top-k with higher precision. ### Deep Dive: The XLA Compiler Bug - Claude samples the next token using top-p sampling, which requires sorting probabilities across tens of TPU chips. - A December 2024 workaround addressed a case where the most probable token was dropped at temperature zero. - The root cause was a precision mismatch. Probabilities were computed in bf16, but the compiler's `xla_allow_excess_precision` optimization (default `true`) moved some operations to fp32. This made operations disagree about the top token. - An August 26 sampling rewrite removed the December workaround, which had been masking a deeper bug in the approximate top-k operation. That bug returned wrong results only for certain batch sizes and model configurations. - The bug was inconsistent: the same prompt could succeed or fail depending on surrounding operations and whether debugging tools were enabled. - Anthropic moved to exact top-k, which no longer carried a prohibitive cost, and standardized more operations on fp32, accepting a minor efficiency cost. - Tokens near the top-p threshold may now be included slightly differently, so a few users may need to re-tune their top-p setting. ### Why Detection Took So Long - Benchmarks, safety evaluations, spot checks, and canary deployments did not capture the degradation, partly because Claude often recovers from isolated mistakes. - Privacy controls limit engineers' access to conversations that users did not submit as feedback, which made the problematic interactions hard to examine. - Each bug produced different symptoms on different platforms at different rates, so the reports looked random. - Anthropic relied too heavily on noisy evaluations and did not quickly connect the August 29 spike in reports to the load balancing change. ### What Anthropic Is Changing - Developing evaluations that more reliably separate working implementations from broken ones. - Running quality evaluations continuously on production systems, not only in regular testing. - Building debugging tools that work with community feedback without compromising user privacy. - Encouraging direct feedback through `/bug` in Claude Code or the thumbs-down button in the Claude apps. Developers with new evaluation methods can reach out to feedback@anthropic.com. If you use top-p sampling, it's worth checking your settings after these fixes. And if Claude produces unexpected output, the `/bug` command or thumbs-down button helps Anthropic catch problems like these sooner.

Anthropic2024-12-196 min readCurated summary

Building effective AI agents

This post, from Anthropic, argues that the most effective LLM agent systems are built from simple, composable patterns rather than complex frameworks. It distinguishes predefined workflows from autonomous agents and advises starting with the simplest solution, adding complexity only when measured results justify it. The authors cover five workflow patterns, when to use full agents, and how to design tools for them. ### Workflows Versus Agents - Workflows orchestrate LLMs and tools through predefined code paths. - Agents let the LLM dynamically direct its own processes and tool usage, keeping control over how it accomplishes tasks. - Both are grouped as "agentic systems," but the distinction is architecturally important. ### When to Use Agents and Frameworks - Agentic systems often trade latency and cost for better task performance, so the tradeoff must be justified. - Workflows suit well-defined tasks that need predictability, while agents suit open-ended problems that need flexibility and model-driven decisions at scale. - Many applications only need a single LLM call optimized with retrieval and in-context examples. - Frameworks such as the Claude Agent SDK, Strands Agents SDK, Rivet, and Vellum simplify setup, but their abstractions can hide prompts and responses, making debugging harder and tempting developers to add unnecessary complexity. - The authors recommend starting with LLM APIs directly, and understanding the framework's underlying code if you do use one. ### The Augmented LLM Building Block - The foundation of agentic systems is an LLM enhanced with retrieval, tools, and memory, which it can use actively by generating search queries, selecting tools, and deciding what to retain. - Key considerations are tailoring these capabilities to the use case and exposing them through a clear, well-documented interface. - The Model Context Protocol is one way to integrate third-party tools using a simple client implementation. ### Core Workflow Patterns - **Prompt chaining:** Decomposes a task into sequential LLM calls, with optional programmatic "gates" between steps. It trades latency for accuracy. Examples include writing marketing copy and then translating it, or drafting an outline, checking it against criteria, and then writing the document. - **Routing:** Classifies an input and sends it to a specialized follow-up task, which separates concerns and allows specialized prompts. Examples include directing customer service queries to different processes, or sending simple questions to a smaller model like Claude Haiku 4.5 and hard ones to Claude Sonnet 4.5. - **Parallelization:** Runs LLM calls simultaneously and aggregates the outputs programmatically, in two variations: - *Sectioning* splits a task into independent subtasks, such as running a guardrail model alongside the core response model, or evaluating different aspects of a model's output separately. - *Voting* runs the same task multiple times for diverse outputs, such as several prompts reviewing code for vulnerabilities. - **Orchestrator-workers:** A central LLM dynamically breaks down a task, delegates subtasks to worker LLMs, and synthesizes the results. Unlike parallelization, subtasks aren't predefined. This suits coding tasks where the required file changes depend on the input, and multi-source search. - **Evaluator-optimizer:** One LLM generates a response while another evaluates it and provides feedback in a loop. This works best when evaluation criteria are clear and iterative refinement measurably helps, as with literary translation or multi-round search. ### Agents in Production - Agents begin with a command or interactive discussion with the user, then plan and operate independently, checking "ground truth" from the environment, such as tool results or code execution, at each step. - They can pause for human feedback at checkpoints or blockers, and should include stopping conditions, such as a maximum number of iterations. - Structurally, agents are often just LLMs using tools in a loop, so the design of toolsets and their documentation is critical. - Agents suit open-ended problems where the number of steps is unpredictable, but their autonomy raises costs and the risk of compounding errors, so extensive sandbox testing and guardrails are essential. - Anthropic's own examples include a coding agent for SWE-bench tasks and the "computer use" reference implementation. ### Combining Patterns and Guiding Principles - The patterns are not prescriptive. They are starting points to shape and combine for specific use cases. - Success depends on measuring performance and iterating. Added complexity should only be kept when it demonstrably improves outcomes. - The authors suggest three principles for agents: keep the design simple, make planning steps transparent, and carefully craft the agent-computer interface (ACI) through thorough tool documentation and testing. ### Agents in Practice - **Customer support:** Suits agents because conversations need external data (customer records, order history, knowledge base articles), actions like refunds can be handled programmatically, and success is measurable through user-defined resolutions. Some companies charge only for successful resolutions. - **Coding agents:** Suit agents because solutions can be verified with automated tests, agents can iterate on test feedback, and output quality can be measured objectively. Anthropic's agent can solve real GitHub issues from SWE-bench Verified based on the pull request description alone, though human review remains essential. ### Prompt Engineering Your Tools - Tool definitions deserve as much prompt-engineering effort as the main prompts, since Claude invokes tools through structured tool-use blocks in the API. - Some formats are much harder for LLMs to produce than others. For example, diffs require counting lines in chunk headers before writing code, and code inside JSON requires escaping newlines and quotes. - Format guidelines: - Give the model enough tokens to reason before committing to an output. - Stick to formats common in internet text. - Avoid formatting overhead like line counting or string escaping. - Designing the agent-computer interface deserves as much care as the human-computer interface. Put yourself in the model's shoes, write documentation like a docstring for a junior developer (with examples, edge cases, and input requirements), test the tools on many inputs, and "poka-yoke" them so mistakes are harder to make. - In the SWE-bench agent, the team spent more time on tools than on the prompt. Requiring absolute file paths eliminated errors that occurred after the agent changed directories. ### Practical Takeaway Start with the simplest prompts and direct API calls, and measure results carefully. Add workflows or autonomous agents only when simpler approaches fall short, and invest heavily in tool design and testing, since they largely determine whether an agent succeeds.