Files
leleka/docs/prefix-cache.md
T

15 KiB

Cross-session prefix cache

Branch claude/prefix-cache (cut from claude/port-gpu-bringup 6b94e7c). Code: crates/leleka-runtime/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 120 MB 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. Cost model: the copy is a host memcpy of 14.2 KB per token (2.56 GB for 180k cold: about 0.3-0.5 s), against ~60 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.
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.

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

RESULTS_PLACEHOLDER

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

REMAINING_PLACEHOLDER