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.

feat(observability): make ES stats + Prometheus metrics reflect real load (RC4 W4 A)

xerj-orga59a4319d6f9
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index b70098c40..5b77a2f42 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -5240,6 +5240,76 @@ pub async fn search_all(
search(State(state), Path("*".to_string()), Query(params), body).await
}
+/// Bounded top-level query-type label for the `query_latency_by_type`
+/// histogram. Returns the outermost query clause name (e.g. `bool`, `term`,
+/// `match`) when it is one of the known Elasticsearch query types, `match_all`
+/// when the request has no `query`, and `other` for anything unrecognised — so
+/// the Prometheus label set stays bounded no matter what a client sends.
+pub(crate) fn top_level_query_type(body_query: &Option<serde_json::Value>) -> &'static str {
+ // Bounded allow-list of ES top-level query clause names.
+ const KNOWN: &[&str] = &[
+ "match_all",
+ "match_none",
+ "match",
+ "match_phrase",
+ "match_phrase_prefix",
+ "multi_match",
+ "combined_fields",
+ "term",
+ "terms",
+ "terms_set",
+ "range",
+ "exists",
+ "prefix",
+ "wildcard",
+ "regexp",
+ "fuzzy",
+ "ids",
+ "bool",
+ "boosting",
+ "constant_score",
+ "dis_max",
+ "function_score",
+ "nested",
+ "has_child",
+ "has_parent",
+ "parent_id",
+ "geo_distance",
+ "geo_bounding_box",
+ "geo_shape",
+ "geo_polygon",
+ "shape",
+ "more_like_this",
+ "script",
+ "script_score",
+ "wrapper",
+ "pinned",
+ "rank_feature",
+ "distance_feature",
+ "intervals",
+ "query_string",
+ "simple_query_string",
+ "percolate",
+ "knn",
+ "span_near",
+ "span_term",
+ "span_first",
+ "span_or",
+ "span_not",
+ ];
+ let Some(q) = body_query else {
+ return "match_all";
+ };
+ match q.as_object().and_then(|o| o.keys().next()) {
+ Some(first) => KNOWN
+ .iter()
+ .copied()
+ .find(|&k| k == first.as_str())
+ .unwrap_or("other"),
+ None => "match_all",
+ }
+}
+
pub async fn search(
State(state): State<AppState>,
Path(index): Path<String>,
@@ -5531,7 +5601,13 @@ pub async fn search(
// `?typed_keys` — prefix agg names with their type in the response.
let typed_keys = params.typed_keys.is_some();
- state.metrics.queries_executed.inc();
+ // RC4 W4 item 2: bracket the live-search gauge for this request. The guard
+ // increments `active_searches` now and decrements on drop (any return path
+ // below), so `/metrics` reflects real in-flight search concurrency.
+ // `queries_by_index` is recorded per resolved index in the loop below;
+ // `queries_executed` + the latency histograms via `record_query_global` at
+ // completion.
+ let _search_guard = state.metrics.active_search_guard();
// Support comma-separated multi-index with wildcard patterns:
// /index1,index2/_search — comma-separated exact names
@@ -7941,7 +8017,16 @@ pub async fn search(
}
let took_ms = started.elapsed().as_millis() as u64;
- state.metrics.query_latency.observe(took_ms as f64 / 1000.0);
+ // RC4 W4 item 2: record the index-agnostic side of the completed search —
+ // the global `queries_executed` counter plus BOTH latency histograms
+ // (overall + by query type, which were previously never recorded).
+ // `queries_by_index` is deliberately NOT touched here: it is already
+ // incremented once per *resolved* concrete index in the loop above, which
+ // correctly attributes multi-index / wildcard searches (vs. this handler's
+ // single raw target label). Replaces the bare `query_latency.observe`.
+ state
+ .metrics
+ .record_query_global(top_level_query_type(&body.query), took_ms as f64 / 1000.0);
// v0.8 8-P6: record into the slow query log if over the threshold.
state.engine.slow_query.maybe_record(
index.as_str(),
@@ -11789,8 +11874,23 @@ async fn process_bulk_body(
// statuses.
let all_backpressure = !result.items.is_empty() && result.items.iter().all(|i| i.status == 429);
+ // RC4 W4 item 2: tally successfully-written docs per index so the
+ // `docs_indexed` / `docs_indexed_by_index` counters reflect bulk ingest.
+ // The bulk pipeline is the demo's primary ingest path and previously never
+ // touched these counters — they read 0 even at millions of docs. Tallied
+ // locally and flushed with one `inc_by` per index after the loop (keeps the
+ // global atomic off the per-doc hot path). `item.index` here is the
+ // concrete resolved index, so the label set stays bounded.
+ let mut docs_indexed_tally: std::collections::HashMap<String, u64> =
+ std::collections::HashMap::new();
let mut items: Vec<EsBulkItem> = Vec::with_capacity(result.items.len());
for item in result.items {
+ if item.error.is_none()
+ && (200..300).contains(&item.status)
+ && matches!(item.action.as_str(), "index" | "create" | "update")
+ {
+ *docs_indexed_tally.entry(item.index.clone()).or_insert(0) += 1;
+ }
let get = item.get_source.clone().map(|s| {
serde_json::json!({
"found": true,
@@ -11852,6 +11952,12 @@ async fn process_bulk_body(
items.push(action);
}
+ // RC4 W4 item 2: flush the per-index docs-indexed tally (one atomic inc_by
+ // per index) now the whole batch is accounted for.
+ for (idx_name, n) in &docs_indexed_tally {
+ state.metrics.record_docs_indexed(idx_name, *n);
+ }
+
let resp = EsBulkResponse {
took: took_ms,
errors,
@@ -13699,8 +13805,13 @@ pub async fn index_stats(
"dense_vector": dense_vector_stats,
"hnsw": hnsw_stats,
"indexing": {
- "index_total": doc_count,
- "index_time_in_millis": 0,
+ // Real cumulative indexing counters (RC4 W4 item 1): plumbed from
+ // the per-index `metric_index_count` / `metric_index_total_ms`
+ // atomics (index.rs), which every ingest path increments. Noop
+ // updates early-return before `index_document`, so — as in ES —
+ // they land in `noop_update_total` and NOT `index_total`.
+ "index_total": stats.index_count,
+ "index_time_in_millis": stats.index_total_ms,
"index_current": 0,
"index_failed": 0,
"delete_total": 0,
@@ -13725,8 +13836,13 @@ pub async fn index_stats(
// the TTL sweeper and 429 cap are observable. Previously
// hardcoded 0.
"open_contexts": state.engine.scrolls.len(),
- "query_total": 0,
- "query_time_in_millis": 0,
+ // Real cumulative search counters (RC4 W4 item 1): plumbed from the
+ // per-index `metric_query_count` / `metric_query_total_ms` atomics
+ // (index.rs), incremented on every `Index::search`. Previously
+ // hardcoded 0 — `_stats.search.query_total` stayed 0 after real
+ // searches.
+ "query_total": stats.query_count,
+ "query_time_in_millis": stats.query_total_ms,
"query_current": 0,
"fetch_total": 0,
"fetch_time_in_millis": 0,
@@ -16295,6 +16411,15 @@ fn glob_match_simple(pattern: &str, name: &str) -> bool {
pub async fn nodes_stats(State(state): State<AppState>) -> impl IntoResponse {
let (_idx_count, total_docs, store_bytes) = real_index_totals(&state).await;
+ // Live cumulative search + indexing counters, summed across all indices.
+ let (query_total, query_time_ms, index_total, index_time_ms) =
+ real_node_search_index_totals(&state).await;
+ // Real CPU-worker thread count. XERJ sizes its rayon ingest pool and the
+ // global search fan-out pool to the number of available cores (see
+ // xerj-engine/src/lib.rs); this is that number, not the old hardcoded 4.
+ let cpu_threads = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(8);
// Real RSS, host memory, and CPU utilisation from /proc.
let rss_bytes = read_rss_bytes().unwrap_or(0);
@@ -16340,23 +16465,32 @@ pub async fn nodes_stats(State(state): State<AppState>) -> impl IntoResponse {
"heap_used_percent": heap_used_pct,
"non_heap_used_in_bytes": 0,
},
- "gc": {
- "collectors": {
- "young": { "collection_count": 0, "collection_time_in_millis": 0 },
- "old": { "collection_count": 0, "collection_time_in_millis": 0 },
- }
- }
+ // NOTE (RC4 W4 item 1, honesty policy): the `jvm.gc`
+ // collector stats are OMITTED, not faked. XERJ is a native
+ // Rust engine with no garbage collector, so there are no GC
+ // young/old collection counts to report. The `jvm.mem`
+ // block is retained because ES health/monitoring clients
+ // key on it, and its values are real (process RSS vs host
+ // memory).
},
"thread_pool": {
- "search": { "threads": 4, "queue": 0, "active": 0, "rejected": 0 },
- "write": { "threads": 4, "queue": 0, "active": 0, "rejected": 0 },
- "bulk": { "threads": 4, "queue": 0, "active": 0, "rejected": 0 },
+ // Real CPU-worker thread counts (was a hardcoded 4). Search
+ // fan-out runs on the global rayon pool and ingest on the
+ // dedicated ingest pool, both sized to available cores.
+ // `queue`/`active`/`rejected` are an instantaneous idle
+ // snapshot (not persistently instrumented) and stay 0.
+ "search": { "threads": cpu_threads, "queue": 0, "active": 0, "rejected": 0 },
+ "write": { "threads": cpu_threads, "queue": 0, "active": 0, "rejected": 0 },
+ "bulk": { "threads": cpu_threads, "queue": 0, "active": 0, "rejected": 0 },
},
"indices": {
"docs": { "count": total_docs, "deleted": 0 },
"store": { "size_in_bytes": store_bytes },
- "indexing": { "index_total": 0, "index_time_in_millis": 0 },
- "search": { "query_total": 0, "query_time_in_millis": 0 },
+ // Real cumulative counters summed across all indices
+ // (RC4 W4 item 1): previously hardcoded 0, so node-stats
+ // dashboards flatlined under load.
+ "indexing": { "index_total": index_total, "index_time_in_millis": index_time_ms },
+ "search": { "query_total": query_total, "query_time_in_millis": query_time_ms },
// Dense-vector off-heap stats. Populated when at
// least one index has a dense_vector field with
// BBQ index_options. Per-quantisation-type byte
@@ -27204,6 +27338,73 @@ async fn real_index_totals(state: &AppState) -> (usize, u64, u64) {
(indices.len(), total_docs, store_bytes)
}
+/// Sum the live per-index search + indexing counters across every index,
+/// for the node-level `_nodes/stats` `indices.{indexing,search}` rollup.
+///
+/// Returns `(query_total, query_time_ms, index_total, index_time_ms)` read
+/// from the same per-index atomics that back `GET /{index}/_stats`
+/// (`metric_query_count` / `metric_query_total_ms` / `metric_index_count` /
+/// `metric_index_total_ms` in index.rs). Previously the node rollup
+/// hardcoded these to 0, so ES node-stats dashboards flatlined even under
+/// heavy load.
+async fn real_node_search_index_totals(state: &AppState) -> (u64, u64, u64, u64) {
+ let indices = state.engine.list_indices().await;
+ let (mut q_total, mut q_ms, mut i_total, mut i_ms) = (0u64, 0u64, 0u64, 0u64);
+ for info in &indices {
+ if let Ok(s) = state.engine.index_stats(&info.name).await {
+ q_total += s.query_count;
+ q_ms += s.query_total_ms;
+ i_total += s.index_count;
+ i_ms += s.index_total_ms;
+ }
+ }
+ (q_total, q_ms, i_total, i_ms)
+}
+
+/// Refresh the process-level Prometheus gauges from live engine state. Reads
+/// only cheap snapshots (a lock-free store RCU snapshot per index plus a stat
+/// of each WAL dir), so it is safe to call on a short interval.
+async fn refresh_metric_gauges(state: &AppState) {
+ let indices = state.engine.list_indices().await;
+ let mut total_docs: i64 = 0;
+ let mut total_segments: i64 = 0;
+ let mut wal_bytes: i64 = 0;
+ for info in &indices {
+ total_docs += info.doc_count as i64;
+ if let Ok(idx) = state.engine.get_index(&info.name) {
+ total_segments += idx.store_snapshot().segments.len() as i64;
+ // WAL files live under `<index>/wal/*.wal`; sum just that subtree so
+ // the gauge tracks WAL growth (the WAL-runaway ticket) and not the
+ // segments alongside it.
+ wal_bytes += dir_size_bytes(&idx.data_dir().join("wal")) as i64;
+ }
+ }
+ state.metrics.doc_count.set(total_docs);
+ state.metrics.segment_count.set(total_segments);
+ state.metrics.wal_size_bytes.set(wal_bytes);
+ // Real process RSS (the RSS-runaway ticket's key signal).
+ if let Some(rss) = read_rss_bytes() {
+ state.metrics.memory_usage.set(rss as i64);
+ }
+}
+
+/// Background loop that refreshes the Prometheus gauges
+/// (`doc_count` / `segment_count` / `wal_size_bytes` / `memory_usage`) every
+/// 10 s. These are otherwise never written, so before this task `/metrics`
+/// reported them as a flat zero even at millions of docs — hiding exactly the
+/// RSS-runaway and WAL-growth signals operators need. The server spawns this
+/// once at startup. `tokio::time::interval` fires its first tick immediately,
+/// so the gauges are populated on the first pass rather than reading zero for
+/// the first 10 s.
+pub async fn run_metrics_gauge_loop(state: AppState) {
+ let mut ticker = tokio::time::interval(std::time::Duration::from_secs(10));
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ ticker.tick().await;
+ refresh_metric_gauges(&state).await;
+ }
+}
+
#[cfg(test)]
mod scripted_update_tests {
use super::*;
diff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rs
index 5edd4ae35..20bf3d9ea 100644
--- a/engine/crates/xerj-api/src/native.rs
+++ b/engine/crates/xerj-api/src/native.rs
@@ -415,12 +415,11 @@ pub async fn search(
}
};
- state.metrics.queries_executed.inc();
- state
- .metrics
- .queries_by_index
- .with_label_values(&[&name])
- .inc();
+ // RC4 W4 item 2: track in-flight searches on this path too, so the
+ // `active_searches` gauge reflects native-API concurrency (decremented on
+ // drop, any return below). The cumulative counters + latency histograms are
+ // recorded once at completion via `record_query`.
+ let _search_guard = state.metrics.active_search_guard();
// Build a query body for the parser.
let query_body = if let Some(q_str) = &req.q {
@@ -457,10 +456,19 @@ pub async fn search(
}
};
+ let query_type = if req.q.is_some() {
+ "multi_match"
+ } else {
+ crate::es_compat::top_level_query_type(&req.query)
+ };
match idx.search(&search_req).await {
Ok(result) => {
let took_ms = started.elapsed().as_millis() as u64;
- state.metrics.query_latency.observe(took_ms as f64 / 1000.0);
+ // RC4 W4 item 2: one call records the global counter, the per-index
+ // counter, and both latency histograms (overall + by query type).
+ state
+ .metrics
+ .record_query(&name, query_type, took_ms as f64 / 1000.0);
let hits: Vec<Value> = result
.hits
diff --git a/engine/crates/xerj-common/src/metrics.rs b/engine/crates/xerj-common/src/metrics.rs
index c74486d2b..82fecc764 100644
--- a/engine/crates/xerj-common/src/metrics.rs
+++ b/engine/crates/xerj-common/src/metrics.rs
@@ -308,6 +308,21 @@ impl Metrics {
self.docs_indexed_by_index.with_label_values(&[index]).inc();
}
+ /// Record `n` documents successfully indexed into `index` in a single
+ /// batch. Increments the global and per-index counters with one atomic
+ /// `inc_by` each — cheaper on the hot bulk path than calling
+ /// [`Self::record_doc_indexed`] per document (which contends the global
+ /// counter once per doc). A no-op when `n == 0`.
+ pub fn record_docs_indexed(&self, index: &str, n: u64) {
+ if n == 0 {
+ return;
+ }
+ self.docs_indexed.inc_by(n);
+ self.docs_indexed_by_index
+ .with_label_values(&[index])
+ .inc_by(n);
+ }
+
/// Record a completed query.
///
/// Increments counters and records latency histograms.
@@ -320,6 +335,20 @@ impl Metrics {
.observe(latency_secs);
}
+ /// Record the index-agnostic side of a completed query: the global counter
+ /// and both the overall and by-type latency histograms — but NOT
+ /// `queries_by_index`. Use this when the caller increments
+ /// `queries_by_index` itself, once per *resolved* concrete index (a
+ /// multi-index or wildcard search touches several), which is more accurate
+ /// than attributing the whole request to a single raw label.
+ pub fn record_query_global(&self, query_type: &str, latency_secs: f64) {
+ self.queries_executed.inc();
+ self.query_latency.observe(latency_secs);
+ self.query_latency_by_type
+ .with_label_values(&[query_type])
+ .observe(latency_secs);
+ }
+
/// Guard type that decrements `active_searches` when dropped.
///
/// ```no_run
@@ -334,6 +363,33 @@ impl Metrics {
gauge: self.active_searches.clone(),
}
}
+
+ // ── Type-erased observe helpers ───────────────────────────────────────────
+ //
+ // These let crates that do NOT depend on the `prometheus` crate (e.g.
+ // `xerj-engine`) record into the duration histograms at their real call
+ // sites without ever naming a `prometheus` type. `secs` is the observed
+ // duration in seconds (Prometheus convention).
+
+ /// Observe one completed memtable→segment flush, in seconds.
+ pub fn observe_flush(&self, secs: f64) {
+ self.flush_duration.observe(secs);
+ }
+
+ /// Observe one completed segment merge, in seconds.
+ pub fn observe_merge(&self, secs: f64) {
+ self.merge_duration.observe(secs);
+ }
+
+ /// Observe one WAL append (durability write) latency, in seconds.
+ pub fn observe_wal_write(&self, secs: f64) {
+ self.wal_write_latency.observe(secs);
+ }
+
+ /// Observe one end-to-end indexing (ingest) operation latency, in seconds.
+ pub fn observe_index(&self, secs: f64) {
+ self.index_latency.observe(secs);
+ }
}
/// RAII guard for the `active_searches` gauge.
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index b2fb86a97..2c169c946 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -1395,6 +1395,10 @@ impl Index {
self.metric_index_count.fetch_add(1, Ordering::Relaxed);
self.metric_index_total_ms
.fetch_add(index_elapsed_ms, Ordering::Relaxed);
+ // RC4 W4 item 2: end-to-end latency of this single-document index call.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_index(index_elapsed_ms as f64 / 1000.0);
+ }
debug!(doc_id = doc_id.as_str(), seq_no, "document indexed");
@@ -1587,7 +1591,12 @@ impl Index {
})
.collect();
+ let wal_t = std::time::Instant::now();
let seq_nos = self.store.wal_append_batch(&wal_refs)?;
+ // RC4 W4 item 2: WAL durability-write latency.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_wal_write(wal_t.elapsed().as_secs_f64());
+ }
let t3_dur = t3.elapsed();
// ── M5.1 HOT PATH: one shard lock per BATCH ───────────────────────
@@ -1738,6 +1747,10 @@ impl Index {
.fetch_add(batch_len as u64, Ordering::Relaxed);
self.metric_index_total_ms
.fetch_add(elapsed_ms, Ordering::Relaxed);
+ // RC4 W4 item 2: end-to-end latency of this indexing (batch) call.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_index(elapsed_ms as f64 / 1000.0);
+ }
debug!(batch = batch_len, elapsed_ms, "turbo batch indexed");
@@ -1829,7 +1842,12 @@ impl Index {
.map(|(id, bytes)| (id.clone(), Arc::clone(&null_val), Arc::clone(bytes)))
.collect();
+ let wal_t = std::time::Instant::now();
let seq_nos = self.store.wal_append_batch(&wal_refs)?;
+ // RC4 W4 item 2: WAL durability-write latency.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_wal_write(wal_t.elapsed().as_secs_f64());
+ }
if prof {
p_wal_us = p_t.elapsed().as_micros();
}
@@ -2016,6 +2034,10 @@ impl Index {
.fetch_add(batch_len as u64, Ordering::Relaxed);
self.metric_index_total_ms
.fetch_add(elapsed_ms, Ordering::Relaxed);
+ // RC4 W4 item 2: end-to-end latency of this indexing (batch) call.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_index(elapsed_ms as f64 / 1000.0);
+ }
Ok(responses)
}
@@ -2094,7 +2116,12 @@ impl Index {
// Fast-path WAL append: no Arc<Value> wrapper, no per-batch Vec
// allocation. `wal_append_batch_raw` borrows docs directly.
+ let wal_t = std::time::Instant::now();
let seq_nos = self.store.wal_append_batch_raw(&docs)?;
+ // RC4 W4 item 2: WAL durability-write latency.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_wal_write(wal_t.elapsed().as_secs_f64());
+ }
// Use the instance method so routing matches the actual configured
// shard count. The previous `Self::shard_for` was hardcoded to a
@@ -2163,6 +2190,10 @@ impl Index {
.fetch_add(batch_len as u64, Ordering::Relaxed);
self.metric_index_total_ms
.fetch_add(elapsed_ms, Ordering::Relaxed);
+ // RC4 W4 item 2: end-to-end latency of this indexing (batch) call.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_index(elapsed_ms as f64 / 1000.0);
+ }
Ok(batch_len)
}
@@ -2363,6 +2394,10 @@ impl Index {
.fetch_add(batch_len as u64, Ordering::Relaxed);
self.metric_index_total_ms
.fetch_add(elapsed_ms, Ordering::Relaxed);
+ // RC4 W4 item 2: end-to-end latency of this indexing (batch) call.
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_index(elapsed_ms as f64 / 1000.0);
+ }
debug!(
batch = batch_len,
@@ -2628,7 +2663,19 @@ impl Index {
}
// Ensure we clear the flag on every exit path.
let _clear = MergeFlagClear(&self.merge_in_progress);
- self.merge_pass_locked(None).await
+ // RC4 W4 item 2: record merge latency, but only for passes that
+ // actually merged segments (n > 0). A pass that finds nothing to merge
+ // returns immediately and must not pollute `merge_duration`.
+ let merge_start = std::time::Instant::now();
+ let result = self.merge_pass_locked(None).await;
+ if let Ok(n) = &result {
+ if *n > 0 {
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_merge(merge_start.elapsed().as_secs_f64());
+ }
+ }
+ }
+ result
}
/// True while a merge pass (background or forced) holds the merge flag.
@@ -2680,6 +2727,7 @@ impl Index {
}
let _clear = MergeFlagClear(&self.merge_in_progress);
+ let merge_start = std::time::Instant::now();
let mut total = 0usize;
loop {
let n = self.merge_pass_locked(Some(target)).await?;
@@ -2689,6 +2737,15 @@ impl Index {
break;
}
}
+ // RC4 W4 item 2: record operator-triggered forcemerge latency (the whole
+ // convergence) when it actually merged something, so `merge_duration`
+ // reflects forcemerges too — background merges are recorded separately
+ // in `run_merge_once`.
+ if total > 0 {
+ if let Some(m) = crate::engine_metrics() {
+ m.observe_merge(merge_start.elapsed().as_secs_f64());
+ }
+ }
Ok(total)
}
@@ -14726,6 +14783,22 @@ impl Index {
/// 3. Build the FTS inverted index files for the new segment using ordinal
/// positions (0, 1, 2, …) so that the segment search path can look up
/// stored docs by their ordinal.
+/// RAII timer that records one `flush_duration` (seconds) observation when it
+/// drops — i.e. when `do_flush_shard` returns on any path. It holds an owned
+/// `Arc<Metrics>` cloned from the process-global handle so it survives across
+/// the `.await`s in the flush, and is a no-op when metrics are not installed.
+struct FlushDurationTimer {
+ start: std::time::Instant,
+ metrics: Option<std::sync::Arc<xerj_common::metrics::Metrics>>,
+}
+impl Drop for FlushDurationTimer {
+ fn drop(&mut self) {
+ if let Some(m) = &self.metrics {
+ m.observe_flush(self.start.elapsed().as_secs_f64());
+ }
+ }
+}
+
#[allow(clippy::too_many_arguments)] // free fn threading the full flush-pipeline dependency set
async fn do_flush_shard(
shard_idx: usize,
@@ -14892,6 +14965,14 @@ async fn do_flush_shard(
None => return Ok(()),
};
+ // RC4 W4 item 2: record flush latency. Armed only past the empty-drain
+ // early-return above, so the histogram reflects real segment builds; fires
+ // on drop when this fn returns (covers the multiple Ok(()) exits below).
+ let _flush_timer = FlushDurationTimer {
+ start: std::time::Instant::now(),
+ metrics: crate::engine_metrics().cloned(),
+ };
+
// ── Phase 2: build segment + FTS side-cars without holding any lock ───
//
// From this point on, new ingests are appending to a fresh memtable in
diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rs
index e9c1e65b4..2499e5601 100644
--- a/engine/crates/xerj-engine/src/lib.rs
+++ b/engine/crates/xerj-engine/src/lib.rs
@@ -38,6 +38,34 @@ pub use index::{
};
pub use memtable::FtsMemtable;
+// ── Process-global metrics handle ─────────────────────────────────────────────
+//
+// Flush, merge, and WAL writes happen deep in the engine, whose types are
+// constructed (`Index::open`) before the server's `Metrics` instance exists and
+// without a handle to it. Rather than thread `Arc<Metrics>` through every
+// constructor and the free-fn flush pipeline, the server installs the single
+// process-wide `Metrics` here once at startup (there is exactly one per
+// process). Call sites record via `engine_metrics()` — a no-op when unset
+// (e.g. in unit tests), so the engine never fabricates observations.
+//
+// This mirrors the `OnceLock` pattern the rayon pools below already use.
+static ENGINE_METRICS: std::sync::OnceLock<std::sync::Arc<xerj_common::metrics::Metrics>> =
+ std::sync::OnceLock::new();
+
+/// Install the process-wide metrics handle the engine records into. Idempotent;
+/// the first call wins (later calls are ignored). Called once by the server at
+/// startup with the same `Metrics` the HTTP `/metrics` endpoint scrapes.
+pub fn set_engine_metrics(metrics: std::sync::Arc<xerj_common::metrics::Metrics>) {
+ let _ = ENGINE_METRICS.set(metrics);
+}
+
+/// The installed metrics handle, or `None` if the server has not installed one
+/// (unit tests, embedded uses). Engine call sites guard on this so recording is
+/// a no-op when metrics are not wired.
+pub fn engine_metrics() -> Option<&'static std::sync::Arc<xerj_common::metrics::Metrics>> {
+ ENGINE_METRICS.get()
+}
+
// ── Ingest/flush/merge rayon pool ────────────────────────────────────────────
/// Dedicated rayon pool for ingest-side CPU work: bulk-body parse, P2.1
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 98de7f67a..b7a635691 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -1216,6 +1216,17 @@ async fn async_main() -> Result<()> {
// 9b. Application state
let state = AppState::new(cfg.clone(), engine, metrics);
+ // 9b-i. Observability wiring (RC4 W4 item 2).
+ // (a) Install the process-wide metrics handle the engine records
+ // flush/merge/WAL/index-latency observations into — the flush, merge
+ // and WAL write sites live deep in xerj-engine, which is built before
+ // `Metrics` exists and holds no handle to it.
+ // (b) Spawn the 10 s gauge refresher that keeps doc_count / segment_count
+ // / wal_size_bytes / memory_usage live (otherwise a flat zero even at
+ // millions of docs, hiding the RSS-runaway and WAL-growth signals).
+ xerj_engine::set_engine_metrics(state.metrics.clone());
+ tokio::spawn(xerj_api::es_compat::run_metrics_gauge_loop(state.clone()));
+
// 9c. Routers — engine and Xerj Console are *peer* surfaces. Each crate
// builds a complete Router (routes + its own auth + its own
// middleware) and `xerj-server` merges them onto the same TCP