Skip to content
Skip to lesson
Back to Topics
HardSystem Design14 min read

Code Completion System

A suggestion for `is_allowed =` can arrive after the developer has typed past it. Keep the useful ones, and do not paint the stale line.

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 to condition on prefix and suffix, while coding agents run off the keystroke clock.

Targeting 200 ms for single-line inline completions drives every decision: keep exact lookups local, ship compact suffix-preserving context, reuse blocks across keystrokes, and drop stale replies before paint.

Editor snapshot S with document, version, caret, ACL, and epoch routes three triggers into parallel completion lanes: Polic to local lexical index (<5 ms), graph. to local LSP (<20 ms), and is_allowed = to remote FIM (<200 ms p95 when permitted). All lanes rejoin an editor freshness gate that drops stale replies, paints fresh ghost text, and enforces version-checked Tab insertion. Beside it, an off-clock coding agent runs a Plan, Edit, Test, Review loop at second-to-minute scale.
Exact lookups stay local, open spans call remote FIM if allowed, and freshness checks guard paint and Tab.

One cursor, five lanes

Five lanes apply at different keystrokes in validate_token_scope:

LaneInputBest for
LexicalPolicLocal identifiers and keywords
Semanticgraph.Exact members from the language server
Inline generationis_allowed =Open expression matching return is_allowed
Next-editAccepted editFollow-up change elsewhere in the file
Coding agentRepo + testsMulti-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 separately so transport and queue wait are not double-counted.

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

latency-budget-check.py
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")
Output
immediate=183ms headroom=17ms debounced=333ms
whole_p95=101ms vs sum_stage_p95=2ms
Left: shared 0 to 350 ms scale comparing an immediate 183 ms serial budget (12 parse, 55 net, 28 context, 78 queue and model, 10 paint, leaving 17 ms headroom to 200 ms) against a 333 ms debounced lane adding 150 ms debounce. Right: 20 traces with rows (100,1), (1,100), and eighteen (1,1) show whole-trace p95 is 101 ms while summing stage p95 values gives only 2 ms.
Immediate stages sum to 183 ms (333 ms with 150 ms debounce). Always compute p95 on complete traces.

Who owns the is_allowed = keystroke

Three components cooperate: the IDE extension (snapshots, cancellation), the context engine (allowed snippet packing), and the inference server (). 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'.

Three encoding tapes align on the character boundaries of a😀b where the emoji is U+1F600. Python uses 1 code point, UTF-16 uses surrogate pair D83D and DE00, and UTF-8 uses 4 bytes F0 9F 98 80. A vertical green caret before b aligns at Python index 2, UTF-16 offset 3, and UTF-8 byte 5. Slicing Python at UTF-16 offset 3 drops b, while cutting UTF-8 at byte 3 splits the 4-byte emoji in half.
Convert UTF-16 editor positions to native indices before slicing so non-BMP characters never corrupt the suffix.

Context gathering and management

Long miss 200 ms even on 128k . 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:

PFIM=<PRE>+xprefix+<SUF>+xsuffix+<MID>P_{\text{FIM}} = \texttt{<PRE>} + x_{\text{prefix}} + \texttt{<SUF>} + x_{\text{suffix}} + \texttt{<MID>}

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.

Three-stage non-crossing Fill-In-the-Middle flow. Left: active file split into blue prefix def validate_token_scope(request): is_allowed =, dashed green cursor hole, and purple suffix return is_allowed. Center: Prefix-Suffix-Middle prompt places PRE prefix, SUF suffix, and MID sentinel so causal attention reads the suffix before generating graph.allows(request.scope) up to EOT. Right: only the generated middle is inserted into the cursor hole while prefix and suffix stay untouched.
Prefix-Suffix-Middle (PSM) exposes code below the cursor before generating the middle span.

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]

text
<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, / ,[8] or precomputed search (with only if it fits 28 ms).

select-nearby-context.py
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))
Output
selected: [('scope_rules.py', 0.5), ('policy_graph.py', 0.25)]
tokens: {'frame': 100, 'suffix': 1200, 'prefix': 4800, 'retrieval': 1900}
Left: upload-permitted files enter a symbol-membership matrix for PolicyGraph, ScopeRule, TokenClaims, AccessEvent, Node, Counter, and Histogram. Active file A shares 2 of 4 union symbols with scope_rules.py (0.50), 1 of 4 with policy_graph.py (0.25), and 0 of 5 with metrics.py (0.00); a 0.25 threshold keeps scope_rules and policy_graph. Right: an 8,000-token prompt packs 100 framing and 1,200 reserved suffix tokens first, then 4,800 prefix and 1,900 retrieval tokens (trimming 1,100), keeping output reserve separate.
Rank only upload-permitted files; suffix reservation keeps 1,200 tokens intact before retrieval.

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 KK tokens and the target verifies all KK in one parallel pass.[9][10]

Speculative decoding pipeline showing five draft tokens (graph, dot, allows, open paren, user) proposed sequentially by a small draft model, verified in one parallel target forward pass that accepts the first four, rejects user, and resamples request from the residual distribution, yielding five target-exact tokens in two compute passes.
Parallel verification accepts four draft tokens and resamples the fifth to match target distribution p.

To preserve target distribution p(x)p(x) from draft q(x)q(x), accept xx with probability α(x)=min⁡(1,p(x)/q(x))\alpha(x) = \min(1, p(x)/q(x)), and on first rejection resample from:

p′(x)=max⁡(0,p(x)−q(x))∑vmax⁡(0,p(v)−q(v))p'(x) = \frac{\max(0, p(x) - q(x))}{\sum_v \max(0, p(v) - q(v))}

All-KK acceptance adds a (K+1)(K+1)-th bonus token, yielding expected tokens E[tokens]=(1−αK+1)/(1−α)\mathbb{E}[\text{tokens}] = (1 - \alpha^{K+1})/(1 - \alpha) at constant α\alpha. Enable speculation per slice only when both mean accepted length and p95 latency improve.

speculative-decoding-math.py
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}")
Output
accept=0.250 residual=[0.0, 0.667, 0.333] E(0.8)=3.69 enabled=['python_imports']
Dual-axis scatter qualification gate for speculative decoding slices. The green qualified region requires at least 2.0 mean accepted draft tokens and at least 10 ms p95 latency reduction. Python imports pass at (3.8 tokens, +42 ms, p95 178 to 136 ms), while SQL queries fail at (1.1 tokens, -7 ms, p95 169 to 176 ms).
Qualify speculation per language slice: Python imports save 42 ms while SQL queries regress 7 ms.

KV cache reuse (prefix caching)

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

Left: a 1,280-token prompt splits into 1,200 cached prefix tokens (93.8%) and 80 delta tokens. On a shared 0 to 100 ms axis, a cold miss spends 72 ms prefill plus 24 ms decode (96 ms total) while a warm hit spends 11 ms prefill plus the same 24 ms decode (35 ms total), saving 61 ms. Right: editing the prefix in PSM invalidates downstream suffix KV blocks, whereas suffix-first SPM keeps suffix KV warm.
Prefix caching cuts prefill over shared tokens while 24 ms decode stays unchanged.

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.

prefix-cache-key.py
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}")
Output
same          : True
other_tenant  : False
changed_id    : False
other_adapter : False
revoked_acl   : False

Quantization

Post-training (like GPTQ[12][13]) shrinks 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.

Epoch timeline across five editor events. Typing r (epoch 1) and o (epoch 2) arm 150 ms debounces that are canceled before dispatch. Typing dot (epoch 3) fires immediately at 0 ms; reply comp-3 arrives at epoch 3 and paints ghost text, while late stale-2 drops. Moving the caret to (0,0) advances to epoch 4, clears ghost text, and rejects late epoch 3 replies. Changing policy ACL 7 to 8 advances to epoch 5, clears ghost text, and guards Tab insertion.
Every edit, cursor move, or permission change advances epoch, clears ghost text, and guards paint and Tab.

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.

debouncing-and-cancellation.py
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())
Output
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.

Horizontal stacked bar chart for four distinct shown suggestion IDs on a 0 to 45 character scale. ID A inserts 18 characters and retains 0 (all 18 deleted). ID B inserts and retains 4. ID C inserts 42, retaining 35 and deleting 7. ID D is dismissed with 0 inserted. Beside it, summary meters show 3 of 4 distinct IDs accepted (75.0%) versus 39 of 64 inserted characters retained (60.9%).
Multiple partial accepts count as one accepted ID (3/4 = 75%), while 39/64 inserted chars survive (60.9%).
MetricDefinitionSignal
Acceptance rateDistinct shown IDs with any insertionEarly Copilot linked 27% acceptance to productivity.[17]
Retained charactersInserted chars surviving the windowCatches plausible completions quickly deleted.[17]
Shown rateEligible triggers painting ghost textExposes overly timid models
End-to-end p95/p99Whole-trace latency + timeout/drop rateStops 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.

Planar client-to-gateway routing tree. First, dot or open-paren triggers with known semantic types route to LOCAL_SEMANTIC (60 ms p95). Otherwise, a strict literal remote_permitted is True gate sends False, string False, None, or 1 to LOCAL_FALLBACK (60 ms p95, on device). Literal True crosses an independent Gateway auth and upload policy boundary into REMOTE_MULTILINE (500 ms after signature) or REMOTE_INLINE (200 ms mid-line). All lanes pass the Editor Freshness Gate before paint and Tab.
Semantic triggers stay local; remote lanes require literal True with independent gateway enforcement.

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.
KV reuse requires exact scope, model, tokenizer, adapter, layout, and prefix ID matches.

At equal base queue wait qq, extra warm wait Δ\Delta, and service times Tcold,TwarmT_{\text{cold}}, T_{\text{warm}}, the warm replica wins strictly when Δ<Tcold−Twarm\Delta < T_{\text{cold}} - T_{\text{warm}} (61 ms for 96 ms cold vs. 35 ms warm).

Break-even plot comparing cold worker completion time (flat at q + 96 ms) against warm cached worker time (rising as q + delta + 35 ms) over extra warm queue wait delta from 0 to 100 ms. The lines intersect at delta = 61 ms (96 ms total). Green shading below 61 ms marks where routing warm wins; blue shading above 61 ms marks where routing to a cold worker finishes faster.
Once warm queue wait exceeds the 61 ms prefill savings, routing to a cold worker finishes faster.

Size GPUs by uncached token volume summed per cohort: ∑iλiLi(1−si)\sum_i \lambda_i L_i (1 - s_i). 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 mixCohorts (λi req/s,Li tok,si cache share)(\lambda_i\text{ req/s}, L_i\text{ tok}, s_i\text{ cache share})Uncached prefill rateGPUs at 20,000 tok/s
Uniform 2,048(400,2048,0.75)+(400,2048,0.0)(400, 2048, 0.75) + (400, 2048, 0.0)1,024,000 tok/s52
Long hits(400,3072,0.75)+(400,1024,0.0)(400, 3072, 0.75) + (400, 1024, 0.0)716,800 tok/s36
Long misses(400,1024,0.75)+(400,3072,0.0)(400, 1024, 0.75) + (400, 3072, 0.0)1,331,200 tok/s67
Top funnel shows 5,000 typing editors sending 2,000 raw req/s, 60% canceled pre-GPU leaving 800 surviving req/s (400 hits skipping 75% prefill + 400 full misses) with 2,048-token overall mean. Below, calibrated stacked bars compare uncached prefill demand at 20,000 tok/s per GPU: Long Hits need 716.8k tok/s (36 GPUs), Uniform 2,048 needs 1,024k tok/s (52 GPUs), and Long Misses need 1,331.2k tok/s (67 GPUs, +86%).
Identical QPS, mean length, and hit rate swing prefill capacity from 36 to 67 GPUs.

Continuous batching

Continuous batching with ( or , recommended over ) 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 ; enforce privacy before tokens leave the laptop.

Data isolation

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

mask-known-secrets-before-upload.py
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))
Output
upload: client = API('<API_KEY_1>') | local: ['<API_KEY_1>'] | meta: ['bucket', 'model', 'tenant']
Client-to-cloud redaction boundary. Inside client memory, a local scanner detects demo_api_token_abc123 in the buffer, masks it to placeholder <API_KEY_1>, and keeps the secret-to-placeholder map strictly local (aborting if a reserved placeholder already exists). Only the sanitized prompt crosses the TLS trust boundary to the gateway, KV cache, and FIM model. Server telemetry logs allowlisted fields (tenant, model, bucket) and excludes prompt text and raw secrets.
Mask secrets locally before upload, keep maps on the client, and log allowlisted telemetry only.

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

DimensionShip bar
LatencyWhole-trace edit-to-paint meets p95 with debounce and drops counted
Context & infillSuffix reserved first inside cap; native FIM sentinels without source collision
Serving & freshnessVerified speculation/prefix wins; snapshot + epoch checked at paint and Tab
PrivacyClient redaction, allowlisted logs, tenant-scoped KV keys, gateway enforcement
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.Serial stages allocate 10 ms parse, 45 ms net, 25 ms context, 70 ms model, 8 ms paint; typing adds 60 ms debounce. Against 200 ms, what holds?
2.In ab😀cd, caret is right after the emoji. What are (Python, UTF-16, UTF-8) offsets and Python suffix?
3.FIM cap 1,200: 50 framing, 200 suffix, 500 prefix, 300 defs. One allowed snippet needs 250; a higher-scoring restricted file is blocked. What fits?
4.Target p=[0.1,0.6,0.3], draft q=[0.4,0.4,0.2], draft proposes index 0. Acceptance probability and rejection residual?
5.Reply for F v8 sel(10,10) epoch 55 is in flight. Caret moves to (12,12) (epoch 56, no edit/call). Old reply arrives. Action?
6.Equal base wait: cold needs 60 ms prefill + 20 ms decode; warm needs 15 ms prefill + 20 ms decode + 50 ms extra wait. Which wins?
7.Five shown IDs insert [10,20,0,8,0] chars and retain [4,20,0,0,0]. Acceptance and retention rates?
8.6,000 editors * 0.5 req/s, 50% cancel pre-GPU. Of 1,500 surviving: 600 hits (1,800 tok, 50% skipped) + 900 misses (800 tok) at 30,000 tok/GPU-s. Load and GPUs?
9.File A has demo_api_token_fern82. File B adds # expect <API_KEY_24> when <API_KEY_ is reserved. Upload?
10.In PSM FIM (<PRE>prefix<SUF>suffix<MID>), why insert only the generated middle and encode user code strictly as text tokens?

10 questions remaining.

References

GitHub Copilot code suggestions in your IDE

GitHub · 2026

https://docs.github.com/en/copilot/concepts/completions/code-suggestions

GitHub Copilot cloud agent

GitHub · 2026

https://docs.github.com/en/copilot/concepts/agents/cloud-agent/about-cloud-agent

Language Server Protocol

Microsoft · 2026

https://microsoft.github.io/language-server-protocol/

Tree-sitter

Tree-sitter Contributors · 2026

https://tree-sitter.github.io/tree-sitter/

VS Code API: document versions, positions, and inline completion providers (pinned source)

Microsoft · 2026

https://github.com/microsoft/vscode/blob/1fe7285a1162756215a684ee702b16d0ce42bdb4/src/vscode-dts/vscode.d.ts#L269

Efficient Training of Language Models to Fill in the Middle.

Bavarian, M., et al. · 2022 · arXiv preprint

https://arxiv.org/abs/2207.14255

Qwen2.5-Coder Technical Report

Qwen Team, Alibaba Group · 2024 · arXiv preprint

https://arxiv.org/abs/2409.12186

The Probabilistic Relevance Framework: BM25 and Beyond.

Robertson, S., & Zaragoza, H. · 2009 · Foundations and Trends in Information Retrieval

https://doi.org/10.1561/1500000019

Fast Inference from Transformers via Speculative Decoding.

Leviathan, Y., Kalman, M., & Matias, Y. · 2023 · ICML 2023

https://arxiv.org/abs/2211.17192

Speculative Decoding

vLLM Team · 2026 · vLLM Documentation

https://docs.vllm.ai/en/latest/features/speculative_decoding/

Automatic Prefix Caching

vLLM · 2026

https://docs.vllm.ai/en/stable/design/prefix_caching/

GPTQ: Accurate Post-Training Quantization for Generative Pre-Trained Transformers

Frantar, E., et al. · 2023 · ICLR 2023

https://arxiv.org/abs/2210.17323

GPTQ

Hugging Face · 2026

https://huggingface.co/docs/transformers/main/en/quantization/gptq

Visual Studio Code API: InlineCompletionItemProvider

Microsoft · 2026

https://code.visualstudio.com/api/references/vscode-api#InlineCompletionItemProvider

Programmatic Language Features: Show Inline Completions

Visual Studio Code · 2026

https://code.visualstudio.com/api/language-extensions/programmatic-language-features

Getting code suggestions in your IDE with GitHub Copilot: accepting partial suggestions

GitHub · 2026

https://docs.github.com/en/copilot/how-tos/get-code-suggestions/get-ide-code-suggestions#accepting-partial-suggestions

Productivity Assessment of Neural Code Completion

Albert Ziegler, Eirini Kalliamvakou, Shawn Simister, Ganesh Sittampalam, Alice Li, Andrew Rice, Devon Rifkin, Edward Aftandilian · 2022 · MAPS 2022

https://arxiv.org/abs/2205.06537

Evaluating Large Language Models Trained on Code (HumanEval).

Chen, M., et al. · 2021 · arXiv preprint

https://arxiv.org/abs/2107.03374

Efficient Memory Management for Large Language Model Serving with PagedAttention.

Kwon, W., et al. · 2023 · SOSP 2023

https://arxiv.org/abs/2309.06180

Text Generation Inference.

Hugging Face · 2026

https://huggingface.co/docs/text-generation-inference/index

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.