AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(search): isolate cold vector segment loads
bugerc8df0452e5c7
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 901d31efd..aa0377cf2 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -121,6 +121,11 @@ mod semantic_deadline_regression_tests {let request = match_all(1);let timed_out = idx.search(&request).await.unwrap();assert!(timed_out.timed_out);+ assert_eq!(+ idx.metric_query_count.load(Ordering::Relaxed),+ 1,+ "admission timeout must be included in query metrics"+ );assert!(idx.query_cache.is_empty(),"partial timeout must never enter the result cache"@@ -135,6 +140,232 @@ mod semantic_deadline_regression_tests {assert_eq!(cached.took_ms, 0);}+ #[tokio::test(flavor = "multi_thread", worker_threads = 1)]+ async fn cold_vector_segment_load_does_not_block_async_worker() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine.create_index("cold-vector", Schema::empty()).unwrap();+ let idx = engine.get_index("cold-vector").unwrap();+ idx.index_document(+ Some("v1".into()),+ serde_json::json!({"embedding": [1.0, 0.0]}),+ )+ .await+ .unwrap();+ idx.flush().await.unwrap();+ idx.stored_value_cache.clear();+ idx.test_stored_value_load_delay_ms+ .store(250, Ordering::Relaxed);+ idx.test_stored_value_load_count.store(0, Ordering::Relaxed);++ let mut queries = Vec::new();+ for _ in 0..8 {+ let query_idx = Arc::clone(&idx);+ queries.push(tokio::spawn(async move {+ query_idx+ .run_knn_brute_force(+ &match_all(2_000),+ "embedding",+ &[1.0, 0.0],+ 1,+ None,+ "cosine",+ None,+ None,+ )+ .await+ }));+ }++ tokio::time::timeout(std::time::Duration::from_secs(1), async {+ while idx.test_stored_value_load_count.load(Ordering::Relaxed) == 0 {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("cold load never reached blocking pool");++ // With one runtime worker this timer cannot complete while a+ // synchronous 250 ms segment load is running on that worker.+ tokio::time::timeout(+ std::time::Duration::from_millis(100),+ tokio::time::sleep(std::time::Duration::from_millis(10)),+ )+ .await+ .expect("cold segment load starved the async runtime worker");++ for query in queries {+ let result = query.await.unwrap().unwrap();+ assert!(!result.timed_out);+ assert_eq!(result.hits.len(), 1);+ }+ assert_eq!(+ idx.test_stored_value_load_count.load(Ordering::Relaxed),+ 1,+ "concurrent cold requests must share one parse"+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 1)]+ async fn request_deadline_can_drop_cold_vector_load_wait() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine+ .create_index("cold-deadline", Schema::empty())+ .unwrap();+ let idx = engine.get_index("cold-deadline").unwrap();+ idx.index_document(+ Some("v1".into()),+ serde_json::json!({"embedding": [1.0, 0.0]}),+ )+ .await+ .unwrap();+ idx.flush().await.unwrap();+ idx.stored_value_cache.clear();+ idx.test_stored_value_load_delay_ms+ .store(250, Ordering::Relaxed);++ let started = std::time::Instant::now();+ let result = idx+ .run_knn_brute_force(+ &match_all(20),+ "embedding",+ &[1.0, 0.0],+ 1,+ Some(Box::new(QueryNode::MatchAll)),+ "cosine",+ None,+ None,+ )+ .await+ .unwrap();+ assert!(result.timed_out);+ assert_eq!(result.total.relation, TotalHitsRelation::Gte);+ assert!(+ started.elapsed() < std::time::Duration::from_millis(150),+ "request waited for detached cold load instead of its deadline"+ );++ // `spawn_blocking` is deliberately not aborted: the immutable load+ // completes and warms the cache for a later request.+ tokio::time::timeout(std::time::Duration::from_secs(1), async {+ while idx.stored_value_cache.is_empty() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("detached load did not warm the cache");+ }++ #[tokio::test]+ async fn retired_segment_cannot_be_reinserted_by_detached_load() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine+ .create_index("retired-load", Schema::empty())+ .unwrap();+ let idx = engine.get_index("retired-load").unwrap();+ idx.index_document(Some("v1".into()), serde_json::json!({"value": 1}))+ .await+ .unwrap();+ idx.flush().await.unwrap();+ let old_meta = idx.store.snapshot().segments[0].clone();+ idx.stored_value_cache.clear();+ idx.test_stored_value_load_pause_before_publish+ .store(true, Ordering::Release);+ idx.test_stored_value_load_ready_to_publish+ .store(false, Ordering::Release);++ let load_idx = Arc::clone(&idx);+ let old_id = old_meta.id.clone();+ let load = tokio::spawn(async move { load_idx.stored_values_for_async(&old_id).await });+ tokio::time::timeout(std::time::Duration::from_secs(2), async {+ while !idx+ .test_stored_value_load_ready_to_publish+ .load(Ordering::Acquire)+ {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("cold load did not reach publication gate");++ // Publish a replacement exactly as merge does, then perform the+ // stored-value eviction while holding the lifecycle write guard.+ let mut replacement = old_meta.clone();+ replacement.id = Uuid::new_v4().to_string();+ replacement.seg_path = format!("segments/{}.seg", replacement.id);+ replacement.sidx_path = format!("segments/{}.sidx", replacement.id);+ idx.store+ .apply_merge(std::slice::from_ref(&old_meta.id), replacement)+ .unwrap();+ {+ let _publication = idx.stored_value_cache_lifecycle.write();+ idx.stored_value_cache.remove(&old_meta.id);+ }+ idx.test_stored_value_load_pause_before_publish+ .store(false, Ordering::Release);++ assert!(+ load.await.unwrap().is_some(),+ "old-snapshot caller should receive the completed immutable load"+ );+ assert!(+ !idx.stored_value_cache.contains_key(&old_meta.id),+ "detached completion resurrected a retired segment"+ );+ }++ #[tokio::test]+ async fn failed_cold_load_closes_followers_and_clears_singleflight() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine.create_index("failed-load", Schema::empty()).unwrap();+ let idx = engine.get_index("failed-load").unwrap();++ let mut followers = Vec::new();+ for _ in 0..4 {+ let idx = Arc::clone(&idx);+ followers.push(tokio::spawn(async move {+ idx.stored_values_for_async("missing-segment").await+ }));+ }+ for follower in followers {+ assert!(follower.await.unwrap().is_none());+ }+ assert!(idx.stored_value_loads.is_empty());+ assert!(idx.stored_value_cache.is_empty());+ }++ #[tokio::test]+ async fn singleflight_wait_timeout_is_counted() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine+ .create_index("follower-metrics", Schema::empty())+ .unwrap();+ let idx = engine.get_index("follower-metrics").unwrap();+ let request = match_all(1);+ let bytes = serde_json::to_vec(&request).unwrap();+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ std::hash::Hasher::write(&mut hasher, &bytes);+ let key = (+ std::hash::Hasher::finish(&hasher),+ idx.dataset_version.load(Ordering::Acquire),+ );+ let (leader, _receiver) = tokio::sync::watch::channel(None);+ idx.query_inflight.insert(key, leader);++ let follower = idx.search(&request).await.unwrap();+ assert!(follower.timed_out);+ assert_eq!(+ idx.metric_query_count.load(Ordering::Relaxed),+ 1,+ "single-flight wait timeout must be counted before leader returns"+ );+ idx.query_inflight.remove(&key);+ }+#[tokio::test]async fn cancelled_singleflight_leader_drains_and_follower_recomputes() {let dir = TempDir::new().unwrap();@@ -256,6 +487,23 @@ mod semantic_deadline_regression_tests {let idx = engine.get_index("future-deadline").unwrap();seed_vectors(&idx).await;let request = match_all(250);+ // Isolate cooperative scan timing from the independently tested cold+ // segment-load deadline: warm any auto-flushed segment first.+ idx.test_scan_checkpoint_delay_ms+ .store(0, Ordering::Relaxed);+ idx.run_knn_brute_force_with_deadline(+ &request,+ std::time::Instant::now() + std::time::Duration::from_secs(2),+ "embedding",+ &[1.0, 0.0],+ 10,+ None,+ "cosine",+ None,+ None,+ )+ .await+ .unwrap();for timeout_ms in [1, 10, 250] {idx.test_scan_checkpoint_delay_ms@@ -326,6 +574,53 @@ mod semantic_deadline_regression_tests {);}+ #[tokio::test]+ async fn nested_knn_uses_the_shared_request_deadline() {+ let dir = TempDir::new().unwrap();+ let engine = engine(&dir);+ engine+ .create_index("nested-timeout", Schema::empty())+ .unwrap();+ let idx = engine.get_index("nested-timeout").unwrap();+ for n in 0..256 {+ idx.index_document(+ Some(format!("n{n}")),+ serde_json::json!({"items": [{"vector": [1.0, 0.0]}]}),+ )+ .await+ .unwrap();+ }+ idx.test_scan_checkpoint_delay_ms+ .store(20, Ordering::Relaxed);+ idx.test_scan_checkpoint_count.store(0, Ordering::Relaxed);++ let request = SearchRequest {+ query: QueryNode::Nested {+ path: "items".into(),+ query: Box::new(QueryNode::Knn {+ field: "items.vector".into(),+ vector: vec![1.0, 0.0],+ k: 10,+ num_candidates: Some(10),+ filter: None,+ boost: None,+ similarity: None,+ }),+ score_mode: None,+ },+ timeout_ms: Some(5),+ ..SearchRequest::default()+ };+ let result = idx.search(&request).await.unwrap();+ assert!(result.timed_out);+ assert_eq!(result.total.relation, TotalHitsRelation::Gte);+ assert_eq!(+ idx.test_scan_checkpoint_count.load(Ordering::Relaxed),+ 2,+ "nested scan must stop at its first non-zero checkpoint"+ );+ }+#[tokio::test]async fn concurrent_unique_semantic_requests_share_bounded_deadlines() {let dir = TempDir::new().unwrap();@@ -874,6 +1169,14 @@ pub struct Index {test_scan_checkpoint_delay_ms: Arc<AtomicU64>,#[cfg(test)]test_scan_checkpoint_count: Arc<AtomicU64>,+ #[cfg(test)]+ test_stored_value_load_delay_ms: Arc<AtomicU64>,+ #[cfg(test)]+ test_stored_value_load_count: Arc<AtomicU64>,+ #[cfg(test)]+ test_stored_value_load_pause_before_publish: Arc<std::sync::atomic::AtomicBool>,+ #[cfg(test)]+ test_stored_value_load_ready_to_publish: Arc<std::sync::atomic::AtomicBool>,// ── Per-index enrich lookup tables ────────────────────────────────────────/// Named enrich tables: each table maps a key to a JSON object of extra/// fields to merge into matching documents at ingest time.@@ -1014,6 +1317,18 @@ pub struct Index {/// are immutable once flushed, so this cache is correct without/// invalidation. Same `Left unbounded for now` caveat as `dv_cache`.stored_value_cache: Arc<dashmap::DashMap<String, Arc<Vec<Value>>>>,+ /// Serializes the short "is this segment still published? + cache insert"+ /// transaction against merge eviction. Segment parsing never holds it.+ stored_value_cache_lifecycle: Arc<parking_lot::RwLock<()>>,+ /// Per-segment cancellation-safe cold-load single-flight. The sender+ /// publishes the immutable parsed section to every concurrent vector+ /// query; the detached producer survives cancellation of any requester.+ stored_value_loads:+ Arc<dashmap::DashMap<String, tokio::sync::watch::Sender<Option<Arc<Vec<Value>>>>>>,+ /// Bounds simultaneous whole-segment decompression/parsing across distinct+ /// cold segments. Per-segment single-flight removes duplicate work; this+ /// bound prevents a many-segment cold storm from multiplying peak memory.+ stored_value_load_semaphore: Arc<Semaphore>,/// Per-segment cache of the DECOMPRESSED stored section plus per-doc/// `(start, end)` byte offsets, used by the sorted-DV candidate path@@ -1275,6 +1590,18 @@ impl Index {test_scan_checkpoint_delay_ms: Arc::new(AtomicU64::new(0)),#[cfg(test)]test_scan_checkpoint_count: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_delay_ms: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_count: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_pause_before_publish: Arc::new(+ std::sync::atomic::AtomicBool::new(false),+ ),+ #[cfg(test)]+ test_stored_value_load_ready_to_publish: Arc::new(std::sync::atomic::AtomicBool::new(+ false,+ )),enrichments: Arc::new(RwLock::new(HashMap::new())),hnsw: Arc::new(RwLock::new(None)),hnsw_id_map: Arc::new(RwLock::new(HashMap::new())),@@ -1309,6 +1636,9 @@ impl Index {id_pos_cache: Arc::new(dashmap::DashMap::new()),row_seq_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),+ stored_value_cache_lifecycle: Arc::new(parking_lot::RwLock::new(())),+ stored_value_loads: Arc::new(dashmap::DashMap::new()),+ stored_value_load_semaphore: Arc::new(Semaphore::new(4)),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),@@ -1509,6 +1839,18 @@ impl Index {test_scan_checkpoint_delay_ms: Arc::new(AtomicU64::new(0)),#[cfg(test)]test_scan_checkpoint_count: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_delay_ms: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_count: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]+ test_stored_value_load_pause_before_publish: Arc::new(+ std::sync::atomic::AtomicBool::new(false),+ ),+ #[cfg(test)]+ test_stored_value_load_ready_to_publish: Arc::new(std::sync::atomic::AtomicBool::new(+ false,+ )),enrichments: Arc::new(RwLock::new(HashMap::new())),store,memtable: Arc::new(memtable),@@ -1560,6 +1902,9 @@ impl Index {id_pos_cache: Arc::new(dashmap::DashMap::new()),row_seq_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),+ stored_value_cache_lifecycle: Arc::new(parking_lot::RwLock::new(())),+ stored_value_loads: Arc::new(dashmap::DashMap::new()),+ stored_value_load_semaphore: Arc::new(Semaphore::new(4)),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),@@ -4064,11 +4409,26 @@ impl Index {if merged_batches > 0 {self.dataset_version.fetch_add(1, AtomicOrdering::Release);self.query_cache.clear();+ // Pair with cold-load publication's read guard. `apply_merge`+ // already removed these ids from the authoritative snapshot:+ // a loader that checked before retirement must publish before+ // this writer and be removed here; one that arrives after this+ // writer sees the retired snapshot and cannot publish.+ {+ let _publication = self.stored_value_cache_lifecycle.write();+ for id in &dropped_seg_ids {+ self.stored_value_cache.remove(id.as_str());+ }+ }+ // Do not remove `stored_value_loads` here. Callers holding the+ // pre-merge snapshot are entitled to receive that immutable+ // producer's result; the producer removes its own single-flight+ // key on completion, and the lifecycle transaction above+ // prevents it from retaining the retired value in the cache.for id in &dropped_seg_ids {self.dv_cache.remove(id.as_str());self.id_pos_cache.remove(id.as_str());self.row_seq_cache.remove(id.as_str());- self.stored_value_cache.remove(id.as_str());if let Some((_, slices)) = self.stored_slices_cache.remove(id.as_str()) {self.stored_slices_cache_bytes.fetch_sub(slices.retained_bytes(), Ordering::Relaxed);@@ -4582,7 +4942,7 @@ impl Index {let snap = self.store.snapshot();for meta in snap.segments.iter() {- let docs_arc = match self.stored_values_for(&meta.id) {+ let docs_arc = match self.stored_values_for_async(&meta.id).await {Some(a) => a,None => {// Segment unreadable (transient I/O, or merged away@@ -5034,21 +5394,29 @@ impl Index {'segments: for meta in snap.segments.iter() {let segment_started = std::time::Instant::now();// Cache-backed: first KNN against this segment pays the- // I/O + decompress + simd_json parse, every subsequent+ // I/O + decompress + serde_json parse, every subsequent// query reads from `stored_value_cache`. For a 100-segment// index this turns repeated KNN from O(seg_count * 100MB)// copy work into Arc clone + iterate.- // `stored_values_for` may synchronously read, decompress, and- // parse one segment on a cold cache. That operation cannot be- // interrupted internally; the deadline is checked immediately- // before and after it, bounding the overrun to one segment load.+ // A cold miss is coalesced and parsed on the bounded blocking+ // pool. This executor's absolute deadline can drop the await+ // while the detached producer finishes warming the segment.if std::time::Instant::now() >= deadline {timed_out = true;break;}- let docs_arc = match self.stored_values_for(&meta.id) {- Some(a) => a,- None => continue,+ let docs_arc = match tokio::time::timeout_at(+ tokio::time::Instant::from_std(deadline),+ self.stored_values_for_async(&meta.id),+ )+ .await+ {+ Ok(Some(a)) => a,+ Ok(None) => continue,+ Err(_) => {+ timed_out = true;+ break;+ }};if std::time::Instant::now() >= deadline {timed_out = true;@@ -5981,8 +6349,40 @@ impl Index {pre_filter: Option<Box<QueryNode>>,post_filter: Option<Box<QueryNode>>,similarity: &str,+ ) -> Result<SearchResult> {+ let deadline = std::time::Instant::now()+ + std::time::Duration::from_millis(request.timeout_ms.unwrap_or(30_000));+ self.run_nested_knn_brute_force_with_deadline(+ request,+ deadline,+ nested_path,+ field,+ query_vec,+ k,+ num_candidates,+ pre_filter,+ post_filter,+ similarity,+ )+ .await+ }++ #[allow(clippy::too_many_arguments)] // deadline plus ES nested-kNN request surface+ async fn run_nested_knn_brute_force_with_deadline(+ &self,+ request: &SearchRequest,+ deadline: std::time::Instant,+ nested_path: &str,+ field: &str,+ query_vec: &[f32],+ k: usize,+ num_candidates: usize,+ pre_filter: Option<Box<QueryNode>>,+ post_filter: Option<Box<QueryNode>>,+ similarity: &str,) -> Result<SearchResult> {let started = std::time::Instant::now();+ let mut timed_out = false;// The sub-field name inside each nested element.let subfield = field.strip_prefix(&format!("{}.", nested_path))@@ -5997,15 +6397,36 @@ impl Index {}let snap = self.store.snapshot();let mut seen: HashSet<String> = candidates.iter().map(|(id, _)| id.clone()).collect();- for meta in snap.segments.iter() {+ 'segments: for meta in snap.segments.iter() {+ if std::time::Instant::now() >= deadline {+ timed_out = true;+ break;+ }// Cache-backed: see comment on the matching loop in// run_knn_brute_force.- let docs_arc = match self.stored_values_for(&meta.id) {- Some(a) => a,- None => continue,+ let docs_arc = match tokio::time::timeout_at(+ tokio::time::Instant::from_std(deadline),+ self.stored_values_for_async(&meta.id),+ )+ .await+ {+ Ok(Some(a)) => a,+ Ok(None) => continue,+ Err(_) => {+ timed_out = true;+ break;+ }};+ if std::time::Instant::now() >= deadline {+ timed_out = true;+ break;+ }// Cache + serde_json under the hood (see stored_values_for).- for doc in docs_arc.iter() {+ for (position, doc) in docs_arc.iter().enumerate() {+ if position & 127 == 0 && self.exact_scan_checkpoint(position, deadline).await {+ timed_out = true;+ break 'segments;+ }let id = match doc.get("_id").and_then(Value::as_str) {Some(s) => s.to_string(),None => continue,@@ -6037,7 +6458,12 @@ impl Index {// ── Score each parent by best-matching nested element ─────────// Pre-filter is applied before scoring (alias filter, knn.filter).let mut scored: Vec<(String, f32, Value)> = Vec::new();- for (id, src) in candidates {+ let mut nested_position = 0usize;+ 'candidates: for (position, (id, src)) in candidates.into_iter().enumerate() {+ if position & 127 == 0 && self.exact_scan_checkpoint(position, deadline).await {+ timed_out = true;+ break;+ }if let Some(ref f) = pre_filter {let mut src_with_id = src.clone();if let Some(obj) = src_with_id.as_object_mut() {@@ -6054,6 +6480,13 @@ impl Index {};let mut best: Option<f32> = None;for elem in &nested_arr {+ nested_position = nested_position.saturating_add(1);+ if nested_position & 127 == 0+ && self.exact_scan_checkpoint(nested_position, deadline).await+ {+ timed_out = true;+ break 'candidates;+ }let vec_val = match elem.get(&subfield) {Some(v) => v,None => continue,@@ -6117,11 +6550,15 @@ impl Index {hits,total: TotalHits {value: total_value,- relation: TotalHitsRelation::Eq,+ relation: if timed_out {+ TotalHitsRelation::Gte+ } else {+ TotalHitsRelation::Eq+ },},took_ms: started.elapsed().as_millis() as u64,aggs: None,- timed_out: false,+ timed_out,profile: None,max_score: None,})@@ -6795,17 +7232,27 @@ impl Index {let request_started = std::time::Instant::now();let request_deadline = request_started+ std::time::Duration::from_millis(request.timeout_ms.unwrap_or(30_000));- let timed_out_result = || SearchResult {- hits: vec![],- total: xerj_query::executor::TotalHits {- value: 0,- relation: TotalHitsRelation::Gte,- },- took_ms: request_started.elapsed().as_millis() as u64,- aggs: None,- timed_out: true,- profile: None,- max_score: None,+ let timed_out_result = || {+ let took_ms = request_started.elapsed().as_millis() as u64;+ // Admission and single-flight waits can consume the complete+ // deadline before `search_inner` starts. They are still real+ // queries and must be visible in the same counters as executor+ // timeouts; otherwise overload makes query_count under-report.+ self.metric_query_count.fetch_add(1, Ordering::Relaxed);+ self.metric_query_total_ms+ .fetch_add(took_ms, Ordering::Relaxed);+ SearchResult {+ hits: vec![],+ total: xerj_query::executor::TotalHits {+ value: 0,+ relation: TotalHitsRelation::Gte,+ },+ took_ms,+ aggs: None,+ timed_out: true,+ profile: None,+ max_score: None,+ }};// M3 framework: response cache. Hash the request shape and the// current dataset version; on a hit return the cloned `Arc<SearchResult>`@@ -7049,9 +7496,16 @@ impl Index {// Pre-M5.21 a concurrent QPS bench collapsed to <1 QPS. See// the commit body for `perf/search-block-in-place` for the// full root-cause analysis.+ // Hybrid remains under the M5.21 blocking boundary because it may+ // contain an ordinary lexical child whose generic scan is not yet+ // cooperative. Its vector children still receive the shared absolute+ // deadline and stop at their own checkpoints. Removing the boundary+ // for all hybrid shapes would trade timeout overrun for async-worker+ // starvation on lexical hybrids.let cooperative_vector_query = peel_knn_query(&request.query).is_some()|| peel_multi_knn_query(&request.query).is_some()- || peel_semantic_query(&request.query).is_some();+ || peel_semantic_query(&request.query).is_some()+ || peel_nested_knn_query(&request.query).is_some();let is_multi_thread = tokio::runtime::Handle::current().runtime_flavor()== tokio::runtime::RuntimeFlavor::MultiThread;let search_fut = self.search_inner(request, request_deadline);@@ -7349,8 +7803,9 @@ impl Index {// smaller fan-out than the requested top-k makes no sense).let num_candidates = num_candidates_opt.unwrap_or(k).max(k);return self- .run_nested_knn_brute_force(+ .run_nested_knn_brute_force_with_deadline(request,+ search_deadline,&nested_path,&field,&query_vec,@@ -13993,9 +14448,8 @@ impl Index {/// section, and parses the result. Subsequent calls return an/// `Arc<Vec<Value>>` clone — no I/O, no decompress, no parse./// Segments are immutable post-flush so the cache value remains- /// valid until the segment is removed by a merge (at which point- /// `stored_value_cache.clear()` flushes the entire map; see the- /// merge-completion site).+ /// valid until the segment is removed by a merge (at which point its+ /// precise entry is evicted under the lifecycle write guard).////// Uses `serde_json::from_slice` not `simd_json::serde::from_slice`:/// per ffd49ac, simd_json silently corrupts some payloads produced@@ -14013,11 +14467,126 @@ impl Index {let stored_bytes = xerj_storage::stored_codec::decode_stored(stored_bytes_raw).ok()?;let docs: Vec<Value> = serde_json::from_slice(&stored_bytes).ok()?;let arc = Arc::new(docs);- self.stored_value_cache- .insert(segment_id.to_string(), Arc::clone(&arc));+ {+ let _publication = self.stored_value_cache_lifecycle.read();+ if self+ .store+ .snapshot()+ .segments+ .iter()+ .any(|meta| meta.id == segment_id)+ {+ self.stored_value_cache+ .insert(segment_id.to_string(), Arc::clone(&arc));+ }+ }Some(arc)}+ /// Async boundary for a cold stored-value load.+ ///+ /// A cache miss opens and decompresses the segment and parses its complete+ /// stored section. That is synchronous file/CPU work and can take seconds+ /// for a large segment, so vector queries must not run it on a Tokio+ /// worker. Cache hits stay on the caller because they are only a DashMap+ /// lookup and `Arc` clone.+ ///+ /// `spawn_blocking` tasks cannot be cancelled once started. A timed-out or+ /// dropped request therefore leaves the load running to completion, which+ /// is useful: it warms the immutable segment for the next request. The+ /// segment-current check prevents such a detached completion from+ /// resurrecting a cache entry that a concurrent merge already retired.+ async fn stored_values_for_async(&self, segment_id: &str) -> Option<Arc<Vec<Value>>> {+ if let Some(entry) = self.stored_value_cache.get(segment_id) {+ return Some(Arc::clone(entry.value()));+ }++ let segment_id = segment_id.to_string();+ let mut receiver = {+ use dashmap::mapref::entry::Entry;+ match self.stored_value_loads.entry(segment_id.clone()) {+ Entry::Occupied(entry) => entry.get().subscribe(),+ Entry::Vacant(entry) => {+ let (sender, receiver) = tokio::sync::watch::channel(None);+ entry.insert(sender.clone());++ let store = Arc::clone(&self.store);+ let cache = Arc::clone(&self.stored_value_cache);+ let lifecycle = Arc::clone(&self.stored_value_cache_lifecycle);+ let loads = Arc::clone(&self.stored_value_loads);+ let load_semaphore = Arc::clone(&self.stored_value_load_semaphore);+ let load_segment_id = segment_id.clone();+ #[cfg(test)]+ let load_delay_ms = Arc::clone(&self.test_stored_value_load_delay_ms);+ #[cfg(test)]+ let load_count = Arc::clone(&self.test_stored_value_load_count);+ #[cfg(test)]+ let pause_before_publish =+ Arc::clone(&self.test_stored_value_load_pause_before_publish);+ #[cfg(test)]+ let ready_to_publish =+ Arc::clone(&self.test_stored_value_load_ready_to_publish);+ tokio::spawn(async move {+ let Ok(permit) = load_semaphore.acquire_owned().await else {+ loads.remove(&segment_id);+ return;+ };+ let blocking = tokio::task::spawn_blocking(move || {+ #[cfg(test)]+ {+ load_count.fetch_add(1, Ordering::Relaxed);+ let delay_ms = load_delay_ms.load(Ordering::Relaxed);+ if delay_ms > 0 {+ std::thread::sleep(std::time::Duration::from_millis(delay_ms));+ }+ }+ let reader = store.open_segment(&load_segment_id).ok()?;+ let stored_bytes_raw = reader.section(SectionType::Stored).ok()??;+ let stored_bytes =+ xerj_storage::stored_codec::decode_stored(stored_bytes_raw).ok()?;+ let docs: Vec<Value> = serde_json::from_slice(&stored_bytes).ok()?;+ let arc = Arc::new(docs);+ #[cfg(test)]+ {+ ready_to_publish.store(true, Ordering::Release);+ while pause_before_publish.load(Ordering::Acquire) {+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ }+ {+ let _publication = lifecycle.read();+ if store+ .snapshot()+ .segments+ .iter()+ .any(|meta| meta.id == load_segment_id)+ {+ cache.insert(load_segment_id, Arc::clone(&arc));+ }+ }+ Some(arc)+ });+ if let Ok(Some(value)) = blocking.await {+ let _ = sender.send(Some(value));+ }+ drop(permit);+ loads.remove(&segment_id);+ });+ receiver+ }+ }+ };++ loop {+ if let Some(value) = receiver.borrow_and_update().clone() {+ return Some(value);+ }+ if receiver.changed().await.is_err() {+ return None;+ }+ }+ }+/// Cache-backed range pre-filter — returns the set of internal doc/// positions matching a `Range` query, used to skip over non-matching/// docs in the stored-section scan.