Files
leleka/docs/prefix-cache.md
T

33 KiB

Cross-session prefix cache

Branch claude/prefix-cache (cut from claude/port-gpu-bringup 6b94e7c). Code: crates/engine-qwen35-cuda/src/prefix_cache/ (model-free store, hash chain, budget, pool summary), qwen_forward/original_serve_prefix.rs (the binding to the Original serve stack), the park/import primitives in crates/cuda-driver (qsa_mapped_journal.rs, qsa_resident_index.rs) and qwen_forward/session_original_prompt.rs, and the pool surface in control-plane/src/prefix_view.rs.

Why

Coding agents resend their whole context with every request (system and developer instructions, tool schemas, repository context, every earlier turn and tool output), and a pool serves many agents from many runtimes: the next request is not guaranteed to come from the agent that sent the last one. Prefill is 1.8k-3.7k tok/s here, so a 30-100k-token request costs 10-40 s without a hit, and a 180k-token one a minute or more.

The Original's conversation cache (docs/original-serve.md, "Conversation cache") keeps --prompt-cache checkpoints (default 6: the pinned root, periodic ones, the last turn boundary) of the ONE conversation whose K/V the positional buffer holds. A checkpoint is only valid while the positional cells below it still hold ITS tokens, so a request from another session overwrites every cell after the shared prefix and the first session's later checkpoints die with them. Parking whole conversations in host RAM (--conversation-cache-mib) is not bound in the port. Measured effect: see "Results".

Design

One token grid

The prompt is read on a fixed grid (PromptOptions::grid, --prefix-cache-block, default the prefill capacity, so a grid step is one full chunk and the prefill runs at the speed of the chunk size the operator chose): every batched chunk ends on a multiple of block_tokens, apart from the last one of a request, which ends at n - 1 (the last prompt token starts the first verify window). There are no turn or root cuts. Consequences:

  • the recurrent state, the K/V cells and the draft ring after a grid chunk are a pure function of the tokens before it, whichever request read them (the batched prefill's arithmetic depends on how the prompt is cut into chunks, which is why the Original's turn/root cuts make a resumed read differ from a full read);
  • a request resumed at a grid point reads exactly the chunks a full read reads from there, so a cache hit reproduces the full read bit for bit (checked on the real model, "Results");
  • what a session loses at the end of a request is the partial last chunk (on average half a block: 1k tokens at 2048, 4k at 8192). The block size trades that loss against the prefill's per-chunk overhead: on the 5090 a 2048-token chunk prefills at ~1.4k tok/s on a 10-26k context (jobs 921/922) and an 8192-token chunk at ~3.5k tok/s (job 915), so the default follows --original-prefill-capacity.

Blocks, nodes, sharing

  • A block holds the K/V cells (INT8 K+V with scales, 1056 B per cell and layer, host image) and the pooled index rows (128 B per cell and layer) of block_tokens consecutive tokens of the twelve QSA layers: 14,208 B per token, 29.1 MB per 2048-token block, 2.56 GB per 180k tokens. It is keyed by the hash chain value after it (hash::chain_step), so by the whole token prefix it ends, and stores its tokens (verified on every match, so a 64-bit collision cannot produce a hit).
  • A node is a checkpoint at a grid point: the GDN and PLE host images, the predecessors, the index checkpoint tails of the twelve layers (2,564 B each) and the draft ring's snapshot (about 127 MB in all at the 5090 profile), plus the list of its block hashes. A node needs its blocks and nothing else.
  • Blocks are shared by reference (refs = nodes covering them): N agents with the same 8k system prompt hold ONE copy of its four blocks. Evicting a node frees its state and exactly the blocks no other node covers.

Restore path

On a request the store walks the prompt's chain and returns the deepest node that is a prefix of the prompt and ends at or before n - 1 (longest_match: hashing 180k tokens and comparing them is about a millisecond). The stack then (QwenSession::import_parked):

  1. computes how much of the positional buffer already holds the prefix: live is the part known to hold the current prompt's cells (written by the prefill or put back by an import); it is truncated before a chunk or an import overwrites cells and extended after, so a cancelled or failed request never claims cells it did not finish writing;
  2. writes back only the blocks from the first one the buffer does not hold: host K/V pages straight into the pinned host image (OriginalQsaMappedJournal::import_pages, which also resets the VRAM resident window of the layer so no stale slot survives), pooled index rows into the device image (OriginalQsaResidentIndex::import);
  3. re-mints each layer's lineage objects (index checkpoint, mapped prefix, ResidentQsaPrior) from the layer's own owners and bumps the branch generation, which fences every older checkpoint;
  4. installs the GDN/PLE images and the position, re-anchors the draft ring (resume_at + kv_restore) and prefills only the suffix.

The same session continuing copies no K/V at all (the buffer already holds its prefix); a session returning after others copies only the blocks the others overwrote. Measured on the 5090: 98k tokens (1.4 GB) restored in 101 ms and 172-180k tokens (2.4-2.6 GB) in 175-194 ms (13-14 GB/s, a host memcpy of 14.2 KB per token), a hit that copies nothing in 1-3 ms, against 28-55 s of prefill.

Admission and eviction (what is kept)

After every grid chunk the policy may admit a checkpoint (PrefixStore::consider). A node is scored by expected tokens saved per byte its eviction frees:

value(node) = P(hit) * (tokens(node) - tokens(nearest surviving ancestor))
score       = value / (state bytes + bytes of blocks only this node covers)

P(hit) combines a prior that depends on the node's role with the decayed hit mass:

  • frontier (the deepest node a request built: the likeliest resume point of its session): prior 0.5;
  • interior (a deeper neighbour exists in its chain): prior 0.03, raised by each branch below it (a branch point is shared by definition);
  • the prior halves every 256 requests without a touch (recency), and hits add mass: a hit by ANOTHER session than the one that built the node (the live buffer did not extend its prefix: a shared root or a rewritten history) counts 3, a session's own continuation counts 0 (it only says the node was the frontier, which the prior already values).

Measuring against the nearest SURVIVING ancestor makes a thinned chain worth more per node, so a long session settles on its frontier, the previous one or two, and a geometric spread of older nodes (for forks and history rewrites), not a node per block. A candidate is admitted when there is room, or when the sum of the values of the victims it needs (cheapest per byte first, counting the saving the candidate gains once a victim ancestor is gone) is less than its own value; otherwise it is rejected before anything is built. Blocks of the candidate's own path survive the eviction of its ancestors. A byte budget bounds the store (--prefix-cache-mib); the estimate is replaced by the real size after the build and the budget is enforced again.

Unit tests (prefix_cache::store::tests) pin: sharing, refcounts, the node cap, idle frontiers losing to fresh ones, hot shared roots surviving churn, a long session settling on a sparse chain, oversize payloads, collisions.

Budget

--prefix-cache-mib auto|N|0. auto keeps 4 GiB of MemAvailable free and takes 75% of the rest when the stack opens (ceiling 96 GiB, 24 GiB with the laptop profile), and is off when that is under 1 GiB. MemAvailable already excludes the sealed KAR memfd (shmem) and the pinned K/V, and it counts reclaimable page cache. On the 5090 server (121 GB; 55 GB sealed memfd, ~50 GB resident expert source) it was 22 GiB at open in job 922, so the budget came out at 13.7 GiB; right after the model load it can be lower (job 915 sampled 14 GiB while the expert source was still being copied), and it differs run to run with the page cache. The cost of a session is its blocks plus the states of the nodes kept: blocks are 14.2 KB per token (2.56 GB at 180k tokens), a state is about 127 MB (GDN/PLE images, the draft ring, the index tails), so at the default grid a 180k-token session costs 2.6 GB of blocks plus 127 MB per node kept (one node when thinned, 22 at an 8192 grid when all are kept). Before every insertion the live MemAvailable is checked again against a 3 GiB floor: an insertion that would breach it is skipped, and unknown telemetry fails closed. The accounting matches the process: job 922's store reported 5,176 MiB used and the process RSS grew by about 5.3 GB.

Concurrency, cancellation, failure

The engine serves one generation at a time, so the store needs no locking; all of it lives on the owner thread. A request for another session simply finds a different node. A cancelled request keeps the checkpoints of the chunks it finished (they are immutable host images), claims only the cells of its finished chunks, and the next request, from any session, imports over whatever the interrupted one left. A failure of the cache (a checkpoint that cannot be built, an import that fails) drops the whole cache and the request is read from 0 after the usual reset (prefix cache: ...; reading the whole prompt); a lost physical owner invalidates it with the stack.

What the cache does not do

  • It replaces the conversation cache when on (StackConfig::prefix / --prefix-cache-mib); with it off nothing changes.
  • The live continuation of the Original (continue the session's decode-phase K/V as is) is not used: decode-produced cells are not what a prefill produces, and sharing them would break the exactness above. A session resumes from its last grid node and re-reads the partial block, the reply and the new tokens. A tool-call reply ends on EOS, after which the Original's own live continuation is unavailable anyway.
  • K/V is parked as INT8 host images only (--kv int8, the only format with sealed owners); the streamed layout (--kv-resident) needs nothing special because the host image is the authority for every reachable cell.
  • One engine, one buffer: two concurrent sessions on one runtime still alternate; the pool gets concurrency from many runtimes and the router below.

Knobs and observability

Knob Default Meaning
--prefix-cache-mib auto|N|0 off Host-RAM budget; auto per the profile above. Turning it on replaces the conversation cache.
--prefix-cache-block TOKENS the prefill capacity Block size and chunk grid; a multiple of 256, at most the prefill capacity.
--prefix-cache-tail off|prompt|reply off Also checkpoint where the agent's next turn resumes (request-end checkpoints, below). reply is off in the engine; the rtx5090-32g profile sets it, and its live equivalence gate is still OPEN (STRA-328).
LELEKA_PREFIX_TRACE=1 off One line per admitted checkpoint.

Logs (stderr, leleka-serve ...): prefix cache on: ... at open; per request prefix request: n= hit= resume= shared= copied_tokens= import_ms=; prefix request done: admitted= park_ms= prefix stats: nodes= blocks= used_mib= budget_mib= requests= hits= shared_hits= misses= reused_tokens= prompt_tokens= admitted= rejected= evicted=. Usage::reused_input_tokens is the resume point.

Request-end checkpoints (--prefix-cache-tail, claude/ttft)

An agent resends its whole history: the next prompt is the previous prompt, the model's reply (token for token) and ~60-300 new tokens (captures 943b/945: median suffix after prompt+reply 106 tokens). With grid nodes only, a turn resumes at the last 2048-token grid point and re-reads the partial block, the reply and the new tokens (~2.2k tokens per turn; ~214k tokens in all of capture 945 against ~28k needed), which at the measured ~0.83 ms per re-prefilled token plus ~0.6 s fixed is most of the 1.5-1.8 s TTFT.

A tail node is a checkpoint at a position that is not a grid point: its key is the hash chain of the last full block continued over the tail tokens, its value is the full blocks below it (shared with grid nodes), one private partial block (K/V pages rounded up, index rows rounded down; the checkpoint's tail carries the partial index row) and the usual state (GDN, PLE, draft ring). A newer tail supersedes the earlier tails that are token-prefixes of it (the frontier moves forward), tails compete for the budget by value like every node, and they are not published in the router summary. A request that resumes from a tail reads its suffix with the neutral cut (grid 0: as few chunks as the capacity allows), not on the grid.

  • prompt: one checkpoint at n - 1 at the end of the prefill (an extra chunk boundary; a prefill state). The next turn re-reads the reply and the new tokens.
  • reply: also one at the end of the decode, at the end of prompt + committed reply, where the next turn resumes. This needs the session settled (settle_state) and the draft ring in step; the controller drafts the last window too (set_final_draft) so the ring stands at the session's position after EOS. The cells past the prompt were produced by the decode, so the state is not what a prefill would produce (the Original's live continuation). Off by default in the engine. The rtx5090-32g profile sets it (see the paragraph below), but the live gate that would justify a lossy default -- reply restore vs a cold prefill of the same tokens, greedy identity and tool-call integrity -- has NOT been run (STRA-328, plan and tool: scripts/e2e/prefix_tail_equivalence_plan.md).
  • Exactness: grid nodes stay exact by construction. A tail is not canonical: prompt differs from a grid-only full read by where the chunks were cut (rounding level, same as any chunk-size change), reply also by decode-produced cells. The gate is empirical: replay with the static tier, seed off, LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0, arms G (grid only) / P / R in one process (LELEKA_REPLAY_ARMS=G=off,P=prompt,R=reply, LELEKA_REPLAY_OUT=file writes the greedy ids of every request and arm), and compare token for token.
  • Tools: per-request stage marks (REPLAY-MARKS: resume, prefill, assemble, first round), the short-suffix cost sweep (backend::original_serve_ttft::original_serve_ttft_sweep), jobs 9d0-9d2 of claude/ttft.

Session retention (60 minutes)

A pool serves many agent sessions; each one's next request should find its own checkpoint as it would in a slot. The store therefore keeps every node for a retention time of wall-clock minutes since its last use (retention_ms, default 60 minutes; 0 = no limit):

  • Expiry: a node unused for longer than the retention time is dropped with the blocks only it covered (expired= in the stats line, leleka-serve prefix retention: expired N ... in the log). The serve loop sweeps every 15 s while idle and each request refreshes the clock of the node it resumed from, so an active session never expires and an abandoned one gives its host RAM back after an hour.
  • Displacement: when the budget runs out (or the memory governor sheds), the value of a node is multiplied by a recency factor that falls linearly from 1 (just used) to recency_floor (0.1) at the end of the retention window, so the session idle longest is displaced first; a fresh session is never refused because an hour-old one still sits there.
  • Tests: a_session_is_kept_for_the_retention_time_and_dropped_after_it, retention_zero_never_expires, when_the_budget_runs_out_the_session_idle_longest_is_displaced_first (the policy takes the wall time from the caller, so they are exact).

--prefix-cache-tail reply is the slot-equivalent resume (the checkpoint stands where the agent's next turn continues, built from the decode-produced cells exactly as the Original's live continuation; it includes the prompt checkpoint). Measured, and the default of the rtx5090-32g profile although its equivalence gate is open (STRA-328) (memory.prefix_cache_tail): live Codex CRM sessions (jobs 945d grid-only, 9e2 prompt, 9e3 reply, 64-72 requests of ~70k tokens each): median prefill 2265 -> 1094 -> 706 ms, p90 3620 -> 2394 -> 1064 ms, re-prefilled tokens per request 2743 -> 1869 -> 1630, decode unchanged (130.1 / 131.5 / 130.7 tok/s), no failures. Agreement (job 9d4, 40 requests of 9e3 teacher-forced along their recorded tokens, top-16 log-probabilities of 64k rows per arm, scripts/quality/q_tail_gate.py): d_top1 p99 0.394 (prompt) / 0.401 (reply), flips 1.49 % / 1.45 %; the control, the grid-only path with another chunk cut (job 9d5, capacity 4096), deviates by p99 0.394 / flips 1.45 % from the same reference, so the tails are within the rounding noise of any chunk-cut change at 70k tokens of context (the Original's own envelope of p99 0.22 was measured on ~100-token prompts and does not transfer). Replays cannot score reply: an arm's own greedy replies diverge from the recorded ones, so the next recorded prompt no longer extends them; only live sessions can.

Pool protocol

A front router across many runtimes places a request on the runtime that holds the longest prefix of its prompt. Nothing but the prompt's token ids is needed to ask.

Chain. Cut the prompt into blocks of block_tokens tokens (the runtime's block_tokens, 2048 by default); the chain value after block j is h_j = chain_step(h_{j-1}, block_j), h_{-1} = CHAIN_SEED = 0x4C454C454B410001, where chain_step folds each token t (as u32) as h = rotl(h, 5) ^ t; h *= 0x517CC1B727220A95 and finalizes with splitmix64 over h ^ (len << 40) (prefix_cache::hash, version CHAIN_VERSION = 1, pinned by a test; a partial tail has no value). h_j depends on every token before the end of block j.

Summary (prefix_cache::PrefixSummary, JSON). The engine publishes it after every request; leleka-runtime hands it to the runtime gRPC Snapshot.prefix_cache_json; the control plane copies it on its health tick and after every request:

{"version":1,"chain_version":1,"namespace":"00000000000000ab","block_tokens":2048,
 "budget_bytes":32212254720,"used_bytes":1048576,"nodes":2,"blocks":6,"truncated":false,
 "heads":[{"h":"00000000000000a1","tokens":4096},{"h":"00000000000000a2","tokens":12288}],
 "stats":{"requests":3,"hits":1,"shared_hits":1,"misses":2,"reused_tokens":4096,"prompt_tokens":9000,"admitted":2,"rejected":0,"evicted":0}}

heads lists the checkpoint nodes (chain value after the node's last block, tokens covered), best value first, at most 512 (truncated says if some are left out; about 25 KB). namespace fingerprints everything that makes two caches interchangeable (model digest, KV format and window, block size, chain version): compare chain values only between runtimes with equal namespaces.

Surfaces.

  • GET /v1/status carries the summary as prefix_cache (with age_ms), null when the runtime has none.
  • POST /v1/prefix_match with {"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>" (optional)} (the prompt's chain values in order, at most 16,384) answers {"available":true,"compatible":true,"namespace":..,"block_tokens":2048, "cached_tokens":12288,"truncated":false,"age_ms":..}: the tokens of the deepest head among the hashes, 0 when none or when the namespace differs. It is a hint about a snapshot (the runtime may have evicted a head since), computed in microseconds from the control plane's copy; it never touches the GPU thread.
  • In-engine, OriginalServeStack::prefix_match(chain) answers from the live store (exact for hash equality) and PrefixSummary::match_tokens is the same lookup over a summary, for a router that polls summaries instead.

A router's loop: hash the prompt once per distinct block_tokens, ask each candidate runtime (or its cached summary), send the request to the longest cached_tokens, ties to the less loaded. The router itself is not part of this work.

Results

All numbers below are from the real model; every log line is in the job logs named (kept outside Git, with the binary hashes). Greedy decoding, the VRAM expert tier in STATIC mode (LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048, per layer, ADAPT_EVERY=0) with the prompt-routing seed OFF (LELEKA_ORIGINAL_SERVE_SEED=off), so the expert placement is identical for every arm; MTP drafting on; INT8 K/V, --kv-resident 20480, max context 262144. Hardware: RTX 5090 (driver 595.99), 121 GB RAM of which 55 GB is the sealed KAR memfd and ~50 GB the resident expert source; model sha256:4c1eb2ce...aca3 (shard 0); chunk 2048 unless stated. Workload generator: backend_original_serve_prefix_smoke.rs (real tokenizer; deterministic text; the sessions' histories are literally extended, the way an agent resends its context).

How "equal" was checked: after a request served from the cache, the SAME prompt is served again with the cache bypassed (prefix_bypass: no lookup, no insertion; a full read from position 0 on the same chunk grid) and the committed token ids are compared (16-24 greedy tokens each). This is the charter's non-lossy rule applied to the cache: it is not compared with the Original's turn/root cuts, which change the chunking.

1. The failure mode today (job 921, legacy: the Original's conversation cache as shipped)

Three sessions A, B, C share an 8k-token system+tools+repo prefix, requests interleaved A1 B1 C1 A2 B2 C2 ... (5 turns, +4k tokens per turn, 10k -> 26k).

request prompt tokens reused (legacy) re-read (legacy) TTFT legacy reused (prefix) re-read (prefix) TTFT prefix
A1 10,020 0 10,019 11.2 s 0 10,019 8.6 s
B1 / C1 10,020 7,998 2,021 2.2 s 6,144 3,875 2.8-2.9 s
A2 / B2 / C2 14,051 7,998 6,052 4.4-7.5 s 8,192 5,858 4.1 s
A3 / B3 / C3 18,082 7,998 10,083 7.3-7.8 s 12,288 5,793 4.4 s
A4 / B4 / C4 22,113 7,998 14,114 10.0-10.3 s 16,384 5,728 4.3-4.4 s
A5 / B5 / C5 26,144 7,998 18,145 12.9-13.0 s 20,480 5,663 4.5 s
all 15 271,215 111,972 (41.3%) 159,243 mean 8.3 s, p95 13.0 s 184,320 (68.0%) 86,895 mean 4.4 s, p95 4.5 s

Today, after the first request every request reuses only the pinned root (7,998 tokens: the first turn boundary); the session's own later K/V is overwritten by the other sessions and re-read, so TTFT grows with the context (13 s at 26k). With the prefix cache TTFT is flat (4.4 s) because only the suffix since the last grid point is read (~5.7k tokens at ~1.4k tok/s with 2048-token chunks; a bigger chunk reads it faster, see 3). At 10k the cache reuses less than the root (6,144 < 7,998): the grid has no turn cuts, so the shared 8k prefix is cached at its last 2048 boundary. Equality: all 14 verified requests produced the same ids as the full read (job 922). Restore cost: import 11 ms mean (24 ms max, 18,432 tokens = 262 MB copied in 24 ms); lookup 23 us mean; parking 3.5 ms per request mean.

2. A realistic agent trace (jobs 923 legacy, 927 prefix; 924 is the same run with the policy before its last fix)

Synthetic Codex-like trace after docs/experiments/2026-10-03-agent-ab-threejs.md (97 requests, 3.3M input tokens): 4 sessions x 24 requests = 96 requests in seeded random interleaving, a 2.5k-token system+tools prefix shared by all, each session growing from ~3k to ~40k tokens with heavy-tailed tool outputs (64 to ~6k tokens). 2.19M prompt tokens in total.

legacy (job 923) prefix cache (job 927, auto budget 7.8 GiB)
prompt tokens reused 580,618 (26.5%) 1,927,168 (88.0%)
prompt tokens read again 1,608,955 262,405
TTFT mean / p50 / p95 / max 12.5 / 11.3 / 27.6 / 27.6 s 2.5 / 1.7 / 5.5 / 5.8 s
sum of TTFT over the trace 1,200 s 244 s
decode (mean of per-request rates) 29.9 tok/s 31.9 tok/s
context requests legacy reuse legacy mean TTFT prefix reuse prefix mean TTFT
0-8k 18 61% 2.2 s 55% 2.2 s
8-16k 16 39% 5.6 s 76% 2.6 s
16-24k 13 39% 8.9 s 82% 3.0 s
24-32k 19 23% 15.6 s 90% 2.6 s
32-50k 30 21% 22.0 s 93% 2.5 s

Under a real byte budget (7.8 GiB: the memory available when the stack opened was 14.5 GiB) the adaptive policy admitted 68 checkpoints, rejected 8 and evicted 25, ending with 43 nodes and 76 blocks (7,833 MiB used): the trace still reused 88%. RSS grew by the amount the store reports (53.6 -> 61.4 GB). The last request of every session (reused 38,912 of 40.7k tokens) was re-read with the cache bypassed: all 4 equal (TTFT 1.7 s cached vs 28.8-29.2 s full read). Cancel safety (a request cancelled during the prefill, one cancelled after its first round, the same prompt served and verified, a switch to another session): all passed. Restore (job 924): 99 hits; a hit that copied nothing cost 1.3 ms; the 40 hits that copied 20-37k tokens (up to 524 MB) took 34 ms on average (43 ms max). Lookup over a 40k-token prompt: 29 us mean, 59 us max.

Decode speed: the decode path is untouched; the only effect is a one-time cold start of the VRAM resident K/V window after an import (the resolver is reset because the host image changed): for the same request with identical output, decode took 594 vs 565 ms (+5%, 29 ms) at 10k context and 596 vs 593 ms (+0.5%) at 40k (jobs 922 / 924; 14 + 4 pairs, +0.5% to +5%, never more than 30 ms per request).

3. 100k and 180k contexts

Two sessions A and B, each 8k shared + private history, 3 turns (+3k tokens per turn), interleaved A1 B1 A2 B2 A3 B3, chunk = grid = 8192 (the chunk of job 915, where plain prefill of 100k / 180k ran at 3.4 / 3.5k tok/s and decode worked), auto budget 7.8 GiB (only 14.5 GiB were available when the stack opened). legacy = the Original's conversation cache.

context request prompt tokens reused legacy TTFT legacy reused prefix TTFT prefix restore (host RAM -> K/V + state)
100k A1 / B1 (cold) 100,020 0 / 7,998 31.3 / 27.6 s 0 / 0 (the 8,000-token shared prefix is shorter than one 8192 block) 31.4 / 30.0 s -
100k A2 / B2 103,051 7,998 28.2 / 28.1 s 98,304 2.33 / 2.33 s 98,304 tokens (1.4 GB) in 101 ms
100k A3 / B3 106,082 7,998 28.6 / 28.6 s 98,304 2.79 / 2.79 s 101 ms
180k A1 / B1 (cold) 180,020 0 / 7,998 54.8 / 51.3 s 0 / 0 55.1 / 53.7 s -
180k A2 / B2 183,051 7,998 53.1 / 53.1 s 172,032 4.76 / 4.76 s 172,032 tokens (2.4 GB) in 175-177 ms
180k A3 / B3 186,082 7,998 53.7 / 53.6 s 180,224 2.72 / 2.72 s 182-194 ms
  • Re-prefilling a 180k session costs 53 s (legacy: every request, because the other session overwrote the buffer); with the cache the request reads only the suffix since the last 8192 boundary plus what is new: 4.8 s (A2: 11k tokens, two chunks) and 2.7 s (6k tokens), i.e. 11-20 times faster. The restore itself is 0.1-0.2 s for 1.4-2.6 GB (13-14 GB/s host memcpy into the pinned image + the index rows), the lookup over a 186k-token prompt 0.2 ms.
  • Equality: A3 and B3 at 100k and 180k were each re-read with the cache bypassed (30.7 s / 55.7 s full read vs 2.8 s / 2.7 s cached): identical ids. Cancel safety at 100k (prefill cancelled, decode cancelled, retry equal to a full read, switch to the other session): passed.
  • The 7.8 GiB budget holds about two 180k sessions: it ended with 16 nodes and 44 blocks (7,832 MiB), after 32 admissions, 13 rejections and 16 evictions; both sessions still resumed at 172k / 180k, i.e. the policy kept each session's frontier and thinned its history.
  • RAM per session: 8192-token blocks are 116 MB; 180k tokens = 22 blocks = 2.56 GB, plus 127 MB per node kept. The auto budget here is small because the box holds the sealed KAR memfd and the 50 GB resident expert source; with --expert-source mapped (file-backed experts) the cache could take tens of GiB more.
  • Parking cost on the request that builds a session (cold 180k): 350 ms for 9 admitted checkpoints (host copies of 8 blocks + state clones), against 55 s of prefill.

4. Laptop (RTX 3080 Laptop 16 GB, WSL2, mapped experts, sm86 build; slow CPU experts: ~45 tok/s prefill)

Same grid workload, small (3k shared + 1k private, +1.5k per turn, 3 sessions x 3 turns, chunk/grid 1024), legacy vs prefix, auto budget (12.7 GiB): prefix reused 28,672 of 49,950 prompt tokens (57%) vs 23,984 (48%) for legacy, whose turn>=2 requests all reuse the 2,998-token root; all 8 + 8 verified requests were equal to the full read (including the cancelled-prefill and cancelled-decode checks and a copy of 1-4 blocks from host RAM, import 0.2-1.2 s there because the WSL launch latency of the per-layer resolver reset dominates). One run of the same scenario ended in Failed(CudaExecution) on its last request while the host was busy compiling; two reruns on an idle host passed (see Remaining).

5. The policy at the production size, model-free

twelve_sessions_growing_to_180k_tokens... (release, --ignored): 12 sessions behind one runtime, 8k shared prompt, histories growing 4k per request to 184k tokens (516 requests), real node/block sizes (127 MB / 29 MB), 13 GB budget: the budget holds (13,305 of 13,312 MiB), reuse 62.2% (12 sessions of ~90k tokens average do not fit in 13 GB: the cache keeps the sessions it can and rejects 8,212 candidate checkpoints), lookup over up to 184k tokens 124 us mean / 1.2 ms max, the policy 3.0 ms per request mean / 37 ms max.

Tests

  • Model-free (cargo test -p leleka-runtime --lib prefix): hash chain (pinned values), budget profiles and parsing, store (sharing, refcounts, collisions, eviction by value, caps, thinning, budget enforcement, orphans), the orchestrator over a fake device whose positional buffer is a token per cell (cross-session resume, interleaving, copy-only-what-the-buffer-lost, cancellation, failed import, budget, low host memory, pool queries) and PromptPlan grid cuts.
  • GPU, model-free (cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored parked_tests, RTX 3080 Laptop sm86 build, 2026-10-17): parked K/V pages and index rows written back come out byte for byte, in pieces and as sub-ranges, the tail round-trips through the image, malformed spans are refused.
  • HTTP/gRPC (cargo test -p strata-desktop-core --test api_over_runtime, -p strata-control --test prefix_match_http): the summary travels engine -> runtime gRPC snapshot -> worker -> /v1/status and answers /v1/prefix_match.
  • Real model: backend::original_serve_prefix_smoke::original_serve_prefix_cache_smoke (jobs 921-92x).

Remaining

  • Grid granularity. The grid is the price of exactness (a state is shareable only where every request cuts the same way). A shared prefix shorter than one block is not cached (the 8,000-token prompt of the 8192 runs), and a session re-reads on average half a block. Smaller blocks cut that loss but run the prefill at the small chunk's speed (~1.4k tok/s at 2048 vs ~3.5k at 8192 on the 5090). A two-level grid (fine steps over the first tokens, coarse after) would keep both; not built.
  • Cold VRAM window after an import. The resident K/V window is reset when the host image changed; the first decode rounds refill it (+0.5-5%, <= 30 ms per request on identical outputs). A targeted invalidation of only the overwritten pages would remove it.
  • RAM is the ceiling. 2.6 GB of blocks per 180k-token session plus 127 MB per node; the 5090 holder leaves 7-35 GiB depending on the page cache (auto follows it, and re-checks MemAvailable before every insertion). More sessions need --expert-source mapped, a bigger box, or a spill tier (NVMe) that is not built. The INT8 K/V images are not compressed.
  • One buffer, one generation. The cache removes the cost of switching sessions, not the serialization of the engine; concurrent sessions need runtimes, hence the pool summary.
  • Exactness holds for the static expert tier. With the adaptive tier or the prompt-routing seed on, GPU/CPU expert placement noise is the known envelope (the checks above ran with ADAPT_EVERY=0, seed off). The live continuation of the Original is not used (decode-produced cells are not prefill cells).
  • Not defaulted. The cache is opt-in (--prefix-cache-mib auto replaces the conversation cache). One laptop run (host busy compiling) ended in Failed(CudaExecution) on its last request and invalidated the cache as designed; four reruns on an idle host passed. Unexplained (suspect the WDDM watchdog under host-memory contention); enabling by default is a one-line change in leleka-inference once the pool acceptance tests are done.
  • The router and a Bloom summary for hundreds of runtimes are not part of this work; the summary lists up to 512 heads (about 25 KB).