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): do not stall _refresh behind a background merge (#2245)
xerj-org3faac6008022
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ecd09721..9b14502b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `POST /{index}/_refresh` makes recent writes searchable without waiting for+ a background segment merge to finish, and a multi-index or wildcard refresh+ is not serialized behind one busy index. The route used to call the+ durability flush (snapshot fsync and WAL prune) once per index; autoindex+ finalize sent that as one `POST /<prefix>-*/_refresh` and stalled at the+ end of the run when a large matching index had a merge in progress.+ `_refresh` now publishes an unflushed memtable and returns immediately when+ the memtable is already empty. `_flush` is unchanged and still checkpoints+ the WAL. A merge encode no longer occupies a tokio blocking thread for the+ whole encode, so a refresh that does have to publish a segment is not+ queued behind that merge. Autoindex finalize refreshes each dataset index+ (and the edges index) on its own, names the index it is waiting on, and+ does not retry a timed-out refresh+ ([#2234](https://github.com/xerj-org/xerj/issues/2234)).+- A matching index template's `semantic_text` properties and`index.default_pipeline` are applied when an index is created, includingthe body `xerj autoindex` sends and the first bulk or single-documentdiff --git a/engine/crates/xerj-api/Cargo.toml b/engine/crates/xerj-api/Cargo.tomlindex 5c680e4dd..3a6b1f2bf 100644--- a/engine/crates/xerj-api/Cargo.toml+++ b/engine/crates/xerj-api/Cargo.toml@@ -75,5 +75,8 @@ sha2 = "0.10"[dev-dependencies]tempfile = { workspace = true }+# #2234: the HTTP refresh test holds one index inside `Index::refresh`.+# The feature stays off the release graph (resolver v2, dev-dependency only).+xerj-engine = { path = "../xerj-engine", features = ["refresh-test-hook"] }tower = { workspace = true, features = ["util"] }http-body-util = "0.1"diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex b5dc3a1a9..494ea85ad 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -23019,6 +23019,41 @@ fn apply_one_update_stmt(source: &mut Value, stmt: &str, params: &Value) -> Resu// POST /{index}/_refresh// ─────────────────────────────────────────────────────────────────────────────+/// One `_shards.failures` entry for `_refresh`, in selector order. The first+/// failure's HTTP status becomes the response status (ES+/// `BaseBroadcastResponse::getStatus`).+fn record_refresh_failure(+ failures: &mut Vec<Value>,+ response_status: &mut StatusCode,+ name: &str,+ rendered: Value,+) {+ let status = rendered+ .get("status")+ .and_then(Value::as_u64)+ .and_then(|code| StatusCode::from_u16(code as u16).ok())+ .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);+ if failures.is_empty() {+ *response_status = status;+ }+ let reason = rendered+ .pointer("/error/root_cause/0")+ .or_else(|| rendered.pointer("/error"))+ .cloned()+ .unwrap_or_else(|| json!({ "type": "exception", "reason": "refresh failed" }));+ let status_name = status+ .canonical_reason()+ .unwrap_or("Internal Server Error")+ .to_ascii_uppercase()+ .replace([' ', '-'], "_");+ failures.push(json!({+ "shard": 0,+ "index": name,+ "status": status_name,+ "reason": reason,+ }));+}+pub async fn refresh_index(State(state): State<AppState>,Path(index): Path<String>,@@ -23031,39 +23066,42 @@ pub async fn refresh_index(let mut successful = 0u64;let mut failures = Vec::new();let mut response_status = StatusCode::OK;- // #1635: `Index::flush` bounds both flush admission and the caller-visible- // wait. One stuck index returns an error naming that index; this loop- // records it under `_shards.failures` and continues, so the refresh of- // the other indices in the pattern is not parked behind it.- for (name, idx) in &handles {- match idx.flush().await {+ // #2234: `_refresh` makes writes searchable. It is not `_flush`.+ // `Index::flush` also runs verified WAL maintenance (snapshot fsync and+ // prune). That work shares the disk with a background segment merge, and+ // this handler used to await it one index at a time — a wildcard refresh+ // sat behind the first busy index for the whole flush budget, which is+ // what stalled autoindex finalize. `Index::refresh` publishes an+ // unflushed memtable and returns immediately when that memtable is+ // already empty (#1635 still bounds a memtable that does have to be+ // published). The indices run together, so a healthy index is searchable+ // while a busy one is still inside its own budget. Results are collected+ // in selector order: the first failure still sets the HTTP status.+ let mut tasks = Vec::with_capacity(handles.len());+ for (name, idx) in handles {+ let task_name = name.clone();+ tasks.push((+ name,+ tokio::spawn(async move { (task_name, idx.refresh().await) }),+ ));+ }+ for (name, task) in tasks {+ let (name, result) = match task.await {+ Ok(pair) => pair,+ Err(error) => {+ let rendered = ApiError::new(xerj_common::XerjError::internal(format!(+ "index [{name}] refresh task failed: {error}"+ )))+ .into_value();+ record_refresh_failure(&mut failures, &mut response_status, &name, rendered);+ continue;+ }+ };+ match result {Ok(()) => successful += 1,Err(error) => {let rendered = ApiError::new(xerj_common::XerjError::from(error)).into_value();- let status = rendered- .get("status")- .and_then(Value::as_u64)- .and_then(|code| StatusCode::from_u16(code as u16).ok())- .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);- if failures.is_empty() {- response_status = status;- }- let reason = rendered- .pointer("/error/root_cause/0")- .or_else(|| rendered.pointer("/error"))- .cloned()- .unwrap_or_else(|| json!({ "type": "exception", "reason": "refresh failed" }));- let status_name = status- .canonical_reason()- .unwrap_or("Internal Server Error")- .to_ascii_uppercase()- .replace([' ', '-'], "_");- failures.push(json!({- "shard": 0,- "index": name,- "status": status_name,- "reason": reason,- }));+ record_refresh_failure(&mut failures, &mut response_status, &name, rendered);}}}diff --git a/engine/crates/xerj-api/tests/refresh_reports_flush_failure.rs b/engine/crates/xerj-api/tests/refresh_reports_flush_failure.rsindex 9c7506315..9e4a9d327 100644--- a/engine/crates/xerj-api/tests/refresh_reports_flush_failure.rs+++ b/engine/crates/xerj-api/tests/refresh_reports_flush_failure.rs@@ -160,3 +160,111 @@ async fn multi_index_refresh_attempts_every_index_after_a_failure() {"{body}");}++/// #2234 — an already-searchable index must refresh without the durability+/// tail. `Index::flush` (what `_refresh` used to call) always runs verified+/// WAL maintenance, which renames a new `snapshot.json` into place. Replacing+/// that file with a directory makes the rename fail. `_refresh` of an empty+/// memtable must still succeed; `_flush` must still report the failure.+#[tokio::test]+async fn refresh_does_not_wait_on_wal_maintenance() {+ let (app, dir) = app();+ create_text_index_with_document(&app, "refresh-ready").await;++ let (status, body) = request(&app, "POST", "/refresh-ready/_refresh", json!({})).await;+ assert!(+ status.is_success(),+ "the first refresh publishes the document: {status} {body}"+ );+ let (status, body) = request(&app, "GET", "/refresh-ready/_count", json!({})).await;+ assert!(status.is_success(), "{body}");+ assert_eq!(body.get("count"), Some(&json!(1)), "{body}");++ let snap = dir.path().join("refresh-ready").join("snapshot.json");+ assert!(+ snap.is_file(),+ "the publishing refresh should have written snapshot.json"+ );+ std::fs::remove_file(&snap).expect("remove snapshot");+ std::fs::create_dir(&snap).expect("wedge snapshot path");++ let (status, body) = request(&app, "POST", "/refresh-ready/_refresh", json!({})).await;+ assert!(+ status.is_success(),+ "_refresh must not run WAL maintenance: {status} {body}"+ );+ let (status, body) = request(&app, "POST", "/refresh-ready/_flush", json!({})).await;+ assert_eq!(+ status,+ StatusCode::INTERNAL_SERVER_ERROR,+ "_flush must still persist the snapshot: {status} {body}"+ );+}++/// #2234 — a multi-index refresh must not be serialized behind one index.+/// `refresh-busy` is held inside `Index::refresh`. `refresh-healthy` has to+/// finish (its completion counter moves) before that hold is released.+#[tokio::test]+async fn multi_index_refresh_is_not_serialized_behind_one_index() {+ let dir = tempfile::tempdir().expect("data dir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let probe = engine.clone();+ let app = xerj_api::router::build_es_compat_router(xerj_api::state::AppState::new(+ config, engine, metrics,+ ));+ create_text_index_with_document(&app, "refresh-busy").await;+ create_text_index_with_document(&app, "refresh-healthy").await;++ let busy = probe.get_index("refresh-busy").expect("busy index");+ let healthy = probe.get_index("refresh-healthy").expect("healthy index");+ busy.test_set_pause_refresh(true);++ let app_for_request = app.clone();+ let request_task = tokio::spawn(async move {+ request(+ &app_for_request,+ "POST",+ "/refresh-busy,refresh-healthy/_refresh",+ json!({}),+ )+ .await+ });++ tokio::time::timeout(std::time::Duration::from_secs(5), async {+ while !busy.test_refresh_is_paused() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("busy index never entered refresh");++ tokio::time::timeout(std::time::Duration::from_secs(5), async {+ while healthy.test_refresh_finished_count() == 0 {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("healthy index did not finish refresh while the busy index was held");+ assert_eq!(+ busy.test_refresh_finished_count(),+ 0,+ "the held index must not look finished"+ );++ busy.test_set_pause_refresh(false);+ let (status, body) = tokio::time::timeout(std::time::Duration::from_secs(10), request_task)+ .await+ .expect("refresh request did not finish after the hold was released")+ .expect("refresh task");+ assert!(status.is_success(), "{status} {body}");+ assert_eq!(body.pointer("/_shards/total"), Some(&json!(2)), "{body}");+ assert_eq!(+ body.pointer("/_shards/successful"),+ Some(&json!(2)),+ "{body}"+ );+}diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex ded9bd3af..92b086c39 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -622,7 +622,8 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20PHASES, in order. Every long step is a phase of its own, so a line\n\\x20\x20\x20\x20that still says `scan` at 100% means scan — not indexing:\n\\x20\x20\x20\x20\x20\x20default (graph) path: walk, hash, scan, prepare, graph, index,\n\- \x20\x20\x20\x20\x20\x20\x20\x20graph-corpus, finalize-refresh, finalize-count,\n\+ \x20\x20\x20\x20\x20\x20\x20\x20graph-corpus, finalize-refresh (one refresh per dataset,\n\+ \x20\x20\x20\x20\x20\x20\x20\x20the in-flight index named), finalize-count,\n\\x20\x20\x20\x20\x20\x20\x20\x20finalize-correlate, finalize-histogram, finalize-catalog\n\\x20\x20\x20\x20\x20\x20--no-graph path: walk, hash, scan, prepare (install mappings),\n\\x20\x20\x20\x20\x20\x20\x20\x20snapshot (seal + extract, bytes), index (sealed bulk bytes, the\n\diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex a452d3777..3f751adea 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -2241,6 +2241,29 @@ impl Es {)}+ /// One `_refresh`, with no retry.+ ///+ /// [`Self::refresh`] allows six attempts, and each attempt waits on the+ /// client's 300s transport budget. Finalize used to call that against one+ /// wildcard. A single index whose refresh did not return then stalled the+ /// run for the whole budget and started again (#2234). Finalize names the+ /// index it is waiting on and gives that request one attempt: the server+ /// bounds a memtable publish, and a transport timeout is the backstop,+ /// not the start of five more.+ pub fn refresh_once(&self, pattern: &str) -> Result<()> {+ let resp = self+ .req(reqwest::Method::POST, &format!("/{pattern}/_refresh"))+ .send()+ .map_err(|e| anyhow!("refresh {pattern}: {e}"))?;+ if resp.status().is_success() {+ Ok(())+ } else {+ let status = resp.status();+ let body = resp.text().unwrap_or_default();+ Err(anyhow!("refresh {pattern}: HTTP {status}: {body}"))+ }+ }+fn search_raw(&self, index: &str, body: &Value) -> Result<(reqwest::StatusCode, Value)> {self.with_retry("search",@@ -3640,6 +3663,45 @@ mod tests {const BULK: &[u8] = b"{\"index\":{\"_index\":\"i\",\"_id\":\"a\"}}\n{\"v\":1}\n";+ /// #2234 — finalize uses one attempt. `refresh` would open a second+ /// connection after this 500; `refresh_once` must not.+ #[test]+ fn refresh_once_does_not_retry_a_failed_refresh() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let hits = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let hits_for_server = Arc::clone(&hits);+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ hits_for_server.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let _ = read_request(&mut stream);+ respond_status(+ &mut stream,+ "500 Internal Server Error",+ br#"{"error":"no"}"#,+ );+ listener.set_nonblocking(true).unwrap();+ std::thread::sleep(Duration::from_millis(300));+ if listener.accept().is_ok() {+ hits_for_server.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ }+ });++ let es = client(address, 1);+ let error = es.refresh_once("idx").unwrap_err();+ let text = format!("{error:#}");+ assert!(+ text.contains("500"),+ "the failure must name the HTTP status: {text}"+ );+ server.join().unwrap();+ assert_eq!(+ hits.load(std::sync::atomic::Ordering::SeqCst),+ 1,+ "a failed finalize refresh must not be retried"+ );+ }+/// A 429 must shrink the window the run offers load through, and a clean/// streak must probe it back up — never past what the operator asked for.///diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 8db1490b4..110ff55f8 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -10293,30 +10293,43 @@ fn run_index_report_inner(// countable before each loop starts, so it is reported like any other// phase — split into named sub-phases because the mix of one-shot refreshes// and per-dataset round trips has no single honest denominator.- pr.phase("finalize-refresh", 1 + graph.is_some() as u64, 0);- // #1635: a refresh that never returns used to sit here at items=0 with- // no error (`rate=unknown`). The server now fails the stuck index by- // name. Swallowing that (`.ok()`) turned the failure back into a green- // run whose documents were not all refreshed.- let pattern = format!("{}-*", cfg.prefix);- es.refresh(&pattern).map_err(|error| {- anyhow::anyhow!(- "finalize-refresh of {pattern} failed: {error:#}. The server names the index that \- did not refresh; documents already written stay indexed and rerunning the same \- command resumes"- )- })?;- pr.item_done(0);+ // #2234: one wildcard `POST /{prefix}-*/_refresh` made this phase a single+ // request with denominator 1. The server refreshed the matches one index+ // at a time, so a large index with a segment merge in progress held the+ // whole call (and this phase printed nothing until it returned). Refresh+ // each index this run wrote, name it on the bar while the request is in+ // flight, and do not retry a timeout five more times. The server refreshes+ // a multi-index target concurrently; one index here is one request so the+ // wait, if there is one, is that index's own budget.+ pr.phase(+ "finalize-refresh",+ plan.datasets.len() as u64 + graph.is_some() as u64,+ 0,+ );+ let mut refresh_failures: Vec<String> = Vec::new();+ for dataset in &plan.datasets {+ let _waiting = pr.file(&dataset.index, 0);+ if let Err(error) = es.refresh_once(&dataset.index) {+ refresh_failures.push(format!("{}: {error:#}", dataset.index));+ }+ }// The dot-prefixed edges index is outside the {prefix}-* pattern.if let Some(gr) = &graph {- es.refresh(&gr.edges_index).map_err(|error| {- anyhow::anyhow!(- "finalize-refresh of {} failed: {error:#}. Documents already written stay \- indexed and rerunning the same command resumes",- gr.edges_index- )- })?;- pr.item_done(0);+ let _waiting = pr.file(&gr.edges_index, 0);+ if let Err(error) = es.refresh_once(&gr.edges_index) {+ refresh_failures.push(format!("{}: {error:#}", gr.edges_index));+ }+ }+ if !refresh_failures.is_empty() {+ // #1635: swallowing a refresh failure (`.ok()`) turned it back into a+ // green run whose documents were not all refreshed. Name every index+ // that did not refresh. Documents already written stay indexed.+ anyhow::bail!(+ "finalize-refresh failed for {} index(es): {}. Documents already written stay \+ indexed and rerunning the same command resumes",+ refresh_failures.len(),+ refresh_failures.join(" | ")+ );}// live per-dataset counts + time ranges (every claim traces to a run)diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex 567f8feb1..b9b01212a 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -1862,12 +1862,14 @@ impl SyncOperationBackend for EsSyncBackend<'_> {.collect();const REFRESH_WINDOW: usize = 50;for batch in indexes.chunks(REFRESH_WINDOW) {- self.es.refresh(&batch.join(","))?;+ // #2234: one attempt. `Es::refresh` would retry a timed-out window+ // five more times (300s each) with no new information.+ self.es.refresh_once(&batch.join(","))?;for _ in batch {self.pr.item_done(0);}}- self.es.refresh(crate::catalog::CATALOG_INDEX)?;+ self.es.refresh_once(crate::catalog::CATALOG_INDEX)?;let prior_run_id =base.execution.as_ref()@@ -1921,7 +1923,9 @@ impl SyncOperationBackend for EsSyncBackend<'_> {// source already equals that projection is not in `to_write`.if !body.is_empty() {checked_bulk_windowed(self.es, body, self.bulk_bytes)?;- self.es.refresh(crate::catalog::CATALOG_INDEX)?;+ // #2234: one attempt. `Es::refresh` would retry a timed-out+ // catalog refresh five more times (300s each).+ self.es.refresh_once(crate::catalog::CATALOG_INDEX)?;}if !to_write.is_empty() {let written_ids: Vec<String> = to_write.keys().cloned().collect();@@ -1983,13 +1987,27 @@ impl SyncOperationBackend for EsSyncBackend<'_> {desired.plan.datasets.len() as u64 + 1,0,);+ let mut refresh_failures: Vec<String> = Vec::new();for dataset in &desired.plan.datasets {let _refreshing = self.pr.file(&dataset.index, 0);- self.es.refresh(&dataset.index)?;+ // #2234: one attempt per index. The file guard names the index+ // on the progress line for as long as this request is in flight.+ if let Err(error) = self.es.refresh_once(&dataset.index) {+ refresh_failures.push(format!("{}: {error:#}", dataset.index));+ }}{let _refreshing = self.pr.file(crate::catalog::CATALOG_INDEX, 0);- self.es.refresh(crate::catalog::CATALOG_INDEX)?;+ if let Err(error) = self.es.refresh_once(crate::catalog::CATALOG_INDEX) {+ refresh_failures.push(format!("{}: {error:#}", crate::catalog::CATALOG_INDEX));+ }+ }+ if !refresh_failures.is_empty() {+ anyhow::bail!(+ "finalize-refresh failed for {} index(es): {}",+ refresh_failures.len(),+ refresh_failures.join(" | ")+ );}// The generation-wide barrier reads changed groups back. Every// question it asks has the same shape — "how many rows in this indexdiff --git a/engine/crates/xerj-engine/Cargo.toml b/engine/crates/xerj-engine/Cargo.tomlindex 0bb9532a8..28e64dada 100644--- a/engine/crates/xerj-engine/Cargo.toml+++ b/engine/crates/xerj-engine/Cargo.toml@@ -81,6 +81,10 @@ default = []neural = ["xerj-ai/neural"]onnx-experimental = ["xerj-ai/onnx-experimental"]stackprobe = []+# Pause points inside `Index::refresh` (#2234). Release builds leave this+# off. `xerj-api`'s dev-dependency enables it so an HTTP test can hold one+# index's refresh and prove a sibling index is not waiting behind it.+refresh-test-hook = [][dev-dependencies]xerj-storage = { path = "../xerj-storage", features = ["test-hooks"] }diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 4bfb2e212..d74f71aad 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -5507,6 +5507,87 @@ mod merge_publication_transaction_tests {.expect("merge did not reach the pre-apply gate");}+ /// #2234 — `_refresh` must publish a new write while a merge encode is+ /// held, on a runtime whose tokio blocking pool has a single thread.+ ///+ /// The encode used to run inside `spawn_blocking` for its whole duration.+ /// Refresh builds a segment on that same pool, so with one blocking thread+ /// the refresh queued until the merge returned. The encode now runs on the+ /// merge pool; this test parks it there and requires `refresh` to drain+ /// the memtable before the park is released.+ #[test]+ fn refresh_publishes_while_a_merge_encode_is_held() {+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(4)+ .max_blocking_threads(1)+ .enable_all()+ .build()+ .expect("runtime");+ runtime.block_on(async {+ let dir = TempDir::new().unwrap();+ let (_engine, index) = fixture(&dir).await;+ // Releasing on drop covers an assertion failure: a parked merge+ // thread must not outlive the test and pin the process-global+ // merge pool.+ struct ReleaseHold<'a>(&'a AtomicBool);+ impl Drop for ReleaseHold<'_> {+ fn drop(&mut self) {+ self.0.store(false, Ordering::Release);+ }+ }+ index.test_hold_merge_encode.store(true, Ordering::Release);+ let release = ReleaseHold(&index.test_hold_merge_encode);+ let merge_index = Arc::clone(&index);+ let merge = tokio::spawn(async move { merge_index.run_merge_once().await });+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ while !index.test_merge_encode_held.load(Ordering::Acquire) {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("merge encode did not reach the hold");++ index+ .index_document(Some("c".into()), serde_json::json!({"value": "new-c"}))+ .await+ .unwrap();+ assert_eq!(+ index.memtable.doc_count(),+ 1,+ "the new document must still be in the memtable"+ );+ let refreshed =+ tokio::time::timeout(std::time::Duration::from_secs(8), index.refresh()).await;+ assert!(+ refreshed.is_ok(),+ "refresh did not return within 8s while the merge encode was held"+ );+ refreshed+ .expect("timeout already checked")+ .expect("refresh");+ assert_eq!(+ index.memtable.doc_count(),+ 0,+ "refresh must drain the memtable without waiting for the merge"+ );+ assert!(+ index.test_merge_encode_held.load(Ordering::Acquire),+ "the merge encode must still be parked after refresh returns"+ );+ assert_eq!(+ index.get_document("c").await.unwrap().unwrap()["value"],+ "new-c"+ );++ drop(release);+ let merged = tokio::time::timeout(std::time::Duration::from_secs(30), merge)+ .await+ .expect("merge did not finish after the hold was released")+ .expect("merge task");+ assert_eq!(merged.expect("merge"), 1);+ });+ }+#[tokio::test]async fn apply_failure_restores_sources_survives_restart_and_retry() {let dir = TempDir::new().unwrap();@@ -6167,6 +6248,41 @@ mod merge_publication_transaction_tests {);}+ /// Drive the paused clock past one debounce, and give the merge pool a+ /// real turn so an encode can finish.+ ///+ /// #2234 runs that encode on the merge pool, off this runtime. A paused+ /// `sleep` auto-advances while the pass is still awaiting the pool, so+ /// the scheduler never looks idle and a later segment change is only a+ /// bumped epoch on the in-flight pass — the evaluation counter does not+ /// move until the encode returns. `std::thread::sleep` does not advance+ /// the paused clock, so it cannot itself schedule a merge check.+ async fn settle_merge_scheduler(index: &Index) {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);+ loop {+ let before = index.merge_evaluation_count();+ std::thread::sleep(std::time::Duration::from_millis(15));+ tokio::task::yield_now().await;+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;+ tokio::task::yield_now().await;+ let after = index.merge_evaluation_count();+ if after == before && !index.is_merge_in_progress() {+ // A second window with no real sleep: a still-armed debounce+ // is the only thing that can move the counter.+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;+ if index.merge_evaluation_count() == after && !index.is_merge_in_progress() {+ return;+ }+ }+ assert!(+ std::time::Instant::now() < deadline,+ "background merges did not quiesce (evaluations {}, in progress {})",+ index.merge_evaluation_count(),+ index.is_merge_in_progress()+ );+ }+ }+/// #871 — merge scheduling must be event-driven: after an index's merge/// work settles, ZERO further merge-policy evaluations may run until the/// segment set changes again.@@ -6195,10 +6311,9 @@ mod merge_publication_transaction_tests {}// Let the scheduled checks and their cascading merges run to// quiescence (min/max_merge_count = 2 collapses two at a time).- for _ in 0..8 {- tokio::time::sleep(std::time::Duration::from_secs(30)).await;- tokio::task::yield_now().await;- }+ // The encode is on the merge pool (#2234); paused sleeps do not+ // wait for it.+ settle_merge_scheduler(&index).await;let settled = index.merge_evaluation_count();assert!(settled >= 1,@@ -6220,14 +6335,19 @@ mod merge_publication_transaction_tests {.await.unwrap();index.flush().await.unwrap();- for _ in 0..8 {- tokio::time::sleep(std::time::Duration::from_secs(30)).await;+ let wake_deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ loop {+ std::thread::sleep(std::time::Duration::from_millis(15));tokio::task::yield_now().await;+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;+ if index.merge_evaluation_count() > settled {+ break;+ }+ assert!(+ std::time::Instant::now() < wake_deadline,+ "a published segment no longer schedules a merge check"+ );}- assert!(- index.merge_evaluation_count() > settled,- "a published segment no longer schedules a merge check"- );}#[tokio::test]@@ -9300,6 +9420,23 @@ pub struct Index {test_pause_merge_before_apply: Arc<AtomicBool>,#[cfg(test)]test_merge_repoint_ready: Arc<AtomicBool>,+ /// #2234 — park the merge encode on the merge pool, before any segment+ /// bytes are written, so a test can prove `refresh` proceeds while that+ /// encode is held. The park is a merge-pool thread, not a tokio blocking+ /// thread: occupying the blocking pool here is the stall this hook exists+ /// to catch.+ #[cfg(test)]+ test_hold_merge_encode: Arc<AtomicBool>,+ #[cfg(test)]+ test_merge_encode_held: Arc<AtomicBool>,+ /// #2234 — park `refresh` before it looks at the memtable. Off in release+ /// builds; `xerj-api` tests turn it on with the `refresh-test-hook` feature.+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_pause_refresh: Arc<AtomicBool>,+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_paused: Arc<AtomicBool>,+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_finished: Arc<AtomicU64>,/// #1212 — park the next search the instant its capture bracket/// validates (`test_pause_search_after_capture`), announcing via/// `test_search_capture_parked` so a test can publish a merge or flush@@ -9913,10 +10050,21 @@ pub struct Index {/// the fallback (an input the preflight refused, or/// `XERJ_MERGE_FTS_REANALYZE=1`). An index whose merges are silently/// paying the old O(text) cost shows it here and nowhere else.- /// `Arc` because the merge encode runs in `spawn_blocking`.+ /// `Arc` because the merge encode runs on the merge pool, off the caller.merge_fts_reanalysed_docs: Arc<AtomicU64>,}+/// Counts one `Index::refresh` that got past the test hold, on every exit.+#[cfg(any(test, feature = "refresh-test-hook"))]+struct TestRefreshFinished<'a>(&'a Index);++#[cfg(any(test, feature = "refresh-test-hook"))]+impl Drop for TestRefreshFinished<'_> {+ fn drop(&mut self) {+ self.0.test_refresh_finished.fetch_add(1, Ordering::Release);+ }+}+impl Index {/// Apply a WAL-consumer retention floor to this index's WAL shards, live.///@@ -10194,6 +10342,16 @@ impl Index {#[cfg(test)]test_merge_repoint_ready: Arc::new(AtomicBool::new(false)),#[cfg(test)]+ test_hold_merge_encode: Arc::new(AtomicBool::new(false)),+ #[cfg(test)]+ test_merge_encode_held: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_pause_refresh: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_paused: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_finished: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]test_pause_search_after_capture: Arc::new(AtomicBool::new(false)),#[cfg(test)]test_search_capture_parked: Arc::new(AtomicBool::new(false)),@@ -10680,6 +10838,16 @@ impl Index {#[cfg(test)]test_merge_repoint_ready: Arc::new(AtomicBool::new(false)),#[cfg(test)]+ test_hold_merge_encode: Arc::new(AtomicBool::new(false)),+ #[cfg(test)]+ test_merge_encode_held: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_pause_refresh: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_paused: Arc::new(AtomicBool::new(false)),+ #[cfg(any(test, feature = "refresh-test-hook"))]+ test_refresh_finished: Arc::new(AtomicU64::new(0)),+ #[cfg(test)]test_pause_search_after_capture: Arc::new(AtomicBool::new(false)),#[cfg(test)]test_search_capture_parked: Arc::new(AtomicBool::new(false)),@@ -12645,18 +12813,68 @@ impl Index {}}+ /// Hold `refresh` until [`Self::test_set_pause_refresh`] clears.+ ///+ /// The flag is announced only after this call has entered, so a test can+ /// wait until the index is actually inside refresh and not merely racing+ /// the request.+ #[cfg(any(test, feature = "refresh-test-hook"))]+ async fn await_test_refresh_hold(&self) {+ if !self.test_pause_refresh.load(Ordering::Acquire) {+ return;+ }+ self.test_refresh_paused.store(true, Ordering::Release);+ while self.test_pause_refresh.load(Ordering::Acquire) {+ tokio::task::yield_now().await;+ }+ self.test_refresh_paused.store(false, Ordering::Release);+ }++ #[cfg(any(test, feature = "refresh-test-hook"))]+ pub fn test_set_pause_refresh(&self, pause: bool) {+ self.test_pause_refresh.store(pause, Ordering::Release);+ }++ #[cfg(any(test, feature = "refresh-test-hook"))]+ pub fn test_refresh_is_paused(&self) -> bool {+ self.test_refresh_paused.load(Ordering::Acquire)+ }++ #[cfg(any(test, feature = "refresh-test-hook"))]+ pub fn test_refresh_finished_count(&self) -> u64 {+ self.test_refresh_finished.load(Ordering::Acquire)+ }++ /// Make recent writes searchable.+ ///+ /// This is the body of HTTP `_refresh` (#2234). An empty memtable is+ /// already searchable — return without verified WAL maintenance, which is+ /// `flush` / `_flush` and is what used to sit behind a background segment+ /// merge. A non-empty memtable is published to a segment. The HNSW graph+ /// is persisted either way: background flushes skip that save, and an+ /// explicit refresh is the checkpoint for it. `save_hnsw_to_disk` returns+ /// immediately when the index has no graph.pub async fn refresh(&self) -> Result<()> {+ #[cfg(any(test, feature = "refresh-test-hook"))]+ self.await_test_refresh_hold().await;+ // Count a refresh that actually returned, including the empty-memtable+ // path and errors. The hold above is outside this guard so a paused+ // index does not look finished.+ #[cfg(any(test, feature = "refresh-test-hook"))]+ let _refresh_finished = TestRefreshFinished(self);{let mem = &*self.memtable;if mem.doc_count() == 0 {+ let _ = self.save_hnsw_to_disk().await;return Ok(());}}- // Flush the memtable to a new segment on disk. This drains the- // memtable, writes the segment file + FTS index, swaps the snapshot,- // and checkpoints the WAL. The drained memtable is dropped, freeing- // all RAM.+ // Publish the memtable to a new segment. This drains the memtable,+ // writes the segment file + FTS index, and swaps the snapshot. The+ // drained memtable is dropped, freeing its RAM. Verified WAL+ // maintenance (snapshot fsync + prune) is `_flush` / `Index::flush`,+ // not this path (#2234).let (field_configs, excluded_fts_fields, dv_skip) = {let schema = self.schema.read().await;(@@ -13329,18 +13547,36 @@ impl Index {let batch_for_task = batch;let metas_for_task = metas;let failed_for_task = Arc::clone(&failed_batches);-- tokio::task::spawn_blocking(move || -> Option<MergeOutput> {- // Entire merge encode runs on the dedicated SMALL merge- // pool (nice +15, ncores/8 threads): the decompress +- // byte-copy + FTS/DV rebuild below saturates its workers- // for seconds. On the normal-priority blocking pool it- // stole scheduler time from foreground searches (read-- // under-write tail); on the shared ingest pool it queued- // every bulk request's parse/analyze/insert behind it,- // fully stalling 1 M×c8 ingest for ~13 s per merge pass- // (see `crate::merge_pool`).- crate::merge_pool().install(move || -> Option<MergeOutput> {+ #[cfg(test)]+ let hold_merge_encode = Arc::clone(&self.test_hold_merge_encode);+ #[cfg(test)]+ let merge_encode_held = Arc::clone(&self.test_merge_encode_held);++ // #2234 — the encode used to run inside `spawn_blocking` ++ // `merge_pool().install`, which parked one tokio blocking-pool+ // thread for the whole encode (minutes on a large segment; the+ // shutdown path still names that leftover job). `_refresh` builds+ // its segment on that same blocking pool, so one in-progress+ // merge stalled refresh behind it. Queue the encode on the merge+ // pool and wait from this async driver. `spawn` returns as soon+ // as the job is queued. The #1122 inline fallback (the pool+ // cannot start a thread at all) still runs the encode on the+ // caller — the same degradation `install` already had.+ //+ // The CPU work is unchanged: decompress + byte-copy + FTS/DV+ // rebuild on the small nice-+15 merge pool (`crate::merge_pool`),+ // off the ingest pool that a merge used to stall.+ let (encode_tx, encode_rx) = tokio::sync::oneshot::channel();+ crate::merge_pool().spawn(move || {+ #[cfg(test)]+ if hold_merge_encode.load(Ordering::Acquire) {+ merge_encode_held.store(true, Ordering::Release);+ while hold_merge_encode.load(Ordering::Acquire) {+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ merge_encode_held.store(false, Ordering::Release);+ }+ let encoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {use serde_json::value::RawValue;// V4 M4.8 — STREAMING BYTE-COPY MERGE.@@ -14091,7 +14327,19 @@ impl Index {ids_pairs,version_repoint_intents,))- })+ }));+ let _ = encode_tx.send(encoded);+ });+ tokio::spawn(async move {+ match encode_rx.await {+ Ok(Ok(value)) => value,+ Ok(Err(payload)) => std::panic::resume_unwind(payload),+ // The encode task vanished without a result. Panic so the+ // driver counts a failed batch (the `JoinError` arm)+ // instead of treating a lost encode as an empty output+ // and dropping its inputs.+ Err(_closed) => panic!("merge encode dropped its result"),+ }})};@@ -14109,8 +14357,8 @@ impl Index {while !in_flight.is_empty() {// Await the first handle in the queue. tokio doesn't provide// a built-in "select any", but for small parallelism this FIFO- // drain is fine — all spawn_blocking tasks run concurrently- // anyway, we're just reaping their results in submission+ // drain is fine — the encodes run concurrently on the merge+ // pool anyway, we're just reaping their results in submission// order.let handle = in_flight.remove(0);match handle.await {@@ -14439,7 +14687,7 @@ impl Index {}Ok(None) => {}Err(e) => {- tracing::error!("merge: spawn_blocking panicked: {e}");+ tracing::error!("merge: encode task panicked: {e}");failed_batches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);}}