← Back to Pull requests

feat(kv-router): cut hybrid matches and hint chains at recurrent state checkpoints #16875

Open
luckyq opened this pull request with 11654 lines diff across 46 files
View on GitHub
luckyq luckyq commented on Oct 20, 2026 05:23 UTC
Author

Overview

Fixes #16794, stacked on #16876. Hybrid routing now credits each worker only through a matching recurrent checkpoint: for example, a worker with two attention blocks but a checkpoint at block one receives one block of reusable credit. Transfer hints and prediction merges respect the same boundary.

Key Changes

High complexity: more than 900 new core lines across the new prefix-evaluation/observer modules alone, excluding tests, documentation, comments and whitespace.

  • Checkpoint table: one 48-byte record per checkpoint hash holds its Device workers once, and its lower-tier owners only while there are any. A filter in front of the records tells a lookup that no needed worker holds a checkpoint at a position; it is rebuilt larger, off the event threads, when Device checkpoints crowd it. During a rebuild a worker's Device checkpoint events update both tables; they wait for it only while it hands over its table, swaps the tables, or reads the directory shard they write.

  • Forward prefix evaluator: take each matched edge from the tree in one call, record the matched (position, hash) chain during one Device traversal and resolve checkpoints once at emission: one read at the bound the surviving workers share, where one comparison of the walk's fingerprint of them with the record's settles them all when the two agree, a downward search for the rest, and a per-worker bit filter that skips positions where no needed worker holds a checkpoint. Final credit respects each worker's actual attention depth and the request limit; there is no second tree walk.

  • General evaluator: record the blocks each tier walk visits and read their checkpoint records after the walk, outside the tree guards. Keeps lower-tier continuation/floor rules and exact transfer-source identity. Presence is read from current per-record state; the publishing worker decides when a checkpoint is complete and sends one event per checkpoint (#16876), so no evaluator looks at groups.

  • Lookup integration: a hybrid worker keeps the score its checkpoints confirm through the side indexer's merge, so rejected hybrid credit cannot reappear. A frontend on a remote indexer knows which workers are hybrid from the layouts they declare; nothing is added to the wire response. With --router-predicted-ttl-secs, a routing decision predicts the routed hybrid worker's checkpoint for as long as the side indexer keeps the decision. A caller that knows the prompt length passes the engine's reusable-block limit through _with_limit lookups; refresh_overlap and LowerTierQueryOptions keep their 1.7 shape. One struct that dynamo_kv_router::compat aliases gains a public field, IndexerQueryRequest::max_reusable_blocks: a 1.7 struct literal needs ..Default::default(), and the deprecations page lists it. Unknown plain-attention workers remain uncapped; registered hybrid workers with missing checkpoints receive no reusable credit.
  • Validation

    | Case | Before | Current result |
    |---|---|---|
    | Attention depth exceeds recurrent checkpoint | Overcredits reusable prefix | Score and hint chain stop at a complete checkpoint. |
    | Side merge or lower-tier continuation | Can retain credit beyond usable state | The side merge skips a worker that declared a hybrid layout, and a lower-tier walk continues from the worker's checkpoint, so the valid boundary holds. |
    | Qwen3.5-4B and Qwen3.5-27B, asymmetric cache, 96 routed requests each | Picked the worker with the usable checkpoint in 50/96 and 42/96 | Picked it in 96/96 and 96/96. |
    | Official GLM-5.3 FP8, MLA attention control | Repeat/extend requests reused 2,048 tokens | Same reuse; no GLM cache-reuse improvement demonstrated. |

    Key tests.

    | Test | Regression it catches |
    |---|---|
    | forward_device_through_the_tree_matches_an_independent_oracle | A wrong resume point from the forward evaluator: 640 workers through the concurrent tree with random checkpoints, DP ranks, dense workers and limits, against an oracle built from the stored data alone. |
    | built_indexer_predicts_the_checkpoint_of_a_routed_hybrid_worker | Predictions off on the frontend: it goes through indexer::build with one and two event threads. |
    | a_prediction_is_read_within_its_lifetime_and_range | A prediction read after its lifetime ends or outside the lookup's range. The table is read at chosen instants, with no sleep. |
    | a_retired_registration_takes_no_prediction | A prediction landing on a registration that was just retired. |
    | a_remote_primary_takes_the_caller_s_hashes_when_no_side_indexer_reads_them | A copy of the request's hashes where main moves them. |
    | bounded_forward_presence_matches_general_caps_and_keeps_dense_coverage | The two evaluators disagreeing under a request limit, or the limit capping a dense worker. |
    | declared_hybrid_workers_keep_a_remote_primary_s_score_through_the_side_merge | Rejected hybrid credit coming back after a side merge on a remote primary. |
    | a_side_score_counts_for_a_worker_whose_layout_is_not_declared_yet | States the one window where it can: before the frontend has reconciled a new worker's layout. |
    | a_crowded_device_filter_is_rebuilt_larger_and_stays_exact, device_filter_rebuilds_lose_no_concurrent_update, a_device_filter_rebuild_keeps_the_changes_made_around_its_walk | A rebuilt Device filter that misses a holder, never clears a slot, or loses an update made before, during or after the rebuild's walk. |
    | forward_device_equal_signature_settles_survivors_without_reading_members | The forward evaluator reading a record's members when its count and fingerprint already equal the survivors'. It also states what a collision does: the worker the record does not hold is credited with the others. |
    | lower_tier_hits_and_hint_sources_are_settled_by_one_pass | A tier's hint sources settled in a second walk, or a worker that has hits and is also a hint's source getting one answer for both ranges. |
    | only_a_worker_s_registration_or_unlisting_replaces_the_snapshot | The worker summaries copied by anything but a worker's registration or unlisting: a checkpoint event, a clear, a cache owner's registration or a repeated declaration. |
    | a_call_that_names_many_ranks_publishes_one_snapshot, a_declaration_of_many_owners_is_one_task_per_lane | A registration or removal pass that copies the worker summaries once per rank, on a remote primary or on a checkpoint lane. |
    | mooncake_routed_open_loop_credits_predicted_checkpoints | The benchmark's predict-on-route mode not reaching predicted checkpoints. |

    Routing on real models. Two TP1 vLLM workers on B200, 96 routed requests per build. In every request both workers match the same attention prefix, and one of them can resume from a deeper checkpoint. Cache hit rate is engine-reported cached prompt tokens over prompt tokens.

    | Model | Build | Picked the usable worker | Cache hit rate | Mean TTFT |
    |---|---|---:|---:|---:|
    | Qwen3.5-4B | main | 50/96 | 44.5% | 43.7 ms |
    | Qwen3.5-4B | this stack | 96/96 | 88.0% | 28.8 ms |
    | Qwen3.5-27B | main | 42/96 | 45.6% | 108.6 ms |
    | Qwen3.5-27B | this stack | 96/96 | 83.3% | 46.9 ms |

    Per scenario, mean TTFT falls 31–40% on 4B and 36–69% on 27B; the gain grows with the shared history that a wrong pick prefills again. With 128 output tokens, per-user output speed on 27B rose from 35.3 to 37.7 tokens/s at one user and did not change at 4 or 8 users, where decode load decides the choice.

    AgentX. Head 0c24db52c (vLLM 0.34.0), 8 TP1 Qwen3.5 workers on GB200, InferenceX AgentX at 256 concurrent sessions, 900 s per run. Both settings run this PR's image on the same nodes. They differ in one switch: whether the workers publish recurrent checkpoints (DYN_VLLM_RECURRENT_KV_EVENTS), which is what lets the router cut a match at a checkpoint. Each setting ran twice, in the order checkpoint-aware, attention-only, attention-only, checkpoint-aware; each cell gives both runs. No request failed.

    | | Checkpoint-aware routing (switch on) | Attention-only routing (switch off) |
    |---|---:|---:|
    | Requests finished | 9,163 and 9,096 | 8,708 and 8,801 |
    | Output tokens per second | 6,269 and 6,236 | 5,948 and 6,048 |
    | Prompt tokens read from cache | 64.07% and 63.76% | 60.95% and 61.95% |
    | Cached tokens the engine reused, of those the router expected | 99.6% and 99.7% | 90.6% and 91.3% |
    | TTFT p50 | 575 ms and 548 ms | 716 ms and 674 ms |
    | TTFT p90 | 2,226 ms and 2,256 ms | 2,430 ms and 2,463 ms |
    | Router lookup per request, mean | 18.5 µs and 20.0 µs | 12.4 µs and 12.2 µs |
    | Router overhead per request, mean | 199 µs and 204 µs | 193 µs and 189 µs |

  • Router lookup and overhead are the means of the frontend's dynamo_router_overhead_indexer_find_matches_ms and dynamo_router_overhead_total_ms histograms over a run.

  • GPU tier only: the deployment has no offload connector. At 512 concurrent sessions an earlier run found no difference between the settings, because TTFT is queue time there.
  • Lookup cost. Mooncake keep-up replay through the router's Indexer on b45bea8fd: 128 workers and 128 query lanes on one 124-vCPU node, jemalloc 5.3.0 preloaded with the frontend's options. Each cell is the ratio of lookup latency to the dense lookup on main in the same job (p50 / p99 / p99.9), paired per repeat, median over repeats. "Dense" means no hybrid worker.

    | Path | Checkpoints | This head against main | p50 on this head |
    |---|---|---|---:|
    | Device only | None (the hybrid gate alone) | 1.15 / 1.13 / 1.15 | 4.5 µs |
    | Device only | End of each stored run | 1.69 / 1.80 / 3.01 | 6.7 µs |
    | Device only | Every block | 1.76 / 1.52 / 1.63 | 7.2 µs |
    | With a host tier | None | 1.34 / 1.14 / 1.11 | 84.9 µs |
    | With a host tier | End of each stored run | 1.72 / 1.31 / 1.24 | 108.0 µs |
    | With a host tier | Every block | 1.63 / 1.18 / 1.15 | 98.1 µs |

  • A dense lookup on this head costs what it costs on main: 1.01 / 1.01 / 0.96 Device only and 0.98 / 1.00 / 0.98 with a host tier (3.9 µs and 63.2 µs on main).

  • Six repeats per cell; four for every block, which needs a longer window to keep up. Every run in the table kept up.

  • "End of each stored run" is the nearest this trace offers to vLLM's default retention. The every-block cells hold 2.1 M live (worker, checkpoint) memberships, about eight per slot of the Device filter, so they run with the filter saturated.

  • The table predates the changes of 2026-12-01 below; the replay behind it has no predict-on-route overlay and no real engine.
  • Lookup cost at 2,048 workers, and with predict-on-route. Same replay and allocator, 48 s window, three interleaved repeats per cell, every run kept up. Lookup latency at p50 / p99 / p99.9. "Before" is a83ab42bc; "after" adds one Device set per checkpoint record, the growing filter and the one-edge observer hook (81ed8e0d9).

    | Workers | Cell | Before | After |
    |---:|---|---|---|
    | 2,048 | Dense | 29.8 / 100 / 142 µs | 29.9 / 101 / 144 µs |
    | 2,048 | Checkpoint at the end of each stored run | 61.9 / 221 / 321 µs | 59.5 / 210 / 296 µs |
    | 2,048 | Same, with a predict-on-route side indexer | 551 / 2,265 / 2,701 µs | 370 / 1,941 / 2,265 µs |
    | 128 | Checkpoint at the end of each stored run | 7.03 / 34.6 / 82.2 µs | 6.79 / 33.1 / 73.6 µs |
    | 128 | Checkpoint on every block | 7.21 / 29.7 / 47.7 µs | 7.13 / 27.7 / 42.4 µs |
    | 128 | End of each stored run, with a host tier | 114.7 / 771 / 1,948 µs | 107.3 / 772 / 1,929 µs |

  • A dense lookup with a side indexer costs 81.6 / 254 / 479 µs at 2,048 workers, so 52 µs of the predict-on-route row at p50 is the side merge that main already does. The same row was 1,251 / 2,171 / 2,940 µs on the head reviewed on 2026-11-30.

  • The Device filter grew from 2^18 to 2^20 slots in the 2,048-worker hybrid cells and to 2^22 with a checkpoint on every block (2.1 M live memberships).

  • The predict-on-route cells do not credit identical work: blocks credited agree to 0.05%, and the lookups that credit any differ by 11%. A slower lookup runs later in a keep-up replay and sees more of the trace.

  • The later cost items (c83781bc9: continuations handed to the lower-tier query, a reserved block index, a guard-based read view) were measured the same way against the commit before them. With a host tier at 128 workers the hybrid lookup went from 106.2 to 100.9 µs at p50 (lower in 3 of 3 pairs) with the tail unchanged; at 2,048 workers nothing moved beyond 2%.

  • Review round 3 (29b170939: one registry probe per candidate on the general path, the walked chain read in place) was measured the same way. With a predict-on-route side indexer at 2,048 workers the lookup went from 382.3 to 360.3 µs at p50 (lower in 3 of 3 pairs), tail unchanged; the 128-worker host-tier cell and the dense cells did not move.

  • The worker summaries are a copy-on-write map again (85d24c4de). 1a5dd542d had moved the registry into maps updated in place, so a lookup took a DashMap shard lock per candidate. Measured the same way against 5204ea23e, the commit before it, at 2,048 workers:
  • | Cell | 5204ea23e | 85d24c4de |
    |---|---|---|
    | Dense | 29.9 / 101 / 145 µs | 29.8 / 98.5 / 136 µs |
    | Checkpoint at the end of each stored run | 136.9 / 412 / 599 µs | 54.6 / 197 / 270 µs |
    | Same, 512-token blocks and a host tier | 705.0 / 1,334 / 1,705 µs | 545.4 / 1,045 / 1,343 µs |
    | Same, with a predict-on-route side indexer | 568.8 / 2,250 / 2,662 µs | 348.3 / 1,964 / 2,263 µs |

    The three hybrid cells are lower in 3 of 3 pairs. The copy is paid by a worker's registration and by its unlisting. On one thread, 2,048 registrations take 67 ms in all and 2,048 removals 140 ms (0.5 ms and 30 ms at 5204ea23e); at 8,192 workers they take 1.07 s and 2.33 s (2 ms and 0.47 s).

  • A call publishes one registry snapshot however many ranks it names, and a worker's summary is one shared allocation (5fbd872f8). The layout reconciler names a pass's ranks in one call, and a checkpoint lane takes its owners as one task. One thread, to register all ranks / to remove them:
  • | Ranks | 85d24c4de, rank by rank | 5fbd872f8, rank by rank | 5fbd872f8, one call |
    |---:|---|---|---|
    | 2,048 | 66.7 ms / 140.0 ms | 23.8 ms / 53.6 ms | 0.40 ms / 0.22 ms |
    | 8,192 | 1,069 ms / 2,339 ms | 368 ms / 891 ms | 2.2 ms / 1.2 ms |

    Lookups, measured the same way against 85d24c4de: p50 is 1.1–4.5% lower in 3 of 3 pairs in each of the four cells, and p99 and p99.9 stay within 4% either way.

  • A rebuild of the Device filter no longer parks the checkpoint events (c72fcd40b, 1bd1a49df). Overloaded replay at 1bd1a49df, 750 ms window, a checkpoint on every block, three runs per row:
  • | Workers | Live Device sets | Rebuilds finished | Time per rebuild | Gate held | Slots at the end | Lanes drained in |
    |---:|---:|---|---:|---:|---:|---:|
    | 128 | 2,096,884 | 4 / 4 / 4 | 196–1,268 ms | 32–60 µs | 2^22 | 78.3–79.2 s |
    | 2,048 | 33,552,289 | 7 / 6 / 7 | 322–5,069 ms | 32–99 µs | 2^25 | 83.3–84.8 s |

    With the gate held for a rebuild's whole walk the lanes drained in 76.7–77.4 s and 78.4–80.6 s, so the drain is 2% and 5% longer: the rebuild shares the directory shards with the events. The overloaded replay does not keep up by design.

  • Host tier, keep-up replay, lookup p50 / p99 before 6aa2a963b and at d9ebc81fb, where one pass per tier settles the workers' hits and the hint sources:
  • | Cell | Before | d9ebc81fb |
    |---|---:|---:|
    | 128 workers, cache owners | 149.9 / 876 µs | 147.6 / 822 µs |
    | 2,048 workers, 512-token blocks | 749.1 / 1,455 µs | 746.5 / 1,456 µs |
    | The same, a checkpoint on every block | 784.9 / 2,978 µs | 784.1 / 2,671 µs |

  • Not measured: predict-on-route on a real engine.
  • The two-worker model numbers were measured on 2026-11-13, before this branch was ported onto the router crate split: c3df5f98e (main) and fe5ec4eb6 (the forward evaluator before the port and the review fixes of 2026-11-17). The per-user speed run used c27ab4401, an earlier commit of this PR that picked the same workers in the routing test. They were not re-measured on the current head; the AgentX blocks ran on 0c24db52c, and each lookup table names the commits it was measured on. Samples are small and fixed, so these are workload-specific observations. The GLM-5.3 row is from an earlier run of this PR (one TP8 worker on eight B200s, 27 requests per arm) and was not repeated.

    Issues and Ongoing Work

  • Fixes #16794; depends on #16876. #19320 (stacked on this PR) and #19400 (stacked on #16876) still use the per-group interface and the paths from before the crates moved under lib/router/; they need the same update. Merge order: #16876 first; this PR is then retargeted to main and takes one more merge of main before it merges. Related: #15555, vllm-project/vllm#62613 and ai-dynamo/kvcr#103.

  • Overlapping work: #18098 adds an opt-in, in-process Device-only checkpoint cap; this stack also carries the event contract, standalone/remote routing, tiered hints and prediction caps. #12169 proposes a broader group taxonomy; this stack implements the restricted vLLM common-unit Mamba contract. #17232 addresses cache-owner group-kind removal safety.

  • MLA attention was already supported before this stack; GLM is the attention control. The demonstrated routing benefit is for Qwen's recurrent checkpoints.

  • Model runs cover Device events with prefill tracking disabled. Default Side and CPU-offload performance on a real engine remain unmeasured; unit/integration coverage does not substitute for live validation of those paths.

  • Presence follows best-effort, per-record freshness rather than a query-wide snapshot. A concurrent removal after a record has been read can affect the next query; no generation certificate or final proof fence is claimed.

  • With a remote indexer, the frontend caps a hybrid worker from the layouts the workers declare. Until it has reconciled a new worker's layout, the side indexer's score counts for that worker as for a dense one.

  • The forward evaluator settles the surviving workers by comparing their count and the walk's 64-bit fingerprint of them with the checkpoint record's. Two different worker sets of one size collide with probability about 2^-64 per comparison, and a collision credits a survivor at a checkpoint it does not hold.

  • No new Rust package dependency is introduced. Further reduction of hybrid lookup overhead remains ongoing.
  • <details>
    <summary>Pull Request Checklist</summary>

  • I used Dynamo's /pr-checklist skill.
  • </details>

    Diff: 11654 lines (+11164 / -490) across 46 files Reviewer: rishabhsinha17 Review duration: 65751m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.79) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.79 · 11654 lines diff across 46 files
    0.79
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    42 items
    copy-pr-bot[bot] copy-pr-bot[bot] commented on Oct 20, 2026 05:23 UTC
    Bot

    This pull request requires additional validation before any workflows can run on NVIDIA's runners.

    Pull request vetters can view their responsibilities here.

    Contributors can view more details about this message here.

    dynamo-review-agent[bot] dynamo-review-agent[bot] commented on code on Oct 20, 2026 05:36 UTC
    Code Review
    lib/kv-router/src/services/indexer/backend.rs:1
    @@ -768,6 +768,16 @@ impl Indexer {
     
         /// Device-tier overlap scores from the primary only (no side-indexer credit).
         async fn find_primary_matches(&self, hashes: Vec<LocalBlockHash>) -> Result<OverlapScores> {
    +        if let Indexer::Single { lower_tier, .. } | Indexer::Concurrent { lower_tier, .. } = self

    This branch cuts only the primary result, but find_matches then passes it to merge_side_or_warn, whose per-worker max can restore a hybrid worker's score beyond its last recurrent-state checkpoint whenever predict-on-route is enabled. The final merged scheduling score must be cut as well.

    <details open><summary>🤖 AI Fix</summary>

    Retain the hash chain through the side-indexer merge, apply KvCacheGroupResidency::cut_device to the merged MatchDetails, and only then discard the chain and return the scores.

    </details>

    <!-- ai-fix: Retain the hash chain through the side-indexer merge, apply KvCacheGroupResidency::cut_device to the merged MatchDetails, and only then discard the chain and return the scores. -->

    dynamo-review-agent[bot] dynamo-review-agent[bot] commented on code on Oct 20, 2026 05:36 UTC
    Code Review
    lib/kv-router/src/services/indexer/backend.rs:1
    @@ -1047,6 +1057,125 @@ mod tests {
             );
         }
     
    +    /// A hybrid worker's attention chain matches 3 blocks but its recurrent
    +    /// group only checkpointed block 1: the tiered match and the hint chain
    +    /// must stop at block 1, while a dense worker keeps its full match.
    +    #[tokio::test]
    +    async fn recurrent_group_presence_cuts_tiered_match_and_hint_chain() {
    +        use crate::indexer::LowerTierQueryOptions;
    +        use crate::kv_hints::KvTransferCandidateSource;
    +        use crate::protocols::{
    +            ExternalSequenceBlockHash, KvCacheGroupKind, KvCacheGroupTag, KvCacheStoreData,
    +            KvCacheStoredBlockData, compute_seq_hash_for_block,
    +        };
    +
    +        let indexer = create_indexer(4, 1);
    +        let hybrid = WorkerWithDpRank::new(7, 0);
    +        let dense = WorkerWithDpRank::new(8, 0);
    +        let local = [11_u64, 12, 13];
    +        for (event_id, worker) in [(1, hybrid), (2, dense)] {
    +            indexer
    +                .apply_event_routed(store_event(
    +                    worker.worker_id,
    +                    worker.dp_rank,
    +                    event_id,
    +                    &[],
    +                    &local,
    +                    StorageTier::Device,
    +                ))
    +                .await
    +                .unwrap();
    +        }
    +        let chain: Vec<u64> = compute_seq_hash_for_block(
    +            &local
    +                .iter()
    +                .copied()
    +                .map(LocalBlockHash)
    +                .collect::<Vec<_>>(),
    +        );
    +        // Recurrent group 1 of the hybrid worker has a state at block 1 only.

    This setup comment restates the values directly below it: group_idx: 1 and a one-element block vector built from chain[0]. The test-level documentation already explains why this setup matters.

    <details open><summary>🤖 AI Fix</summary>

    Delete this redundant setup comment.

    </details>

    <!-- ai-fix: Delete this redundant setup comment. -->

    dynamo-review-agent[bot] dynamo-review-agent[bot] commented on code on Oct 20, 2026 05:36 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,81 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// Device match with hybrid workers cut to their last complete boundary.

    This sentence only expands cut_primary_match_details and the immediately visible residency.cut_device call. The following two lines contain the useful, non-obvious reason for retaining and later dropping the hash chain, so keep those.

    <details open><summary>🤖 AI Fix</summary>

    Remove the first doc-comment line and retain the hash-chain retention explanation.

    </details>

    <!-- ai-fix: Remove the first doc-comment line and retain the hash-chain retention explanation. -->

    dynamo-review-agent[bot] dynamo-review-agent[bot] commented on code on Oct 20, 2026 05:36 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,19 +258,30 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    +                if let Some(residency) = self.group_residency() {
    +                    residency.cut_device(&mut primary_device);
    +                }
    +                let mut lt = query_lower_tiers_with_options(
                         lower_tier,
                         sequence.as_slice(),
                         &primary_device,
    -                    lower_tier_options,
    +                    LowerTierQueryOptions {
    +                        retain_kv_transfer_chain: retain_kv_transfer_chain || cut,
    +                    },
                     );
    +                self.cut_lower_tiers(&primary_device, &mut lt, retain_kv_transfer_chain);
    +                if cut && !retain_kv_transfer_chain {

    When use_kv_events=true and router_predicted_ttl_secs enables the supported predict-on-route side indexer, this drops the retained chain immediately after cutting the event-driven primary, but the following merge_side_or_warn takes the per-worker maximum. A stale/predicted score deeper than a hybrid worker's last recurrent checkpoint therefore restores the over-large device score, so both tiered scheduling and plain find_matches can again route on an unusable prefix (the added test misses this because approx is None). Keep the chain through the side merge and apply cut_device to the merged scores before optionally dropping it; preserve the primary-only cut for seeding lower tiers.

    <details open><summary>🤖 AI Fix</summary>

    Retain the primary hash chain through side-score merging, reapply recurrent-residency cutting to the merged device details, and only then discard the chain when the caller did not request it.

    </details>

    <!-- ai-fix: Retain the primary hash chain through side-score merging, reapply recurrent-residency cutting to the merged device details, and only then discard the chain when the caller did not request it. -->

    dynamo-review-agent[bot] dynamo-review-agent[bot] commented on code on Oct 20, 2026 05:36 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,19 +258,30 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    +                if let Some(residency) = self.group_residency() {
    +                    residency.cut_device(&mut primary_device);
    +                }
    +                let mut lt = query_lower_tiers_with_options(
                         lower_tier,
                         sequence.as_slice(),
                         &primary_device,
    -                    lower_tier_options,
    +                    LowerTierQueryOptions {
    +                        retain_kv_transfer_chain: retain_kv_transfer_chain || cut,
    +                    },
                     );
    +                self.cut_lower_tiers(&primary_device, &mut lt, retain_kv_transfer_chain);
    +                if cut && !retain_kv_transfer_chain {

    With the supported use_kv_events=true plus router_predicted_ttl_secs configuration, a predict-on-route side indexer coexists with recurrent-group residency. This drops the retained chain immediately after cutting the primary score, and the following merge_side_or_warn can raise that hybrid worker's device score back to the side indexer's uncut value. Requests can therefore still be routed and credited past the last resumable recurrent checkpoint. Keep enough chain information to constrain the merged score, or prevent side credit from raising a tracked hybrid worker above its confirmed recurrent boundary; the plain find_match_details path needs the same ordering fix.

    <details open><summary>🤖 AI Fix</summary>

    Apply recurrent-group residency constraints to the final primary-plus-side device score before discarding the retained chain, including the plain lookup path.

    </details>

    <!-- ai-fix: Apply recurrent-group residency constraints to the final primary-plus-side device score before discarding the retained chain, including the plain lookup path. -->

    rishabhsinha17 rishabhsinha17 commented on code on Oct 26, 2026 03:03 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,90 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<MatchDetails, KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        if let Some(residency) = residency {
    +            residency.cut_device(&mut details);
    +        }
    +        Ok(details)
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint. Drops the chain unless hints were requested.
    +    fn finish_device_cut(&self, details: &mut MatchDetails, retain_kv_transfer_chain: bool) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device(details);

    Verified gap. The first cut removes a hybrid owner that has no state on the matched prefix and, with it, the retained chain, since cut_device sets kv_transfer_candidates to None (kv_cache_groups.rs:203). The side merge then re-adds that worker at the side depth and this second cut returns early with no chain. Local test, your side-merge test with the state moved to a hash off the prefix: find_primary_match_details drops the worker, while find_matches_by_tier, find_match_details and find_matches all give 3. Capturing the primary chain before the first cut and passing it here closes it.

    rishabhsinha17 rishabhsinha17 commented on code on Oct 26, 2026 03:03 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,90 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<MatchDetails, KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        if let Some(residency) = residency {
    +            residency.cut_device(&mut details);
    +        }
    +        Ok(details)
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint. Drops the chain unless hints were requested.
    +    fn finish_device_cut(&self, details: &mut MatchDetails, retain_kv_transfer_chain: bool) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device(details);
    +            if !retain_kv_transfer_chain {
    +                details.kv_transfer_candidates = None;
    +            }
    +        }
    +    }
    +
         async fn find_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    -        if self.side.is_none() {
    +        if self.side.is_none() && self.group_residency().is_none() {
                 return self.find_primary_match_details(sequence).await;
             }
     
    -        let primary_details = self.primary.find_match_details_retained(&sequence).await?;
    -        Ok(merge_side_or_warn(self.side, primary_details, sequence).await)
    +        let primary_details = self.cut_primary_match_details(&sequence).await?;
    +        let mut merged = merge_side_or_warn(self.side, primary_details, sequence).await;
    +        self.finish_device_cut(&mut merged, false);
    +        Ok(merged)
         }
     
         async fn find_primary_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    +        if self.group_residency().is_some() {
    +            let mut details = self.cut_primary_match_details(&sequence).await?;
    +            self.finish_device_cut(&mut details, false);
    +            return Ok(details);
    +        }
             self.primary.find_match_details(sequence).await
         }
     
    +    fn cut_lower_tiers(
    +        &self,
    +        device: &MatchDetails,
    +        lower_tier: &mut HashMap<StorageTier, LowerTierMatchDetails>,
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        let Some(residency) = self.group_residency() else {
    +            return;
    +        };
    +        let device_chain: Vec<_> = device
    +            .kv_transfer_candidates
    +            .as_ref()
    +            .map(|candidates| candidates.block_hashes.clone())
    +            .unwrap_or_default();
    +        for details in lower_tier.values_mut() {
    +            residency.cut_lower_tier(details, &device_chain);

    Verified gap. query_lower_tiers_with_options retains the lower-tier chain for HostPinned only (lower_tier_indexers.rs:346), so for Disk and External cut_lower_tier falls back to the device chain and skips the worker at its end > chain.len() check (kv_cache_groups.rs:239). Local test with device blocks 1 and 2, tier blocks 3 and 4 and a state at block 2 only: HostPinned hits cut to 0, Disk 2, External 2. Either retain the chain for every tier while residency is active, or cut an unverifiable extension to its continuation start instead of skipping it.

    rishabhsinha17 rishabhsinha17 commented on code on Oct 26, 2026 03:03 UTC
    Code Review
    lib/router/kv-indexer/src/backend.rs:1
    @@ -1130,6 +1137,124 @@ mod tests {
             }
         }
     
    +    /// A hybrid worker's attention chain matches 3 blocks but its recurrent
    +    /// group only checkpointed block 1: the tiered match and the hint chain
    +    /// must stop at block 1, while a dense worker keeps its full match.
    +    #[tokio::test]
    +    async fn recurrent_group_presence_cuts_tiered_match_and_hint_chain() {

    Ingress-fed variant of our fixture, in case it is useful. It is the one path that exercises filter_reason, the tag and the cut together, and it passes here with 3 and 3 without the checkpoint event and 1 and 1 with it.

        #[tokio::test]
        async fn recurrent_group_presence_cuts_match_fed_through_ingress() {
            use crate::indexer::LowerTierQueryOptions;
            use crate::protocols::{BlockHashOptions, compute_block_hash_for_seq};
            use crate::zmq_wire::{BlockHashValue, KvCacheSpecKind, RawKvEvent, ZmqEventNormalizer};
    
            async fn overlap_and_hint(with_checkpoint: bool) -> (Option<u32>, usize) {
                let block_size = 2u32;
                let tokens: Vec<u32> = (10..16).collect();
                let worker = WorkerWithDpRank::new(3, 0);
                let stored = |hashes: Vec<u64>, token_ids: Vec<u32>, group_idx: u32, kind| {
                    RawKvEvent::BlockStored {
                        block_hashes: hashes.into_iter().map(BlockHashValue::Unsigned).collect(),
                        parent_block_hash: None,
                        token_ids,
                        block_size: block_size as usize,
                        medium: None,
                        lora_name: None,
                        cache_namespace: None,
                        block_mm_infos: None,
                        is_eagle: None,
                        group_idx: Some(group_idx),
                        kv_cache_spec_kind: Some(kind),
                        kv_cache_spec_sliding_window: None,
                        locality: None,
                        ownership: None,
                        session_id: None,
                    }
                };
                // Qwen3.5 order: attention is group 3, the GDN groups come first.
                let mut raws = vec![stored(vec![11, 12, 13], tokens.clone(), 3, KvCacheSpecKind::FullAttention)];
                if with_checkpoint {
                    raws.push(stored(vec![11], tokens[..2].to_vec(), 0, KvCacheSpecKind::Mamba));
                }
                let indexer = create_indexer(block_size, 1);
                let mut normalizer = ZmqEventNormalizer::new(block_size);
                for (i, raw) in raws.into_iter().enumerate() {
                    let raw = normalizer.preprocess_with_reason(raw, worker).expect("kept at ingress");
                    let event = normalizer
                        .normalize_preprocessed(raw, i as u64 + 1, worker)
                        .expect("converts")
                        .into_router_event()
                        .expect("router event");
                    indexer.apply_event_routed(event).await.unwrap();
                }
                if let Indexer::Single { primary, .. } = &indexer {
                    let _ = primary.flush().await;
                }
                let sequence = compute_block_hash_for_seq(&tokens, block_size, BlockHashOptions::default());
                let tiered = indexer
                    .find_tiered_matches_with_options(
                        sequence,
                        LowerTierQueryOptions { retain_kv_transfer_chain: true },
                    )
                    .await
                    .unwrap();
                let overlap = tiered.device.overlap_scores.scores.get(&worker).copied();
                let hint = tiered
                    .device
                    .kv_transfer_candidates
                    .as_ref()
                    .and_then(|candidates| candidates.best_source(0, |_| true))
                    .map(|(_, hashes)| hashes.len())
                    .unwrap_or(0);
                (overlap, hint)
            }
    
            assert_eq!(overlap_and_hint(false).await, (Some(3), 3));
            assert_eq!(overlap_and_hint(true).await, (Some(1), 1));
        }
    

    rishabhsinha17 rishabhsinha17 commented on Oct 26, 2026 03:03 UTC
    Reviewer

    I am leaving a comment rather than an approval. The cut rule is right and our acceptance fixture passes, but two paths still score past the checkpoint. The project needs this because #16876 only records state presence. Without the cut a hybrid worker is still scored and hinted by attention depth, the over-transfer measured in #16794.

    Ran at df2492c6. cargo fmt check is clean and the dynamo-kv-router lib tests with standalone-indexer, standalone-selection and metrics give 1373 passed, 0 failed, 3 ignored. Dense-only deployments take the old branches, since the residency table only activates after a tagged event.

    Our two-group fixture from the Oct 20 comment, fed through ZmqEventNormalizer into apply_event_routed, scores overlap 1 and hint 1, against 3 and 3 without the checkpoint event. Main gave 3 and 3 either way. I posted it inline on your end-to-end test.

    Each remaining gap has a local test, inline.

    rishabhsinha17 rishabhsinha17 commented on Nov 02, 2026 01:00 UTC
    Contributor

    @luckyq I can take the two remaining gaps off your plate if that gets this pair merged sooner. The side-merge chain fix and the lower-tier cut fix from my October 26 review are ready to go as commits on this branch or as a follow-up PR. Our acceptance fixture passes at df2492c6 either way.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Nov 05, 2026 07:48 UTC
    Bot

    <!-- dynamo-ci-report -->
    <!-- dynamo-ci-report-run: 47383673361-1 -->

    ✅ Dynamo PR CI passed — run 47383673361 (attempt 1) on 33e443c1f2

    Gate checks: ✅ backend-status-check · ✅ deploy-status-check · ✅ dynamo-status-check

    <sub>Posted automatically by Devin for run 47383673361. Updated on every full-CI run of this PR.</sub>

    PeaBrane PeaBrane commented on code on Nov 05, 2026 17:59 UTC
    Code Review
    lib/kv-router/src/indexer/kv_cache_groups.rs:1
    @@ -240,13 +248,11 @@ impl KvCacheGroupResidency {
                     continue;
                 };
                 let start = end - *hits;
    -            if end > chain.len() {
    -                // The chain does not cover this tier's extension (device
    -                // candidates were truncated below it): nothing to verify.
    -                continue;
    -            }
    -            if let Some(p) = self.reusable_blocks(*worker, &chain, end)
    -                && p < end
    +            // Positions past the chain cannot be verified against the
    +            // presence table; a hybrid worker's hits there are not credited.
    +            let verifiable = end.min(chain.len());

    This can panic when lower tiers chain (Host then Disk/External):
    1. For Disk/External the chain is the device chain plus only that tier's own extensions.
    2. Extension positions are absolute and start at the Host end, so the splice above breaks at the gap.
    3. start = end - hits can then exceed chain.len(), p.max(start) is pushed as the cut, and chain[*p - 1] in the continuation below indexes past the end.

    Example: a hybrid worker has device blocks 1–2 (state at 2), Host 3–4 and Disk 5–6, and no worker has a deeper device match. The device chain length is 2. For Disk, end = 6, hits = 2, start = 4, and reusable_blocks(.., 2) = 2, so the cut is (W, 4), and chain[3] is read from a length-2 chain.

    With an empty device chain, the early return at L236 instead leaves Disk hits uncut.

    Suggestion: build one cumulative chain (device, then Host extensions, then Disk, …), pass it from tier to tier, and never index past chain.len().

    PeaBrane PeaBrane commented on code on Nov 05, 2026 17:59 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +169,105 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints. Returns the full primary chain as
    +    /// it was before the cut: the cut truncates or drops the retained one,
    +    /// and the later side-merge cut and lower-tier cuts are keyed by it.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<(MatchDetails, Vec<ExternalSequenceBlockHash>), KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        let chain = details
    +            .kv_transfer_candidates
    +            .as_ref()
    +            .map(|candidates| candidates.block_hashes.clone())
    +            .unwrap_or_default();
    +        if let Some(residency) = residency {
    +            residency.cut_device_with_chain(&mut details, &chain);
    +        }
    +        Ok((details, chain))
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint, or re-add one the first cut dropped. Keyed
    +    /// by the pre-cut primary chain. Drops the chain unless hints were
    +    /// requested.
    +    fn finish_device_cut(
    +        &self,
    +        details: &mut MatchDetails,
    +        primary_chain: &[ExternalSequenceBlockHash],
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device_with_chain(details, primary_chain);
    +            if !retain_kv_transfer_chain {
    +                details.kv_transfer_candidates = None;
    +            }
    +        }
    +    }
    +
         async fn find_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    -        if self.side.is_none() {
    +        if self.side.is_none() && self.group_residency().is_none() {
                 return self.find_primary_match_details(sequence).await;
             }
     
    -        let primary_details = self.primary.find_match_details_retained(&sequence).await?;
    -        Ok(merge_side_or_warn(self.side, primary_details, sequence).await)
    +        let (primary_details, chain) = self.cut_primary_match_details(&sequence).await?;
    +        let mut merged = merge_side_or_warn(self.side, primary_details, sequence).await;
    +        self.finish_device_cut(&mut merged, &chain, false);
    +        Ok(merged)
         }
     
         async fn find_primary_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    +        if self.group_residency().is_some() {
    +            let (mut details, chain) = self.cut_primary_match_details(&sequence).await?;
    +            self.finish_device_cut(&mut details, &chain, false);
    +            return Ok(details);
    +        }
             self.primary.find_match_details(sequence).await
         }
     
    +    /// Cut every lower tier against the pre-cut device chain. Extensions were
    +    /// retained for the cut only; tiers other than HostPinned never expose
    +    /// them, and HostPinned's merged hint chain follows the caller's request.
    +    fn cut_lower_tiers(
    +        &self,
    +        device_chain: &[ExternalSequenceBlockHash],
    +        lower_tier: &mut HashMap<StorageTier, LowerTierMatchDetails>,
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        let Some(residency) = self.group_residency() else {
    +            return;
    +        };
    +        for (tier, details) in lower_tier.iter_mut() {
    +            residency.cut_lower_tier(details, device_chain);

    Each tier is cut independently, which can leave a gapped prefix. Example: with a state only at block 6 on Disk (device 1–2, Host 3–4, Disk 5–6), Host is cut to 0 hits while Disk keeps 2, and scheduling/overlap.rs (~313-314) sums device + host + disk as one contiguous prefix.

    A joint cut per worker would avoid both this and the panic in cut_lower_tier: take the rightmost P on the cumulative chain up to the last tier's end, then set each tier's hits to clamp(P - start_t, 0, hits_t).

    PeaBrane PeaBrane commented on code on Nov 05, 2026 17:59 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,20 +283,46 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    -                    lower_tier,
    -                    sequence.as_slice(),
    -                    &primary_device,
    -                    lower_tier_options,
    -                );
    -                let device = merge_side_or_warn(self.side, primary_device, sequence).await;
    +                let primary_chain: Vec<ExternalSequenceBlockHash> = primary_device
    +                    .kv_transfer_candidates
    +                    .as_ref()
    +                    .map(|candidates| candidates.block_hashes.clone())
    +                    .unwrap_or_default();
    +                if let Some(residency) = self.group_residency() {
    +                    residency.cut_device_with_chain(&mut primary_device, &primary_chain);
    +                }
    +                let options = LowerTierQueryOptions {
    +                    retain_kv_transfer_chain: retain_kv_transfer_chain || cut,
    +                };
    +                let mut lt = if cut {
    +                    // Every tier keeps its extensions so its hits can be
    +                    // verified against the presence table, not just HostPinned.
    +                    query_lower_tiers_retaining_extensions(
    +                        lower_tier,
    +                        sequence.as_slice(),
    +                        &primary_device,
    +                        options,
    +                    )
    +                } else {
    +                    query_lower_tiers_with_options(
    +                        lower_tier,
    +                        sequence.as_slice(),
    +                        &primary_device,
    +                        options,
    +                    )
    +                };
    +                self.cut_lower_tiers(&primary_chain, &mut lt, retain_kv_transfer_chain);
    +                let mut device = merge_side_or_warn(self.side, primary_device, sequence).await;
    +                self.finish_device_cut(&mut device, &primary_chain, retain_kv_transfer_chain);

    The re-cut after the side merge is keyed by the deepest primary chain, so its result depends on other workers:

  • If any worker matches a shared prefix (e.g. a common system prompt), the just-routed hybrid worker is cut to that depth. That effectively turns predict-on-route off for hybrid models.

  • If no worker has a primary match, the chain is empty, cut_device_with_chain returns early (kv_cache_groups.rs:172), and the side credit stands uncut.
  • Cutting against the request's own chain would make this consistent. For exact repeats both outcomes are arguably too strict: the engine keeps a state at the prompt's last full-block boundary, so the side indexer could also predict a state at its predicted end.

    PeaBrane PeaBrane commented on code on Nov 05, 2026 17:59 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +169,105 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints. Returns the full primary chain as
    +    /// it was before the cut: the cut truncates or drops the retained one,
    +    /// and the later side-merge cut and lower-tier cuts are keyed by it.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<(MatchDetails, Vec<ExternalSequenceBlockHash>), KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        let chain = details
    +            .kv_transfer_candidates
    +            .as_ref()
    +            .map(|candidates| candidates.block_hashes.clone())
    +            .unwrap_or_default();
    +        if let Some(residency) = residency {
    +            residency.cut_device_with_chain(&mut details, &chain);
    +        }
    +        Ok((details, chain))
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint, or re-add one the first cut dropped. Keyed
    +    /// by the pre-cut primary chain. Drops the chain unless hints were
    +    /// requested.
    +    fn finish_device_cut(

    finish_device_cut isn't reached on the remote-primary branch. With Indexer::Remote plus a side indexer (built in lib/llm/src/kv_router/indexer/mod.rs), merge_side_or_warn at L354 takes the per-worker max over the remote's already-cut scores, and nothing cuts again locally, because the caller has no presence table. That's the same lift this PR fixes for local primaries.

    Two ways to close it: carry a per-worker hybrid cap in WireTieredMatchDetails, or don't let the side merge raise workers the remote marked as hybrid.

    PeaBrane PeaBrane commented on code on Nov 05, 2026 17:59 UTC
    Code Review
    lib/kv-router/src/indexer/kv_cache_groups.rs:1
    @@ -304,10 +289,52 @@ impl KvCacheGroupResidency {
         }
     }
     
    +/// Apply per-source cuts to a retained hint chain: owners cut to 0 are
    +/// dropped, the rest are capped, suffix intervals past a source's cut are
    +/// dropped, and the chain is truncated to the deepest surviving coverage.
    +/// Returns true when nothing is left and the caller should drop the chain.
    +fn cut_candidates(
    +    candidates: &mut KvTransferCandidates,
    +    cuts: &[(WorkerWithDpRank, usize)],
    +) -> bool {
    +    let cut_sources: FxHashMap<KvTransferCandidateSource, usize> = cuts
    +        .iter()
    +        .map(|(worker, p)| (KvTransferCandidateSource::from(*worker), *p))
    +        .collect();
    +    candidates
    +        .owner_prefix_blocks
    +        .retain_mut(|(source, blocks)| match cut_sources.get(source) {
    +            Some(0) => false,
    +            Some(p) => {
    +                *blocks = *p;

    blocks = p can raise an owner's prefix in the second (post-merge) cut. If the side merge lifted a worker's score past its attention depth and a state exists beyond that depth (a floating vLLM state, or a lower-tier state), p lands above the owner's current blocks, and the hint advertises device blocks the worker doesn't hold.

    Example: attention 3, states at 2 (device) and 6 (CPU), side score 8. The owner prefix goes from 2 to 6. Using blocks = (blocks).min(*p) would prevent this.

    PeaBrane PeaBrane commented on Nov 05, 2026 17:59 UTC
    Reviewer

    Reviewed at d1c71f4 (vLLM main @ 30cff7b for engine behavior).

    The cut rule matches vLLM's hybrid hit: a contiguous attention hit, then the rightmost state in every Mamba group at or below it. Inline findings:

  • A panic in cut_lower_tier when tiers chain (Host then Disk or External).

  • Per-tier cuts that don't compose into one contiguous prefix.

  • A side-merge re-cut that depends on other workers' matches.

  • The remote primary + side path, which is never re-cut.
  • Design suggestion (common cause). Most of these come from two things:

  • The cut is applied at several stages, each with its own chain: device, each tier, after the side merge, and not at all on the remote path.

  • The engine model is implicit: a state on any tier counts for the device cut, and tiers are re-seeded from the cut.
  • One evaluator would remove the panic/gap class and the side-merge ordering issues together. It would run once, as the last stage of every lookup path, over one cumulative chain (the device chain, then each tier's extensions in order), and split credit per tier from a single cut point P.

    Its engine-specific parts fit naturally in the worker-published group layout already listed as follow-up work:

  • which tiers' states count toward which tier's credit;

  • the num_tokens - 1 cap, the EAGLE drop, and alignment;

  • a predicted state at the predicted prompt end, for the side indexer.
  • Sliding window. If each group carries a validity window k, sliding-window groups become the same predicate (all of chain[p-k..p) present in every group), so they don't need to stay dropped:

  • Mamba: k = 1.

  • Sliding window: k = cdiv(window - 1, block_size), +1 with EAGLE, matching vLLM's _contiguous_blocks_for_hit.
  • The wire already carries kv_cache_spec_sliding_window. vLLM's offload tier still emits placeholders for windowed groups, so that side needs a follow-up to vllm-project/vllm#62613.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/router/kv-indexer/src/lookup.rs:1
    @@ -166,25 +169,105 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {

    Every lookup now takes the residency table's process-wide std::sync::RwLock about 9 + 2W + ΣW_tier times: is_active() through group_residency() at each stage, and reusable_blocks() once per worker per cut (kv_cache_groups.rs:178, :254). Each acquisition is two atomic writes to one cache line shared by every routing thread, and std's lock makes readers wait behind a waiting writer, so lookups stall behind apply() on every tagged event.

    Read group_residency() once per lookup, back is_active() with an AtomicBool, and take one read guard per cut. Dense deployments still pay 4 acquisitions per lookup just for the gate.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/indexer/lower_tier_indexers.rs:1
    @@ -352,17 +381,19 @@ pub fn query_lower_tiers_with_options_and_snapshot(
                 }
             }
     
    -        let retain_kv_transfer_chain =
    +        let merge_hint_chain =
                 options.retain_kv_transfer_chain && storage_tier == StorageTier::HostPinned;
    +        let retain_extensions = merge_hint_chain

    With the cut active, retain_kv_transfer_chain is forced to true (lookup.rs:304), so HostPinned runs merge_kv_transfer_tier_candidates on every lookup (device chain clone + owner map). cut_lower_tier clones that again at kv_cache_groups.rs:220, and it's dropped when hints weren't requested. cut_lower_tier splices the extensions itself now, so pass the caller's flag through and use retain_extensions = merge_hint_chain || retain_extensions_for_every_tier.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,20 +283,46 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    -                    lower_tier,
    -                    sequence.as_slice(),
    -                    &primary_device,
    -                    lower_tier_options,
    -                );
    -                let device = merge_side_or_warn(self.side, primary_device, sequence).await;
    +                let primary_chain: Vec<ExternalSequenceBlockHash> = primary_device
    +                    .kv_transfer_candidates
    +                    .as_ref()
    +                    .map(|candidates| candidates.block_hashes.clone())

    The chain is copied on every lookup: here, and again per tier in cut_lower_tier (device_chain.to_vec()) to splice. When hints weren't requested, take() the candidates instead of cloning. In cut_lower_tier, read positions from device_chain then extensions rather than building a Vec per tier.

    jthomson04 jthomson04 commented on Nov 05, 2026 18:14 UTC
    Reviewer

    Performance pass at d1c71f4. The cut runs once per request on the selection path (services/selection/core/run.rs:735 → find_matches_by_tier). One must-fix on the residency lock, a few smaller per-lookup costs, and three nits, inline.

    Do you have before/after numbers for the hybrid case? A Criterion bench on find_tiered_matches_ref_with_options with N hybrid workers sharing a prefix, at 1 and 16 threads, would show both the lock cost and the cost of the cut passes.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/indexer/kv_cache_groups.rs:1
    @@ -240,13 +248,11 @@ impl KvCacheGroupResidency {
                     continue;
                 };
                 let start = end - *hits;
    -            if end > chain.len() {
    -                // The chain does not cover this tier's extension (device
    -                // candidates were truncated below it): nothing to verify.
    -                continue;
    -            }
    -            if let Some(p) = self.reusable_blocks(*worker, &chain, end)
    -                && p < end
    +            // Positions past the chain cannot be verified against the
    +            // presence table; a hybrid worker's hits there are not credited.
    +            let verifiable = end.min(chain.len());
    +            if let Some(p) = self.reusable_blocks(*worker, &chain, verifiable)

    reusable_blocks scans down to position 1, but the result is clamped to start. A hybrid worker with no state in (start, end] walks the whole device prefix again for each tier. Pass start as a floor.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/indexer/kv_cache_groups.rs:1
    @@ -150,20 +150,32 @@ impl KvCacheGroupResidency {
         /// Needs the retained root-aligned chain (`kv_transfer_candidates`); without
         /// it the scores are left as they are.
         pub fn cut_device(&self, details: &mut MatchDetails) {

    nit: cut_device is only used by tests now. Drop it and have the tests call cut_device_with_chain.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,20 +283,46 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();

    nit: find_matches_by_tier and find_primary_matches_by_tier repeat the same steps (retained lookup, clone, cut, lower tiers, cut, finish), including the if cut { retaining } else { with_options } fork. One helper would cover both.

    jthomson04 jthomson04 commented on code on Nov 05, 2026 18:14 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -876,6 +1003,276 @@ mod tests {
             );
         }
     
    +    /// The predict-on-route side indexer credits a hybrid worker with the full
    +    /// attention prefix; the merge takes the maximum, so the cut has to be
    +    /// re-applied after it.
    +    #[tokio::test]
    +    async fn side_merge_does_not_lift_hybrid_worker_above_its_checkpoint() {
    +        use crate::protocols::{
    +            ExternalSequenceBlockHash, KvCacheEvent, KvCacheEventData, KvCacheGroupKind,
    +            KvCacheGroupTag, KvCacheStoreData, KvCacheStoredBlockData, RouterEvent,
    +        };
    +
    +        let primary = Arc::new(ThreadPoolIndexer::new(
    +            ConcurrentRadixTreeCompressed::new(),
    +            2,
    +            4,
    +        ));
    +        let side = Arc::new(ThreadPoolIndexer::new_with_pruning(
    +            ConcurrentRadixTreeCompressed::new(),
    +            1,
    +            4,
    +            PruneConfig {
    +                ttl: Duration::from_secs(60),
    +            },
    +        ));
    +        let side_for_flush = side.clone();
    +        let indexer = Indexer::Concurrent {
    +            primary,
    +            lower_tier: LowerTierIndexers::new(2, 4),
    +            approx: Some(super::SideIndexer::Concurrent(side)),
    +            primary_records_routing_decisions: false,
    +            session_updates: None,
    +        };
    +        let hybrid = WorkerWithDpRank::new(10, 0);
    +        let local = [11_u64, 12, 13];
    +        indexer
    +            .try_apply_event(store_event(10, 0, 1, &[], &local, StorageTier::Device))
    +            .await
    +            .unwrap();
    +        let block_hashes: Vec<LocalBlockHash> = local.iter().copied().map(LocalBlockHash).collect();
    +        let chain = compute_seq_hash_for_block(&block_hashes);
    +        indexer
    +            .try_apply_event(
    +                RouterEvent::with_storage_tier(
    +                    10,
    +                    KvCacheEvent {
    +                        event_id: 2,
    +                        data: KvCacheEventData::Stored(KvCacheStoreData {
    +                            parent_hash: None,
    +                            start_position: None,
    +                            blocks: vec![KvCacheStoredBlockData {
    +                                block_hash: ExternalSequenceBlockHash(chain[0]),
    +                                tokens_hash: LocalBlockHash(local[0]),
    +                                mm_extra_info: None,
    +                            }],
    +                        }),
    +                        dp_rank: 0,
    +                    },
    +                    StorageTier::Device,
    +                )
    +                .with_kv_cache_group(KvCacheGroupTag {

    nit: this Mamba RouterEvent::with_storage_tier(..).with_kv_cache_group(..) literal appears four times at about 25 lines each. A recurrent_store(worker, hash, local) helper in test_util would remove most of that.

    luckyq luckyq commented on code on Nov 16, 2026 20:19 UTC
    Code Review
    lib/kv-router/src/services/indexer/backend.rs:1
    @@ -768,6 +768,16 @@ impl Indexer {
     
         /// Device-tier overlap scores from the primary only (no side-indexer credit).
         async fn find_primary_matches(&self, hashes: Vec<LocalBlockHash>) -> Result<OverlapScores> {
    +        if let Indexer::Single { lower_tier, .. } | Indexer::Concurrent { lower_tier, .. } = self

    find_matches goes through find_match_details when a hybrid layout is active, and the cap is applied after the side merge. Test: side_merge_does_not_lift_hybrid_worker_above_its_checkpoint.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:19 UTC
    Code Review
    lib/kv-router/src/services/indexer/backend.rs:1
    @@ -1047,6 +1057,125 @@ mod tests {
             );
         }
     
    +    /// A hybrid worker's attention chain matches 3 blocks but its recurrent
    +    /// group only checkpointed block 1: the tiered match and the hint chain
    +    /// must stop at block 1, while a dense worker keeps its full match.
    +    #[tokio::test]
    +    async fn recurrent_group_presence_cuts_tiered_match_and_hint_chain() {
    +        use crate::indexer::LowerTierQueryOptions;
    +        use crate::kv_hints::KvTransferCandidateSource;
    +        use crate::protocols::{
    +            ExternalSequenceBlockHash, KvCacheGroupKind, KvCacheGroupTag, KvCacheStoreData,
    +            KvCacheStoredBlockData, compute_seq_hash_for_block,
    +        };
    +
    +        let indexer = create_indexer(4, 1);
    +        let hybrid = WorkerWithDpRank::new(7, 0);
    +        let dense = WorkerWithDpRank::new(8, 0);
    +        let local = [11_u64, 12, 13];
    +        for (event_id, worker) in [(1, hybrid), (2, dense)] {
    +            indexer
    +                .apply_event_routed(store_event(
    +                    worker.worker_id,
    +                    worker.dp_rank,
    +                    event_id,
    +                    &[],
    +                    &local,
    +                    StorageTier::Device,
    +                ))
    +                .await
    +                .unwrap();
    +        }
    +        let chain: Vec<u64> = compute_seq_hash_for_block(
    +            &local
    +                .iter()
    +                .copied()
    +                .map(LocalBlockHash)
    +                .collect::<Vec<_>>(),
    +        );
    +        // Recurrent group 1 of the hybrid worker has a state at block 1 only.

    Removed.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:19 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,81 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// Device match with hybrid workers cut to their last complete boundary.

    This function is gone with the evaluator rewrite.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:19 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,19 +258,30 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    +                if let Some(residency) = self.group_residency() {
    +                    residency.cut_device(&mut primary_device);
    +                }
    +                let mut lt = query_lower_tiers_with_options(
                         lower_tier,
                         sequence.as_slice(),
                         &primary_device,
    -                    lower_tier_options,
    +                    LowerTierQueryOptions {
    +                        retain_kv_transfer_chain: retain_kv_transfer_chain || cut,
    +                    },
                     );
    +                self.cut_lower_tiers(&primary_device, &mut lt, retain_kv_transfer_chain);
    +                if cut && !retain_kv_transfer_chain {

    Lower tiers are seeded from the primary only, and the cap runs after the merge. side_merge_does_not_lift_hybrid_worker_above_its_checkpoint now has a side indexer.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:19 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -200,19 +258,30 @@ impl<'a> LookupPipeline<'a> {
                     // them as lower-tier anchors would over-credit host/disk cache
                     // hits and break the score/hash lockstep `query_lower_tiers_with_options`
                     // expects.
    -                let primary_device = self
    +                let retain_kv_transfer_chain = lower_tier_options.retain_kv_transfer_chain;
    +                let cut = self.group_residency().is_some();
    +                let mut primary_device = self
                         .primary
                         .find_match_details_retained_with_options(
                             &sequence,
    -                        lower_tier_options.retain_kv_transfer_chain,
    +                        retain_kv_transfer_chain || cut,
                         )
                         .await?;
    -                let lt = query_lower_tiers_with_options(
    +                if let Some(residency) = self.group_residency() {
    +                    residency.cut_device(&mut primary_device);
    +                }
    +                let mut lt = query_lower_tiers_with_options(
                         lower_tier,
                         sequence.as_slice(),
                         &primary_device,
    -                    lower_tier_options,
    +                    LowerTierQueryOptions {
    +                        retain_kv_transfer_chain: retain_kv_transfer_chain || cut,
    +                    },
                     );
    +                self.cut_lower_tiers(&primary_device, &mut lt, retain_kv_transfer_chain);
    +                if cut && !retain_kv_transfer_chain {

    find_match_details applies the same cap. Asserted in side_merge_does_not_lift_hybrid_worker_above_its_checkpoint.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:20 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,90 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<MatchDetails, KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        if let Some(residency) = residency {
    +            residency.cut_device(&mut details);
    +        }
    +        Ok(details)
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint. Drops the chain unless hints were requested.
    +    fn finish_device_cut(&self, details: &mut MatchDetails, retain_kv_transfer_chain: bool) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device(details);

    A hybrid worker with no confirmed checkpoint on the prefix gets cap 0 and is dropped. Test: side_merge_does_not_revive_hybrid_worker_without_state_on_prefix.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:20 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +168,90 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<MatchDetails, KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        if let Some(residency) = residency {
    +            residency.cut_device(&mut details);
    +        }
    +        Ok(details)
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint. Drops the chain unless hints were requested.
    +    fn finish_device_cut(&self, details: &mut MatchDetails, retain_kv_transfer_chain: bool) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device(details);
    +            if !retain_kv_transfer_chain {
    +                details.kv_transfer_candidates = None;
    +            }
    +        }
    +    }
    +
         async fn find_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    -        if self.side.is_none() {
    +        if self.side.is_none() && self.group_residency().is_none() {
                 return self.find_primary_match_details(sequence).await;
             }
     
    -        let primary_details = self.primary.find_match_details_retained(&sequence).await?;
    -        Ok(merge_side_or_warn(self.side, primary_details, sequence).await)
    +        let primary_details = self.cut_primary_match_details(&sequence).await?;
    +        let mut merged = merge_side_or_warn(self.side, primary_details, sequence).await;
    +        self.finish_device_cut(&mut merged, false);
    +        Ok(merged)
         }
     
         async fn find_primary_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    +        if self.group_residency().is_some() {
    +            let mut details = self.cut_primary_match_details(&sequence).await?;
    +            self.finish_device_cut(&mut details, false);
    +            return Ok(details);
    +        }
             self.primary.find_match_details(sequence).await
         }
     
    +    fn cut_lower_tiers(
    +        &self,
    +        device: &MatchDetails,
    +        lower_tier: &mut HashMap<StorageTier, LowerTierMatchDetails>,
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        let Some(residency) = self.group_residency() else {
    +            return;
    +        };
    +        let device_chain: Vec<_> = device
    +            .kv_transfer_candidates
    +            .as_ref()
    +            .map(|candidates| candidates.block_hashes.clone())
    +            .unwrap_or_default();
    +        for details in lower_tier.values_mut() {
    +            residency.cut_lower_tier(details, &device_chain);

    The evaluator observes every tier walk. Test: lower_tier_cut_covers_every_tier (HostPinned, Disk, External).

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:20 UTC
    Code Review
    lib/router/kv-indexer/src/backend.rs:1
    @@ -1130,6 +1137,124 @@ mod tests {
             }
         }
     
    +    /// A hybrid worker's attention chain matches 3 blocks but its recurrent
    +    /// group only checkpointed block 1: the tiered match and the hint chain
    +    /// must stop at block 1, while a dense worker keeps its full match.
    +    #[tokio::test]
    +    async fn recurrent_group_presence_cuts_tiered_match_and_hint_chain() {

    Added as recurrent_group_presence_cuts_match_fed_through_ingress. Thanks.

    resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:20 UTC
    Code Review
    lib/kv-router/src/indexer/kv_cache_groups.rs:1
    @@ -240,13 +248,11 @@ impl KvCacheGroupResidency {
                     continue;
                 };
                 let start = end - *hits;
    -            if end > chain.len() {
    -                // The chain does not cover this tier's extension (device
    -                // candidates were truncated below it): nothing to verify.
    -                continue;
    -            }
    -            if let Some(p) = self.reusable_blocks(*worker, &chain, end)
    -                && p < end
    +            // Positions past the chain cannot be verified against the
    +            // presence table; a hybrid worker's hits there are not credited.
    +            let verifiable = end.min(chain.len());

  • The cut no longer indexes the chain. Test: hybrid_cumulative_cut_uses_one_boundary_for_host_and_disk.

  • A hybrid worker with no device checkpoint gets cap 0, so its lower-tier hits go to 0.
  • resolved

    luckyq luckyq commented on code on Nov 16, 2026 20:20 UTC
    Code Review
    lib/kv-router/src/services/indexer/lookup.rs:1
    @@ -166,25 +169,105 @@ impl Indexer {
     }
     
     impl<'a> LookupPipeline<'a> {
    +    fn group_residency(&self) -> Option<&'a KvCacheGroupResidency> {
    +        self.lower_tier
    +            .map(LowerTierIndexers::group_residency)
    +            .filter(|residency| residency.is_active())
    +    }
    +
    +    /// The hash chain is retained whenever a cut may be needed, because the
    +    /// cut is keyed by positional hash; it is dropped again before returning
    +    /// unless the caller asked for hints. Returns the full primary chain as
    +    /// it was before the cut: the cut truncates or drops the retained one,
    +    /// and the later side-merge cut and lower-tier cuts are keyed by it.
    +    async fn cut_primary_match_details(
    +        &self,
    +        sequence: &HashInput<'_>,
    +    ) -> Result<(MatchDetails, Vec<ExternalSequenceBlockHash>), KvRouterError> {
    +        let residency = self.group_residency();
    +        let mut details = self
    +            .primary
    +            .find_match_details_retained_with_options(sequence, residency.is_some())
    +            .await?;
    +        let chain = details
    +            .kv_transfer_candidates
    +            .as_ref()
    +            .map(|candidates| candidates.block_hashes.clone())
    +            .unwrap_or_default();
    +        if let Some(residency) = residency {
    +            residency.cut_device_with_chain(&mut details, &chain);
    +        }
    +        Ok((details, chain))
    +    }
    +
    +    /// Re-apply the cut after the predict-on-route side merge: the merge takes
    +    /// the per-worker maximum, which can lift a hybrid worker back above its
    +    /// last recurrent checkpoint, or re-add one the first cut dropped. Keyed
    +    /// by the pre-cut primary chain. Drops the chain unless hints were
    +    /// requested.
    +    fn finish_device_cut(
    +        &self,
    +        details: &mut MatchDetails,
    +        primary_chain: &[ExternalSequenceBlockHash],
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        if let Some(residency) = self.group_residency() {
    +            residency.cut_device_with_chain(details, primary_chain);
    +            if !retain_kv_transfer_chain {
    +                details.kv_transfer_candidates = None;
    +            }
    +        }
    +    }
    +
         async fn find_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    -        if self.side.is_none() {
    +        if self.side.is_none() && self.group_residency().is_none() {
                 return self.find_primary_match_details(sequence).await;
             }
     
    -        let primary_details = self.primary.find_match_details_retained(&sequence).await?;
    -        Ok(merge_side_or_warn(self.side, primary_details, sequence).await)
    +        let (primary_details, chain) = self.cut_primary_match_details(&sequence).await?;
    +        let mut merged = merge_side_or_warn(self.side, primary_details, sequence).await;
    +        self.finish_device_cut(&mut merged, &chain, false);
    +        Ok(merged)
         }
     
         async fn find_primary_match_details(
             &self,
             sequence: HashInput<'_>,
         ) -> Result<MatchDetails, KvRouterError> {
    +        if self.group_residency().is_some() {
    +            let (mut details, chain) = self.cut_primary_match_details(&sequence).await?;
    +            self.finish_device_cut(&mut details, &chain, false);
    +            return Ok(details);
    +        }
             self.primary.find_match_details(sequence).await
         }
     
    +    /// Cut every lower tier against the pre-cut device chain. Extensions were
    +    /// retained for the cut only; tiers other than HostPinned never expose
    +    /// them, and HostPinned's merged hint chain follows the caller's request.
    +    fn cut_lower_tiers(
    +        &self,
    +        device_chain: &[ExternalSequenceBlockHash],
    +        lower_tier: &mut HashMap<StorageTier, LowerTierMatchDetails>,
    +        retain_kv_transfer_chain: bool,
    +    ) {
    +        let Some(residency) = self.group_residency() else {
    +            return;
    +        };
    +        for (tier, details) in lower_tier.iter_mut() {
    +            residency.cut_lower_tier(details, device_chain);

    One cap per worker across tiers, anchored at the device checkpoint. Test: hybrid_cumulative_cut_uses_one_boundary_for_host_and_disk. Device credit needs a Device-tier checkpoint.

    resolved

    luckyq luckyq commented on Nov 16, 2026 23:27 UTC
    Author

    @PeaBrane @jthomson04 @rishabhsinha17 could you take another look?

  • The evaluator changed since your reviews: one cap per worker across tiers, applied after the side merge and on the remote path. Test results are in the description.

  • I replied to and resolved the threads that are fixed. @rishabhsinha17, that includes the side-merge and lower-tier cut gaps from your offer above; both are on this branch now.

  • Two threads are still open: predict-on-route gives a hybrid worker no uplift, and the general evaluator still reads presence per worker and per block.

  • Stacked on #16876, which merges first.
  • jthomson04 jthomson04 requested changes on Nov 17, 2026 05:42 UTC
    Changes Requested Reviewer

    Re-reviewed at a38aac7. I found no problem with the cut rule or the single cap per worker across tiers.

    My main worry is the shape of the lookup. The CRTC exists so that a lookup doesn't probe a hash table per block: it scans edges, and its cost is memory latency and what fits in L1/L2. Both evaluators bring per-block probes back (inline at hybrid_prefix.rs:369 and forward_prefix.rs:204).

    Could the checkpoints live on the edge instead, as per-worker positions next to worker_cutoffs? The lane lookup and edge_index already resolve a (worker, hash) to a node and position, and the walk would read them from the node it already holds.

    The other inline comments apply if the side table stays. One nit outside the diff: is_hybrid (kv_cache_groups.rs:1202) clones the owner Arc to test presence; registry.load().owners.contains_key(..) avoids the refcount write.

    luckyq luckyq commented on Nov 17, 2026 22:43 UTC
    Author

    @jthomson04 on the review summary:

  • Both evaluators now read checkpoint records after the walk, outside the node guard. The walk only records the blocks it visited.

  • Checkpoints on the edge: I read through it and would not do it in this PR. A checkpoint and its attention blocks are evicted separately, so an edge that is removed and stored again loses the checkpoint position unless a hash-keyed index is kept. The single-thread tree, the worker-local index, lower tiers, cache owners and dumps would still need the table. I can look at it as a follow-up if the measurements call for it.

  • is_hybrid uses contains_key (in #16876).

  • Not done yet: the three measurements (general evaluator with a lower tier or side indexer, a multi-prefix chain without checkpoints, the Mooncake keep-up replay against main). I will post the numbers here.
  • luckyq luckyq commented on Nov 20, 2026 00:13 UTC
    Author

    @jthomson04 on putting the checkpoints on the edge:

  • I prototyped it: Device checkpoints as per-worker positions next to worker_cutoffs. Mooncake keep-up replay, 128-token blocks, one checkpoint per store, against main.

  • Reads improve as you predicted: forward path p50 1.83 → 1.28, p99.9 3.61 → 1.26.

  • Writes do not keep up: a checkpoint event has to go through the worker's lane to find its node, and update_accepted_to_finished p50 goes from about 1 ms to about 1 s. No run kept up.

  • At Qwen3.5's block sizes the side table costs 1.3 to 1.6 µs per lookup, with no long tail.
  • Proposal: land the side table here, and follow up with the edge design once its write path keeps up.

    still open: whether the side table can land first.

    Assignees
    luckyq luckyq
    Labels
    risk: low confidence: 85.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 78.5% (HIGH) · Higher = larger blast radius
    78.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.6% · Lower = rushed or shallow review
    85.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 11.3% · Safe to merge
    11.3%