Prefix Cache Hit Validation and State Recovery for Heterogeneous KV Caches
Prefix caching in inference services reuses KV cache blocks when token hashes match. That rule breaks down when layers mix full-history compression, sliding window attention, and sparse routing, because a hash match does not prove that every part of the cache can be read. This article explains how to track five cache states, record state tags in the allocator, apply four layers of checks to find the usable prefix length, and enforce four consistency constraints.
1. Why Prefix Caching Breaks Down
Inference services usually split the token sequence into fixed-size blocks and compute a hash for each block. When a new request arrives, the system looks up existing blocks by hash. Matched blocks reuse their precomputed KV cache, and only the remaining part is computed. This mechanism rests on one assumption: the same prefix produces the same KV cache, so identical hashes allow reuse.
This assumption holds when all layers use the same attention mechanism. It weakens once different layers mix different mechanisms. Three common types are:
- Full-history compression: the entire history is compressed into a smaller representation, and each block is sealed as the sequence grows.
- Sliding window attention (SWA): only the KV cache within a recent window is kept, and data outside the window can be released.
- Sparse routing: an index structure first selects a subset of historical blocks, and attention is computed only over those blocks.
Each mechanism has a different lifecycle for its cache objects and different recovery conditions. Therefore, two requests with the same prefix only show that their token sequences are identical. They do not show that the cache for every layer is ready to be read.
When context lengths reach the order of millions of tokens, the cache for the full context does not fit in the memory of a single GPU. The system must offload part of the prefix to external storage. Cross-request reuse also means the same prefix appears in different sessions, and the recovery progress of each session can differ. When these three factors combine, a single hash rule cannot reflect the true state of the cache.
Consider an example. Two requests have the same hash for their first 4096 tokens. The current position needs window data starting from token 3072. Request A has a window start at 3000, so it covers the required data. Request B has just been loaded back from external storage, and its window start is still at 3500. It is missing data for tokens 3072 through 3499. The hash match reports a hit for both requests. After Request B reuses the cache directly, attention reads data that does not exist. The output is wrong, and the system usually raises no exception.
2. A Hit Does Not Mean the Data Is Readable
A normal cache lookup works like this: you find a shelf number in a catalog, then you go to the shelf to get the book. A heterogeneous cache needs several more checks. After finding the shelf number, you need to confirm five things. First, whether the book is on the shelf. Second, whether the most recent pages are already bound into the book. Third, whether all the chapters you are reading are on hand. Fourth, whether the catalog index is in sync with the text. Fifth, whether the book is still in the remote repository and has not been brought back. Reading can start only when all five are confirmed.
Each of the five items corresponds to one of the five states described below. The book on the shelf corresponds to compressed KV. The most recent pages correspond to the uncompressed tail. The current chapter corresponds to the SWA window. The catalog index corresponds to indexer state. The remote repository corresponds to the on-disk prefix.
Therefore, prefix matching should change from “Are the hashes the same?” to “Are the hashes the same, and can every state component be recovered?” When only hashes are checked, a common problem follows. The hit is reported as successful, but during computation the unsealed tail KV, window data, or index routing is missing. The output is then wrong, but the system reports no error, and troubleshooting is costly.
3. Five States That Need Explicit Tracking
The table below lists five states. The recovery conditions are general design descriptions. Implementation details vary by system.
| State | Meaning | Recovery Condition | Hit Check | Handling on Failure |
|---|---|---|---|---|
| compressed KV | Sealed compressed history | The corresponding block has finished compression | Block boundaries are complete, and the compression version matches the operator used by the request | Reject the segment if the versions do not match |
| uncompressed tail | Unsealed raw tail | Raw KV is still in GPU memory, or can be refilled from the source data | Tail length matches the prefix length | If the lengths do not match, truncate to the last complete block |
| SWA window | KV within the sliding window | All tokens in the window are in place | Window start is no later than the earliest position needed by the next token | If the window is incomplete, recompute from the available positions |
| indexer state | Index state used by sparse routing | Synchronized with the KV version | Index version equals block version | If the index lags, reject the segment or rebuild the index first |
| on-disk prefix | Prefix offloaded to external storage | Loaded back into GPU memory and passed validation | State is resident, and the load-back completion flag is set | On timeout, validation failure, or unfinished I/O, do not hit |
The five states have different lifecycles. Compressed KV grows as the sequence grows, until the sequence ends or the data is evicted. The uncompressed tail becomes compressed KV when its block is sealed, and this transition happens only once. The SWA window keeps sliding as decoding advances, and old data outside the window is discarded. Indexer state follows KV updates. If either side falls behind, routing produces errors.
Load-back from external storage takes an unpredictable amount of time, so the on-disk prefix cannot be assumed to be ready immediately. While a load-back is in progress, that segment does not count as a hit. A request can choose to wait, but the wait time must have an upper limit. The exact threshold depends on the system’s I/O capacity. If the limit is exceeded, validation fails, or an I/O error occurs, the segment state is set to failed. It cannot be hit, and the request falls back to recomputation. Failed segments can be retried in the background. After repeated failures, they are marked for cleanup so they do not repeatedly tie up resources.
4. State Tags the Allocator Must Record
A traditional allocator only finds free blocks for new tokens and writes data into them. With a heterogeneous cache, the allocator must also record the current state of each token segment. Otherwise, the prefix matching module can only rely on hashes to report a hit, and it cannot tell whether the data in that segment is complete.
Boolean values can only answer “does it exist?” They cannot answer “which version?” or “up to which position?” Therefore, the code below uses version numbers and positions in place of some boolean values:
```python
from dataclasses import dataclass
from enum import Enum
class DiskState(Enum):
NONE = 0 # Never offloaded; all data is in GPU memory
RESIDENT = 1 # Loaded back into GPU memory and passed validation
LOADING = 2 # Loading back; not counted as a hit for now
FAILED = 3 # Load-back timed out or failed validation; must not hit
@dataclass
class SegmentState:
compressed_ready: bool
compressed_version: int
tail_len: int
tail_ready: bool
window_start: int
window_ready: bool
block_version: int
indexer_version: int
disk_state: DiskState
def hit_ready(self, cur_pos: int, window: int) -> bool:if self.disk_state not in (DiskState.NONE, DiskState.RESIDEN
