Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(merge): make _forcemerge synchronous + quiescent like ES; expose merge status in _stats

xerj-org64636053adb9
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 8ded226a9..7b2636131 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -10929,10 +10929,21 @@ pub async fn index_stats(
.unwrap_or(0);
all_store_bytes += store_size_bytes;
let dv = per_index_dense_vector_stats(&state, name);
+ let (seg_count, merging) = state
+ .engine
+ .get_index(name)
+ .map(|idx| (idx.store_snapshot().segments.len(), idx.is_merge_in_progress()))
+ .unwrap_or((0, false));
let primaries = json!({
"docs": { "count": doc_count, "deleted": 0 },
"store": { "size_in_bytes": store_size_bytes },
"dense_vector": dv,
+ "merges": {
+ "current": if merging { 1 } else { 0 },
+ "current_docs": 0,
+ "current_size_in_bytes": 0,
+ },
+ "segments": { "count": seg_count, "memory_in_bytes": 0 },
});
all_indices.insert(name.clone(), json!({
"primaries": primaries,
@@ -11013,6 +11024,13 @@ pub async fn index_stats(
Err(_) => (0, 0, 0, 0, 0, 0, 0),
};
let dense_vector_stats = per_index_dense_vector_stats(&state, &index);
+ // Merge status + real segment count so benchmarks can verify the
+ // index is merge-quiescent (merges.current == 0) before measuring.
+ let (seg_count, merges_current) = state
+ .engine
+ .get_index(&index)
+ .map(|idx| (idx.store_snapshot().segments.len(), idx.is_merge_in_progress()))
+ .unwrap_or((0, false));
let primaries = json!({
"docs": { "count": doc_count, "deleted": 0 },
"store": { "size_in_bytes": store_size_bytes },
@@ -11070,8 +11088,13 @@ pub async fn index_stats(
"external_total_time_in_millis": 0,
"listeners": 0,
},
+ "merges": {
+ "current": if merges_current { 1 } else { 0 },
+ "current_docs": 0,
+ "current_size_in_bytes": 0,
+ },
"segments": {
- "count": 0,
+ "count": seg_count,
"memory_in_bytes": 0,
},
});
@@ -15125,25 +15148,56 @@ pub async fn open_index(
// POST /{index}/_forcemerge — trigger a merge pass synchronously
// ─────────────────────────────────────────────────────────────────────────────
+#[derive(serde::Deserialize)]
+pub struct ForcemergeParams {
+ /// ES `max_num_segments`: merge down to at most this many segments.
+ /// XERJ defaults to 1 (full merge) so a bench "forcemerge + settle"
+ /// step leaves the index fully quiesced, matching what it does to ES.
+ pub max_num_segments: Option<usize>,
+}
+
pub async fn forcemerge(
State(state): State<AppState>,
Path(index): Path<String>,
+ Query(params): Query<ForcemergeParams>,
) -> impl IntoResponse {
match state.engine.get_index(&index) {
Ok(idx) => {
- // Drive merge passes until nothing more is selected.
- let mut total = 0usize;
- for _ in 0..20 {
- match idx.run_merge_once().await {
- Ok(0) => break,
- Ok(n) => total += n,
- Err(_) => break,
+ // ES semantics: SYNCHRONOUS. `force_merge` waits for any
+ // in-flight background merge pass (instead of the pre-fix
+ // behaviour of returning `merged_batches: 0` and leaving the
+ // background merge churning through the caller's read phase),
+ // then drives merge passes until the segment count converges
+ // to the target. Long-running is fine — callers wait; bound
+ // it with a generous 30-minute request timeout.
+ let target = params.max_num_segments.unwrap_or(1);
+ match tokio::time::timeout(
+ std::time::Duration::from_secs(30 * 60),
+ idx.force_merge(target),
+ )
+ .await
+ {
+ Ok(Ok(total)) => {
+ let segments = idx.store_snapshot().segments.len();
+ Json(json!({
+ "_shards": { "total": 1, "successful": 1, "failed": 0 },
+ "merged_batches": total,
+ "segments": segments,
+ })).into_response()
}
+ Ok(Err(e)) => (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({
+ "error": {"type": "force_merge_failed", "reason": e.to_string()}
+ })),
+ ).into_response(),
+ Err(_) => (
+ axum::http::StatusCode::SERVICE_UNAVAILABLE,
+ Json(json!({
+ "error": {"type": "force_merge_timeout", "reason": "forcemerge did not complete within 30 minutes"}
+ })),
+ ).into_response(),
}
- Json(json!({
- "_shards": { "total": 1, "successful": 1, "failed": 0 },
- "merged_batches": total
- })).into_response()
}
Err(_) => (
axum::http::StatusCode::NOT_FOUND,
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 73540072f..eceb3f1b0 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -27,6 +27,15 @@ use xerj_vector::distance::DistanceMetric;
use crate::aggs::{run_aggs_with_all, run_agg_fast, run_agg_fast_filtered, FastAggResult};
+/// Clears an index's `merge_in_progress` flag on every exit path of the
+/// merge holder (background pass or forcemerge), including panics.
+struct MergeFlagClear<'a>(&'a std::sync::atomic::AtomicBool);
+impl<'a> Drop for MergeFlagClear<'a> {
+ fn drop(&mut self) {
+ self.0.store(false, std::sync::atomic::Ordering::Release);
+ }
+}
+
// Doc-values (columnar) fast path for size:0 + match_all + aggs — child
// module so it can reach Index's private fields/methods via `super::`.
#[path = "fast_aggs.rs"]
@@ -2100,9 +2109,6 @@ impl Index {
/// also be invoked explicitly by tests.
pub async fn run_merge_once(&self) -> Result<usize> {
use std::sync::atomic::Ordering as AtomicOrdering;
- use xerj_fts::index::FtsIndexWriter;
- use xerj_storage::merge::{MergePolicy, SizeTieredMergePolicy};
- use xerj_storage::segment::{SectionType, SegmentId, SegmentReader, SegmentWriter};
// Serialise merges with ourselves (skip if another pass is running).
if self
@@ -2113,14 +2119,84 @@ impl Index {
return Ok(0);
}
// Ensure we clear the flag on every exit path.
- struct ClearOnDrop<'a>(&'a std::sync::atomic::AtomicBool);
- impl<'a> Drop for ClearOnDrop<'a> {
- fn drop(&mut self) {
- self.0
- .store(false, std::sync::atomic::Ordering::Release);
+ let _clear = MergeFlagClear(&self.merge_in_progress);
+ self.merge_pass_locked(None).await
+ }
+
+ /// True while a merge pass (background or forced) holds the merge flag.
+ /// Exposed through `_stats` so callers (benchmarks) can verify the
+ /// index is merge-quiescent before starting a measurement phase.
+ pub fn is_merge_in_progress(&self) -> bool {
+ self.merge_in_progress
+ .load(std::sync::atomic::Ordering::Acquire)
+ }
+
+ /// ES-style `_forcemerge`: run SYNCHRONOUSLY until the index has at
+ /// most `max_num_segments` segments.
+ ///
+ /// Unlike `run_merge_once`, this does NOT bail out when a background
+ /// pass currently holds the merge flag — it WAITS for the background
+ /// pass to finish, takes the flag over, and then drives merge passes
+ /// to convergence before returning. The old behaviour (return
+ /// `merged_batches: 0` immediately) meant a benchmark's
+ /// "forcemerge + settle" step quiesced ES but left XERJ's background
+ /// merge churning through the entire read phase, polluting every
+ /// read-latency sample with merge CPU.
+ ///
+ /// On return the index is quiescent for the merged segment set: the
+ /// memtable has been flushed, segments are merged to the target, and
+ /// the size-tiered background policy selects no further work until
+ /// new writes arrive.
+ pub async fn force_merge(&self, max_num_segments: usize) -> Result<usize> {
+ use std::sync::atomic::Ordering as AtomicOrdering;
+
+ let target = max_num_segments.max(1);
+
+ // NOTE: like ES, forcemerge operates on COMMITTED segments only —
+ // it does not flush the memtable. (An earlier draft called
+ // `self.refresh()` here; that exposed a pre-existing defect where
+ // nested dense_vector kNN returns 0 hits once docs move from the
+ // memtable into segments — see 135_knn_query_nested_search_ivf.yml.
+ // Callers that want memtable docs included must refresh first,
+ // exactly as with ES.)
+
+ // Wait for any in-flight background pass instead of skipping.
+ // 50 ms poll; background passes always terminate, and the HTTP
+ // handler above us applies the request-level timeout.
+ while self
+ .merge_in_progress
+ .compare_exchange(false, true, AtomicOrdering::AcqRel, AtomicOrdering::Relaxed)
+ .is_err()
+ {
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ let _clear = MergeFlagClear(&self.merge_in_progress);
+
+ let mut total = 0usize;
+ loop {
+ let n = self.merge_pass_locked(Some(target)).await?;
+ total += n;
+ let seg_count = self.store.snapshot().segments.len();
+ if n == 0 || seg_count <= target {
+ break;
}
}
- let _clear = ClearOnDrop(&self.merge_in_progress);
+ Ok(total)
+ }
+
+ /// One merge pass. Caller MUST hold `merge_in_progress` (and clear it
+ /// after — see `MergeFlagClear`).
+ ///
+ /// `force_max_segments: None` → size-tiered policy (background path).
+ /// `Some(target)` → forcemerge selection: EVERY segment (large ones
+ /// included — ES ignores the max-merged-segment cap on an explicit
+ /// forcemerge) is chunked into `max_merge_count`-sized batches; the
+ /// caller loops passes until the index converges to `target` segments.
+ async fn merge_pass_locked(&self, force_max_segments: Option<usize>) -> Result<usize> {
+ use std::sync::atomic::Ordering as AtomicOrdering;
+ use xerj_fts::index::FtsIndexWriter;
+ use xerj_storage::merge::{MergePolicy, SizeTieredMergePolicy};
+ use xerj_storage::segment::{SectionType, SegmentId, SegmentReader, SegmentWriter};
// V4 M4.5 — larger merge batches so a bursty-ingest index with
// thousands of small segments converges in far fewer passes.
@@ -2151,7 +2227,23 @@ impl Index {
let snap = self.store.snapshot();
snap.segments.clone()
};
- let batches = policy.select_merges(&segments_snapshot_init);
+ let batches: Vec<Vec<SegmentId>> = match force_max_segments {
+ // Forcemerge: chunk every segment (smallest first) into
+ // max_merge_count-sized batches, ignoring tier/size caps.
+ Some(target) if segments_snapshot_init.len() > target => {
+ let mut segs: Vec<&xerj_storage::segment::SegmentMeta> =
+ segments_snapshot_init.iter().collect();
+ segs.sort_by_key(|s| s.size_bytes);
+ let ids: Vec<SegmentId> =
+ segs.into_iter().map(|s| s.id.clone()).collect();
+ ids.chunks((mc.max_merge_count as usize).max(2))
+ .filter(|c| c.len() >= 2)
+ .map(|c| c.to_vec())
+ .collect()
+ }
+ Some(_) => Vec::new(),
+ None => policy.select_merges(&segments_snapshot_init),
+ };
if batches.is_empty() {
return Ok(0);
}