Governance of Heterogeneous KV Cache for Million-Token Contexts

    As hybrid attention breaks the assumptions behind prefix caching, this article explains why high cache hit rates can hide correctness failures in long-context LLM inference. It breaks down five cache object types—compressed KV, uncompressed tail, SWA window, indexer state, and on-disk prefix—along with their lifecycles and recovery conditions, then outlines a four-layer hit validation, a state-machine allocator with consistency constraints, and a practical engineering checklist for stable million-token serving.

    1. The Starting Problem: A Long-Held Assumption Is Failing

    In long-context inference serving, prefix caching is almost a standard capability. Its classic logic is simple: split token history into fixed-size pages, map them to physical cache blocks through a page table, and when a new request shares a prefix with an existing one, reuse the physical blocks directly and skip redundant computation. This mechanism has run reliably in mainstream inference frameworks for a long time and supports many scenarios, including system prompt reuse, multi-turn conversations, and batch document Q&A.

    However, this logic relies on an implicit assumption: attention behavior is homogeneous across layers, and the representation of historical tokens stays consistent throughout its lifecycle. Once a model adopts hybrid attention—where different layers use full-history compression, sliding windows, sparse routing, or other mechanisms—“same prefix” no longer means “cache can be reused directly.”

    It is important to stress that the prefix cache hit rate is not a correctness metric. A high hit rate only means the matching logic is triggered frequently; it does not mean the generated output is correct. Treating hit rate as the primary signal of service health is the most common source of misjudgment in long-context scenarios.

    2. Why Hybrid Attention Breaks the Original Assumption

    A library analogy helps. In a traditional homogeneous model, hitting a cache block is like finding a shelf number and picking up the book directly. Under hybrid attention, a hit requires confirming at least five things:

    1. Whether the book is still on the shelf (whether the compressed history representation is complete);
    2. Whether the latest pages have been bound (whether the uncompressed tail segment is complete);
    3. Whether the borrowing card is still valid (whether the SWA coverage still includes the target position);
    4. Whether the index catalog is in sync (whether the sparse routing state is consistent);
    5. Whether the item has been sent to a suburban warehouse and not yet returned (whether cold data has been written to disk and can be migrated back in time).

    These five things have different lifecycles, recovery conditions, and hit criteria. The rest of this article uses five consistent names: compressed KV, uncompressed tail, SWA window, indexer state, and on-disk prefix.

    Three types of input push cache state into a situation that no single rule can cover: mixing the three attention mechanisms, context length exceeding single-GPU memory capacity, and prefix reuse across requests. When these three overlap, any one-size-fits-all reuse strategy will produce silent errors under specific combinations.

    3. Five Cache Object Types: Lifecycles and Recovery Conditions

    3.1 Compressed KV

    Produced by full-history compression layers, it is characterized by larger block granularity and a strong coupling to the compression ratio and chunking strategy. The recovery condition is that the compressed block must be available as a whole, and the compression parameters must match the current request. Half blocks or cross-version compressed blocks cannot be reused.

    3.2 Uncompressed Tail

    The most recent tokens usually retain original precision to preserve near-field modeling quality. It keeps “sliding out” of the tail region as generation advances, so its effective boundary is dynamic. On recovery, the tail start point must be realigned; otherwise, position misalignment occurs.

    3.3 SWA Window

    Sliding-window layers only attend to history within a fixed window. The window position is determined by sequence length, so the same physical block carries different semantics in requests of different lengths. The recovery condition is that the target position still falls within the window coverage.

    3.4 Indexer State

    Sparse routing depends on index structures (such as selection results, routing tables, and cumulative statistics). This state is often bound to a specific request’s token sequence, making cross-request reuse the riskiest. The recovery condition usually means recomputation rather than a direct read.

    3.5 On-Disk Prefix

    When the context exceeds memory capacity, cold prefixes are swapped out to external storage. A hit does not equal availability: migration bandwidth and latency determine whether recovery can complete within the current request’s scheduling window.

    4. Hit Validation: All Four Layers Are Required

    The hit rate can be misleading because the matching stage only performs hash comparison. To determine whether a hit can really be used to continue computation, at least four layers of validation are needed:

    • Whole-block validation: compressed blocks must be complete; half-block concatenation is forbidden;
    • Interface consistency validation: the version of the compute kernel and the cache layout must match, since layout drift causes misaligned reads;
    • Multi-cache-group intersection validation: hybrid attention involves multiple cache groups, so the intersection of each group’s state must be taken, and if any group is not satisfied, it is treated as a miss;
    • Byte-level alignment validation: when migrating across hardware or precision, alignment and recoverability must be confirmed at byte granularity.

    Illustrative pseudocode:

    1. def try_hit(req, cache):
    2. blk = cache.match(req.prefix_hash) # hash match only
    3. if blk is None:
    4. return Miss()
    5. checks = [
    6. whole_block(blk.compressed), # whole block
    7. abi_compatible(blk.layout_version), # interface consistency
    8. all_group_ready(blk.groups), # multi-group intersection
    9. byte_aligned(blk.device_desc), # byte alignment
    10. ]
    11. if not all(checks):
    12. return Miss(reason=first_failed(checks))
    13. return Hit(recover=plan_recovery(blk, req))

    5. The Allocator: From “Finding a Free Block” to a State Machine

    Once cache objects become heterogeneous, the allocator’s job is no longer only to pick a free block of memory for new tokens; it must also record the current form of each token segment (which of the five types it belongs to and which lifecycle stage it is in). If the parallel matching action still reports a hit based on a single hash, downstream read failures such as “missing tail, missing window, missing routing” will appear.

    Four consistency constraints should be written into the state machine and must not be violated by any path:

    1. Admission cap: set admission thresholds by context length and cache form; requests that exceed the limit are queued or degraded to avoid a single request consuming memory and bandwidth;
    2. Five-type state routing: ingestion, eviction, and migration back each use independent channels; sharing one general path is forbidden;
    3. Timing consistency: prevent state from being modified concurrently between matching and allocation (the check-then-use race), and use an explicit state snapshot pointer to fix the view when necessary;
    4. Static topology constraint: when using graph-capture-based execution optimization, cache addresses and topology must remain static, and dynamic changes must go through an explicit update process.

    6. Engineering Implementation Checklist

    • Rework observability metrics: track hit rate, recovery success rate by type, migration latency, and degradation rate separately; hit rate is no longer treated as evidence of correctness;
    • Correctness regression: build gate tests for three cases—“same prefix, different length,” “cross-version compressed block,” and “window boundary crossing”;
    • Capacity planning: estimate memory and external storage usage for each of the five object types, rather than converting solely by token count;
    • Degradation strategy: when indexer state cannot be recovered, prioritize recomputing locally rather than falling back entirely to the no-cache path;
    • Rollout order: first validate the framework changes on homogeneous-layer models, then gradually enable hybrid attention and on-disk prefix capabilities.

    7. Conclusion

    The real bottleneck in long-context inference is shifting from “how fast it computes” to “whether cache state is managed correctly.” As attention mechanisms move toward hybrid designs, prefix caching must evolve from a single hash rule into an explicit state governance scheme: model the five object types separately, decide hits with four layers of validation, constrain allocation and reclamation with a state machine, and hold the line with four consistency checks. In the practice of inference services on platforms such as Baidu AI Cloud, this state-centric governance approach is a key step in moving million-token contexts from “runs” to “stable and usable.”