Why Prefix Cache Hits Can Still Produce Incorrect Results in Long-Context Inference

    In long-context inference, a prefix-chain hash hit is only a candidate match. Hybrid attention can split a prefix across compressed KV, uncompressed tail, sliding-window, indexer, and offloaded states, each with its own recovery conditions. This article explains the five states that must be tracked, how prefix matching should consult allocator state, a four-layer hit validation process, and the concurrency and reload issues that can still cause errors.

    1. Background and Problem

    In inference serving, multiple requests often share the same prefix, such as an identical system prompt, the same long document, or the history portion of a multi-turn conversation. Once the server identifies a reusable prefix, it can skip prefill computation for that segment and reduce time to first token.

    The traditional approach divides token history into fixed-size blocks, maps them to physical KV blocks through a page table, and computes a hash for each full block. This method relies on one premise: the same prefix under the same model and the same positional encoding parameters produces the same KV data.

    Therefore, a block hash cannot depend only on the tokens in the current block. It should be computed from the parent block hash, the current block tokens, the model identifier, and the positional encoding parameters. This is the prefix-chain hash. Hashing only the current block’s tokens would incorrectly treat the same text at different prefix positions as identical data.

    Under full attention, every layer performs the same computation over the complete history, and the data in a block is a deterministic function of the prefix. A prefix-chain hash hit therefore means the data is usable. Hybrid attention breaks this conclusion.

    2. Why Hybrid Attention Breaks “Hit Means Usable”

    To control the compute and memory cost of long contexts, models use different attention mechanisms at different layers. Common combinations include three types:

    • Full-history compression: retains the entire history but compresses the KV of multiple tokens into fewer entries.
    • Sliding window: attends only to a recent segment of tokens, and information outside the window is discarded.
    • Sparse routing: an indexer selects a small set of relevant positions for each query to participate in computation.

    With hybrid use, the KV of the same prefix is distributed across several structures, and each structure has its own lifecycle. A hash hit only shows that this token sequence has appeared before. It cannot show that every type of state still exists and is in a readable form.

    A library analogy helps build intuition: a normal cache is like a shelf number, and finding the number is enough to retrieve the book. Under a hybrid structure, after finding the number, you must also confirm that the book is still on the shelf, that the latest pages have been bound, that the borrowing period is valid, that the index catalog is synchronized, and that the book has not been moved to an external warehouse. The analogy is only for intuition; the decision conditions are governed by the state table and validation flow below.

    3. Five Cache States That Must Be Explicitly Tracked

    The server needs to model each state separately and record its recovery conditions independently.

    State Created when Recovery condition Impact if missing Primary storage
    Compressed KV Produced after history accumulates to the completion of a compression unit Compression is complete, the compression boundary aligns with the block boundary, and the covered token range exactly equals the request prefix Long-range history is missing, and output deviates from expectations GPU memory, possibly offloaded
    Uncompressed tail Tokens at the end shorter than one compression unit, kept in their original form Tail data exists completely Recent context is missing, and short-range dependencies fail GPU memory
    Sliding window KV of the most recent tokens within the window Every position in the window has data, and the window start matches the request’s absolute position The window is misaligned, and attention reads data from other positions GPU memory
    Indexer state Selection information maintained by sparse routing for each layer and each query Same layer, same version, and complete with the corresponding KV The system does not know which positions to read, and output can still be wrong even when KV is complete GPU memory, small footprint
    Offloaded prefix Prefix moved to host memory or disk when GPU memory is insufficient Reloaded to GPU memory, and the reload task has completed Cannot participate directly in computation before reload Host memory or disk

    Strictly speaking, an offloaded prefix is a storage tier, not an attention state. It is included among the five because its reload state also determines whether the prefix can be reused.

    The five states have different recovery conditions. If any one of them is not satisfied, the entire prefix cannot be directly continued for computation. Tail and window states change most frequently and are the most likely to be missing or misaligned.

    4. Allocation and Prefix Matching: Two Actions, Two Responsibilities

    The allocator finds free blocks for new tokens and records the current form of each data segment, such as “compression complete,” “tail uncompressed,” “window loaded,” or “reloading.”

    Prefix matching is a separate action. It uses the prefix-chain hash to find the longest complete usable prefix. The matcher must read the state maintained by the allocator and cannot rely only on the hash table.

    The illustrative code below shows the decision order.

    1. # Illustrative code: shows decision order only; not an API from any specific framework
    2. def match_prefix(request_tokens, cache):
    3. hit_len = 0
    4. for block in cache.iter_blocks_by_prefix_hash(request_tokens):
    5. state = cache.get_state(block)
    6. if state.tier != "gpu" or state.loading:
    7. break # Not yet reloaded to GPU memory; cannot participate directly
    8. if not (state.compressed_ready
    9. and state.compressed_end == block.end
    10. and state.tail_ready
    11. and state.window_ready
    12. and state.indexer_ready):
    13. break # Stop at the first incomplete block
    14. if state.window_start != block.abs_start:
    15. break # Window position does not match the current request
    16. hit_len = block.end
    17. return hit_len

    There are three points to note in this code:

    • Stop at the first incomplete block instead of skipping it and continuing to report a longer prefix. Skipping produces a discontinuous prefix, and the missing middle portion will inevitably cause incorrect computation.
    • The matcher reports only the length that is already resident in GPU memory and ready. Reload is triggered separately by the scheduler, and its cost is estimated separately.
    • The loop performs one hash lookup and one state read per block, so its time is proportional to the number of matched blocks. In a production implementation, the state read and reference count must be completed in the same atomic operation, as discussed in Section 6.

    5. Four-Layer Hit Validation

    A hash match is only the first step. Whether the hit length can be used for computation must pass the following four layers of validation.

    1. Hash and prefix chain: compare the prefix-chain hash and confirm that the model version, tokenizer, and positional encoding parameters match. Hash equality is only a candidate, not proof of usability.
    2. Five-state completeness: all five states of the candidate block satisfy their recovery conditions. If any state is missing, truncate at that block.
    3. Position and storage tier: the window start equals the request’s absolute position, the compression boundary aligns with the block boundary, and the offloaded prefix has been reloaded to GPU memory. If reload time exceeds the recomputation cost, abandon reuse and recompute directly.
    4. Version and references: on a successful match, record the state version and increment the reference count for the hit blocks. Before computation starts, check the version again to confirm that the blocks have not been evicted or rewritten.

    Before launch, check each item in the following list:

    • The prefix-chain hash includes the model, tokenizer, and positional encoding parameters
    • All five states are in ready form
    • The compression boundary and window start match the request position
    • The offloaded prefix has completed reload
    • Hit blocks are referenced, and the version number is unchanged before computation

    6. Concurrency Consistency and Reload Strategy

    • State transitions must be atomic. For example, switching from “compressing” to “compression complete” should be committed by the writer in one step under a lock or through a version number. Readers must see a complete version, never an intermediate state.
    • Reference counting: after a successful match, increment the reference count for the hit blocks, and release it when the request ends. Referenced blocks cannot be evicted or migrated.
    • Eviction race: before selecting a victim block, the evictor must check both the reference count and the state. Blocks that are being reloaded cannot be evicted.
    • Sharing and writes: when multiple requests share a prefix, the tail changes with subsequent writes. Only the already frozen portion can be safely shared. New tokens should be written to new blocks, and already shared blocks must not be modified.
    • Reload: reload is an asynchronous task. At the start, mark the state as reloading, and after completion, atomically switch it to ready. Reload time can be estimated by dividing the data bytes by the available bandwidth, then compared with the time required to recompute prefill.

    7. Common Mistakes

    1. Reporting a hit based only on the hash without checking each cache state.
    2. Skipping an incomplete block during matching and continuing to report a longer length.
    3. Ignoring the absolute position of the sliding window and treating a window from another position as usable data.
    4. Starting computation before an offloaded prefix has finished reloading.
    5. Failing to increment the reference count after a hit, so the block is evicted or rewritten during computation.
    6. Omitting the model version or positional encoding parameters from the hash, causing cache data to be misused across versions.