On this page
A developer types is_allowed =, pauses, and keeps typing graph.. Half a second later, a remote suggestion computed for the earlier buffer arrives. Accepting it corrupts working code. Even a brilliant completion fails when it arrives behind the cursor.
Code completion runs against moving editor state. Tools such as GitHub Copilot split this into dimmed ghost text at the cursor and next-edit suggestions elsewhere in the file.[1] Inline generation uses fill-in-the-middle (FIM) to condition on prefix and suffix, while coding agents run off the keystroke clock.
Targeting 200 ms p95 SLO for single-line inline completions drives every decision: keep exact lookups local, ship compact suffix-preserving context, reuse KV cache blocks across keystrokes, and drop stale replies before paint.

One cursor, five lanes
Five lanes apply at different keystrokes in validate_token_scope:
| Lane | Input | Best for |
|---|---|---|
| Lexical | Polic | Local identifiers and keywords |
| Semantic | graph. | Exact members from the language server |
| Inline generation | is_allowed = | Open expression matching return is_allowed |
| Next-edit | Accepted edit | Follow-up change elsewhere in the file |
| Coding agent | Repo + tests | Multi-file patches off the keystroke clock |
Lexical and semantic first
A local prefix index completes PolicyGraph in milliseconds; after graph., the language server returns exact typed members (falling back to local lexical matches when types are unknown).
Inline generation for an open-ended span
An empty assignment is_allowed = has no symbol-table answer; generating a matching boolean expression needs imports and return is_allowed below, earning the 200 ms remote FIM call.
Agents stay off the keystroke clock
Coding agents search repos, run tests, and build multi-file patches.[2] Mixing that loop into inline completion breaks the 200 ms ghost-text clock.
The keystroke budget
Measure end-to-end latency from qualifying edit to fresh paint (debounce, parse, context, network, server wait, prefill, visible decode, render), tracking client TTFT separately so transport and queue wait are not double-counted.
An immediate GPU-backed request (0 ms debounce) spends 183 ms across five serial stages (17 ms headroom): 12 ms client parse, 55 ms network RTT, 28 ms context assembly, 78 ms queue + model service, and 10 ms UI render. Adding 150 ms debounce reaches 333 ms, requiring tighter debounce, local completions, or a pause-to-suggestion target.
import math, numpy as np
total = sum([12, 55, 28, 78, 10])
p95 = lambda a: float(np.sort(a)[math.ceil(0.95 * len(a)) - 1])
traces = np.array([(100, 1), (1, 100)] + [(1, 1)] * 18)
print(f"immediate={total}ms headroom={200 - total}ms debounced={total + 150}ms")
print(f"whole_p95={p95(traces.sum(axis=1)):.0f}ms vs sum_stage_p95={p95(traces[:, 0]) + p95(traces[:, 1]):.0f}ms")immediate=183ms headroom=17ms debounced=333ms
whole_p95=101ms vs sum_stage_p95=2ms
Who owns the is_allowed = keystroke
Three components cooperate: the IDE extension (snapshots, cancellation), the context engine (allowed snippet packing), and the inference server (continuous batching). The Language Server Protocol (LSP) powers semantic lookup,[3] while Tree-sitter recovers partial syntax trees around half-typed lines.[4]
Local fallback lane
Keep deterministic local lookups for instant offline response: language-server members on ./(, prefix tries, and fuzzy typo matching. Avoid two client bugs: use syntax-node ranges instead of backward def text scans (which cross dedents), and convert coordinates before slicing because VS Code counts UTF-16 code units, Python indexes code points, and byte APIs count UTF-8 bytes.[5] After the emoji in a😀b, Python index 2 is UTF-16 offset 3 and UTF-8 byte 5; slicing Python at 3 drops 'b'.

Context gathering and management
Long prefills miss 200 ms even on 128k context windows. Cap inline prompts around 8,000 tokens (including FIM sentinels) with output reserved separately.
Context priority strategy
Filter candidate files by upload permissions before ranking. Reserve framing and a minimum suffix slice first so greedy prefix packing never erases code below the cursor: (1) prefix before cursor, (2) reserved suffix, (3) referenced imports/definitions, (4) recently edited files, (5) neighboring files.
Fill-in-the-middle (FIM)
FIM reorders prefix and suffix with checkpoint-specific sentinels so the causal decoder reads both boundaries before generating the hole:
Emit sentinel token IDs from the adapter and encode user code strictly as text tokens so comments containing <MID> cannot hijack framing. Insert only the generated middle span back into the hole.

FIM pretraining splits documents into (prefix, middle, suffix) under causal next-token loss.[6] PSM (<PRE>prefix<SUF>suffix<MID>middle, used by Qwen2.5-Coder[7]) invalidates suffix KV blocks whenever the prefix changes; SPM (<PRE><SUF>suffix<MID>prefixmiddle) keeps suffix KV warm while typing in the prefix.[6]
<PRE>from authz.rules import PolicyGraph
def validate_token_scope(request):
is_allowed = <SUF>
return is_allowed
<MID>Repository-level context
Index asynchronously outside the 28 ms budget using Jaccard symbol overlap, BM25 / sparse retrieval,[8] or precomputed vector search (with reranking only if it fits 28 ms).
active = {"PolicyGraph", "ScopeRule", "TokenClaims"}
files = {
"scope_rules.py": {"ScopeRule", "TokenClaims", "AccessEvent"},
"metrics.py": {"Counter", "Histogram"},
"policy_graph.py": {"PolicyGraph", "Node"},
}
ranked = sorted(((len(active & s) / len(active | s), p) for p, s in files.items()), reverse=True)
print("selected:", [(p, round(sc, 2)) for sc, p in ranked if sc >= 0.25])
def alloc(cap: int, frame: int, suf_min: int, pre: int, ret: int) -> dict[str, int]:
rem = max(0, cap - frame)
suf = min(suf_min, rem); rem -= suf
p = min(pre, rem); rem -= p
return {"frame": frame, "suffix": suf, "prefix": p, "retrieval": min(ret, rem)}
print("tokens:", alloc(8000, 100, 1200, 4800, 3000))selected: [('scope_rules.py', 0.5), ('policy_graph.py', 0.25)]
tokens: {'frame': 100, 'suffix': 1200, 'prefix': 4800, 'retrieval': 1900}
Model serving for low latency
Profile queueing, prefill, and decode separately: prefix caching cuts prefill, speculative decoding accelerates decode, and quantization relieves memory bandwidth.
Speculative decoding
A small draft model proposes tokens and the target verifies all in one parallel pass.[9][10]

To preserve target distribution from draft , accept with probability , and on first rejection resample from:
All- acceptance adds a -th bonus token, yielding expected tokens at constant . Enable speculation per slice only when both mean accepted length and p95 latency improve.
import numpy as np
p, q = np.array([0.1, 0.6, 0.3]), np.array([0.4, 0.4, 0.2])
res = np.maximum(0.0, p - q); res /= res.sum()
etok = lambda a, k=5: (1.0 - a ** (k + 1)) / (1.0 - a)
slices = {"python_imports": (3.8, 178, 136), "sql_queries": (1.1, 169, 176)}
enabled = [k for k, (a, b, s) in slices.items() if a >= 2.0 and (b - s) >= 10]
print(f"accept={min(1.0, p[0]/q[0]):.3f} residual={np.round(res, 3).tolist()} E(0.8)={etok(0.8):.2f} enabled={enabled}")accept=0.250 residual=[0.0, 0.667, 0.333] E(0.8)=3.69 enabled=['python_imports']
KV cache reuse (prefix caching)
Automatic prefix caching reuses KV blocks for unchanged file headers so requests prefill only the delta while decode stays unchanged.[11] On a 1,280-token prompt sharing 1,200 cached tokens, cold prefill + decode takes 72 + 24 = 96 ms, while a warm hit takes 11 + 24 = 35 ms.

Key KV blocks on gateway-derived security scope (such as vLLM cache_salt[11]), model/tokenizer/adapter revisions, KV layout, and exact prefix token IDs (not raw text). Sampling temperature changes keep prefix KV valid, unlike response caching.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Key:
scope: str; model: str; tok: str; adapter: str; layout: str; ids: tuple[int, ...]
base = Key("acme/repo-a/acl-7", "w3", "t3", "none", "fp16-v1", (10, 20, 30))
store = {base: "kv-7"}
for name, k in [
("same", base), ("other_tenant", replace(base, scope="contoso/repo-a/acl-7")),
("changed_id", replace(base, ids=(10, 20, 31))), ("other_adapter", replace(base, adapter="lora-2")),
("revoked_acl", replace(base, scope="acme/repo-a/acl-8")),
]:
print(f"{name:14s}: {k in store}")same : True
other_tenant : False
changed_id : False
other_adapter : False
revoked_acl : FalseQuantization
Post-training quantization (like GPTQ[12][13]) shrinks FP16 weights ~2x (8-bit) or ~4x (4-bit) before scale/KV overhead, speeding bandwidth-bound decode. Re-check syntax validity and retained characters because subtle precision loss breaks API names before perplexity moves.
Debounce r and o; fire on .
Dispatching a remote request on every keystroke floods GPUs with completions that expire in flight.

Debouncing and cancellation
Use 0 ms delay on explicit triggers (., (, \n) and 150 ms during ordinary typing. Every edit, selection change, or permission change advances the epoch, clears ghost text, and cancels pending tasks even when no new call fires.[14] Check snapshot and epoch at both paint and Tab acceptance, and propagate cancellations alongside server-side token/deadline caps.
import asyncio
from dataclasses import dataclass
@dataclass(frozen=True)
class Snap:
doc: str; ver: int; sel: tuple[int, int]; acl: int
class Manager:
def __init__(self) -> None:
self.pending = self.snap = self.ghost = None
self.epoch = 0; self.sent, self.shown = [], []
def on_change(self, snap: Snap, ch: str | None = None) -> None:
self.epoch += 1; self.snap, self.ghost = snap, None
if self.pending and not self.pending.done():
self.pending.cancel()
if ch is not None:
self.pending = asyncio.create_task(self._fetch(0.0 if ch in {".", "(", "\n"} else 0.15, self.epoch, snap))
async def _fetch(self, delay: float, ep: int, snap: Snap) -> None:
try:
await asyncio.sleep(delay); self.sent.append(ep); self.on_reply(ep, snap, f"comp-{ep}")
except asyncio.CancelledError:
return
def on_reply(self, ep: int, snap: Snap, text: str) -> None:
if ep == self.epoch and snap == self.snap:
self.ghost = (ep, snap, text); self.shown.append(text)
def accept(self) -> str | None:
g, self.ghost = self.ghost, None
return g[2] if g and g[0] == self.epoch and g[1] == self.snap else None
async def main() -> None:
m, tasks = Manager(), []
for v, ch in enumerate("ro.", 1):
s = Snap("h.py", v, (v, v), 7); m.on_change(s, ch); tasks.append(m.pending)
await asyncio.gather(*tasks, return_exceptions=True)
m.on_reply(2, s, "stale-2")
m.on_change(Snap("h.py", 3, (0, 0), 7)); m.on_reply(3, s, "stale-move"); assert m.accept() is None
m.on_reply(m.epoch, m.snap, "fresh"); m.on_change(Snap("h.py", 3, (0, 0), 8)); assert m.accept() is None
print("sent:", m.sent, "shown:", m.shown)
asyncio.run(main())sent: [3] shown: ['comp-3', 'fresh']Ghost text, not a second product
Keep completions as lightweight ghost text at the cursor.[15] Typing characters matching the ghost prefix trims and rebases the remainder onto the new version; any mismatch clears it immediately.
Did is_allowed = actually help?
Developers accept whole blocks, accept word-by-word, or dismiss.[16] Optimizing raw acceptance rewards tiny punctuation; pair it with retained characters over a fixed window to expose suggestions deleted seconds later.

| Metric | Definition | Signal |
|---|---|---|
| Acceptance rate | Distinct shown IDs with any insertion | Early Copilot linked 27% acceptance to productivity.[17] |
| Retained characters | Inserted chars surviving the window | Catches plausible completions quickly deleted.[17] |
| Shown rate | Eligible triggers painting ghost text | Exposes overly timid models |
| End-to-end p95/p99 | Whole-trace latency + timeout/drop rate | Stops surviving subsets hiding timeouts |
Pair offline suites (HumanEval[18] plus frozen-repo infill tests) with randomized online experiments, computing retention locally on the client and treating early-closed sessions as censored.
Routing by suggestion size
Use a compact FIM model (such as Qwen2.5-Coder[7]) for single-line keystrokes (200 ms p95), local semantic lookup on ./( (60 ms), and heavier models for post-signature multi-line bodies (500 ms). Require literal remote_permitted is True on the client (rejecting truthy strings like "False"), and verify upload rules independently at the gateway.

The fleet behind one keystroke
Completion traffic is high-churn and prefill-heavy: most calls cancel before paint, and demand spikes during regional work hours.
GPU fleet management and load balancing
Balance prefix-aware routing, geographic proximity (50 ms RTT eats a quarter of 200 ms), and model tiering (isolating fast single-line from slow multi-line pools).
![Planar KV prefix compatibility diagram with zero crossing lines. Left: cached KV entry keyed by six exact fields (scope acme/repo-a/acl-7, model w3, tokenizer t3, adapter none, layout fp16-v1, prefix IDs [10,20,30]). Center: five incoming requests test exact match (HIT, skipping prefill) versus four single-field mismatches (other tenant contoso, changed token ID 31, adapter lora-2, revoked acl-8) that all route to Full Prefill. Right: both KV HIT and Full Prefill converge on the shared Decode step.](https://assets.leetllm.com/v1/dc71ba4f8de2/system-design/design-code-completion-system/illustrations/_generated/compatible_kv_prefix_dark.png)
At equal base queue wait , extra warm wait , and service times , the warm replica wins strictly when (61 ms for 96 ms cold vs. 35 ms warm).

Size GPUs by uncached token volume summed per cohort: . With 5,000 editors sending 0.4 req/s (2,000 raw req/s; 60% canceled pre-GPU leaves 800 surviving req/s) and 20,000 tok/s per GPU, the same 50% hit rate and 2,048-token mean length swing prefill capacity by 86%:
| Workload mix | Cohorts | Uncached prefill rate | GPUs at 20,000 tok/s |
|---|---|---|---|
| Uniform 2,048 | 1,024,000 tok/s | 52 | |
| Long hits | 716,800 tok/s | 36 | |
| Long misses | 1,331,200 tok/s | 67 |

Continuous batching
Continuous batching with PagedAttention (vLLM or SGLang, recommended over TGI) lets short completions join/exit every step.[19][20] Cap concurrency against 200 ms p95.
Cost economics
Track cost per accepted-and-retained suggestion, not cost per request, pairing cost wins with retention and shown-rate checks.
What of this buffer may leave the laptop
Open buffers sit beside proprietary logic and credentials; enforce privacy before tokens leave the laptop.
Data isolation
Enforce tenant isolation end to end: disable training exports by default, log only allowlisted metadata (scrubbing proxies and crash dumps), key KV caches by gateway-derived tenant scope, and verify GPU memory isolation across tenants.
Secret redaction and upload controls
Scan buffers locally with regex and entropy checks before upload, replacing secrets with placeholders like <API_KEY_1> while keeping the map strictly in local memory. Never auto-restore raw secrets into generated output, and abort upload if the buffer already contains the reserved placeholder prefix.
import re
PAT = re.compile(r"demo_api_token_[A-Za-z0-9]+")
def redact(text: str) -> tuple[str, dict[str, str]]:
if "<API_KEY_" in text:
raise ValueError("reserved placeholder present")
local: dict[str, str] = {}
def sub(m: re.Match[str]) -> str:
k = f"<API_KEY_{len(local) + 1}>"
local[k] = m.group(0); return k
return PAT.sub(sub, text), local
clean, smap = redact("client = API('demo_api_token_abc123')")
meta = {k: v for k, v in {"tenant": "acme", "model": "fim-v3", "bucket": "100_200ms", "prompt": clean}.items() if k != "prompt"}
print("upload:", clean, "| local:", list(smap), "| meta:", sorted(meta))upload: client = API('<API_KEY_1>') | local: ['<API_KEY_1>'] | meta: ['bucket', 'model', 'tenant']
On-premises deployment
Regulated teams forbidding multi-tenant cloud endpoints require private VPC hosting, customer-managed inference servers, or air-gapped local deployments.
Public-code matching and the mastery gap
Optional public-code filters suppress verbatim matches or attach license references.[1] Reviewing generated code remains essential so fluent completions do not smuggle subtle bugs or broken auth checks.
Common pitfalls
- Stale ghost text: Advance epoch on edits, cursor moves, and permission changes; verify snapshot at paint and Tab.
- High acceptance, low value: Track retained characters and shown rate alongside acceptance.
- Slow
.lookup: Keep deterministic members on the local language server. - Cold prefix cache: Use queue-aware prefix affinity instead of random balancing.
- Conflicts below cursor: Reserve suffix tokens first and use native FIM sentinels.
- Broken mid-line scope: Use Tree-sitter recovery and convert UTF-16 editor offsets cleanly.
What to ship with
| Dimension | Ship bar |
|---|---|
| Latency | Whole-trace edit-to-paint meets p95 with debounce and drops counted |
| Context & infill | Suffix reserved first inside cap; native FIM sentinels without source collision |
| Serving & freshness | Verified speculation/prefix wins; snapshot + epoch checked at paint and Tab |
| Privacy | Client redaction, allowlisted logs, tenant-scoped KV keys, gateway enforcement |