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(engine): flush one shard at a time when draining for memory pressure (#2753)
xerj-orge5675decc350
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c2c5cab2..a56a382da 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -68,6 +68,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0longer take a node from below the watermark into the parent breaker band andturn ingest into HTTP 429s. The relief for a search node resting between themerge-pool ceiling and the watermark is kept (#2427).+- **A memory-pressure drain no longer spikes RSS past the cap while it+ flushes** (#2427). The breaker drain and the cache-release path+ flushed each index with every non-empty memtable shard building its+ segment at once, and that working set (parsed documents, columns,+ postings, stored blocks) is not charged to the memtable budget. On a+ 1,536 MB-capped node one drain took RSS from 1,460 MB to 2,323 MB in+ about a second. Memory-release flushes now build one shard at a time;+ ordinary flushes still run in parallel.- The per-index document version map is smaller and now visible in theingest memory trace. Its keys are `Box<str>` instead of `String`, whichdiff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 0143387b8..e5dcae4ee 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -4566,8 +4566,11 @@ impl Engine {if release_caches {return self.release_rebuildable_memory(&loaded).await;}+ // One shard at a time (#2427): the flush working set is uncharged,+ // and building every shard at once is what pushed RSS past the cap+ // in the middle of the drain meant to bring it down.for idx in &loaded {- if idx.memtable_bytes() > 0 && idx.flush().await.is_err() {+ if idx.memtable_bytes() > 0 && idx.flush_one_shard_at_a_time().await.is_err() {tracing::warn!("memory pressure drain: flush failed");}}@@ -4641,7 +4644,9 @@ impl Engine {/// released.pub async fn release_rebuildable_memory(&self, indices: &[Arc<Index>]) -> usize {for idx in indices {- if idx.memtable_bytes() > 0 && idx.flush().await.is_err() {+ // Serial for the same reason as `pressure_drain` (#2427): a+ // release must not spike RSS on its way down.+ if idx.memtable_bytes() > 0 && idx.flush_one_shard_at_a_time().await.is_err() {tracing::warn!("memory release: flush failed, releasing caches anyway");}idx.release_memory();@@ -6616,3 +6621,75 @@ mod pressure_drain_tests {);}}++#[cfg(test)]+mod serial_pressure_flush_tests {+ use super::Engine;+ use crate::index::FlushShardProbe;+ use serde_json::json;+ use tempfile::TempDir;+ use xerj_common::config::Config;+ use xerj_common::types::{FieldConfig, FieldType, Schema};++ async fn seed(engine: &Engine, name: &str, n: usize) {+ let mut schema = Schema::empty();+ schema+ .fields+ .push(FieldConfig::new("body", FieldType::Text));+ engine.create_index(name, schema).expect("create");+ let idx = engine.get_index(name).expect("get");+ for i in 0..n {+ idx.index_document(+ Some(format!("d{i}")),+ json!({ "body": format!("document number {i}") }),+ )+ .await+ .expect("index");+ }+ }++ async fn count_all(engine: &Engine, name: &str) -> u64 {+ let idx = engine.get_index(name).expect("get index");+ let req = xerj_query::parse_request(+ &json!({ "query": { "match_all": {} }, "size": 0, "from": 0 }),+ )+ .expect("parse_request");+ idx.search(&req).await.expect("search").total.value+ }++ /// #2427: a breaker drain builds one shard segment at a time. The flush+ /// working set (parsed docs, columns, postings, stored blocks) is not+ /// charged to the memtable budget, and a drain that built every shard at+ /// once took RSS from 1,460 MB to 2,323 MB on a 1,536 MB-capped node.+ /// The control index shows the ordinary flush still fans out, so the+ /// probe does see concurrency when there is some. FAIL-BEFORE:+ /// `pressure_drain` called `Index::flush`, which runs every non-empty+ /// shard at once (peak > 1 here).+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn a_pressure_drain_flushes_one_shard_at_a_time() {+ let dir = TempDir::new().unwrap();+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ let engine = Engine::new(config).expect("engine::new");++ seed(&engine, "serial-drain-control", 400).await;+ let control = engine.get_index("serial-drain-control").unwrap();+ control.flush().await.expect("flush");+ assert!(+ FlushShardProbe::peak("serial-drain-control") > 1,+ "the ordinary flush runs shards concurrently"+ );++ seed(&engine, "serial-drain", 400).await;+ let idx = engine.get_index("serial-drain").unwrap();+ assert!(idx.memtable_bytes() > 0);+ engine.pressure_drain(false).await;+ assert_eq!(idx.memtable_bytes(), 0, "the drain published the memtable");+ assert_eq!(+ FlushShardProbe::peak("serial-drain"),+ 1,+ "a pressure drain must build one shard at a time"+ );+ assert_eq!(count_all(&engine, "serial-drain").await, 400);+ }+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 20fe721a9..1bdbe3341 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -28693,6 +28693,25 @@ impl Index {/// Flush the memtable to a new segment on disk, then build the FTS index.pub async fn flush(self: &Arc<Self>) -> Result<()> {+ self.flush_with(FlushFanout::Parallel).await+ }++ /// [`Self::flush`] with one shard building at a time (#2427).+ ///+ /// A shard flush parses the drained documents, builds columns, postings+ /// and the stored blocks, and none of that working set is charged to the+ /// memtable budget. The parallel flush builds every non-empty shard at+ /// once (bounded only by the finalize gate), so a breaker drain on a+ /// 1,536 MB-capped node took RSS from 1,460 MB to 2,323 MB in about a+ /// second while four shards built together. A memory-release caller+ /// wants the peak bounded more than it wants the drain short: each+ /// shard's segment publishes and its working set is freed before the+ /// next shard starts.+ pub async fn flush_one_shard_at_a_time(self: &Arc<Self>) -> Result<()> {+ self.flush_with(FlushFanout::Serial).await+ }++ async fn flush_with(self: &Arc<Self>, fanout: FlushFanout) -> Result<()> {// #873: this flush is about to take whatever the memtable holds, so// every idle-probe observation about it is stale from here on. Clear// the pair at the ONE coordinator every flush path runs through@@ -28756,6 +28775,7 @@ impl Index {// coordinator is not aborted (#1015).let coordinator = tokio::spawn(async move {let mut shard_futures = Vec::with_capacity(n_shards);+ let mut result: Result<()> = Ok(());for shard_idx in 0..n_shards {// #1226 — do not fan a finalize out for an EMPTY shard.//@@ -28789,7 +28809,9 @@ impl Index {let shard_index_name = coordinator_name.clone();#[cfg(test)]let test_hook = flush_test_hook.clone();- shard_futures.push(tokio::spawn(async move {+ let shard_task = tokio::spawn(async move {+ #[cfg(test)]+ let _in_flight = FlushShardProbe::enter(&shard_index_name).await;let permit = match wait_for_flush_permit(&shard_index_name,"the flush semaphore",@@ -28831,19 +28853,14 @@ impl Index {let _ = guard.take();}result- }));+ });+ match fanout {+ FlushFanout::Parallel => shard_futures.push(shard_task),+ FlushFanout::Serial => fold_shard_flush(&mut result, shard_task.await),+ }}- let mut result: Result<()> = Ok(());for fut in shard_futures {- match fut.await {- Ok(Ok(())) => {}- Ok(Err(e)) => result = Err(e),- Err(error) => {- result = Err(EngineError::Common(xerj_common::XerjError::internal(- format!("flush shard task failed: {error}"),- )));- }- }+ fold_shard_flush(&mut result, fut.await);}// Publication completion must invalidate results even when the// request that initiated the flush was cancelled. The coordinator@@ -36686,6 +36703,79 @@ tokio::task_local! {static FLUSH_PUBLISHER_TEST_HOOK: FlushPublisherTestHook;}+/// How [`Index::flush_with`] runs its shard flushes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum FlushFanout {+ /// Every non-empty shard at once (M5.15): the shortest flush.+ Parallel,+ /// One shard after another: the smallest uncharged working set (#2427).+ Serial,+}++/// Keep the last shard error, as the parallel join always has.+fn fold_shard_flush(+ result: &mut Result<()>,+ joined: std::result::Result<Result<()>, tokio::task::JoinError>,+) {+ match joined {+ Ok(Ok(())) => {}+ Ok(Err(e)) => *result = Err(e),+ Err(error) => {+ *result = Err(EngineError::Common(xerj_common::XerjError::internal(+ format!("flush shard task failed: {error}"),+ )));+ }+ }+}++/// Test-only count of shard-flush tasks in flight per index, with the peak.+#[cfg(test)]+static FLUSH_SHARD_PROBE: std::sync::LazyLock<+ dashmap::DashMap<+ String,+ (+ Arc<std::sync::atomic::AtomicUsize>,+ Arc<std::sync::atomic::AtomicUsize>,+ ),+ >,+> = std::sync::LazyLock::new(dashmap::DashMap::new);++#[cfg(test)]+pub(crate) struct FlushShardProbe(Arc<std::sync::atomic::AtomicUsize>);++#[cfg(test)]+impl FlushShardProbe {+ /// Count this shard task in, then yield so sibling tasks of a parallel+ /// flush get scheduled while it is still counted.+ async fn enter(index: &str) -> Self {+ use std::sync::atomic::Ordering;+ let (in_flight, peak) = FLUSH_SHARD_PROBE+ .entry(index.to_string())+ .or_default()+ .value()+ .clone();+ let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ peak.fetch_max(now, Ordering::SeqCst);+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ FlushShardProbe(in_flight)+ }++ /// Peak shard-flush tasks in flight at once for `index` so far.+ pub(crate) fn peak(index: &str) -> usize {+ FLUSH_SHARD_PROBE+ .get(index)+ .map(|e| e.value().1.load(std::sync::atomic::Ordering::SeqCst))+ .unwrap_or(0)+ }+}++#[cfg(test)]+impl Drop for FlushShardProbe {+ fn drop(&mut self) {+ self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ }+}+// This deliberately remains a free function so background tasks can own every// flush dependency without retaining `Index`; grouping the values would only// hide the same pipeline dependency set behind an uninformative bag of fields.