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(ingest): bounded window concurrency for neural _bulk embedding (#938 slice 1)
xerj-org2c5091dd950b
diff --git a/benchmarks/neural-path-triage/window_concurrency_bench.py b/benchmarks/neural-path-triage/window_concurrency_bench.pynew file mode 100644index 000000000..3db20d3b6--- /dev/null+++ b/benchmarks/neural-path-triage/window_concurrency_bench.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+"""`_bulk` ingest throughput into a `semantic_text` field at a given+`embedding.neural_window_concurrency`, on a SYNTHETIC corpus (no BEIR+download), with the server's own CPU use so "how many cores did it keep busy"+is a number (#938).++ python3 window_concurrency_bench.py <url> <server_pid> <n_docs> \+ [--chars 1470] [--bulk 50] [--clients 1] [--seed 938] [--warmup 20]++The server must ALREADY be running with `--embed-mode neural` and the+`neural_window_concurrency` you want to measure — the harness does not restart+it. Warmup docs are indexed first so the model download/load lands outside the+timed window. Deterministic: the corpus is a fixed seed, so every run against+the same <n_docs>/<chars>/<seed> sends identical bytes. Linux only (/proc).+WRITES to the node: creates and deletes throwaway indices named wc_*.+"""+import concurrent.futures as cf+import json+import os+import random+import sys+import time++from common import http, process_cpu_seconds++url, pid, n = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])+rest = sys.argv[4:]+opt = {rest[i]: rest[i + 1] for i in range(0, len(rest) - 1, 2)}+CHARS = int(opt.get("--chars", "1470"))+BULK = int(opt.get("--bulk", "50"))+CLIENTS = int(opt.get("--clients", "1"))+SEED = int(opt.get("--seed", "938"))+WARMUP = int(opt.get("--warmup", "20"))++WORDS = ("the model encodes a passage into one vector by averaging token "+ "embeddings attention weights layer normalization training corpus "+ "retrieval relevance ranking query document evidence abstract "+ "scientific study result method analysis evaluation benchmark "+ "index shard segment memory disk throughput latency measurement "+ "engine thread core scheduler window concurrent forward pass").split()+++def doc(rng, chars):+ parts, total = [], 0+ while total < chars:+ n = rng.randint(14, 24)+ s = " ".join(rng.choice(WORDS) for _ in range(n)) + "."+ parts.append(s.capitalize() if parts else s.capitalize())+ total += len(s) + 1+ return " ".join(parts)[:chars]+++rng = random.Random(SEED)+docs = [doc(rng, CHARS) for _ in range(n)]+mean_chars = sum(map(len, docs)) / len(docs)+print(f"docs={len(docs)} mean_chars={mean_chars:.0f} bulk={BULK} "+ f"clients={CLIENTS} cores={os.cpu_count()}", flush=True)+++def bulk(name, part, off):+ lines = []+ for j, d in enumerate(part):+ lines.append(json.dumps({"index": {"_index": name, "_id": str(off + j)}}))+ lines.append(json.dumps({"text": d, "body": d}))+ r = http(url, "POST", "/_bulk", ("\n".join(lines) + "\n").encode(),+ "application/x-ndjson")+ return bool(r.get("errors")), str(r)[:200]+++def one_pass(name, corpus):+ http(url, "DELETE", "/" + name)+ http(url, "PUT", "/" + name, {"mappings": {"properties": {+ "text": {"type": "text"}, "body": {"type": "semantic_text"}}}})+ parts = [(corpus[i:i + BULK], i) for i in range(0, len(corpus), BULK)]+ load = open("/proc/loadavg").read().split()[0]+ c0, t0 = process_cpu_seconds(pid), time.time()+ with cf.ThreadPoolExecutor(CLIENTS) as ex:+ res = list(ex.map(lambda a: bulk(name, *a), parts))+ wall, used = time.time() - t0, process_cpu_seconds(pid) - c0+ errs = [r for r in res if r[0]]+ http(url, "POST", f"/{name}/_refresh")+ count = http(url, "GET", f"/{name}/_count").get("count")+ print(f"loadavg={load} docs={len(corpus)} indexed={count} errors={len(errs)} "+ f"wall={wall:6.1f}s docs/s={len(corpus) / wall:6.1f} "+ f"server_cpu_s={used:7.1f} avg_cores_busy={used / wall:5.1f}", flush=True)+ if errs:+ print(" first error:", errs[0][1])+ sys.exit(1)+ http(url, "DELETE", "/" + name)+++if WARMUP:+ one_pass("wc_warmup", docs[:WARMUP]) # pays model download + load+one_pass("wc_measure", docs)diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex fdb3ed173..474bfd6e4 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -1,6 +1,6 @@//! xerj configuration system.//!-//! Configuration is intentionally minimal: **120 settings** versus+//! Configuration is intentionally minimal: **121 settings** versus//! Elasticsearch's 3000+. Every option is named, documented, and has a sensible//! production-ready default. The format is TOML, loaded from a single file.//!@@ -72,7 +72,7 @@ pub struct Config {pub vector: VectorConfig,/// Log (time-series) retention — 2 settings.pub logs: LogsConfig,- /// External embedding service — 19 settings.+ /// External embedding service — 20 settings.pub embedding: EmbeddingConfig,/// Resource limits — 14 settings.pub limits: LimitsConfig,@@ -99,7 +99,7 @@ pub struct Config {pub rerank: RerankProviderConfig,}-// 22 sub-configs, 120 leaf settings in total. Do not maintain that sum by hand+// 22 sub-configs, 121 leaf settings in total. Do not maintain that sum by hand// — `journey_zero_config` in xerj-engine/tests/product_experience.rs counts a// serialised `Config::default()` and fails if this comment and the module// header stop matching. `Default` is derived: every field is a sub-config that@@ -251,6 +251,11 @@ impl Config {"embedding.onnx_session_pool_size must be in 1..=2",));}+ if !(1..=64).contains(&self.embedding.neural_window_concurrency) {+ return Err(XerjError::config(+ "embedding.neural_window_concurrency must be in 1..=64",+ ));+ }// ── Config honesty guards ────────────────────────────────────────────// Some config knobs exist in the schema but are not wired into any code@@ -463,7 +468,7 @@ impl Config {}// ═════════════════════════════════════════════════════════════════════════════-// Sub-configs (120 user-facing settings total; counted by+// Sub-configs (121 user-facing settings total; counted by// `journey_zero_config`, not by hand)// ═════════════════════════════════════════════════════════════════════════════@@ -1295,7 +1300,7 @@ impl Default for LogsConfig {/// * `"auto"` (default) — use the proxy when [`default_endpoint`] is set,/// otherwise lexical. This preserves the historical behavior exactly.///-/// **19 settings.**+/// **20 settings.**#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default, deny_unknown_fields)]pub struct EmbeddingConfig {@@ -1320,6 +1325,16 @@ pub struct EmbeddingConfig {/// safetensors weights from this local directory instead of downloading/// — for air-gapped / offline deployments. Empty (default) = download.pub local_model_dir: String,+ /// Neural backend: how many of one `_bulk` request's scheduling windows+ /// may run through the embedder concurrently (default: `1`, range:+ /// `1..=64`). The default preserves the historical strictly-serial+ /// window loop exactly. `1` is also right for the lexical and proxy+ /// backends, where there is nothing to overlap. For+ /// `mode = "neural"` on a many-core box, raising it lets one `_bulk`+ /// stream keep several BERT forward passes in flight on the shared+ /// model instead of one (#938); every window is still embedded as its+ /// own batch and reassembled by position, so outputs are unchanged.+ pub neural_window_concurrency: usize,/// Experimental ONNX backend: local FP32 all-MiniLM-L6-v2-compatible/// model with int64 BERT inputs and a width-384 token-embedding output./// Required when `mode = "onnx-experimental"`; never auto-downloaded.@@ -1375,6 +1390,7 @@ impl Default for EmbeddingConfig {neural_model: "sentence-transformers/all-MiniLM-L6-v2".to_string(),model_cache_dir: String::new(),local_model_dir: String::new(),+ neural_window_concurrency: 1,onnx_model_path: String::new(),onnx_tokenizer_path: String::new(),onnx_scheduling_window: 64,@@ -2935,6 +2951,41 @@ mod tests {assert_eq!(cfg.embedding.onnx_session_pool_size, 1);}+ /// The window concurrency opt-in must default to serial (#938): an+ /// operator who never touches it keeps the one-window-at-a-time loop+ /// that shipped before the key existed.+ #[test]+ fn neural_window_concurrency_defaults_to_serial() {+ assert_eq!(Config::default().embedding.neural_window_concurrency, 1);+ let cfg = Config::from_toml_str("[embedding]\n").unwrap();+ assert_eq!(cfg.embedding.neural_window_concurrency, 1);+ let cfg = Config::from_toml_str("[embedding]\nmode = \"neural\"\n").unwrap();+ assert_eq!(cfg.embedding.neural_window_concurrency, 1);+ // Round-trips through the file format.+ let cfg = Config::from_toml_str("[embedding]\nneural_window_concurrency = 8\n").unwrap();+ assert_eq!(cfg.embedding.neural_window_concurrency, 8);+ }++ #[test]+ fn neural_window_concurrency_accepts_only_bounded_values() {+ for value in [1usize, 2, 8, 64] {+ Config::from_toml_str(&format!(+ "[embedding]\nneural_window_concurrency = {value}\n"+ ))+ .unwrap_or_else(|error| {+ panic!("neural_window_concurrency={value} must be valid: {error}")+ });+ }+ for value in [0usize, 65] {+ Config::from_toml_str(&format!(+ "[embedding]\nneural_window_concurrency = {value}\n"+ ))+ .expect_err(&format!(+ "neural_window_concurrency={value} must be rejected"+ ));+ }+ }+#[test]fn onnx_throughput_controls_accept_only_bounded_values() {for (key, valid) in [@@ -3018,7 +3069,7 @@ mod tests {("fts", 1),("vector", 6),("logs", 2),- ("embedding", 19),+ ("embedding", 20),("limits", 14),("indexing", 3),("engine", 4),@@ -3072,7 +3123,7 @@ mod tests {"the section table must sum to the whole config");assert_eq!(- total, 120,+ total, 121,"the total settings count changed. It is quoted in this module's \header, in xerj-common/src/lib.rs, in engine/README.md, in \xerj.default.toml and in EXPECTED_SETTINGS in \diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 0910053a2..f86d0b666 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -14788,6 +14788,15 @@ impl Index {// windows together, drain both, then consume results in input// order. This bounds native work and keeps retry/publication// behavior deterministic when one sibling fails.+ //+ // Every other backend runs the same windows through a+ // bounded-concurrency scheduler: the default bound of 1 is the+ // historical one-window-at-a-time loop, and+ // `embedding.neural_window_concurrency` raises it so a single+ // `_bulk` stream can keep several neural forward passes in flight+ // on the shared model instead of one (#938). Each window is still+ // embedded as its own batch and reassembled by position, so the+ // vectors computed per passage are identical to the serial loop.let mut window_results = Vec::with_capacity(windows.len());if dual_session_scheduler_enabled(onnx_pinned,@@ -14805,14 +14814,21 @@ impl Index {.map(|(window, result)| (window.0, window.1, window.2, result)),);} else {- for &(start, end, passages) in &windows {- window_results.push((- start,- end,- passages,- embedder.embed_batch(window_texts(start, end)).await,- ));- }+ let results = collect_ordinal_buffered(+ windows.len(),+ self.embedding_config.neural_window_concurrency,+ |ordinal| {+ let (start, end, _passages) = windows[ordinal];+ embedder.embed_batch(window_texts(start, end))+ },+ )+ .await;+ window_results.extend(+ windows+ .iter()+ .zip(results)+ .map(|(window, result)| (window.0, window.1, window.2, result)),+ );}for (start, end, passages, batch_result) in window_results {@@ -47876,10 +47892,75 @@ fn dual_session_scheduler_enabled(onnx_pinned: bool, pool_size: usize) -> bool {onnx_pinned && pool_size == 2}+/// Run at most `bound` futures concurrently and return every result in input+/// order (#938). With `bound = 1` this is the historical strictly-serial loop;+/// higher bounds let one `_bulk` request keep several embedding scheduling+/// windows in flight at once. Like `collect_ordinal_buffered_two`, a future+/// that resolves with an error (as a value) neither cancels nor reorders its+/// neighbours — every launched ordinal yields exactly one result, and the+/// caller keeps per-window failure semantics. Only completed results at the+/// front of the window are retired, so no ordinal is launched before an+/// in-flight slot is free and nothing is materialized beyond `bound` windows.+async fn collect_ordinal_buffered<T, F, Fut>(count: usize, bound: usize, launch: F) -> Vec<T>+where+ F: Fn(usize) -> Fut,+ Fut: std::future::Future<Output = T>,+{+ use std::collections::VecDeque;+ use std::pin::Pin;+ use std::task::Poll;++ let bound = bound.max(1);+ let mut next_ordinal = 0usize;+ // Futures are boxed so the window can shrink and grow without moving a+ // pinned future; `done` mirrors it slot-for-slot so a finished future is+ // never polled twice.+ let mut in_flight: VecDeque<Pin<Box<Fut>>> = VecDeque::new();+ let mut done: VecDeque<Option<T>> = VecDeque::new();+ let mut results = Vec::with_capacity(count);+ while results.len() < count {+ while in_flight.len() < bound && next_ordinal < count {+ in_flight.push_back(Box::pin(launch(next_ordinal)));+ done.push_back(None);+ next_ordinal += 1;+ }+ // Poll the whole window each wakeup; wake when the FRONT is finished,+ // because results are retired strictly in ordinal order.+ std::future::poll_fn(|cx| {+ let mut front_done = false;+ for (slot, fut) in in_flight.iter_mut().enumerate() {+ if done[slot].is_some() {+ front_done |= slot == 0;+ continue;+ }+ if let Poll::Ready(value) = fut.as_mut().poll(cx) {+ done[slot] = Some(value);+ front_done |= slot == 0;+ }+ }+ if front_done {+ Poll::Ready(())+ } else {+ Poll::Pending+ }+ })+ .await;+ // Retire every already-finished future at the front of the window,+ // freeing slots (this is the only place the bound is enforced).+ while let Some(value) = done.front_mut().and_then(Option::take) {+ done.pop_front();+ in_flight.pop_front();+ results.push(value);+ }+ }+ results+}+#[cfg(test)]mod semantic_embedding_window_tests {use super::{- collect_ordinal_buffered_two, dual_session_scheduler_enabled, semantic_embedding_window_end,+ collect_ordinal_buffered, collect_ordinal_buffered_two, dual_session_scheduler_enabled,+ semantic_embedding_window_end,};fn windows(counts: &[usize], limit: usize) -> Vec<(std::ops::Range<usize>, usize)> {@@ -47938,6 +48019,169 @@ mod semantic_embedding_window_tests {assert_eq!(completed.load(Ordering::SeqCst), 3);assert_eq!(results, vec![Err("first failed"), Ok(1), Ok(2)]);}++ /// #938: the bounded scheduler must actually fill its window. Ordinal 0+ /// yields until `bound` futures have entered, so it can only complete if+ /// the scheduler truly launched `bound` windows before retiring any — a+ /// scheduler that ignored the bound and ran serially would spin here+ /// forever and trip the bounded loop's assertion.+ #[tokio::test]+ async fn bounded_scheduler_runs_a_full_window_concurrently() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;++ let bound = 4;+ let count = 10;+ let entered = Arc::new(AtomicUsize::new(0));+ let in_flight = Arc::new(AtomicUsize::new(0));+ let max_in_flight = Arc::new(AtomicUsize::new(0));++ let results = collect_ordinal_buffered(count, bound, |ordinal| {+ let entered = Arc::clone(&entered);+ let in_flight = Arc::clone(&in_flight);+ let max_in_flight = Arc::clone(&max_in_flight);+ async move {+ let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ max_in_flight.fetch_max(now, Ordering::SeqCst);+ if ordinal < bound {+ // Hold the front of the window open until the whole first+ // window is in flight (the gate is one-shot: only the+ // first `bound` ordinals wait).+ entered.fetch_add(1, Ordering::SeqCst);+ for _ in 0..10_000 {+ if entered.load(Ordering::SeqCst) >= bound {+ break;+ }+ tokio::task::yield_now().await;+ }+ assert!(+ entered.load(Ordering::SeqCst) >= bound,+ "ordinal {ordinal} released without {bound} windows in flight"+ );+ }+ in_flight.fetch_sub(1, Ordering::SeqCst);+ ordinal * 2+ }+ })+ .await;++ assert_eq!(results, (0..count).map(|i| i * 2).collect::<Vec<_>>());+ assert_eq!(+ max_in_flight.load(Ordering::SeqCst),+ bound,+ "the scheduler must reach exactly its bound and never exceed it"+ );+ }++ /// #938: reversed completion drains in ordinal order and a window that+ /// fails as a value neither cancels nor displaces its neighbours — the+ /// same per-window failure contract the pair scheduler has.+ #[tokio::test]+ async fn bounded_scheduler_drains_reversed_completion_in_ordinal_order() {+ use std::sync::Arc;+ let front_park = Arc::new(tokio::sync::Notify::new());+ let results = collect_ordinal_buffered(5, 3, |ordinal| {+ let front_park = Arc::clone(&front_park);+ async move {+ if ordinal == 0 {+ // The front window finishes LAST: ordinal 2 must pass it+ // through before it can retire.+ front_park.notified().await;+ Err("first failed")+ } else {+ if ordinal == 2 {+ front_park.notify_one();+ }+ Ok(ordinal)+ }+ }+ })+ .await;+ assert_eq!(+ results,+ vec![Err("first failed"), Ok(1), Ok(2), Ok(3), Ok(4)]+ );+ }++ /// #938 golden-vector guard: raising the bound must not change WHAT is+ /// computed, only how many windows compute at once. Each window is+ /// embedded as its own batch with its own texts in every configuration,+ /// and results are reassembled by position.+ #[tokio::test]+ async fn bounded_scheduler_output_is_independent_of_the_bound() {+ use std::sync::{Arc, Mutex};++ // ~120-passage jobs cut into windows of 64 passages, like a `_bulk`+ // request of 3-4 passage documents through the default window.+ let counts = [30, 34, 60, 4, 64, 10, 1, 7];+ let windowed = windows(&counts, 64);+ assert!(windowed.len() >= 3, "exercise multiple windows");++ for bound in [1usize, 2, 8] {+ // The launch closure must be `Fn`: share the window table by+ // reference instead of letting each iteration capture it by move.+ let windowed = &windowed;+ let batches: Arc<Mutex<Vec<(usize, Vec<String>)>>> = Arc::new(Mutex::new(Vec::new()));+ let batches_for_launch = Arc::clone(&batches);+ let results = collect_ordinal_buffered(windowed.len(), bound, |ordinal| {+ let batches = Arc::clone(&batches_for_launch);+ async move {+ let range = windowed[ordinal].0.clone();+ let texts: Vec<String> = range+ .map(|job| format!("passages:{}:{}", counts[job], job))+ .collect();+ let vectors: Vec<Vec<f32>> = texts+ .iter()+ .map(|t| vec![t.len() as f32, ordinal as f32])+ .collect();+ // Completion order varies with the bound; the ordinal+ // restores the launch order for the comparison below.+ batches.lock().unwrap().push((ordinal, texts));+ vectors+ }+ })+ .await;+ let mut batches = batches.lock().unwrap().clone();+ batches.sort_by_key(|(ordinal, _)| *ordinal);++ // Same window batches, in the same order, at every bound.+ let expected_texts: Vec<Vec<String>> = windowed+ .iter()+ .map(|(range, _)| {+ range+ .clone()+ .map(|job| format!("passages:{}:{}", counts[job], job))+ .collect()+ })+ .collect();+ assert_eq!(+ batches+ .into_iter()+ .map(|(_, texts)| texts)+ .collect::<Vec<_>>(),+ expected_texts,+ "bound={bound} changed the batches"+ );+ // Same vectors at the same positions at every bound.+ let expected_vectors: Vec<Vec<Vec<f32>>> = windowed+ .iter()+ .enumerate()+ .map(|(ordinal, (range, _))| {+ range+ .clone()+ .map(|job| {+ let text = format!("passages:{}:{}", counts[job], job);+ vec![text.len() as f32, ordinal as f32]+ })+ .collect()+ })+ .collect();+ assert_eq!(+ results, expected_vectors,+ "bound={bound} changed the vectors"+ );+ }+ }}/// The chunker used by the auto-embed-on-ingest path.diff --git a/engine/crates/xerj-engine/tests/product_experience.rs b/engine/crates/xerj-engine/tests/product_experience.rsindex ce82bc807..02724d786 100644--- a/engine/crates/xerj-engine/tests/product_experience.rs+++ b/engine/crates/xerj-engine/tests/product_experience.rs@@ -753,7 +753,7 @@ fn count_settings(value: &serde_json::Value) -> usize {/// Settings in a default `Config`, measured by `count_settings`. Quoted in/// `xerj-common/src/config.rs`; keep the two in step.-const EXPECTED_SETTINGS: usize = 120;+const EXPECTED_SETTINGS: usize = 121;#[tokio::test]async fn journey_zero_config() {diff --git a/engine/xerj.default.toml b/engine/xerj.default.tomlindex 402d6d9c1..4db05597e 100644--- a/engine/xerj.default.toml+++ b/engine/xerj.default.toml@@ -1,6 +1,6 @@# xerj Default Configuration# ============================================================-# This file sets 55 of XERJ's 120 user-facing settings to their+# This file sets 55 of XERJ's 121 user-facing settings to their# production-ready defaults, and describes the rest in comments.# Every value here IS the default, so copying this file changes# nothing until you edit it (a test enforces that). The complete@@ -410,6 +410,14 @@ batch_size = 64# request fails with a timeout error.timeout_ms = 5000+# Neural backend (`--embed-mode neural`): how many scheduling windows of one+# _bulk request may run through the embedder concurrently. Default 1 keeps the+# historical strictly-serial window loop. Raise it on a many-core box to let a+# single _bulk stream keep several BERT forward passes in flight on the shared+# model instead of one; outputs are unchanged (each window stays its own batch).+# Range: 1 – 64.+# neural_window_concurrency = 1+# ── Resource Limits (6 of 14 settings) ────────────────────────────────────────[limits]