Heterogeneous KV Cache State Management: Why a Prefix Cache Hit Is Not Reusable

    Prefix caching is a standard throughput optimization in LLM inference, but a prefix hash match only identifies candidate reuse; it does not prove that every cached object is recoverable. This article examines the assumptions behind traditional prefix reuse and the state-management problems introduced by hybrid attention and very long contexts. It defines five cache states that must be tracked explicitly—compressed KV, uncompressed tail, sliding-window KV, indexer state, and on-disk prefix—and explains how allocator and matcher responsibilities should be separated. It then presents four validation layers that shrink a hash-hit length to a usable prefix length: block alignment, kernel ABI compatibility, intersection across cache groups, and byte-level hardware alignment. Finally, it outlines allocator state-machine constraints, including admission caps, state-specific recovery paths, TOCTOU safeguards, and static-graph topology, plus engineering practices for observability and correctness testing.

    Introduction: A Rule Assumed for Two Years

    In large model inference serving, prefix caching is a common way to improve throughput. The basic approach is to split token history into fixed-size pages, use a page table to map logical positions to physical KV blocks, and let requests with the same prefix directly reuse blocks that have already been computed. This approach has run stably in mainstream inference frameworks for a considerable period of time.

    However, prefix hit rate is only a performance metric, not a correctness metric. As long as all layers of a model use the same attention mechanism, cached objects have a uniform form, and the rule “the same prefix hash means reusable” holds. Once different layers mix different attention mechanisms, this premise no longer holds.

    This article discusses exactly that problem: when cached objects become heterogeneous, how to determine whether a hit is truly usable, and what additional responsibilities the allocator should take on.

    1. Implicit Assumptions Behind Traditional Prefix Reuse

    The workflow of traditional paged KV caching is roughly as follows:

    1. A new request arrives, and hashes are computed for input tokens by page.
    2. The longest matching hash chain is looked up in the prefix index.
    3. Hit pages are attached directly to the new request’s page table, skipping computation for that portion.
    4. The non-hit portion is recomputed, and new physical blocks are allocated to write KV.

    This implies three assumptions:

    • Content consistency assumption: The same prefix produces the same KV content.
    • Uniform shape assumption: Every physical block has the same data structure and is read in the same way.
    • Fully readable assumption: Finding a block means the data inside it can be used directly for computation.

    The first two assumptions generally hold in homogeneous attention models. The third requires additional validation, because “the block exists” is not equivalent to “the block is usable.”

    2. Boundary Changes Introduced by Hybrid Attention

    The situation changes when a model uses the following three types of attention at the same time:

    • Full-history compression attention: Compresses historical tokens to retain long-range information; what is cached is the compressed representation.
    • Sliding-window attention: Focuses only on raw KV within the most recent window; data outside the window no longer participates in computation.
    • Sparse routing attention: Selects some historical blocks through an index to participate in computation, relying on an additional index structure.

    The cache forms of the three attention types differ from one another. The same prefix segment may correspond to a compressed representation, a raw representation, or an index record on different layers. As a result, hit determination changes from “find a block” to “confirm that every cache object involved by that prefix is in a recoverable state.”

    Another change comes from input scale. When context length reaches millions of tokens, a single accelerator’s memory cannot hold all cached data, and cache data migrates between GPU memory, host memory, and local storage. This makes “where the block is” a question that must be answered.

    3. Five Cache States That Must Be Tracked Explicitly

    In heterogeneous cache scenarios, the serving side needs to record the current state of each token segment. The five typical states below are named only as conventions for discussion.

    1. Compressed KV

    • Meaning: The compact representation obtained after historical tokens are compressed.
    • Lifecycle: Generated progressively as the sequence grows and finalized once a compression unit is full.
    • Recovery condition: The corresponding compression unit already exists in an accessible storage tier.
    • Hit determination: The compression unit is complete, and its coverage range aligns with the request prefix.

    2. Uncompressed tail

    • Meaning: The most recent tokens that have not yet filled a compression unit and are still kept in raw form.
    • Lifecycle: Continuously written during decoding and merged into compressed KV once the unit is full.
    • Recovery condition: Tail data has been fully written, with no missing pages caused by mid-way eviction.
    • Hit determination: The tail length matches the length recorded in the request.

    3. SWA window

    • Meaning: The raw KV within the recent window required for current computation.
    • Lifecycle: The window advances with the generation position, and data outside the window can be reclaimed.
    • Recovery condition: All raw data within the window range is readable.
    • Hit determination: The window start and end positions exactly match the request positions.

    4. Indexer state

    • Meaning: The index structure used by sparse routing, which determines which historical blocks are read.
    • Lifecycle: Updated in sync with compressed KV.
    • Recovery condition: The index is consistent with the version of the data it points to.
    • Hit determination: The version number recorded in the index matches the corresponding data block.

    5. On-disk prefix

    • Meaning: The prefix portion that has been swapped out to slower storage due to insufficient GPU memory.
    • Lifecycle: Writing is triggered by the eviction policy, and migration back is triggered by request access.
    • Recovery condition: Data has been fully written, and the migration-back path is available.
    • Hit determination: After migration back is complete, the data check passes.

    The table below summarizes the differences among the five states:

    State Main source Recovery concern Common failure cause
    Compressed KV History compression Unit completeness Compression unit not finalized
    Uncompressed tail Recent decoding Length consistency Missing pages caused by mid-way eviction
    SWA window Window advancement Range coverage Window boundary misalignment
    Indexer state Sparse routing Version matching Index and data out of sync
    On-disk prefix Capacity eviction Migration-back completion Write incomplete or check failed

    4. Splitting Responsibilities Between Allocator and Matcher

    Heterogeneous caching requires separating two kinds of actions.

    Allocation action (alloc): Traditionally, the allocator is only responsible for finding a free physical block for new tokens. In heterogeneous scenarios, it must also record the current state label of each token segment, such as “compressing,” “finalized,” or “swapped out.”

    Matching action (prefix match): The matcher returns candidate prefixes by hash, but it cannot simply trust the result. It must check each state involved by that prefix one by one.

    The following is illustrative check logic, used only to explain the idea rather than to represent a specific implementation:

    1. STATES = [
    2. "compressed_kv",
    3. "uncompressed_tail",
    4. "swa_window",
    5. "indexer_state",
    6. "on_disk_prefix",
    7. ]
    8. def check_block(block):
    9. """Check all five states of a cache block and return the first unrecoverable state."""
    10. for state in STATES:
    11. if not block.is_recoverable(state):
    12. return False, state
    13. return True, None
    14. def match_prefix(candidate_blocks):
    15. """Take the contiguous prefix that can be reused directly from candidate blocks."""
    16. usable = []
    17. for block in candidate_blocks:
    18. ok, _ = check_block(block)
    19. if not ok:
    20. break # The prefix must be contiguous; stop at the first unusable block.
    21. usable.append(block)
    22. return usable

    There are two key points here. First, the prefix must be contiguous. If an unusable block appears in the middle, later blocks cannot be used even if their states are normal. Second, the length returned by the matcher may be shorter than the hash-hit length. This is correct behavior and should not be treated as an exception.

    5. Four-Layer Validation: Determining the Usable Hit Length

    A hash hit only gives a candidate length. The truly usable length needs to be shrunk through the following four validation layers in order.

    1. Whole-block alignment

    Different cache groups often have different block sizes. For example, a compression unit has one length, and a physical page has another. Reads and writes can only be performed in whole-block units of their least common multiple (lcm).

    Suppose the compression unit length is 48 and the physical page length is 64. The alignment unit is then lcm(48, 64) = 192. A candidate prefix of length 200 can use only 192 of its tokens.

    2. Kernel interface compatibility (kernel ABI)

    The compute kernel has fixed requirements for input layout. If the cache data layout does not match what the kernel expects, it cannot be read directly even if the values are correct. Therefore, validation needs to confirm that the layout version matches the kernel version.

    3. State intersection across multiple cache groups

    Each cache group has its own longest recoverable prefix. The overall usable length is the intersection of all groups, that is, the shortest one.

    1. def usable_prefix_len(request_len, cache_groups):
    2. # Each group returns its own longest recoverable prefix length.
    3. lens = [g.recoverable_len(request_len) for g in cache_groups]
    4. return min(lens)

    4. Byte-level hardware alignment

    Memory access addresses and strides must satisfy hardware alignment requirements. When they do not, either the layout must be adjusted or the length must be rounded down to an alignable boundary. This step is often the easiest to overlook, but when it goes wrong, the result is usually a silent numerical deviation that is very hard to troubleshoot.

    6. Consistency Constraints: Four Bottom Lines for the Allocator State Machine

    The allocator state machine should satisfy the following constraints at all times.

    1. Admission cap

    Before a new request enters, the required space needs to be estimated under the worst case, including compression intermediates, tail buffers, and window data. Requests exceeding the cap should be queued or rejected rather than failing midway through execution.

    2. Five-state separation

    Different states need different recovery paths. Compressed KV and indexer state need version checks; on-disk prefix needs to wait for migration back; sliding window needs boundary confirmation. Mixing all states into a single “hit/miss” flag causes some recovery paths to be skipped.

    3. Time-of-check-to-time-of-use race (TOCTOU)

    There is a time interval between validation passing and the actual read. During this interval, the block may be evicted or rewritten. Common practices include:

    • Increasing the reference count of validated blocks to prevent reclamation.
    • Before reading, checking the pointers of state data again, for example by recording the addresses of each state buffer and comparing them at read time.
    • When pointers or versions do not match, falling back to recomputation instead of continuing to read.

    4. Static topology constraints of graph capture

    Some inference frameworks record a forward computation as a static graph and then replay it repeatedly to reduce scheduling overhead. Static graphs require fixed tensor addresses. Therefore, the cache pool should be preallocated with stable addresses, and cache scaling should be performed at whole-pool granularity rather than reallocating individual blocks at runtime.

    7. Engineering Recommendations

    1. Include usable hit length in observability metrics. In addition to hash hit rate, record the difference between “hash-hit length” and “validated usable length.” If the difference remains large, it indicates a high invalidation rate for some state, and that state should be identified.

    2. Build test scenarios with cross-layer mixing. Tests should cover the following cases: a prefix crossing a compression unit boundary, a window boundary falling exactly in the middle of a block, a prefix migrated to disk and then migrated back, and concurrent requests contending for the same prefix.

    3. Validate correctness by comparing cached and uncached results. For the same input, run inference with prefix reuse enabled and disabled and compare whether the outputs are consistent. Because floating-point computation has small differences, a reasonable error tolerance should be set during comparison, and attention should be paid to whether systematic bias appears.

    4. Ensure correctness first, then pursue hit rate. When state validation is incomplete, the higher the hit rate, the more incorrect results appear. State tracking and validation should be completed first, and reuse conditions should then be relaxed gradually.

    5. Replace a single hit rate with “effective reuse rate.” Effective reuse rate can be defined as the proportion of the request prefix length that actually participates in computation after validation. This metric reflects both hit efficiency and the impact of correctness constraints.

    Conclusion

    The core question of prefix reuse shifts from “can the cache be found” to “can the found cache be used safely.” When hybrid attention and very long contexts coexist, cache objects coexist in multiple forms. The allocator needs to record the state of each token segment, and the matcher needs to validate each item and shrink the usable length across four dimensions: whole-block alignment, interface compatibility, multi-group intersection, and hardware alignment. Only when all these steps have been validated can a hit result correspond to the correct computation input.