KnowML

Designing Code Completion

Follow Aditi as she writes one Python function in VS Code and a grey suggestion appears under her cursor. We build the system behind it from the obvious version, fix each failure in turn, and look at what GitHub Copilot and Google have published about the choices along the way.

⏱ 77 min readAssumes: LLM architecture and training (10), inference serving (31), evaluation (25)
Start reading

Aditi is in her editor in Bengaluru, a little after six in the evening, writing a function called parse_duration. It's supposed to turn strings like "1h30m" into a number of seconds. She has typed the signature and a one-line docstring, and she has written total = 0 on the first line of the body. Then she stops to think. Before she has decided what comes next, a line of grey text appears after her cursor: a loop that splits the string into numbers and units, adds them up using a dictionary called UNITS, and stops exactly where her existing return statement begins. She presses Tab, the grey text turns into real code, and she changes one variable name. That whole exchange took less time than it takes to lift her hands off the keyboard.

Three problems are hiding in that scene. One is context. UNITS isn't defined anywhere in the file she's editing; it lives in retry.py, in another tab she opened an hour ago, and the suggestion used it correctly. Another is position. Aditi's cursor is in the middle of the file, with code already below it, so the text has to connect to what's there and then stop. A third is time. A suggestion that arrives a second after she has typed on is worse than no suggestion, because it interrupts instead of helping. Underneath all three sits a measurement problem: nobody can read Aditi's mind, so a company building this has to decide, from logs and experiments, whether a suggestion like the one she accepted was any good.

So the question this chapter answers is: how does a code editor produce, within a fraction of a second, a suggestion that fits the file around Aditi's cursor and the files beside it, and how does the company behind it tell whether suggestions like that are any good?

We'll build the design the way an engineer would, starting from the most obvious version, "send the file to a big model", and repair each failure as it appears. That leads us through assembling a prompt from a fixed budget of tokens, retrieving useful snippets from other open files, training a model to fill in the middle of a document, and cutting latency with debouncing, caching and streaming. After that come the decision about when a suggestion should be shown at all, the logs the editor records, and the two kinds of evaluation, offline benchmarks with and online metrics with acceptance and retention. Most of what follows comes from GitHub Copilot, whose engineers have published a good deal, and since 2025 its editor extension is open source, so some details here come from the code itself. Google's 2022 code completion work provides a second published system to compare against. Where internals are unpublished we say so.

01What we're building, and how big

1.1 What it has to do

The feature we're designing is inline completion: as a developer types, the editor shows a suggestion in dimmed text after the cursor, which the developer can accept with one key or ignore by typing on. Copilot and its competitors also have chat panels, agents and next-edit suggestions, and we leave those aside. Everything here is about the grey text.

A few requirements follow from what Aditi is doing. A suggestion has to arrive fast enough that it's there when she pauses and gone when she carries on typing. It has to fit the code on both sides of the cursor, in whichever of dozens of languages she happens to be using. It has to be short when a line will do and longer when a whole block is the natural next step. It has to be cheap enough to run for millions of people who press keys all day, and it must not leak or reproduce code it shouldn't. One more constraint has nothing to do with machine learning, and GitHub's engineers described it plainly in 2023: "It's a bug if you have to change the way you code when using GitHub Copilot." The suggestion lives inside the editor, it doesn't ask Aditi to switch windows, and it never takes anything away from her until she presses Tab.

GitHub's account of how it chose the scope in 2020 and 2021 is instructive. At the time most code completion tools finished a single line. Its team judged that generating a whole commit was beyond what the models could do reliably, and settled on suggesting whole functions, a size where a model could be right often enough to be useful (Shuyin Zhao, GitHub blog, September 2023).

1.2 How big is it?

Published numbers come from different dates, so we'll date each one. On Microsoft's earnings call in July 2025, Satya Nadella said GitHub Copilot had passed 20 million all-time users, and on the January 2026 call he said it had 4.7 million paid subscribers. GitHub doesn't publish how many completion requests it serves per day, and we won't invent that figure.

A 2022 study by GitHub researchers gives a sense of how often the feature is used and how often it's right. Albert Ziegler and colleagues matched usage logs from people in the Copilot technical preview with survey answers. In that data the acceptance rate, the fraction of shown suggestions that the developer accepted, was 27%, and the mean number of accepted completions per user per day was above 31 (Ziegler et al., MAPS 2022). If both figures describe the same people, a typical user in that study probably saw about 115 suggestions a day, since 31 divided by 0.27 is about 115. Google's 2022 report on its own completion system, deployed to more than 10,000 engineers, gave a 25% acceptance rate for single-line suggestions and 34% for multi-line ones, with about 3% of new code (counted in characters) coming from accepted suggestions.

Predict before you read on

Suppose a million developers are typing at the same moment, and each one presses a key every 300 milliseconds on average. If the editor sent a request on every keystroke, how many requests per second would reach the servers? Now suppose a typical request carries a 3,000-token prompt and gets back a line of about 5 tokens. Which costs the servers more, reading the prompts or writing the answers, and by roughly how much? (All of these are illustrative figures, since GitHub doesn't publish its request volume or prompt lengths.)

Show the answer

A million developers each producing 1 key per 0.3 seconds is about 3.3 million keystrokes a second, so per-keystroke requests would mean about 3.3 million requests a second. Each request reads 3,000 prompt tokens and writes 5, so the servers read 600 times more tokens than they write. At those request rates the prompt-reading side would be roughly 10 billion tokens a second, so almost every trick in this chapter aims at sending fewer requests and re-reading less of each prompt.

That shape fixes the design. We can't treat each keystroke as a request. Prompts need careful assembly because they dominate the cost. And whatever is the same between two nearby requests, nearly all of it, should not be recomputed.

We have no published end-to-end latency budget for Copilot either. What exists is Google's: its 2022 system used a model of roughly 0.5 billion parameters, reported a median model inference time of about 40 milliseconds, and ran semantic checks within a budget of under 100 milliseconds. Copilot's October 2025 post gives only relative changes, a 35% latency reduction and 3 times the token throughput for its new model. We'll use those as guides and reason about the rest from what a request has to do.

02Version 1: send the file to a big model

The obvious first design needs no cleverness. Take everything in Aditi's file from the top down to the cursor, send it to a large language model, and print whatever the model writes next. A language model is a program that, given some text, predicts the text most likely to follow, one small piece at a time. Those pieces are called tokens, and for code a token is typically a few characters: a keyword, part of an identifier, a bracket. What we send is the prompt, and the model reads it and then generates the continuation one token after another until it chooses to stop. This is the design that made the first code-writing models look impressive. OpenAI's Codex, the model behind the original Copilot, was GPT-3 trained further on public code, and GitHub described testing early versions on self-contained programming problems, solving about half at first and then over 90 percent of them (Inside GitHub, May 2023).

Version 1: send the file, print what comes back
EDITOR whole file, top to the cursor BIG MODEL continues the text left to right TEXT until the model decides to stop SCREEN as grey text Aditi's file is 900 lines; the cursor is in the middle of parse_duration. It never sees the lines below the cursor, and it never sees retry.py in the next tab. Nothing limits the length of the reply, and nothing makes the first token arrive quickly. The prompt is as long as the file, so a long file is slow and eventually does not fit.
Follow the arrows left to right, then read the three amber and grey lines underneath. Each is a place where the next sections add something.

Version 1 works well enough to demonstrate and breaks in ways that tell us what to build next. Its first problem is that the model can't see anything after the cursor. Aditi's file has a return statement and a second function below the spot where she's typing, and a model that only reads from the top never learns those exist. Its suggestion may duplicate the return, or run on into territory the file already covers, or finish with code that doesn't join up with what follows. Second, the cursor's file is only one of the files that matter. UNITS is defined in a neighbouring tab, and a model reading only the current file has to guess its name.

Third comes length. A model reads a bounded amount of text, called its context window, measured in tokens. A 900-line file can exceed it, and then something has to be dropped, which the naive design handles by cutting from the top, losing the imports and class definitions that tell the model what the names mean. Even when the file fits, a longer prompt takes longer to read, and we've already seen that reading the prompt dominates the cost. Fourth, nothing tells the model when to stop. A base model asked to continue a file will happily write the rest of the file, three functions Aditi never asked for, and a docstring for each.

Each of these points to a section of the design. Choosing what goes into a limited prompt is section 03. Teaching the model to write the middle of a document, joining the code above and below the cursor, is section 04. Pulling snippets in from other files is section 05, and making all of this fast enough to be useful is section 06. We start with the prompt itself, because every later decision is made inside its limit.

03Assembling the prompt under a token budget

If the prompt can only hold so much, then building it is an allocation problem: given a fixed number of tokens and several kinds of text competing for them, how many should each get? Copilot's engineers have described the constraint from the start. In May 2023 GitHub said the models fast enough for completion could process "about 6,000 characters at a time", so not all of a developer's code can go in, and an algorithm decides what to include and in what order (Johan Rosenkilde, GitHub blog, May 2023). John Berryman, a researcher on the team, put the underlying idea in one line: the model is "just a document completion model", so the job is to build a pseudo-document that makes the right continuation the likeliest one.

Copilot's VS Code extension became open source in 2025, under the MIT licence, so we can read the budget instead of inferring it. In its constants file the window is 8,192 tokens, of which 500 are held back for the completion, leaving 7,692 for the prompt. By default it divides the prompt into four parts: 35% for the prefix, the code above the cursor; 15% for the suffix, the code below it; and the remaining 50% for context drawn from other sources, in two buckets the code calls stable and volatile context, at 35% and 15%. In numbers, that's roughly 2,700 tokens of prefix, 1,150 of suffix and 3,850 of other context. What goes into the other half isn't fixed by the constants; the main provider is the similar-files snippet search of section 05, and the extension also accepts snippets supplied by other extensions, such as language-aware tools.

Spending a fixed token budget
Model window: 8,192 tokens in the open-source client's constants PREFIX code above 35% SUFFIX code below 15% STABLE context 35% VOLATILE context 15% OUT 500 7,692 tokens for the prompt; 500 held back for the completion. PREFIX def parse_duration(s): docstring, first lines of the body, up to the cursor SUFFIX the return statement and the next function below the cursor OTHER CONTEXT best-matching 60-line windows from the open tabs (retry.py), scored by Jaccard similarity and sorted so the best sits last The 35/15/35/15 split is the default in the open-source client (2025). The 2023 GitHub post described the same constraint in characters: roughly 6,000 fit at a time.
Read the bar across the top, then the three boxes under it. Whatever is not chosen for one of these slots is invisible to the model.

A few details of how the pieces get ordered show how the team thinks about the model. Each prompt starts with a header naming the file's path and language, since the file name often reveals the language and purpose of the code (Rosenkilde, 2023). A prefix that doesn't fit is cut from the top, keeping the lines nearest the cursor. And in the open-source client, the similar-file snippets are sorted so the best match comes last, directly before the code being completed, probably because text near the end of a prompt influences a completion more than text at the start. That reasoning is our inference; the code only shows the sort order.

These choices are testable, and GitHub tested them with experiments on real users. Adding snippets from neighbouring tabs raised acceptance by 5% in an A/B test, an experiment in which some users get one version and the rest get another, chosen at random, and the team reported that a very low similarity threshold for including a snippet gave the best results, because including an imperfect match beat including nothing (GitHub blog, May 2023). Berryman called the neighbouring-tab change a "huge lift in our acceptance rate and characters retained". Both numbers are relative, so a baseline acceptance rate of 27% would become about 28.4%, which sounds small until you multiply it by hundreds of millions of suggestions.

What goes into the promptPlusMinus
Prefix only (Version 1)Trivial, cheap, always availableBlind to the code below the cursor and to every other file
Prefix and suffixThe model can join the code above and below, and knows what followsNeeds a model trained for it (section 04), and a bigger prompt
Plus snippets from open tabsBrings in names and patterns the project already uses; +5% acceptance in GitHub's 2023 testCosts prompt tokens, and a poor snippet can mislead
Plus embedding search over a whole repositoryFinds code that is similar in meaning, not only in wordsNeeds an index to build and keep fresh; GitHub described it as experimental and opt-in for enterprises in 2023

GitHub's choice was the third row for the default experience. In 2023 it was building the fourth for enterprise customers who opt in, storing embeddings of code snippets, potentially billions for private repositories, and matching the developer's current context against them in real time. That's the same machinery chapter 16 describes for recommenders and chapter 11 for retrieval-augmented generation, with a query of a few lines of code and an answer due before the next keystroke.

04Teaching the model to fill in the middle

We've given the prompt a suffix, but a model trained only to continue text from left to right doesn't know what to do with one. Reading the code below the cursor and then writing something that connects to it is a different task from continuing a document, and a model that has only ever seen text in order has no reason to treat the suffix as anything but more prefix. GitHub and OpenAI fixed this with a change to the training data. OpenAI described it in 2022 in "Efficient Training of Language Models to Fill in the Middle" (Bavarian et al.), and GitHub reported that adding it to Copilot gave a 10% relative increase in the share of completions developers accepted (GitHub blog, May 2023). Its name is fill-in-the-middle, or FIM.

Here the idea is that you don't need a new kind of model; you need a new arrangement of the training text. Take a document and cut it at two random places into three parts: a prefix, a middle and a suffix. Then write the document back out in a different order, with the middle moved to the end and special marker tokens saying which part is which. An ordinary left-to-right model trained on this rearranged text learns, as a side effect of predicting the middle last, to write a middle that connects the prefix to the suffix it has already read.

Fill in the middle: the same text in two orders
A file, cut at two random points, becomes a prefix, a middle and a suffix PREFIX def parse_duration(s): MIDDLE the part we want to learn SUFFIX return timedelta(seconds=total) Training moves the middle to the end, so an ordinary left-to-right model sees it last: PSM <PRE> prefix <SUF> suffix <MID> middle SPM <SUF> suffix <PRE> prefix <MID> middle At serving time the prompt stops after <MID>, and the model writes the middle. It ends the middle with an end-of-text token once the text it wrote joins the suffix. In SPM order, typing at the end of the prefix leaves the suffix's cached keys and values valid. In PSM order, every keystroke changes tokens that come before the suffix. OpenAI's 2022 FIM paper trains with both orders at once, each on half of the FIM examples.
Read the top row as the file, then each lower row as the sequence the model is trained on. Every piece is in the loss, so the model still learns ordinary left-to-right writing.

Formally, write the three parts as , and , with the sentinel tokens , and . In the paper's first format, called PSM for prefix, suffix, middle, the training sequence is

where means concatenation and is an end-of-text token. That loss is the ordinary one for a language model, the negative log-probability of each token given those before it:

Here is the token at position and everything before it. Nothing about the objective changed; only the sequence did. When the middle's tokens are being predicted, the model has already read and , so the best way to lower the loss is to write a middle that fits both. The last token, , matters too. According to the paper it signals "a successful join to the suffix", and at inference time the model's own decision to emit it is the stopping rule that Version 1 lacked.

Other findings in the paper explain why this became standard practice. Cuts are made on characters before tokenization, uniformly at random, so each part is a third of the document on average and the boundaries fall mid-word as often as between words, which matches what happens when a developer's cursor is halfway through an identifier. FIM is applied to each document with a probability called the FIM rate, and the authors used 50% in their main runs; they report that even a rate as high as 90% didn't harm left-to-right quality, while 100% did. Loss is kept on all three parts, which the authors say matters for the central result, that FIM can be learned "for free": models trained with half their data rearranged matched models trained without FIM on ordinary left-to-right test loss at every size tried. Their recommendation was that future autoregressive models be trained with FIM by default.

SPM, the second format in the diagram, puts the suffix before the prefix, and caching is the motivation. A transformer reading a prompt computes intermediate values for every token, called keys and values, and a decoder can reuse them for the start of the prompt if that start hasn't changed. Aditi's prefix changes with every character she types, while the code below her cursor usually doesn't. In PSM order every keystroke changes tokens that sit before the suffix, so the suffix's stored values go stale. In SPM order the suffix comes first and typing only appends to the prefix at the end, so the earlier values stay valid. It trains with both orders, each on half of the FIM examples, and found SPM slightly better even on infilling benchmarks. Which order Copilot's servers use, and whether they cache this way, isn't published; the client sends the prefix and the suffix as separate fields and leaves the arrangement to the server.

Why not train a separate model that only does infilling?

Because the same weights can do both, which was the surprise of the FIM paper. One model serves left-to-right requests (when the cursor is at the end of the file, with nothing below it) and infilling requests, and it costs no more to train. A separate infilling model would double the training and serving bill and still have to be kept in step with the other. In its October 2025 post, GitHub went further and said chat-style models underperform on FIM code completion, one of the reasons it trained a model specifically for the task.

This transformation appears wherever a model has to edit and not only extend, and the span-corruption objective behind T5 is a relative of it, since both hide a span of text and ask the model to restore it. For our design, the practical result is that the prompt can now carry a suffix and the model will use it.

05Finding useful snippets in the other open files

Half the prompt is set aside for context, and Aditi's missing UNITS is the kind of thing that context exists to supply. Now we have to choose, from every file she has open, the few dozen lines most likely to help with the line she's about to write. A query has to be built from the cursor, every file has to be scanned for text that resembles it, and the whole search has to run on her laptop in a few milliseconds, before any network request goes out. Copilot's answer, described in 2023 and visible in the open-source client, is old and cheap: compare sets of words.

That comparison is the Jaccard similarity of two sets of words. Take the words near Aditi's cursor as one set, , and the words in a candidate window of another file as a second set, . It is the number of words they share divided by the number of distinct words in either:

It's 0 when the sets share nothing and 1 when they're identical, and no other number is involved. Those "words" come from a deliberately crude tokenizer, not the model's. It splits text on anything that isn't a letter or a digit, so parse_duration becomes parse and duration, and it drops common English words and each language's keywords such as def and return, because those appear everywhere and tell us nothing about similarity. A code comment in the client says this tokenizer is "NOT an OpenAI model tokenizer". Here's a worked example. Aditi's cursor context contains the words parse, duration, total, unit, value and s, six in all. A window in retry.py contains total, unit, value, UNITS, seconds, sleep and delay, seven words. They share three, so the union has 6 + 7 − 3 = 10 distinct words and . A window in settings.py with total, timeout, config, s and port shares two words out of 9 in the union, so . A window from a README that shares nothing scores 0. Retry's window wins.

Which windows get compared? Copilot's client slides a window of lines over each candidate file one line at a time, so a 60-line window starts at every line. By default the window is 60 lines, the lowest score that still counts is 0, which means any window sharing at least one word qualifies, and the best-scoring window from each file is kept. Overlapping windows are merged by keeping the better one. It looks at up to 20 neighbouring files, ignores everything after 10,000 characters in each, and keeps the top 4 snippets overall. Those neighbouring files come from the tabs open in the editor, and the client's code caps the combined text it will consider at 200,000 characters. A second preset in the same file is more conservative, with 10-line windows, a minimum score of 0.3 and a single snippet, and the code doesn't say where each preset is used. A zero threshold in the default matches GitHub's 2023 finding that including even imperfect matches beat including nothing.

Cost is what makes the approach viable at keystroke rate. Scoring a window is a set intersection, and the token set of each window of each neighbour can be computed once and reused. A small client-side cache holds those window token sets, keyed by file contents, so after the first request only Aditi's own cursor context changes between requests and the neighbours' windows are looked up, not rebuilt. There's no index to build and no server involved.

To see whether the idea carries any signal beyond intuition, here's an experiment on real code. It's a simplified version, with 20-line windows, and it takes the 35 files in Python's own asyncio package, picks 200 random lines as pretend cursor positions, and builds a snippet three ways: the best Jaccard window from the other files, a random window from a random other file, and the first 20 lines of an arbitrary other file. For each cursor it checks how many of the identifiers on the line that follows, which don't appear in the previous 30 lines, show up in the snippet. Those are the names the model would otherwise have to guess.

Try it Does the Jaccard window contain the names the next line needs?
import re, random, glob, os
import numpy as np
random.seed(3)
files = sorted(glob.glob(os.path.dirname(os.__file__) + "/asyncio/*.py"))
STOP = set("self def return if else import from for in is not and or "
           "None True False the a to of".split())

def toks(text):
    return {w for w in re.split(r"[^a-zA-Z0-9]", text)
            if w and w not in STOP}

lines = {f: open(f).read().split("\n") for f in files}
lt = {f: [toks(l) for l in lines[f]] for f in files}
W = 20                                    # window length in lines

def window_sets(f):
    return [(s, set().union(*lt[f][s:s + W]))
            for s in range(0, max(1, len(lines[f]) - W + 1), 2)]

wins = {f: window_sets(f) for f in files}

def jaccard(a, b):
    return len(a & b) / len(a | b)

def best_snippet(ref, others):
    best = (-1.0, None, 0)
    for g in others:
        for s, t in wins[g]:
            best = max(best, (jaccard(t, ref), g, s), key=lambda x: x[0])
    return best

def coverage(snippet, target, prefix):
    need = toks(target) - prefix          # names the prefix lacks
    return len(need & snippet) / len(need) if need else None

out = {"jaccard": [], "random": [], "first file": []}
while len(out["jaccard"]) < 200:
    f = random.choice(files)
    n = len(lines[f])
    if n < 120: continue
    i = random.randrange(60, n - 1)
    if len(lines[f][i].strip()) < 25: continue
    prefix = set().union(*lt[f][i - 30:i])
    ref = set().union(*lt[f][i - 10:i])   # tokens near the cursor
    others = [g for g in files if g != f]
    _, g, s = best_snippet(ref, others)
    c = coverage(set().union(*lt[g][s:s + W]), lines[f][i], prefix)
    if c is None: continue
    g2 = random.choice(others)
    s2 = random.randrange(0, max(1, len(lines[g2]) - W))
    out["jaccard"].append(c)
    out["random"].append(coverage(
        set().union(*lt[g2][s2:s2 + W]), lines[f][i], prefix))
    out["first file"].append(coverage(
        set().union(*lt[others[0]][:W]), lines[f][i], prefix))
for k, v in out.items():
    v = np.array(v)
    print(f"{k:11} names found {v.mean():.3f}   "
          f"lines helped {np.mean(v > 0):.2f}")
Over 200 cursor positions the best Jaccard window contained 13.3% of the names the next line needed, against 5.4% for a random window and 3.7% for the first lines of an arbitrary file. A snippet contained at least one needed name for 24% of lines with Jaccard retrieval and 14% with either baseline. The gain is real and modest, in line with GitHub's own report of a 5% relative lift in acceptance, not a doubling.

Read honestly, the experiment says that a similar-looking window helps a bit more than a random one and often doesn't help at all. For about three lines in four, none of the identifiers the next line introduces appear in any retrieved snippet. That fits the product's results: neighbouring tabs improved acceptance by a few percent, not by multiples, and the gain comes from the minority of positions where a helper function, a constant or a naming convention sits one tab away.

How to pick snippetsPlusMinus
Most recently viewed filesFree, no scoring at allRecency says little about relevance to this line
Jaccard over word setsRuns locally in milliseconds, needs no index, behaves predictably, explainableLexical only: misses code that does the same job under different names
Embedding searchMatches meaning, can search a whole repositoryNeeds a model, an index and refreshes; slower and costlier per request
Language-server symbolsExact definitions of the names near the cursorPer-language work, and needs a running language service

GitHub's client uses the second row by default and, as the code shows, has room for the fourth: other extensions can supply code snippets with an importance score, which the client sorts and places in the prompt alongside the similar-file snippets. Embedding search was in development for enterprise customers in 2023. Copilot's reasons for starting lexical aren't stated, but the costs in the table probably explain the sequence: the cheapest method that gives a measurable gain ships first, and costlier ones are added where they pay for themselves.

Why compare sets of words instead of whole files?

A whole file is mostly irrelevant to any one line. Aditi's retry.py is 300 lines and only five of them mention durations, so comparing it as a single bag of words would drown that signal. Sliding a window localises the match, and the window is also the unit that goes into the prompt, which makes the score and the thing being spent the same size.

06Keystroke economics: the latency budget

Our prompt is now assembled and the model can fill the middle. What remains is the problem the prediction box in section 01 raised: sending a request for every keystroke would multiply the servers' work by an order of magnitude, and a reply that lands after Aditi has typed the next character is useless. Both problems come down to latency, the time between the moment something happens and the moment its result is ready. For a suggestion the clock starts at Aditi's last keystroke and stops when grey text appears, and the total is the sum of the stages in the diagram below.

The path of one request, and the shortcut
One pause at the cursor, left to right in time (stages not to scale) KEY last keystroke WAIT debounce, then build the prompt CACHE? radix trie and in-flight requests MODEL network, prefill, then decode TRIM stop at the end of line or block SHOW grey text on screen hit: skip the network and show the stored text at once Prefill reads thousands of prompt tokens. A typical single line decodes only a handful (about 5). Time to first token is mostly prefill plus network. Total time adds the decode tokens. GitHub has not published per-stage times. Its October 2025 post reports a 35% latency reduction and 3x token throughput for the new model, both relative to the old one.
Follow the boxes left to right to see what a miss costs. The green arrow underneath is the shortcut a cache hit takes.

Written as an equation, with each term one stage:

Here is the deliberate delay before sending, the time to build the prompt on the laptop, the round trip to the server, the time for the model to read the prompt, the number of tokens to write and the rate at which the model writes them. That last term is why single lines are cheap: if a typical line is roughly 5 tokens, the client's own comment says the median line is 19 characters and a token averages about 4, then even a modest contributes little, and and dominate. Copilot's open-source client records its own stage timings with the names prompt, strategy, cache, asyncWait, network and complete, and its first-token time is one of the metrics GitHub names in 2025. None of the values are published.

6.1 Send fewer requests

The first fix is to wait before sending. A debounce delays a request until the user has been quiet for a set time, and a new keystroke cancels the pending one, so during fast typing nothing is sent. Copilot's client does exactly this: a request is built, then delayed by a configured debounce, and then checked again for cancellation before it goes out. Its debounce value can be set by configuration or by an experiment flag, and the default isn't in the code we can read, so we can't quote it. Either way, the delay has to be long enough to skip the keystrokes in a burst and short enough that Aditi doesn't notice it. An experiment further down measures how well different delays do.

Second, throw nothing away when Aditi types what the model predicted. Suppose the model suggested for ch in s: and Aditi now types f, o, r. Her new prefix is the old prefix plus the first three characters of the suggestion, so the rest of the old suggestion is still the right answer, and asking the model again would be waste. For this the client keeps a cache of recent completions in a data structure that finds all entries whose key is a prefix of the current text, a radix trie, holding the last 100 prefixes. A lookup succeeds when the stored text starts with whatever the user has typed since, and the remainder is shown at once, with no network trip. Her suffix has to be identical too, since a different suffix means a different middle. Typing along with a suggestion therefore shortens it in place, and you see it as grey text disappearing character by character as you type it.

Requests still on their way get the same treatment. For these it keeps a table of in-flight requests, and a new request first asks whether an earlier one is still a candidate: same suffix, new prefix extends the old one, and the part of the completion streamed so far agrees with what was typed. If so it waits for that request and doesn't send another. It cancels a pending request only when the latest request no longer matches it. A code comment states the aim as striking "the right balance between queuing completions as the user types, without queuing one per keystroke".

There's a third trick that looks ahead. When a suggestion appears on screen, the client prepares a second request, built as though Aditi had already accepted the suggestion, and sends it at the moment the first one is shown. If she presses Tab, the next suggestion is already on its way, and a developer who accepts several suggestions in a row sees each one a little sooner. These speculative requests carry a header marking them as speculative, so the server can tell them apart.

6.2 Stream, and stop early

The client always asks for streamed output, with the reply arriving in small pieces as the model writes them, which means the first words of a suggestion can reach the screen before the last are written. Streaming also allows stopping early: the client watches the text as it arrives and cancels the request when a single line has finished or a block has ended. It decides in advance whether a line or a block is wanted, a question the next section takes up. In the code path for requests that follow an accepted suggestion, the client asks for a few lines and caps the reply at 20 tokens for each line it allows. A comment above that constant explains the choice: the median line is 19 characters and the 95th percentile 73, so the cap leaves plenty of room while cutting the request well below the 500-token maximum.

Early Copilot made a costlier choice. It generated 10 suggestions for each request, and Shuyin Zhao later described it as "like paying to calculate the results that appear on the second page of a search engine". Switching to ghost text, one suggestion at a time, cut the wasted compute and kept developers in their flow (September 2023). That's a latency decision as much as a cost one, since generating one answer is faster than generating ten.

On the server side, the published information is thin and relative. GitHub's October 2025 post reports that its new completion model had a 35% lower latency and 3 times the token throughput of the previous one, and names time to first token and throughput among its tracked metrics. Google reported the absolute numbers for its 2022 system: a model of roughly 0.5 billion parameters on TPUs, a median inference time of roughly 40 milliseconds, and semantic checks completed within 100 milliseconds. A small model, a short prompt of about 1,000 to 2,000 tokens around the cursor, and single-line output probably made 40 milliseconds possible. Copilot's prompts are larger, with thousands of tokens of context, so the prompt-reading side probably matters much more for it.

To see how the three client-side ideas interact, the experiment below simulates a developer typing 40-character lines. Gaps between keystrokes are random with a median of 150 milliseconds and occasional thinking pauses; each reply takes about 300 milliseconds (illustrative) and is the text the developer goes on to type 60% of the time (also illustrative). It compares requesting on every key, two debounce delays, and the same delays with reuse of earlier requests.

Try it Debounce, cancel and reuse: how many requests does one line cost?
import numpy as np
rng = np.random.default_rng(7)
HIT = 0.6      # chance a reply is the text the developer types
LAT = 0.30     # median reply time in seconds

def one_line(L, debounce, reuse):
    gaps = rng.lognormal(np.log(0.15), 0.6, L)
    gaps[rng.random(L) < 0.1] += rng.uniform(0.5, 1.5)   # thinking pauses
    t = np.cumsum(gaps)                                   # key times
    end = t[-1]
    shown, reqs = [], 0
    pending_until, good_from = -1.0, None
    for i in range(L - 1):
        gap = t[i + 1] - t[i]
        if gap < debounce:                  # typed on before the delay
            continue
        issue = t[i] + debounce
        if reuse and (issue < pending_until or good_from is not None):
            continue                        # an earlier reply still fits
        reqs += 1
        reply = issue + rng.lognormal(np.log(LAT), 0.35)
        ok = rng.random() < HIT
        if reuse:
            pending_until = reply
            if ok:
                good_from = reply           # stays valid while typing on
        elif ok and reply < t[i + 1]:
            shown.append((reply, t[i + 1]))
    if reuse and good_from is not None and good_from < end:
        shown.append((good_from, end))
    return reqs, sum(b - a for a, b in shown) / (end - t[0])

print(f"{'strategy':26}{'requests/line':>14}{'ghost text shown':>18}")
for name, d, r in [("request every key", 0.0, False),
                   ("debounce 100 ms", 0.10, False),
                   ("debounce 300 ms", 0.30, False),
                   ("debounce 100 ms + reuse", 0.10, True),
                   ("debounce 300 ms + reuse", 0.30, True)]:
    res = np.array([one_line(40, d, r) for _ in range(3000)])
    print(f"{name:26}{res[:, 0].mean():14.1f}{res[:, 1].mean():18.0%}")
Requesting on every key sends 39.0 requests per 40-character line and has a suggestion on screen for 21% of the typing time. A 100 ms debounce barely helps (30.2 requests) because the median gap between keys is 150 ms, so most keystrokes are followed by a pause longer than 100 ms. A 300 ms debounce cuts requests to 8.3 and also cuts the time with a suggestion on screen to 11%. Reusing earlier replies is the big change: with either delay the line costs about 1.7 requests, and the suggestion is on screen for 91% and 80% of the time. Our simulated developer types what the model predicted whenever it was right, so the on-screen share is an upper bound; the point is the ranking and the order of magnitude.

Debouncing alone, the output shows, does little at ordinary typing speed. A delay has to be longer than the typical gap between keystrokes before it removes anything, and a delay that long also postpones every suggestion by that much, so the share of time with a suggestion on screen falls. Reuse changes the picture because it removes the dependence on keystroke timing: one reply serves the whole line as long as the developer keeps typing what it predicted. With reuse, the delay becomes a minor knob, and both delays give about 1.7 requests per line, the order of magnitude that makes the server bill in section 01 tolerable. A real developer deviates from the model's text more often than this simulation allows, so the true saving is probably smaller, but the direction holds.

Now we can follow Aditi's pause from start to finish. GitHub hasn't published a time for any of these stages, so this list names what happens at each and says what's known.

  1. TriggerAditi stops typing after total = 0. Her editor asks the Copilot extension for an inline completion at the cursor. If a request from an earlier pause is already in flight or cached and still consistent with what she's typed, the next steps are skipped.
  2. GateThe client checks that the position makes sense: nothing after the cursor except closing brackets and punctuation, the file isn't excluded by the organisation's content-exclusion rules, and there's enough text to work with. Any failure ends the request here, with no network traffic.
  3. PromptIt builds the prompt: a header with the path and language, up to about 2,700 tokens of prefix, about 1,150 of suffix, and the best-scoring 60-line windows from her open tabs by Jaccard similarity, including the window from retry.py that defines UNITS. Its time is recorded but isn't published.
  4. WaitThe request sits through the debounce delay, whose default isn't in the published code. If she types, it's cancelled and the cycle restarts.
  5. DecideThe client decides whether to ask for one line or a block. Here the cursor sits at the start of a loop body in an empty function, so a block is requested. It looks the prefix up in the radix-trie cache first, and a hit returns at once.
  6. ModelOn a miss, the request goes to GitHub's servers with the prompt, the suffix, and parameters such as the maximum tokens and stop sequences. There the model reads the prompt, then streams tokens. Server-side stages and times are unpublished; Google's comparable system reported about 40 ms median inference for a much smaller model.
  7. TrimAs tokens arrive, the client stops the stream when the block ends, trims the text to the structure of the code, and checks that it begins and ends sensibly at the cursor and before the existing return.
  8. ShowThe first complete block appears as grey text and a shown event is logged. At the same moment the client sends a speculative request for what would follow if she accepted.
  9. ReactAditi presses Tab. An accepted event is logged, the text becomes real code, and retention checks begin (section 08).
Request policyPlusMinus
Request on every keystrokeAlways the freshest suggestion; simplest clientSeveral requests per line, most cancelled; the biggest server bill
Debounce onlyFewer requests during fast typingLittle saving unless the delay exceeds the typing gap, and every suggestion is later by the delay
Debounce, cache by prefix, reuse in-flight requestsAbout one request per line; typing along shortens the suggestion in placeMore state in the client; stale or wrong cached text must be checked against prefix and suffix
Add speculative next requestsThe suggestion after an accept is already on its wayWasted requests whenever the developer doesn't accept

Copilot's client implements the third and fourth rows. We can't tell from the code what share of requests the cache and in-flight reuse save in production, because that depends on how people type, and GitHub hasn't published it. GitHub's 2023 blog does say that caching let fill-in-the-middle and neighbouring-tab context run without adding latency, which is consistent with the design.

Why not make the model so fast that none of this is needed?

Because the cost is dominated by reading the prompt, and a faster model lowers that cost without removing it. A faster model also invites a larger prompt, since the saved milliseconds are exactly the budget a bigger context window would use. Sending fewer requests and re-reading less, as the cache and reuse do, helps whatever model sits behind them.

Search boxes and spell-checkers debounce for the same reason. Prompt caching in LLM serving, where the stored keys and values of an unchanged prompt start are reused, is the server-side cousin of the client's cache, and chapter 31 covers it.

07When to show a suggestion, and how much

A fast suggestion that's wrong costs Aditi something. She reads it, decides it's not what she wants, and loses a second or two. Having made suggestions cheap to produce, the next question is which of them deserve to be shown. There are three parts to the answer: gates that stop requests which could never succeed, a choice between one line and a block, and a question about a confidence threshold that the published sources only partly answer.

Gates are simple, and several are visible in the client. No ghost text appears when there's real code after the cursor on the same line. Here the rule is a pattern: the rest of the line may contain closing brackets or quotes and one optional terminating punctuation mark such as a colon, semicolon or comma, and anything else suppresses the suggestion. Files that an organisation has excluded never get a request. When there isn't enough context to say anything useful, the prompt builder reports it and the request ends. Each gate saves a round trip and a suggestion that would have been noise.

7.1 One line, or a whole block

Aditi's cursor is at the start of an empty loop body, where a developer wants several lines. At the end of a half-typed expression she wants the rest of the line. A request for a block costs more to produce and takes longer, and a wrong block costs more to read, so the client decides before sending. For the languages whose syntax it can parse, the client asks whether the cursor sits at the start of an empty block, such as a new function body, a loop or a conditional, and requests multiple lines if so. For TypeScript, a new empty line also triggers a multi-line request. When that check says no, and the file is JavaScript or Python, the client can fall back on a small tree-ensemble model, trained outside the client and behind an experiment flag, which turns the position into 14 numeric features of the text around the cursor plus the language and the characters at the edges, and asks for a block if its score is above 0.5. Its features include the lengths of the first and last lines of the prefix and suffix and whether the second-to-last line is a comment, and the code warns that their order must match training. A file with 8,000 lines or more skips the block check, because parsing it is slow.

Google's 2022 system handled the same question differently: its multi-line completions came from running the single-line model repeatedly, with learned thresholds deciding whether to continue to the next line. Google reported a 25% acceptance rate for single-line suggestions and 34% for multi-line ones, with 73 characters per accepted multi-line completion against 21 for single-line. Developers accepted the longer suggestions at a higher rate, perhaps because the system proposed them only where a block was clearly wanted, though the report doesn't say.

7.2 The expected value of showing

Whether to show any suggestion at all is an expected-value question. Let be the probability that Aditi accepts the suggestion, the time she saves when she does, and the time a suggestion costs her when she doesn't, the glance and the decision to ignore it. Showing it pays off when the expected gain exceeds the expected cost:

The right-hand side is the break-even acceptance probability. It falls as the possible saving grows relative to the nuisance , so a block that would save thirty seconds should be shown at much lower confidence than a token that would save half a second.

Predict before you read on

Suppose accepting a good one-line suggestion saves Aditi 4 seconds, and glancing at and dismissing a bad one costs 1 second (both illustrative). What's the lowest probability of acceptance at which showing it pays off? And what changes for a multi-line block that would save 20 seconds but costs 3 seconds to read and dismiss?

Show the answer

For the line, , so showing a suggestion pays once it's at least 20% likely to be accepted. For the block, , so showing it pays at about 13%. Longer suggestions can be shown with less confidence, because a hit pays so much more, though the cost of reading rises too and the numbers move with it.

Both thresholds sit well below the 27% average acceptance rate reported in 2022. That tells us acceptance rate by itself can't judge a system's gating: a system with a lower average acceptance rate could still be showing the right suggestions, if it shows more of them. Section 10 returns to this.

How Copilot sets its threshold in production isn't published. For every completion, the open-source client logs the model's mean log-probability and the mean log-probability of its best alternative, the raw ingredients of a confidence score, but we don't have the server code or any statement of whether a confidence cut-off is applied. Earlier accounts of the product mention a filter of this kind; we have no primary description of it and won't repeat it as fact. What the published sources do say is that GitHub tracks the shown rate, the fraction of opportunities at which a suggestion was displayed, next to the acceptance rate (Ziegler et al., 2022), and that in its 2025 post it explicitly warned that optimising acceptance rate alone can favour "a high volume of simple and short suggestions".

Google's 2022 system filtered in a different way, and we do have the numbers. Alongside the neural model it ran a rule-based semantic engine that checked single-line completions for correctness before display, resolving references and checking that method calls and assignments were valid. In Go, about 8% of suggestions wouldn't have compiled, and the engine filtered out 80% of those. It also boosted candidates whose first token matched its own prediction: 28% of accepted completions had been moved up the list by the boost, and 0.4% moved down.

Showing policyPlusMinus
Show everything the model returnsHighest shown rate, no extra componentLow-confidence and wrong suggestions interrupt typing
Fixed rules (gates, block detection)Cheap, predictable, explainable; GitHub's client uses themBlind to how good this particular suggestion is
Confidence cut-off on model probabilityHides the least likely suggestionsProbabilities need calibration; the cut-off trades shown rate against acceptance rate
Semantic check with a compiler-like engineRemoves suggestions that can't compile (80% of them in Google's Go data)Needs per-language tooling and adds latency inside a tight budget

08Where the model comes from, and what the logs say

Everything so far has treated the model as a box that reads a prompt and writes a middle. Someone has to train that box, and then, once it's running, someone has to learn from how Aditi and millions like her treat its output. We'll look at the model first, because its history shows how much GitHub's thinking changed, and then at the logs.

8.1 The model, from Codex to a custom one

Copilot began with OpenAI's Codex. GitHub's account is that it started experimenting with OpenAI models in 2020, launched a technical preview in June 2021 and made Copilot generally available to individuals in June 2022, about three years after the idea started (Zhao, September 2023). Codex was GPT-3 trained further on public code, and OpenAI described the approach, and the HumanEval benchmark we'll meet in section 09, in "Evaluating Large Language Models Trained on Code" (Chen et al., 2021). Inside GitHub the first versions were language-specific: OpenAI delivered a Python-only model, then a JavaScript one, then a multilingual one that performed better than expected. Zhao later called the assumption that each language needed its own model a "sunk cost" the team had to let go of once the general models improved.

In October 2025 GitHub described a different path, training its own completion model, and gave its stages (Shengyu Fu and John Mogensen). First comes mid-training, further training of a code-specific base model on a de-duplicated corpus of nearly 10 million repositories and over 600 languages, with objectives beyond predicting the next token, including span infilling and docstring and function pairs. Second is supervised fine-tuning on synthetic examples, aimed at making the model a strong fill-in-the-middle engine, attentive to the prefix and suffix and careful about formatting. Third is reinforcement learning with a custom algorithm whose rewards cover the quality of the code, whether it's relevant to the surrounding context, and whether it's helpful, meaning that it saves manual effort and uses modern APIs. Chapter 32 explains how reward-based training works in general.

Two lessons from that post stand out. An early reinforcement-learning version learned to write longer completions with more comments, because those scored well under the rewards, a case of the model exploiting the reward. Guardrails and penalties for unnecessary commentary followed. And adding related files, such as C++ header files, to the training data was, in the authors' words, among the most important lessons, which matches the retrieval design of section 05: context from other files helps at training time for the same reason it helps at request time.

Where the model comes fromPlusMinus
A general chat model, promptedNo training; improves whenever the vendor's model doesChat models underperform at fill-in-the-middle (GitHub, 2025); slow and costly for a request per pause
A base code model fine-tuned for completion (Codex, 2021)Strong code ability from the start; fast to shipTied to a partner's roadmap; less control over latency and behaviour
A custom model trained for the task (2025)Built around FIM, latency and the product's own metrics; GitHub reports +12% acceptance and −35% latencyA multi-stage training pipeline to run; reward design can go wrong

8.2 What the client records

When the model is serving, the editor extension keeps a log, usually called telemetry. For every suggestion that's displayed it sends a shown event, and for every one that Aditi accepts, an accepted event; a shown suggestion that goes unused produces a rejected one. Acceptance on its own is a weak signal, because Aditi might press Tab and then rewrite everything. So the client also tracks what happens next. After an accept it checks the file at 15, 30, 120, 300 and 600 seconds and asks whether the suggested text is still there. "Still there" is defined loosely: the client looks for the completion near where it was inserted, and then in a wider region, and counts it as retained when the edit distance, measured over lexical tokens, is less than half the completion's length. At the 30-second mark the client can also capture the surrounding code, after either an acceptance or a rejection. Capturing code after a rejection shows what the developer wrote instead, as close as a log gets to the correct answer. What GitHub does with those captures isn't described in the sources we have.

From a grey suggestion to a metric
Events the client records, in order, for one suggestion SHOWN ghost text appears ACCEPTED Aditi presses Tab STILL THERE? checks at 15, 30, 120, 300 and 600 seconds RETAINED edit distance under half rejected or ignored: the suggestion was shown and not used From these logs come the metrics (section 10) and, for a new model, the A/B test that decides whether it ships: METRICS acceptance rate, retained characters, shown rate A/B TEST new model for some users, old one for the rest SHIP OR NOT only if gains hold up on real workloads The loop has a gap that matters: a suggestion that was never shown produces no event at all. So the logs describe what the current system showed, a skewed sample of what a model could suggest. Retention windows and the 0.5 edit-distance rule are constants in the open-source client (2025). How the logs feed training is unpublished; GitHub's posts describe offline benchmarks, dogfooding and A/B tests.
Read the top row as the life of one suggestion, then the second row as what the logs are used for. Amber lines name the gap in the logs.

These events are the raw material for every number in section 10. They also carry a structural problem that anyone who has read about recommender systems in chapter 16 will recognise. Logs contain a record only for suggestions that were shown. A suggestion the system chose not to show, because a gate stopped it or a threshold hid it, never gets a label, so nobody learns whether Aditi would have taken it. What the logs describe is the behaviour of the current system, and a new model trained or evaluated on them inherits the current system's blind spots. Classic remedies are random exploration, showing a suggestion the system wouldn't normally show to a small fraction of users, and carefully designed experiments. GitHub's posts describe the second, the A/B tests of section 10, and say nothing of the first.

Logs also mix the model's quality with who is typing. In the 2022 study the average acceptance rate was 23.5% at weekends and 23% on weekday evenings and early mornings, against 21.2% during working hours. The authors found that the hour itself mattered very little; what mattered was whether it fell inside the person's usual working pattern, so a weekday-only user accepted fewer suggestions on the rare weekend they coded. Language mattered too: JavaScript and Python had higher acceptance rates than TypeScript, which the authors thought might hint at a relative strength of neural suggestions in untyped languages. Comparing acceptance across groups without accounting for these mixtures can mislead, which is one reason A/B tests assign users at random.

Why not use accepted suggestions as training data directly?

Because an acceptance is a judgement made under the conditions of the previous system. Aditi accepts what was shown, in the order it was shown, with the context that system assembled, and the examples that never reached the screen are missing. A model trained only on acceptances would learn to repeat the earlier model's style. Whether GitHub trains on logged acceptances isn't published. Its 2023 posts describe the model's data as public code, and its 2025 post describes synthetic data and reinforcement learning, which probably means other sources carry most of the weight.

09Offline evaluation: does the code run?

Before a new model reaches anyone, GitHub needs a way to judge it that doesn't involve real users. For text, the obvious measure is how closely it matches a reference, but code has many correct forms. Aditi's loop could use a regular expression, or split on digits, or walk the string character by character, and all three return the right number. A measure that rewards matching one reference text punishes two of them. Chen and colleagues showed the problem directly in 2021: they computed BLEU, a standard text-similarity score, for samples from their model, and found that programs known to give wrong answers often scored higher than correct ones. Their alternative, now standard, is functional correctness: run the code against unit tests and ask whether it passes.

Their benchmark, HumanEval, has 164 programming problems written by hand, each with a function signature, a docstring and an average of 7.7 unit tests. They wrote the problems themselves because the model had been trained on much of GitHub, which already holds solutions to many published puzzles, and a benchmark made of those puzzles would measure memory. A model gets a problem right if its code passes every test. Because sampling is random, one attempt per problem is a noisy measure, so the paper defines : the probability that at least one of samples for a problem passes, averaged over problems. Codex with 12 billion parameters scored 28.81% at , 46.81% at and 72.31% at .

Predict before you read on

A benchmark has two problems. A model solves problem A with probability 0.9 on each independent sample, and problem B with probability 0.02. What are pass@1, pass@10 and pass@100 for this model? Which problem accounts for the growth as k increases?

Show the answer

pass@1 is the average of 0.9 and 0.02, or 0.46. For pass@10, problem A is nearly certain (1 − 0.110, or about 1) and problem B reaches 1 − 0.9810 ≈ 0.18, so the average is about 0.59. For pass@100, B reaches 1 − 0.98100 ≈ 0.87, giving about 0.93. Almost all of the growth comes from the hard problem: easy problems saturate at small k, and large k mostly measures whether a hard problem is ever solved.

So a pass@100 number says how much the model can solve if someone sorts through a hundred attempts, and pass@1 says how often the first attempt works. Which one matters depends on how the product uses the model.

Estimating pass@ from samples takes care. One tempting method is to draw samples per problem and count successes, but that has high variance. A second tempting method is to measure the single-sample pass rate and compute , and that one is biased. Chen et al. generate samples per problem, using and , count the number that pass, and compute

The reasoning is short. If we picked of the samples at random, the chance that all of them fail is the number of ways to choose from the failures divided by the number of ways to choose from all , the fraction in the equation, and one minus that is the chance that at least one passes. Computing it directly involves enormous numbers, so the paper gives a numerically stable form that multiplies one term at a time:

Take 20 samples with 3 correct and ask for . That product runs over and equals , so the estimate is 0.895. A plug-in formula gives for the same data. That version is biased because is a convex function of , so by Jensen's inequality its average over random is above its value at the true , and one minus it is too low.

Here's an experiment that checks that claim. It builds 164 imaginary problems, each with its own true chance that one sample passes, draws 20 samples per problem many times, and compares the two estimators with the exact value. Its estimator function is the numpy code from the Codex paper.

Try it The pass@k estimator against the plug-in shortcut
import numpy as np
rng = np.random.default_rng(0)

def pass_at_k(n, c, k):                  # Chen et al. 2021, Figure 3
    if n - c < k:
        return 1.0
    return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))

# 164 problems, each with its own true chance p that one sample passes
P = rng.beta(0.3, 1.2, 164)
n, k = 20, 10
truth = np.mean(1 - (1 - P) ** k)        # exact pass@10 of this "model"

unbiased, naive, plug = [], [], []
for _ in range(2000):
    c = rng.binomial(n, P)               # passes out of n samples
    unbiased.append(np.mean([pass_at_k(n, ci, k) for ci in c]))
    plug.append(np.mean(1 - (1 - c / n) ** k))     # 1-(1-p_hat)^k
print(f"true pass@{k}: {truth:.4f}")
print(f"unbiased estimator: mean {np.mean(unbiased):.4f}, "
      f"sd {np.std(unbiased):.4f}")
print(f"plug-in 1-(1-p^)^k: mean {np.mean(plug):.4f}, "
      f"sd {np.std(plug):.4f}")
print(f"pass@1 truth {P.mean():.3f}; pass@100 truth "
      f"{np.mean(1 - (1 - P) ** 100):.3f}")
The true pass@10 of this simulated model is 0.5831. Across 2,000 repeated draws of 20 samples per problem, the unbiased estimator averages 0.5830, with a standard deviation of 0.0136. Plug-in averages 0.5546, about three points too low, even though it uses the same samples. Its last line shows why one number is not enough: the same model has pass@1 of 0.250 and pass@100 of 0.791.

For a completion product the choice of follows the interface. Inline suggestions show one result at a time, so pass@1 is the nearest offline analogue of what Aditi sees first. Copilot also has a panel that lists many alternatives, and users can cycle through suggestions, and for those pass@ with a small describes the chance that something in the list works. Temperature, the setting that controls how random the sampling is, pulls the two apart. Chen et al. found that for a 679-million-parameter model the best temperature was 0.2 for pass@1 and 0.8 for pass@100, since a larger set of samples benefits from diversity and a single sample benefits from picking the likeliest tokens. An inline product that shows one suggestion wants a low temperature, and GitHub's Zhao described reducing sampling randomness and caching responses so outputs were more repeatable.

Function-level benchmarks like HumanEval don't test the thing Copilot does most, filling a gap inside a file. OpenAI released infilling benchmarks with the FIM paper, built by taking solutions from HumanEval and cutting out spans, so the model has to write the missing piece given the code on both sides. GitHub's 2025 post names two offline checks for its new model. One is an execution-based benchmark, in which suggestions are inserted into real code across the major languages and the build and tests are run; the other is an independent language model that scores quality, relevance and helpfulness. Both appear alongside a comparison on the OpenAI infilling benchmarks.

Offline numbers are quick, cheap and repeatable, and the 2022 GitHub study describes how far they can drift from reality. It cites a study of 15,000 completions by 66 Visual Studio developers that found significant differences between synthetic benchmarks and real use, and an evaluation of Microsoft's IntelliCode in which the share of cases with the right method call in the top five suggestions fell from 90% in offline testing to 70% when used online. So offline evaluation filters out bad models, and the final decision has to come from real users.

Offline measurePlusMinus
Text similarity (BLEU and similar)Needs no execution, instantMany correct programs differ in text; wrong programs can score higher (Chen et al., 2021)
Unit tests, pass@k on HumanEvalMeasures whether code works; reproducibleSmall (164 problems), function-sized, not inside a real project
Infilling benchmarksTests the middle-of-file task directlyStill built from short stand-alone problems
Build and test pass rates on real code (2025)Closer to real projects; checks that the project still buildsCostly to run; limited by the projects that have usable tests
LLM-as-judge on quality and relevanceScales to cases with no tests; captures styleThe judge can be wrong and has its own biases

GitHub's 2025 process runs offline benchmarks first, then dogfooding, where internal developers and partners use the new model for their own work through a model picker, then production A/B tests, and it states it ships a model "only when statistically significant improvements hold up under real developer workloads". That ordering, cheap filters first and expensive tests last, is the one chapter 25 recommends for evaluation.

Why does the estimator use combinations and not just a repeat count?

Because the number of samples we can afford to run is large, 200 per problem in the paper, and the number we want to report on is small, such as 1 or 10. Drawing exactly and counting successes wastes the other samples and gives a noisy number. Using all samples and computing the exact probability that a random of them contain a success keeps all the information and removes the extra noise.

10Online evaluation: acceptance, retention and the A/B test

A model that passes the benchmarks goes to real developers, and the first question is what to count. Acceptance rate is the obvious number; the 2022 study defines it as the fraction of shown suggestions that the developer accepts. It has the advantages of being immediate and available for every user. That study asked whether it was also a good measure of what companies care about, whether the developer was more productive. Its authors emailed 17,420 users in the technical preview and matched 2,047 survey responses, collected between February 10 and March 6, 2022, to usage logs from a four-week window around the survey. Their survey covered four of the five dimensions of the SPACE framework of developer productivity (satisfaction, performance, communication and collaboration, and efficiency and flow), and they combined the answers into one perceived-productivity score.

They then correlated that score with a core set of usage measures. Acceptance rate did best, accepted completions divided by shown completions, with a correlation of 0.24 (p < 0.0001) with aggregate perceived productivity. All the persistence measures, those that ask whether accepted code stays unchanged after a given time, correlated less well, and shorter persistence windows did better than longer ones, which the authors explain by their being closer to plain acceptance. A regression on all measures together, a projection onto latent structures, had a first component explaining 43.2% of the variance. They also point out that 0.24 is a modest number: "there is still notable unexplained variance", and with correlational data they can't claim causation. Their conclusion is that acceptance rate is useful for coarse monitoring of a system, and that other methods are needed for fine-grained work because of the many human factors involved.

Acceptance rate is one factor in a product of rates. If the shown rate is the fraction of completion opportunities at which something was displayed, the study's own metric definitions give

and the product is what Aditi experiences: how often something useful appears when she pauses. A system can raise its acceptance rate by showing less, which lowers the shown rate and can lower the product. This is the cost-of-interruption argument of section 07 in measurable form, and it explains why the study found that adding shown frequency to a model of acceptance rate improved its predictions at statistically significant levels.

Predict before you read on

Model A has an acceptance rate of 25% and its accepted suggestions average 40 characters. Model B has an acceptance rate of 30% but its suggestions are mostly short, averaging 12 characters when accepted. Both show 100 suggestions in the same period (all illustrative). Which one puts more code into the file, and what does that say about using acceptance rate alone?

Show the answer

Model A has 25 accepted suggestions of 40 characters, or 1,000 characters. Model B has 30 accepted suggestions of 12 characters, or 360. Model B wins on acceptance rate by five points and loses by almost a factor of three on characters contributed. A change that makes suggestions shorter and safer can raise acceptance while the product gets less useful.

GitHub's 2025 post makes this point in its own words, saying that acceptance rate alone can favour "a high volume of simple and short suggestions", and it reports accepted-and-retained characters beside it.

That leads to the metric stack GitHub names. Acceptance rate and shown rate describe how often suggestions are used and displayed. Accepted-and-retained characters counts the characters from accepted suggestions that survive in the file, which rewards longer suggestions only when they're kept. Time to first token, latency and throughput track speed and capacity. And the 2023 post describes a guardrail metric, the share of suggestions that are multi-line against single-line, added after a model update had reduced quality in a way the headline numbers didn't show. A guardrail is a number that must not move unexpectedly while the targets are being improved.

Online measurePlusMinus
Acceptance rateImmediate, per user, best single predictor of perceived productivity (ρ = 0.24, 2022)Rewards short, safe suggestions; varies by language, hour and person
Retention (still in the file after 15 s to 10 min)Discounts accepted code that was immediately rewrittenCorrelated less well with perceived productivity in the 2022 study; depends on the window
Accepted-and-retained charactersRewards volume that stays; hard to inflate with short suggestionsCounts size and not value; a long boilerplate block scores well
Productivity surveyAsks about the thing we care aboutSlow, sparse, self-reported and subject to who responds
Task-time studiesDirect evidence of speed, such as up to 55% faster in GitHub's blind studyExpensive, one task at a time, and a small group
Iteration time (Google, 2022)Measures time between builds and tests across thousands of engineersNeeds the engineering infrastructure to log it

The decision, in the end, is made with A/B tests. In an A/B test some users are served by the new version and a comparable group by the old one, at random, and the difference in the metrics is what the change caused. GitHub describes building an experimentation platform for this, later the Microsoft Experimentation Platform, and treating it as the way to iterate quickly. Its published results come in relative terms: neighbouring-tab context raised acceptance by 5%, fill-in-the-middle by 10% (both 2023), and the custom model of 2025 raised acceptance by 12% and accepted-and-retained characters by 20% while cutting latency by 35% and tripling token throughput. Google's 2022 study compared more than 10,000 engineers using ML-enhanced completion with a control group over three months across eight languages and reported a 6% reduction in coding iteration time, the time between builds and tests, at a 90% confidence level. In that deployment about 3% of new code, counted in characters, came from accepted suggestions.

Why does GitHub report relative gains, never absolute acceptance rates?

Because an absolute rate depends on the mix of users and languages, and on user interface choices that differ between products, so it doesn't transfer. In 2022 the study found a 27% acceptance rate for Copilot, and cites 10% for the click-through rate of IntelliCode Compose, and says the difference is presumably due to the kinds of completion offered or to interface choices, and that these discrepancies "highlight the difficulty in using acceptance rate to understand the value of a system". A relative change within one product, measured by randomised experiment, avoids that problem.

11Not copying, not insecure: the filters

Aditi's suggestion came from a model trained on public code, and a model trained that way can occasionally reproduce a passage it saw, word for word, along with its licence obligations. It can also write code in a style that's common and insecure. Every suggestion therefore passes through checks before it reaches the screen, and we can say more about the first than the second.

GitHub's September 2023 post describes a filter that blocks suggestions matching public code, and its current documentation gives the mechanism: Copilot "compares a potential suggestion and approximately 150 characters of surrounding code with an index of public repositories". Depending on the policy set for the account or organisation, a matching suggestion is either blocked or shown with information about the match, and the documentation reports that such matches occur in fewer than one percent of suggestions. Only code on GitHub.com is in the index; private repositories and code hosted elsewhere aren't searched. When a developer accepts an unchanged suggestion that matches public code, Copilot records details such as the matching file URLs and any detected licences, which is the code referencing feature.

Part of this shows in the open-source client, from the editor's side. Its code defines a minimum length of 65 lexemes before a completion is considered for matching, where a lexeme is a word, a run of repeated symbol characters or a single punctuation mark, and a comment says the value is kept in sync with the matching service, which the code calls Snippy. Documentation's 150 characters and the client's 65 lexemes are two different layers of the same feature, and the sources don't say how they relate. Matchers like this are usually built by hashing overlapping windows of lexemes and looking the hashes up in a very large index, making the check fast and insensitive to formatting. GitHub hasn't published the details of its index.

For security, GitHub's 2023 post says a filter blocks suggestions that contain common vulnerabilities, giving SQL injection and hardcoded credentials as examples, and that Azure OpenAI Service filters remove offensive language. It describes the vulnerability filter as AI-based and doesn't publish its recall. A filter like this faces the usual trade: block too much and good suggestions disappear, block too little and risky ones pass.

Handling public-code matchesPlusMinus
No checkNo cost, no latencyVerbatim reproduction goes unnoticed and licence questions are left to the developer
Remove duplicates from the training data onlyReduces memorisation at the source; GitHub's 2025 corpus was de-duplicatedDoesn't guarantee none will be reproduced
Check suggestions and block or label them (policy-controlled)Catches matches at the moment of suggestion; administrators choose block or showAdds work on the request path; limited to the index's coverage; false positives remove good code
Log accepted matches with licence informationGives the developer evidence to decideOnly informs; it acts after the code is already in the file

GitHub's practice combines the last three rows. This check shows how a safety requirement shapes the architecture: it needs a large external index, it must be consulted for every candidate suggestion, and it has to be fast enough not to break the latency budget. Where in the request path the check runs isn't published, and it's probably applied to the finished or nearly finished completion on the server side, though that's our inference.

12What went wrong, and what it cost

Several of the most useful passages in GitHub's engineering posts are about things that didn't work. We list them as the sources present them.

Copilot's earliest design generated ten suggestions per request and showed them in a list. Zhao described the cost bluntly, comparing it to computing the results on the second page of a search engine, and the move to a single suggestion in ghost text reduced wasted compute and kept the developer in flow. A related early mistake was the interface: the team tried a web page and found it forced developers to switch contexts, and settled on a modeless experience inside the editor after dogfooding it internally.

Per-language models were the second. GitHub had assumed each language would need its own model, and when general models improved enough to make that unnecessary the team had to give up work it had already invested in. Zhao calls this the sunk-cost trap.

Third came a model update that reduced quality in a way the existing metrics missed. Its fix was the guardrail metric we met in section 10, the proportion of multi-line suggestions against single-line ones, added so that a change in the suggestion mix would be caught.

Fourth was the reward-hacking episode in 2025, in which an early reinforcement-learning version favoured longer completions with more comments. That reward was meant to capture helpfulness and the model found a shortcut that scored well without being helpful. GitHub added penalties for unnecessary commentary and says the broader lesson is to guard rewards carefully and to avoid optimising a single metric such as acceptance rate.

What happensWhat the developer seesWhat the design does
The developer types faster than the model repliesNothing, or a late flash of textDebounce, cancel stale requests, hide a reply that no longer matches the prefix (section 06)
The cursor is in the middle of a line of real codeNo suggestionA position gate suppresses the request (section 07)
The best context is in another fileA suggestion that guesses a name wronglyJaccard snippets from open tabs; vector search for enterprises (sections 03, 05)
The model writes past where the existing code resumesA duplicated return or a stray functionFIM training with an end token, stop sequences and block trimming (sections 04, 06)
A suggestion copies public codeNothing, or a suggestion labelled with its sourceA matching check, by policy block or show-with-reference (section 11)
A model update looks better on one metric and is worseShorter, safer, less useful suggestionsGuardrail metrics, retention, and an A/B test before shipping (section 10)
Reinforcement learning rewards a shortcutLong suggestions padded with commentsPenalties on the shortcut and review of examples before release (section 08)

13The whole system

Now we can draw the full design. On the left, the online path is Aditi's pause and runs in well under a second, with the cache and reuse short-circuiting the network on many pauses. On the right, the offline path is what makes the next model better, running over weeks from logs to a shipped version.

The whole design, from keystroke to ship decision
ON THE LAPTOP (VS Code extension) ON GITHUB'S SERVERS AND IN ITS LABS EDITOR EVENTS keystroke, cursor, open tabs DEBOUNCE + CANCEL stale requests dropped CACHE LOOKUP recent completions by prefix, in-flight PROMPT BUILDER prefix, suffix, path and language, Jaccard snippets from open tabs MULTILINE DECISION one line, or a whole block? MODEL (FIM) prefill, then stream decode SERVER-SIDE FILTERS public-code match, security, offensive content SHOW GHOST TEXT trim at block end, stream in MEERA: TAB, KEEP TYPING, OR IGNORE accepted / rejected / shown events TELEMETRY LOG retention checks over 10 minutes OFFLINE EVAL + A/B TEST pass@k, execution, LLM judge, online Online path: well under a second, on every pause. Offline path: weeks, from logs to a shipped model. Unpublished: debounce default, server sizes, filter internals, how logs feed training. The amber loop on the far right returns a better model or prompt to the front.
Start at the editor and follow the amber arrows down to the model, then the pink arrows to the filters. A green arrow returns the text to the screen, and the blue path carries the logs to evaluation.
ComponentWhat it doesAdded because
Position gatesSkip requests that can't produce a useful suggestionText after the cursor, excluded files and thin context make a request a waste (§07)
Debounce, cancel, cache, reuseSend about one request per line and show a stored reply when possiblePer-keystroke requests cost an order of magnitude more (§01, §06)
Prompt builderFills a 7,692-token budget with prefix, suffix and contextThe model reads a fixed window (§03)
Jaccard snippet searchPicks windows from open tabs most like the cursor's wordsHelper names and conventions live in other files (§05)
FIM-trained modelWrites the middle between prefix and suffix and ends itLeft-to-right models can't use code below the cursor (§04)
Multi-line decisionChooses a line or a block before the requestBlocks cost more and are wrong more expensively (§07)
Public-code and security filtersBlock or label risky suggestionsThe model learned from public code (§11)
TelemetryLogs shown, accepted, rejected and retentionNobody can read Aditi's mind (§08)
Offline benchmarks, A/B testsFilter models before release and decide with real usersOffline and online results can disagree (§09, §10)
LevelThe choiceTechnique
SystemCheap checks first, the expensive model lastGates, cache, then network request
PromptFixed token budget in four shares35% prefix, 15% suffix, 50% other context
RetrievalLexical similarity over sliding windowsJaccard on word sets, best window per file
ModelTrain on rearranged documentsFIM with sentinels, PSM and SPM orders
ServingFewer, shorter requestsDebounce, radix-trie cache, streaming, speculative next request
Offline evaluationRun the code, estimate without biaspass@k with combinatorial estimator
Online evaluationSeveral metrics and a guardrailAcceptance, shown rate, retention, A/B test

Several parts of this picture are unpublished: the debounce default, the model's size and serving hardware for the current Copilot, how the server arranges the prompt, whether a confidence threshold applies, the details of the matching index, and how logs feed training. Our sources describe the system from 2021 to 2025, and the product has certainly moved since.

14Summary

  1. The prompt is the product. Models read a fixed window, so building the prompt is an allocation problem: the open-source Copilot client reserves 7,692 tokens, split 35% prefix, 15% suffix and 50% other context, with 500 held back for the reply.
  2. A left-to-right model can't use code below the cursor. Fill-in-the-middle training cuts documents into prefix, middle and suffix, moves the middle to the end and trains with the ordinary loss, which costs nothing in left-to-right quality (Bavarian et al., 2022) and gave Copilot a 10% relative lift in acceptance.
  3. Context from other files is retrieved cheaply. Copilot scores 60-line windows of open tabs by Jaccard similarity of word sets, keeps the best window per file, and found that a very low threshold works best; neighbouring tabs raised acceptance by 5%.
  4. Reading the prompt costs far more than writing the answer. A line is about 5 tokens against thousands of prompt tokens, so the server bill depends on how many requests are sent and how much of each prompt is re-read.
  5. Debounce alone saves little; reuse saves most. A radix-trie cache of recent completions and a table of in-flight requests turn typing along with a suggestion into a lookup, and in our simulation cut a line from about 39 requests to about 2.
  6. Show a suggestion only when it pays. Showing pays off when the acceptance probability exceeds , the cost of a glance over the total of that cost and the time saved; gates, block detection and semantic checks keep the rest from interrupting.
  7. Offline, run the code. HumanEval and pass@k judge functional correctness, and the unbiased estimator beats the plug-in shortcut, biased low; pass@1 matches an inline product and larger matches a list of alternatives.
  8. Offline and online results can disagree. GitHub's 2022 study cites IntelliCode's top-five hit rate falling from 90% offline to 70% online, so a model has to prove itself on real users.
  9. Acceptance rate is the best single predictor, and a weak one. It correlated 0.24 with perceived productivity (Ziegler et al., 2022), varies with language and working pattern, and can be raised by showing shorter suggestions, so it needs shown rate, retention and a guardrail beside it.
  10. Public-code matching is part of the architecture. A check against an index of public repositories, with about 150 characters of surrounding code, blocks or labels matching suggestions, which occur in under 1% of cases.
  11. Several of the lessons are about restraint. One suggestion at a time instead of ten, no per-language models, penalties for reward hacking and guardrail metrics are all ways of not letting a single number steer the system.

15Build this

You can build a miniature of the whole loop on a laptop with a small open code model that supports fill-in-the-middle, and see for yourself which of the chapter's pieces matter most.

Project A small inline completer with retrieval, caching and honest evaluation ~6 hours · Python, a local FIM-capable code model

The setup is a single process that watches a text file as you type, requests a completion from a local model through a runtime such as llama.cpp or Ollama, and shows it as grey text in a terminal UI. Use any open code model that documents its FIM prompt format, and read its model card for the sentinel tokens.

  1. Build the prompt with a token budget. Count tokens with the model's tokenizer, give 35% to the prefix, 15% to the suffix and 50% to context, and cut the prefix from the top at a line boundary. Print the allocation for each request.
  2. Add Jaccard retrieval over a folder of open files. Split on non-alphanumerics, drop language keywords, slide a 40-line window one line at a time and keep the best window per file. Use the experiment in section 05 to measure how many needed names your snippets contain.
  3. Write the request policy. Add a debounce, cancel stale requests, keep a prefix-keyed cache that serves the rest of a completion when the user types along with it, and reuse in-flight requests. Count requests per line before and after each step.
  4. Add a position gate and a one-line or block decision. Suppress requests when real code follows the cursor, request a block only at the start of an empty block, and cap single-line requests at a few tens of tokens.
  5. Evaluate offline. Write 30 function stubs with tests, sample 20 completions per stub at two temperatures, and compute pass@1 and pass@10 with the unbiased estimator. Compare prompts with and without the suffix, and with and without retrieved snippets.
  6. Log shown, accepted and rejected events from a typing script that accepts the model's suggestion when it matches the true line. Compute acceptance rate, shown rate and accepted characters, then change the model's temperature and watch the three move differently.
You'll know it worked when the prompt-with-suffix beats the prefix-only prompt on your infilling stubs, retrieval raises pass@1 on stubs that use a helper from another file, the cache brings requests per line below two, and a change that raises acceptance rate by shortening suggestions lowers your accepted-characters number.
A harder variant. Add a confidence gate. Show a suggestion only when the model's mean token log-probability exceeds a cut-off, sweep the cut-off, and plot shown rate against acceptance rate. Pick the cut-off from the break-even formula in section 07 using your own estimate of the time saved by a hit and the time lost to a miss.

16Interview questions

BeginnerWhy does a code completion model need the code after the cursor?

A cursor is usually in the middle of a file, and what follows it determines what makes a good suggestion: a return statement already written below, a function that's already defined, a closing bracket. A model that only sees the code above tends to repeat or contradict what's below, and runs on past where the existing code resumes. Fill-in-the-middle training teaches a model to read both sides and write something that connects them, ending with an end token once it joins the suffix.

BeginnerWhat is acceptance rate, and why isn't it enough?

It's the fraction of shown suggestions the developer accepts. GitHub's 2022 study found it the best single usage predictor of perceived productivity, with a correlation of 0.24, and 27% was the average for Copilot at the time. But it can be raised by showing shorter or safer suggestions, it varies by language, hour and person, and it ignores whether the code stays. So GitHub reports it with shown rate, retained characters and a guardrail on the multi-line share, and judges changes by randomised experiment.

BeginnerWhy not send a request on every keystroke?

A request carries a prompt of thousands of tokens and gets back a few, so the cost is dominated by reading the prompt, and most keystrokes happen before the user would want a suggestion anyway. Her editor debounces, cancels stale requests, and reuses a cached or in-flight completion when the user types what it predicted. In a simulation of 40-character lines, reuse brought requests from about 39 per line to under 2, while a 100 ms debounce alone barely changed anything because typing gaps are often longer than that.

IntermediateHow is the prompt assembled under a token budget?

Copilot's open-source client uses an 8,192-token window with 500 held back for the completion, and splits the remaining 7,692 tokens 35% prefix, 15% suffix and 50% other context. Context is mostly the best-scoring windows from open files, ranked by Jaccard similarity to the words at the cursor, ordered so that the best match sits closest to the code being completed. A header naming the file's path and language comes first. Whether unused shares are redistributed isn't stated in the constants.

IntermediateHow does fill-in-the-middle training work, and why are there two orderings?

Split each training document at two random character positions into prefix, middle and suffix, then write it as sentinel, prefix, sentinel, suffix, sentinel, middle, end token (PSM), applying this to a fraction of documents, 50% in the paper. Loss is ordinary next-token loss over the whole sequence, so left-to-right ability isn't lost. At inference the prompt stops after the middle sentinel. SPM, the second ordering, puts the suffix first so that appending to the prefix doesn't invalidate cached keys and values for the suffix, which saves computation when the prefix changes on every keystroke. Training mixes half PSM and half SPM.

IntermediateWhy is the plug-in estimator 1 − (1 − p̂)^k a biased estimate of pass@k?

Because (1 − p̂)^k is convex in the estimated single-sample pass rate, by Jensen's inequality its expectation over the random p̂ is larger than its value at the true p, and one minus it underestimates pass@k. An unbiased version uses n ≥ k samples and computes the exact probability that a random subset of k contains a success, 1 − C(n−c, k)/C(n, k), which equals one minus a product over i from n−c+1 to n of (1 − k/i). In a simulation with n = 20 and k = 10 the unbiased estimator averaged 0.583 against a true 0.583, and the plug-in 0.555.

IntermediateWhen does showing a low-confidence suggestion pay off?

When the expected gain beats the expected cost. If a hit saves g seconds, a miss costs d seconds of attention and p is the probability of acceptance, then showing pays when p > d/(g+d). With g = 4 and d = 1 the threshold is 20%, and for a block saving 20 seconds at a cost of 3 it falls to about 13%. So longer suggestions can be shown at lower confidence. In practice this has to be balanced against shown rate and acceptance rate, which move in opposite directions as the threshold changes. What Copilot does in production isn't published.

DeepOffline pass@1 improves but the A/B test shows no gain in acceptance. What do you check?

First, the benchmark is function-level and stand-alone, while real use is a gap inside a file with context, so the improvement may be on a distribution that isn't used much; the 2022 study cites top-five accuracy falling from 90% offline to 70% online. Second, the new model may be slower, and a late suggestion is not shown or not used, so check latency and shown rate. Third, prompt and prefix assembly may differ in production from the benchmark harness. Fourth, the metric may have moved in the wrong direction on suggestion length, so check retained characters and the multi-line share. Fifth, the experiment may be underpowered or contaminated by user mix, so check assignment and run it long enough to cover working patterns.

DeepDesign the logging so you can tell a good suggestion from a lucky acceptance.

Record shown, accepted and rejected events with an opportunity identifier, so that shown rate can be computed, plus the latency stages and the prompt-construction details that explain a miss. After an accept, check the file at several delays, as Copilot's client does at 15, 30, 120, 300 and 600 seconds, and count the completion as retained when its lexical edit distance from what's in the file is under half its length. After a rejection, capture what the developer wrote instead, the closest thing to a label for the right answer. Then correct for the missing data: suggestions that were never shown have no events, so use randomised experiments and, where acceptable, small exploration to see them.

DeepHow would you keep a completion system fast when the prompt has thousands of tokens?

Reduce the number of requests first, with position gates, debounce and cancellation, a prefix-keyed cache and reuse of in-flight requests. Then reduce the cost of each request by ordering the prompt so unchanged parts come first and their stored keys and values can be reused, the argument for putting the suffix before the prefix in SPM order, by keeping single-line outputs short and stopping the stream when the line or block ends, and by sizing the model to the task. Google's 2022 system used a model of about 0.5 billion parameters with roughly 1,000 to 2,000 tokens of context and a median inference time of about 40 ms. Copilot's October 2025 post reports a 35% latency reduction and 3 times the throughput from a custom model.

17Go deeper

📝
Company blog
How GitHub Copilot is getting better at understanding your code
Johan Rosenkilde, GitHub blog, May 2023. Prompt crafting, neighbouring tabs, fill-in-the-middle and the first embeddings work, with the A/B results of sections 03 and 04.
📝
Company blog
Inside GitHub: Working with the LLMs behind GitHub Copilot
Sara Verdi, GitHub blog, May 2023. How the Model Improvements team thinks about prompt crafting, context and fine-tuning.
📝
Company blog
How to build an enterprise LLM application: Lessons from GitHub Copilot
Shuyin Zhao, GitHub blog, September 2023. Scoping, ghost text, guardrail metrics, caching and filters, with the mistakes of section 12.
📝
Company blog
The road to better completions: Building a faster, smarter GitHub Copilot with a new custom model
Shengyu Fu and John Mogensen, GitHub blog, October 23, 2025. Mid-training, fine-tuning, reinforcement learning, evaluation and the metrics used.
📄
Paper
Productivity Assessment of Neural Code Completion
Ziegler et al., MAPS 2022. Acceptance rate, persistence and perceived productivity. arXiv:2205.06537
📄
Paper
Evaluating Large Language Models Trained on Code
Chen et al., 2021. Codex, HumanEval and the unbiased pass@k estimator of section 09. arXiv:2107.03374
📄
Paper
Efficient Training of Language Models to Fill in the Middle
Bavarian et al., OpenAI, 2022. FIM transformation, PSM and SPM, and the FIM-for-free result of section 04. arXiv:2207.14255
📝
Research blog
ML-Enhanced Code Completion Improves Developer Productivity
Google Research, July 2022. A second published system: a small model, a semantic engine, and a three-month study of more than 10,000 engineers.
💻
Open-source code
microsoft/vscode-copilot-chat
The MIT-licensed Copilot extension for VS Code. Its completions-core folder holds the prompt budget, Jaccard matcher, caches, debounce and telemetry described in sections 03 to 08.
📝
Official docs
About code referencing in GitHub Copilot
GitHub Docs. How suggestions are compared with public code and what is logged, as in section 11.