This page shows the source for this entry, with WebCore formatting language tags and attributes highlighted.
Title
Stephen Toub rewrote the GitHub Copilot runtime in Rust with itself
Description
<img attachment="stephen_toub.webp" align="right" title="Stephen Toub">The article/white paper <a href="https://github.blog/ai-and-ml/generative-ai/migrating-the-github-copilot-runtime-to-rust-using-copilot/" source="GitHub Blog" author="Stephen Toub">Migrating the GitHub Copilot runtime to Rust, using Copilot</a> writes about a months-long, LLM-heavy project in extremely useful detail. The original paper is fascinating and is 54 pages long. I have included what I consider to be the highlights below.
<h level="3">JSON-RPC</h>
<bq>We also still need JSON-RPC for runtimes that genuinely are remote, whether across a subprocess boundary or over TCP. <b>Keeping the same protocol in-process means maintaining one bidirectional API and dispatch system rather than JSON-RPC for remote connections plus a second per-method FFI surface for local ones.</b> That’s a real tradeoff rather than a no-brainer decision. We avoid the process hop, but we still pay JSON-RPC overhead on every call. <b>For inference-dominated workloads, that serialization is generally small potatoes compared to the model round trip. It is still measurable in high-throughput local workloads, but not enough today to justify duplicating hundreds of methods across six SDK bindings.</b> And it’s a decision we can easily revise later should the performance need present itself. The payload encoding is a private detail of the two ends, and swapping JSON for something denser like MessagePack would not change a single declared export. <b>Typed per-method exports can also be added later for hot paths, calling the same engine and the same handlers, without replacing the byte channel</b>, which would remain the substrate for streaming, server-to-client requests, and the long tail of rarely called methods where a bespoke export buys nothing.</bq>
<h level="3">High-level architect</h>
<bq><b>My role was less “assign a task and wait” and more “operate the control loop”: inspect the result, challenge technical decisions, enforce quality gates, and push when an agent treated an intermediate stopping point as the finish line.</b> Human judgment was still very heavily involved even though agents were doing “the work.” My involvement just moved upward… instead of being responsible for writing syntax, <b>I was responsible for framing the problems, defining boundaries, choosing strategies, adjudicating exceptions</b>, and overall ensuring everything was moving in a good direction.</bq>
<h level="3">High prompt-cache hits</h>
<bq><b>The prompt-cache hit rate was 96.22%</b>: cache reads divided by all input-side token volume (cache reads plus cache writes plus fresh input). Cache writes were 3.07%, and fresh input was 0.71%. This is not an accident. <b>GitHub Copilot shapes the agent loop specifically to preserve a long and stable prefix (the system prompt, then the tool definitions, then the accumulated conversation)</b>, so each turn appends to context the model has already processed. The expensive part of the context is paid for once and then re-read at an order of magnitude less monetary cost on every subsequent call.</bq>
<h level="3">Compacting and agent hierarchies</h>
<bq><b>The single sessions-infrastructure port pull request compacted 647 times over its many-day lifespan</b>, while one small port never compacted once. Sustained multi-hundred-hour autonomous work is only possible because <b>the agent can recycle its working memory over and over without losing the thread.</b> Every one of those thousands of summarizations was a point where a lossy handoff could have quietly derailed the port, and mostly didn’t. Copilot’s subagents also greatly factor into minimizing compaction. <b>Each subagent gets its own context, so a parent session can effectively ask a question, have a subagent go off and exert a fair amount of context in computing the answer, and then report just the answer back to the parent.</b> The parent’s context needn’t be impacted by all of that intermediate information.</bq>
<h level="3">Static typing FTW 🙌 </h>
<bq>These are the kinds of mistakes bulk translation easily and accidentally produces and exactly the ones a compiler catches very quickly. But note what’s absent from that list: anything truly specific to Rust. <b>Every one of those four categories is bread-and-butter static typing, and a C# or Java or Go compiler would catch all of them just as well, several of them with friendlier diagnostics, and all of them a great deal faster.</b> If this is the argument for pointing agents at Rust, it’s really an argument for pointing them at any statically typed language. <b>A strongly typed compiler and/or a language with excellent static analysis and linting is genuinely a good fit for this work, with the agents using it as a fast feedback loop.</b></bq>
<h level="3">25-hour porting run</h>
<bq>The porting session that took it on did not start by just diving in and writing Rust. <b>It spent its first fifty-six minutes reading, with 122 tool calls before it created anything, building a picture of what the file actually owned and where the seams were.</b> Only then did it start delegating, logically splitting up the file and delegating slices to subsessions. <b>Across the whole 25-hour run, it made 222 shell calls, 205 file views, and 197 ripgrep searches</b> of its own, on top of everything its child sessions did.</bq>
<bq><b>That’s 15 child sessions, each one a separate branch with its own worktree and a separate agent, all created implicitly by the parent session at the top. The parent session created them in seven waves over about three hours</b>: the first wave created five, the second another two about twenty minutes later, then another pair twenty minutes after that, then singles and pairs spread out over the next two hours.</bq>
<bq>Alongside those 15 subsessions, <b>the same parent session also employed five subagents: three explore agents fired in parallel with the first wave, one code-review, and one rubber-duck.</b> These subagents explored questions, feeding back to the parent answers it needed in its context before it could decide what to do next. <b>The subagents allowed the parent to get deeply thought out answers without needing to spend its own context window on deriving them.</b></bq>
<h level="3">Agentic mutex</h>
<bq>Later I took that one step further and <b>made an otherwise ordinary chat session into a build scheduler for eight independent porting sessions.</b> The prompt was embarrassingly simple: send every open session a policy to avoid CPU-intensive building and testing where possible, require it to ask this session for permission when a build was necessary, and act as a gate, handing out the ability for one session at a time to build. <b>Basically I turned the chat session into an agentic mutex.</b> The gate kept an explicit owner and queue and granted one lease at a time through the same cross-session messaging mechanism the sessions already used to coordinate code. <b>Sessions that asked for and were denied the lease often waited by doing other work in the meantime, like picking off things from its todo list.</b></bq>
<h level="3">Beware greediness</h>
<bq>The root cause here was me. <b>I partitioned this work top-down and bottom-up at the same time</b>, and the two directions met in the middle at the single most connected file in the codebase. <b>I was too greedy to make forward progress.</b></bq>
<h level="3">Validation is the lion's share</h>
<bq>[...] <b>effectively all of the code generation was done in the first 12 hours</b>; the next day of work after that is all validation.</bq>
<bq>With the frequent rebasing, it’s easy for incoming changes to get lost accidentally. But we found an unexpected benefit to the in-place atomic swap: by deleting the TypeScript at the same time as we were adding the corresponding Rust, <b>we were implicitly creating conflicts with rebase-induced incoming changes to that TypeScript: one branch changing it and the other deleting it. This guaranteed we’d notice changes to already ported code</b>, rather than needing to rationalize for every incoming line whether it was something that might have been touching previously ported code.</bq>
<bq>For my review, I focused on architecture, design, conventions, and approach. <b>The agents did the exhaustive old-versus-new comparisons; tests and static analysis checked mechanically enforceable properties</b>; human reviewers concentrated on architecture, API contracts, risk, and any suspicious places surfaced by those other layers. <b>I chose the destination architecture, decided what behavior mattered, partitioned the work, resolved ambiguous trade-offs, judged the evidence, manually reviewed high-risk areas, reviewed agentic responses to feedback, and made the final merge decisions.</b> The agents changed the amount of code one engineer could supervise. They did not remove the need for an engineer who understood the system and could vouch for the direction, the guardrails, and the release.</bq>
<bq>In one merge loop pass, the port had deleted one of the functions exposed to the SDK. <b>Our repo’s schema compatibility CI leg did exactly its job and failed.</b> The agent’s response was to apply the repo’s <c>schema-break-ok</c> automation label, which is the escape hatch to make the check pass. In reviewing the pull request before merge, I asked the obvious question: “What is the schema break? You added the <c>schema-break-ok</c> label to the pull request; why is it ok?” It wasn’t. The method existed on main; the port had simply lost it. <b>I called it an unacceptable regression and told the agent to bring it back fully in Rust. Twenty-one seconds later, the waiver was removed, and the method was restored with a native Rust implementation.</b></bq>
<h level="3">unsafe code only for interop</h>
<bq><b>Within the entire runtime crate, we now have 158 unsafe blocks, across only 36 files</b> (alongside them are 26 unsafe fn declarations, 26 unsafe extern blocks, and nine unsafe impl trait implementations). Importantly, <b>every single one of these is about interop with external components.</b></bq>
<bq>Every one of those unsafe blocks marks a place where the guarantees Rust makes genuinely end: <b>the thing on the other side is a C function, a syscall, a pointer from a foreign runtime, or process-global host state.</b></bq>
<bq><b>The useful property is that unsafe makes all of these places in the Rust code we own auditable.</b> The equivalent code in the TypeScript runtime crossed exactly the same boundaries, through Node’s C++ internals and native npm packages, and nothing in our source marked where the checked world stopped.</bq>
<h level="3">Regressions</h>
<bq>Nearly all of the correctness regressions land in three large families: the new code implemented a different behavioral contract; state, ownership, or lifetime behavior changed; or <b>some part of the migration was omitted, only partially applied, or lost in rebasing.</b> A smaller set came from requirements at the host or interop boundary, and even from <b>tests that confidently validated the wrong behavior.</b></bq>
<bq><b>Several regressions came from behavior the source language left implicit. TypeScript has one number type; Rust requires choosing among several</b>, including whether a value can be fractional. And the agents guess wrong. Fields that were conceptually integers became f64s, so Rust serialized values such as 42.0 instead of 42: strongly typed SDKs like Go and C# couldn’t unmarshal a repo ID into an int64 and rejected a hook timestamp and task duration.</bq>
<bq>One port omitted SDK callbacks and deleted their end-to-end test, <b>prompting a new rule that agents must not change E2E tests without explicit consent.</b> A session abort kept its native half but lost the in-process cancellation needed to interrupt a turn waiting in a tool.</bq>
<bq><b>Some regressions lost existing efficiencies such as memoization, fully asynchronous waiting, or bounded log streaming.</b> Others added migration-specific overhead at the Rust-TypeScript boundary: redundant serialization, locking, polling, unbounded native concurrency, and native-to-host crossings. These weren’t later optimization opportunities; each was a degradation introduced by the port.</bq>
<bq><b>The compiler can prove that an f64 is used consistently. It cannot know that a repository ID must be serialized as an integer</b> or that a timestamp serialized with a trailing .0 will be rejected by every strongly-typed SDK at the other end of the wire. The compiler can prevent unsynchronized data races in the code it can see, but <b>it can’t prevent a perfectly synchronized state machine from encoding the wrong states.</b></bq>
<h level="3">The goal: improve performance</h>
<bq>So what did we buy with all of this? <b>The port was deliberately behavior-preserving. It did not set out to redesign algorithms or fix bugs; in fact, I repeatedly pushed the agents away from opportunistic optimization because changing language and behavior at the same time makes it much harder to know which one broke you.</b> A key goal of the rewrite, however, was indeed performance and scalability (in addition to reliability and other factors). When folks asked me why did I set out to rewrite the runtime in Rust, my answer was often along the lines of “<b>I didn’t set out to move to Rust, I set out to move away from Node.js and V8</b>”. That move has indeed significantly moved our needle on performance.</bq>
<bq>The pre-port TypeScript CLI completed 7.55 of those lifecycles per second. Rust out-of-process completed 57.45. Rust in-process completed 120.0.</bq>
<bq>Looking at resident private memory added during the ten-client batch, the pre-port process tree peaked 1,383 MB above baseline. <b>Rust out-of-process peaked at only 247 MB. And Rust in-process at 126 MB, an order of magnitude less.</b></bq>
<h level="3">Next steps: move architecture from TS to RS</h>
<bq>The best part is this is the baseline port. <b>Much of the implementation still consists of TypeScript-shaped algorithms faithfully rendered in Rust.</b> We haven’t yet done the broad redesign work that the new ownership model, concurrency model, and in-process architecture enable. Getting an in-process client through creation, a complete one-turn session, and teardown in about 55 milliseconds, <b>pushing a shared client to 120 one-turn session lifecycles per second, and cutting the measured ten-client memory delta by 91% before that optimization work begins is a very good place to start.</b></bq>
<h level="3">Tokens and costs</h>
<bq>My <b>token spend for all of the porting work was ~136.3 billion total tokens</b>, including ~130.6 billion cached input read tokens, ~4.2 billion cached input write tokens, ~900 million fresh input tokens, and ~600 million output tokens. <b>The monetary bill for all those tokens came to ~$120,000.</b></bq>
<h level="3">Lessons learned and advice</h>
<bq>The goal needs to be clearly and fully stated. <b>Our early instructions were too vague.</b></bq>
<bq><b>End-to-end tests are absolutely, unequivocally critical.</b> With one exception, all of the regressions that involved missing features, and many of the others, were due to lack of sufficient end-to-end tests.</bq>
<bq><b>Translate first, redesign second. Preserving behavior and existing algorithms kept the number of variables moving at once manageable.</b> Once the old implementation and the transitional scaffolding are gone, ownership, concurrency, and performance can be redesigned against a stable baseline.</bq>
<bq><b>The execution runtime that was entirely TypeScript in May is now entirely Rust in August, and it shipped to real users continuously the whole way</b> rather than landing as one terrifying cutover at the end.</bq>
<bq>A rewrite producing hundreds of thousands of lines of production Rust in a live system, done in place, in main, by one engineer supported by a team, is not a proposal that would have been accepted before agents. It would have needed a whole team and a year or two, <b>it would have competed against every feature that team could have shipped instead, and it would have lost (and, honestly, should have lost). Agents moved the price to where the project became tenable.</b></bq>
<bq>The port itself is complete: <b>the runtime’s production implementation is 100% Rust, and the temporary internal TypeScript/N-API seam is gone.</b> There is still plenty of work we desire to do, though: further improving the build system and developer inner loop, cleaning up translated structures, redesigning around Rust’s ownership and concurrency models, and pursuing further performance wins.</bq>