From 1443c96f9ee1c5ab769bcdd81338366b026f2d25 Mon Sep 17 00:00:00 2001 From: ouyyy18 Date: Wed, 18 Nov 2026 08:23:17 +0800 Subject: [PATCH 1/3] Limit pair-enumeration candidates in snapshot selection select_snapshots builds an inverted index and enumerates candidate pairs to find the cheapest two-row quote. With heavily shared prefixes (agent-style traffic that reuses one long context across many requests) every posting list carries almost every candidate, so the pair loop approaches O(n^2 * pages): a single quote on a package with ~2000 free snapshots measured 9.4 s in release mode, and the quoting loop re-runs it after every eviction, wedging the scheduler (health stays 200, GPUs idle, no log output). See #319 for full evidence including symbolized stacks of the livelock. Truncate the candidate list entering the pair phase to a constant 128 ids. Candidates arrive in id order and ties already prefer lower ids, so the cap keeps the documented preference while bounding the worst case; quoting stays a heuristic and apply_snapshot_quote re-verifies deterministically. On the reproduced input the quote now takes ~40 ms, and 15 minutes of the wedge-triggering load (12 workers, /v1/responses, max reasoning effort, ~350 KB shared-prefix contexts, mid-stream cancels) run with no stall while decode throughput is unchanged (C16 -1.2%, C32 -0.7% vs the same load before the window). --- helios/src/scheduler/cache_memory.rs | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/helios/src/scheduler/cache_memory.rs b/helios/src/scheduler/cache_memory.rs index 52a22a5fc..09657383b 100644 --- a/helios/src/scheduler/cache_memory.rs +++ b/helios/src/scheduler/cache_memory.rs @@ -66,6 +66,18 @@ fn select_snapshots( Some((id, cost)) }) .collect(); + // Bound the pair-enumeration work. With heavily shared prefixes every posting list + // carries almost every candidate, so the pair loop approaches O(n^2 * pages) and a + // single quote can burn seconds of scheduler time. Candidates arrive in id order, + // and ties already prefer lower ids, so truncating keeps the documented preference + // while capping the worst case. + const MAX_PAIR_CANDIDATES: usize = 128; + let truncated = candidates.len() > MAX_PAIR_CANDIDATES; + let candidates = if truncated { + candidates.into_iter().take(MAX_PAIR_CANDIDATES).collect::>() + } else { + candidates + }; if count == 1 { // The lowest cost, ties to the lowest id, skipping candidates whose cost exceeds the // spare pages. One row is the shape of a quote for an anchor-only capture, so this @@ -1466,3 +1478,37 @@ mod tests { ); } } + +#[cfg(test)] +mod wedge_bench { + use super::*; + + // 合成"共享前缀"工作负载: base_pages 被所有候选共享, 每个候选再独占 tail_pages + #[test] + fn select_snapshots_shared_prefix_blowup() { + let pages: usize = 327_680; // 假设 page_tokens=64: 20.98M KV tokens + let base_pages: usize = 45; // ~90k token 共享前缀 + let tail_pages: usize = 4; + let n_candidates: usize = 1986; // 全部快照槽都在候选集 + let keep = pages / 2; + + let backing = vec![true; pages]; + let protected = vec![0u32; pages]; + let mut ranges = vec![0u32..0; n_candidates]; + for i in 0..n_candidates { + let start = (base_pages + i * tail_pages) as u32; + ranges[i] = 0u32..(start + tail_pages as u32); // 覆盖共享前缀+私有尾页 + } + let candidates: BTreeSet = + (0..n_candidates).map(|i| SnapshotId(i as u32)).collect(); + + let t = std::time::Instant::now(); + let r = select_snapshots(&backing, &protected, &ranges, &candidates, keep, 2); + let elapsed = t.elapsed(); + assert_eq!(r.as_ref().map(|v| v.len()), Some(2), "a quotable pair must still be found"); + println!("select(shared-prefix, {} candidates) took {:?}", n_candidates, elapsed); + // Guard against the pathological pair-enumeration blowup: unbounded this + // takes ~9.4 s on this input; leave generous margin for slower CI hosts. + assert!(elapsed < std::time::Duration::from_secs(5), "pair enumeration is unbounded again"); + } +} From 9aa6e34ea29696561f7acd8db035a4ab6cfa035f Mon Sep 17 00:00:00 2001 From: ouyyy18 Date: Wed, 18 Nov 2026 15:14:43 +0800 Subject: [PATCH 2/3] Bound pair enumeration by cost, not id prefix Review feedback: taking the first 128 ids drops candidates before considering cost, so the only feasible (zero-cost) snapshots can be discarded and the selector rejects an allocation main would make. - Leave the single-row path on the full candidate list (it is already linear; the blowup is only the pair phase). - For pairs, keep the cheapest MAX_PAIR_CANDIDATES by (cost, id) instead of the first ids; zero-cost candidates therefore always survive the bound. Inputs with at most that many candidates run the exact original enumeration unchanged. - Compare ties explicitly on the (union, id pair) key: the candidate list may now be cost-sorted, so scan order no longer encodes the lexicographic id preference. - Add the review's minimal case (feasible zero-cost candidates at ids 128/129 under 130 candidates) as a regression test, alongside the shared-prefix blowup test with a bounded-time assertion. Verified: scheduler suite 310/310; shared-prefix quote still ~40 ms (was 9.4 s unbounded); review case selects [128] and [128,129]. --- helios/src/scheduler/cache_memory.rs | 58 +++++++++++++++++++++------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/helios/src/scheduler/cache_memory.rs b/helios/src/scheduler/cache_memory.rs index 09657383b..50530aab8 100644 --- a/helios/src/scheduler/cache_memory.rs +++ b/helios/src/scheduler/cache_memory.rs @@ -66,18 +66,6 @@ fn select_snapshots( Some((id, cost)) }) .collect(); - // Bound the pair-enumeration work. With heavily shared prefixes every posting list - // carries almost every candidate, so the pair loop approaches O(n^2 * pages) and a - // single quote can burn seconds of scheduler time. Candidates arrive in id order, - // and ties already prefer lower ids, so truncating keeps the documented preference - // while capping the worst case. - const MAX_PAIR_CANDIDATES: usize = 128; - let truncated = candidates.len() > MAX_PAIR_CANDIDATES; - let candidates = if truncated { - candidates.into_iter().take(MAX_PAIR_CANDIDATES).collect::>() - } else { - candidates - }; if count == 1 { // The lowest cost, ties to the lowest id, skipping candidates whose cost exceeds the // spare pages. One row is the shape of a quote for an anchor-only capture, so this @@ -124,6 +112,19 @@ fn select_snapshots( // lowest ids, among pairs whose union fits the spare pages. The union is // |a| + |b| - |a ∩ b|; the inverted index counts the shared pages for every pair, so // the pair loop never builds or merges a set. + // + // With heavily shared prefixes every posting list carries almost every candidate, + // so the pair loop approaches O(n^2 * pages) and one quote can burn seconds of + // scheduler time (see GH #319). Bound the enumerated set to the cheapest candidates + // by (cost, id); ids alone are only a tie-break, so the cheapest K is kept rather + // than the first K ids, and zero-cost candidates always sort first. Inputs with at + // most K candidates run the exact original enumeration unchanged. + const MAX_PAIR_CANDIDATES: usize = 128; + let mut candidates = candidates; + if candidates.len() > MAX_PAIR_CANDIDATES { + candidates.sort_unstable_by_key(|(id, pages)| (pages.len(), *id)); + candidates.truncate(MAX_PAIR_CANDIDATES); + } let budget = available - keep_pages; let mut counts = vec![0usize; backing.len()]; for (_, pages) in &candidates { @@ -156,7 +157,17 @@ fn select_snapshots( } for b in a + 1..candidates.len() { let union = pages.len() + candidates[b].1.len() - overlap[b] as usize; - if union <= budget && best.is_none_or(|(cost, _, _)| union < cost) { + if union > budget { + continue; + } + // Ties prefer the lexicographically lowest id pair; the candidate list may + // be cost-sorted, so compare ids explicitly instead of relying on scan order. + let better = best.is_none_or(|(cost, ba, bb)| { + union < cost + || (union == cost + && (candidates[a].0, candidates[b].0) < (candidates[ba].0, candidates[bb].0)) + }); + if better { best = Some((union, a, b)); } } @@ -1511,4 +1522,25 @@ mod wedge_bench { // takes ~9.4 s on this input; leave generous margin for slower CI hosts. assert!(elapsed < std::time::Duration::from_secs(5), "pair enumeration is unbounded again"); } + + // Review case from GH #326: the only feasible (zero-cost) candidates sit past + // index 127; bounding must keep them reachable for both row counts. + #[test] + fn cheapest_candidates_beyond_the_bound_stay_selectable() { + let base_pages = 2; + let backing = vec![true; base_pages]; + let protected = vec![0u32; base_pages]; + let mut ranges = vec![0u32..base_pages as u32; 128]; + ranges.push(0u32..0); // id 128: zero cost + ranges.push(0u32..0); // id 129: zero cost + let candidates: BTreeSet = + (0..130u32).map(SnapshotId).collect(); + + let one = select_snapshots(&backing, &protected, &ranges, &candidates, base_pages, 1); + assert_eq!(one, Some(vec![SnapshotId(128)]), "single row must pick the zero-cost id 128"); + + let two = select_snapshots(&backing, &protected, &ranges, &candidates, base_pages, 2); + assert_eq!(two, Some(vec![SnapshotId(128), SnapshotId(129)]), + "two rows must pick the zero-cost pair 128/129"); + } } From 6e0e773e4625d46d9a8dd6d45af5f7b1c063321f Mon Sep 17 00:00:00 2001 From: ouyyy18 Date: Wed, 18 Nov 2026 18:44:19 +0800 Subject: [PATCH 3/3] Bound all multi-row snapshot selection paths by cost Live re-testing of the previous revision exposed a second unbounded path: with the bound placed in the two-row branch only, requests whose quote rows exceed two (speculative-decode workloads quote more rows) still reached the count>2 greedy witness with the full candidate list, and the engine wedged again under the same shared-prefix load (symbolized stack: select_snapshots -> simulate_snapshot_quote, hot in BTreeSet probes per page; GH #319 evidence recorded). Move the bound before every multi-row path (both the conservative witness and the two-row enumeration); the single-row path keeps the full candidate list as requested in review. Added a count=7 shared-prefix regression test alongside the pair-path one: both now quote in ~40 ms where the unbounded originals take seconds, and the review's zero-cost-at-id-128/129 case still selects correctly. Validation on 4x RTX PRO 6000 (TP4, draft 7, CSF package): scheduler suite 311/311; 15 min of the #319 wedge load with zero stalls on this revision (the previous revision wedged at ~165 s); decode bench C1 285.5 / C8 1035.8 / C16 1468.7 / C32 1881.2 tok/s vs 290/1076/1465/ 1896 on the working 972e28e baseline (within run-to-run noise). --- helios/src/scheduler/cache_memory.rs | 51 +++++++++++++++++++++------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/helios/src/scheduler/cache_memory.rs b/helios/src/scheduler/cache_memory.rs index 50530aab8..114728299 100644 --- a/helios/src/scheduler/cache_memory.rs +++ b/helios/src/scheduler/cache_memory.rs @@ -83,6 +83,21 @@ fn select_snapshots( } return best.map(|(_, id)| vec![id]); } + // Bound the enumerated set for every multi-row path. With heavily shared prefixes + // (agent-style traffic reusing one long context) the greedy witness below and the + // two-row pair loop both degrade — the pair loop toward O(n^2 * pages) and the + // greedy witness toward O(count * n * pages) with a BTreeSet probe per page — and a + // single quote can burn seconds of scheduler time (see GH #319; an engine livelock + // was reproduced live through both paths). Keep the cheapest MAX_MULTI_ROW_CANDIDATES + // by (cost, id): ids alone are only a tie-break after cost, so the cheapest set is + // kept rather than the first ids, and zero-cost candidates always survive. Inputs + // with at most that many candidates run the exact original algorithms unchanged. + const MAX_MULTI_ROW_CANDIDATES: usize = 128; + let mut candidates = candidates; + if candidates.len() > MAX_MULTI_ROW_CANDIDATES { + candidates.sort_unstable_by_key(|(id, pages)| (pages.len(), *id)); + candidates.truncate(MAX_MULTI_ROW_CANDIDATES); + } if count > 2 { // Future capture capacity uses a conservative witness without enumerating subsets. let mut selected = BTreeSet::::new(); @@ -112,19 +127,6 @@ fn select_snapshots( // lowest ids, among pairs whose union fits the spare pages. The union is // |a| + |b| - |a ∩ b|; the inverted index counts the shared pages for every pair, so // the pair loop never builds or merges a set. - // - // With heavily shared prefixes every posting list carries almost every candidate, - // so the pair loop approaches O(n^2 * pages) and one quote can burn seconds of - // scheduler time (see GH #319). Bound the enumerated set to the cheapest candidates - // by (cost, id); ids alone are only a tie-break, so the cheapest K is kept rather - // than the first K ids, and zero-cost candidates always sort first. Inputs with at - // most K candidates run the exact original enumeration unchanged. - const MAX_PAIR_CANDIDATES: usize = 128; - let mut candidates = candidates; - if candidates.len() > MAX_PAIR_CANDIDATES { - candidates.sort_unstable_by_key(|(id, pages)| (pages.len(), *id)); - candidates.truncate(MAX_PAIR_CANDIDATES); - } let budget = available - keep_pages; let mut counts = vec![0usize; backing.len()]; for (_, pages) in &candidates { @@ -1523,6 +1525,29 @@ mod wedge_bench { assert!(elapsed < std::time::Duration::from_secs(5), "pair enumeration is unbounded again"); } + // The count>2 greedy witness path blew up the same way in the live engine + // (see GH #319 evidence-1118_1807): BTreeSet probes per page over every candidate. + #[test] + fn multi_row_witness_shared_prefix_blowup() { + let pages: usize = 327_680; + let base_pages: usize = 45; + let n_candidates: usize = 1986; + let backing = vec![true; pages]; + let protected = vec![0u32; pages]; + let ranges: Vec<_> = (0..n_candidates) + .map(|i| 0u32..(base_pages as u32 + i as u32 * 4 + 4)) + .collect(); + let candidates: BTreeSet = + (0..n_candidates).map(|i| SnapshotId(i as u32)).collect(); + let t = std::time::Instant::now(); + let r = select_snapshots(&backing, &protected, &ranges, &candidates, pages / 2, 7); + let elapsed = t.elapsed(); + assert!(r.is_some(), "greedy witness must still select a conservative set"); + println!("select(count=7, shared-prefix, {} candidates) took {:?}", n_candidates, elapsed); + assert!(elapsed < std::time::Duration::from_secs(5), + "multi-row witness enumeration is unbounded again"); + } + // Review case from GH #326: the only feasible (zero-cost) candidates sit past // index 127; bounding must keep them reachable for both row counts. #[test]