Skip to main content
← CONCEPTS / AI & MACHINE LEARNING SYSTEMS
An end-to-end domain learning journey

Fill-in-the-Middle (FIM) & Speculative
IDE Code Completion.

Fill-in-the-Middle (FIM) rearranges code around the cursor into <PRE> prefix <SUF> suffix <MID> so autoregressive models condition on both preceding and following code.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When inference latency or GPU memory limits bind throughput, combine FIM token packing with Tree-sitter AST context extraction and client-side keystroke cancellation to keep ghost-text completions < 150 ms.

TL;DR30-second simplified summary
▾

Standard left-to-right LLM generation only sees code before the cursor, ignoring closing braces, return statements, and types below the cursor. Fill-in-the-Middle (FIM) solves this by splitting the editor buffer at the cursor and packing tokens in Prefix-Suffix-Middle (<PRE> prefix <SUF> suffix <MID>) order during training and inference.

Because IDE autocomplete fires on nearly every pause in typing, latency budgets are brutal (< 150 ms end-to-end). Production engines pair a fast 7B/13B FIM model with RadixAttention prefix caching (since the top of the file rarely changes across keystrokes), Tree-sitter AST symbol retrieval across open tabs, and Speculative Decoding (or prompt-lookup drafting) to stream ghost text before the user types the next character.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing)
RadixAttention indexes cached GPU KV-cache blocks in a compressed prefix trie (Radix Tree) with LRU eviction, enabling zero-copy prefix sharing across concurrent and sequential LLM requests.
Context Compression for RAG
Techniques that prune, rerank, or summarize retrieved RAG chunks before LLM generation to slash token cost and TTFT while beating 'lost-in-the-middle' attention decay.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Core Intuition & Failure Mode.

Why this matters: Rearrange cursor context into <PRE> prefix <SUF> suffix <MID> so causal models condition on both sides of the cursor.

Think of Core Intuition & Failure Mode as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Rearrange cursor context into <PRE> prefix <SUF> suffix <MID> so causal models condition on both sides of the cursor.

Fill-in-the-Middle (FIM) rearranges code around the cursor into <PRE> prefix <SUF> suffix <MID> so autoregressive models condition on both preceding and following code.

STAGE 01 · CORE INTUITION

Core Intuition & Failure Mode

Editor BufferRaw CodeFIM TransformToken LayoutCausal 7B/13B ModelBidirectional FitGhost-Text StreamClean Insertinfers middle

1.Left-to-Right Blind Spot: Standard causal LMs ignore closing braces, return types, and variables declared below the cursor.

2.PSM Ordering: Putting Prefix and Suffix before <MID> lets autoregressive decoding see both sides before emitting token 1.

3.Suffix Overlap Trim: Trim trailing generated characters that duplicate the start of the suffix.

FIM (<PRE> prefix <SUF> suffix <MID>) gives causal code models full awareness of code both above and below the cursor.

02
STAGE 02 · CORE MECHANICSfoundation

Architectural Mechanics.

Why this matters: Meet <150 ms IDE ghost-text budgets using 150 ms keystroke debouncing, Tree-sitter AST context, and RadixAttention.

Think of Architectural Mechanics as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Meet <150 ms IDE ghost-text budgets using 150 ms keystroke debouncing, Tree-sitter AST context, and RadixAttention.

Because IDE autocomplete fires on nearly every pause in typing, latency budgets are brutal (< 150 ms end-to-end). Production engines pair a fast 7B/13B FIM model with RadixAttention prefix caching (since the top of the file rarely changes across keystrokes), Tree-sitter AST symbol retrieval across open tabs, and Speculative Decoding (or prompt-lookup drafting) to stream ghost text before the user types the next character.

STAGE 02 · CORE MECHANICS

Architectural Mechanics

150ms Debounce +AbortIDE ClientTree-sitter ContextCross-File ScopeRadixAttentionCacheSub-40ms TTFTSpeculative / Draft150ms p95 Targethits KV cache

1.In-Flight Cancellation: Every new keystroke aborts the previous SSE request so GPU queues never fill with obsolete typing.

2.Prefix Cache Synergy: Because file top lines rarely change, RadixAttention skips re-prefilling 70-85% of prompt tokens.

3.Tree-sitter Packing: Inject only relevant function signatures from open tabs instead of dumping entire files.

Keystroke cancellation, Tree-sitter AST packing, and RadixAttention prefix caching hold IDE completions under 150 ms.

Engineering Decision Framework
Problem
How to implement Fill-in-the-Middle (FIM) & Speculative IDE Code Completion without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When inference latency or GPU memory limits bind throughput, combine FIM token packing with Tree-sitter AST context extraction and client-side keystroke cancellation to keep ghost-text completions < 150 ms.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Fill-in-the-Middle (FIM) & Speculative IDE Code Completion experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

FIM Prompt Packer with Token Budget.

Why this matters: Pack prefix, suffix, and AST context within a strict token budget while prioritizing lines nearest the cursor.

Think of FIM Prompt Packer with Token Budget as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Pack prefix, suffix, and AST context within a strict token budget while prioritizing lines nearest the cursor.

def build_fim_prompt(prefix: str, suffix: str, ast_context: str, max_chars: int = 12000) -> str:
    if not prefix and not suffix:
        raise ValueError('Editor buffer cannot be completely empty')
    ctx_budget = min(len(ast_context), max_chars // 4)
    pre_budget = (max_chars - ctx_budget) * 2 // 3
    suf_budget = max_chars - ctx_budget - pre_budget
    trimmed_ctx = ast_context[:ctx_budget]
    trimmed_pre = prefix[-pre_budget:] if pre_budget > 0 else ''
    trimmed_suf = suffix[:suf_budget] if suf_budget > 0 else ''
    return f'<PRE>{trimmed_ctx}\n{trimmed_pre}<SUF>{trimmed_suf}<MID>'
STAGE 03 · SAFE IMPLEMENTATION

FIM Prompt Packer with Token Budget

Non-Empty GuardInput CheckAST Budget CapHeader AllocationSymmetric CursorTrimContext WindowEmit FIM PromptReady Payloadtrims edges

1.Cursor Proximity First: Truncate from the top of prefix and bottom of suffix—never near the cursor.

2.Ast-First Cache Stability: Place stable cross-file imports at the very top so RadixAttention prefix hashes stay warm.

3.Line-Boundary Alignment: Snap truncation to newline boundaries to avoid broken partial tokens.

Budgeted FIM packing reserves space for AST imports while keeping lines closest to the cursor intact.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Throughput & Latency Trade-Offs.

Why this matters: Scale to 50K peak completion QPS using sticky file routing, FP8 quantization, and speculative decoding.

Think of Throughput & Latency Trade-Offs as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Scale to 50K peak completion QPS using sticky file routing, FP8 quantization, and speculative decoding.

Evaluate asymptotic bounds, cache locality, and tail-latency impact under peak load.

STAGE 04 · SCALING & TRADE-OFFS

Throughput & Latency Trade-Offs

Consistent HashRouteCache AffinityFP8 7B FIM ModelFast Decode2x-3x SpeculativeLow ITL50K QPS @ <150msScale Targetdrafts & verifies

1.Sticky Routing: Routing by (user_id, repo, file_path) sends consecutive keystrokes to the same warm KV-cache pod.

2.Prompt-Lookup Speculation: Code edits often repeat existing lines; n-gram draft speculation yields 2x+ decode speedup.

3.Batch-Size Tuning: Cap continuous batch size to protect inter-token latency (ITL < 15 ms).

File-sticky routing, FP8 weights, and speculative decoding sustain 50K completion QPS below 150 ms.

05
STAGE 05 · FAULT ISOLATIONadvanced

Blast-Radius & Failure Isolation.

Why this matters: Redact secrets client-side before egress and shed non-essential context when GPU queues saturate.

Think of Blast-Radius & Failure Isolation as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Redact secrets client-side before egress and shed non-essential context when GPU queues saturate.

Isolate shared resources, apply bounded queues, and prevent retry amplification.

STAGE 05 · FAULT ISOLATION

Blast-Radius & Failure Isolation

Client Secret RegexPre-Egress GuardHTTP/2 Stream AbortQueue ShieldContext SheddingLoad DegradeZero Secret LeakageSecurity Boundaryunder load

1.Client-Side Redaction: Strip API keys, JWTs, and private keys inside the IDE extension before any network byte leaves.

2.Server Cancellation: Check client disconnect before starting prefill so aborted keystrokes consume zero GPU cycles.

3.Graceful Context Shed: Under GPU saturation, halve AST context size rather than dropping completions entirely.

Pre-egress secret redaction, disconnect-aware prefill cancellation, and context shedding isolate security and load faults.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Durability, Consistency & Recovery.

Why this matters: Preserve deterministic completion behavior across aborted streams, partial multi-line edits, and model rollouts.

Think of Durability, Consistency & Recovery as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Preserve deterministic completion behavior across aborted streams, partial multi-line edits, and model rollouts.

Use idempotent state transitions, atomic commits, and deterministic replay.

STAGE 06 · RECOVERY & CONSISTENCY

Durability, Consistency & Recovery

Request Seq IDClient OrderingAST Stop TokensClean BoundaryModel VersionHeaderSafe RolloutZero Flicker GhostConsistent UXroutes version

1.Monotonic Request IDs: IDE drops any late completion packet whose request_id < latest_cursor_seq.

2.Stop-Sequence Tuning: Trigger single-line vs. multi-line stops based on cursor indentation and AST node type.

3.Zero-Downtime Draining: Drain consistent-hash pods gradually during deploys so KV hit rates stay >75%.

Monotonic cursor sequence IDs and AST-aware stop tokens prevent stale ghost-text flicker during rapid typing.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Telemetry, Circuit Breakers & Failure Modes.

Why this matters: Track ghost-text acceptance rate, TTFT p95, cancellation ratio, and secret-redaction triggers.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Fill-in-the-Middle (FIM) & Speculative IDE Code Completion: Track ghost-text acceptance rate, TTFT p95, cancellation ratio, and secret-redaction triggers.

Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

Acceptance RateQuality KPITTFT & End-to-EndLatency KPICancel / AbortRatioEfficiency SignalRedaction & ShedGuardrailoptimizes

1.Acceptance vs. Latency: Completions arriving after 250 ms see acceptance rates drop by >50% because devs keep typing.

2.Wasted Compute Metric: High cancellation ratio signals debounce_ms is too aggressive (<100 ms).

3.Zero-Prompt Logging: Log anonymized latency and acceptance telemetry—never raw proprietary source code.

Measuring acceptance rate alongside p95 TTFT and abort ratios keeps IDE autocomplete fast, useful, and private.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does FIM place `<SUF>` before `<MID>` in `<PRE> prefix <SUF> suffix <MID>`?

Recommended Learning Flow