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(metrics): #819 wire xerj_bytes_read_total to validated segment opens (#865)
Onyeka Obi5495784b86f6
diff --git a/engine/crates/xerj-common/src/metrics.rs b/engine/crates/xerj-common/src/metrics.rsindex e2a957791..1c267f582 100644--- a/engine/crates/xerj-common/src/metrics.rs+++ b/engine/crates/xerj-common/src/metrics.rs@@ -27,6 +27,32 @@ use prometheus::{use crate::error::XerjError;+// ═════════════════════════════════════════════════════════════════════════════+// Process-global metrics handle+// ═════════════════════════════════════════════════════════════════════════════++// The registry stays per-instance (see the module docs), but some call sites+// are constructed before the server's `Metrics` exists and without a handle+// to it: the engine's flush/merge pipeline (#804) and the storage layer's+// segment-open path (#819). The server installs the single process-wide+// instance here once at startup; call sites record through `global_metrics()`,+// which is `None` (a no-op) when nothing is installed, so libraries never+// fabricate observations. `xerj_engine::set_engine_metrics` delegates here,+// keeping one install site per process.+static GLOBAL_METRICS: std::sync::OnceLock<std::sync::Arc<Metrics>> = std::sync::OnceLock::new();++/// Install the process-wide metrics handle. Idempotent; the first call wins+/// (later calls are ignored).+pub fn set_global_metrics(metrics: std::sync::Arc<Metrics>) {+ let _ = GLOBAL_METRICS.set(metrics);+}++/// The installed process-wide metrics handle, or `None` if no server has+/// installed one (unit tests, embedded uses).+pub fn global_metrics() -> Option<&'static std::sync::Arc<Metrics>> {+ GLOBAL_METRICS.get()+}+// ═════════════════════════════════════════════════════════════════════════════// Metrics collection// ═════════════════════════════════════════════════════════════════════════════@@ -47,7 +73,8 @@ pub struct Metrics {pub queries_executed: IntCounter,/// Total bytes written to segment files (uncompressed).pub bytes_written: IntCounter,- /// Total bytes read from segment files (uncompressed).+ /// Total on-disk bytes read from segment (.seg) files at open-time+ /// validation (reader-cache misses only).pub bytes_read: IntCounter,// ── Per-index counters ────────────────────────────────────────────────────@@ -128,7 +155,7 @@ impl Metrics {let bytes_read = IntCounter::with_opts(Opts::new("xerj_bytes_read_total",- "Total bytes read from segment files (uncompressed)",+ "Total on-disk bytes read from segment (.seg) files at open-time validation (reader-cache misses only)",)).map_err(|e| XerjError::internal(format!("metrics: {e}")))?;@@ -368,6 +395,18 @@ impl Metrics {self.bytes_written.inc_by(n);}+ /// Record `n` on-disk bytes read from a segment (.seg) file, called once+ /// per validated `SegmentReader` open with the opened file's length (the+ /// open path reads and CRC-checks the whole file; the reader-cache hit+ /// path reuses the mmap and reads nothing). A no-op when `n == 0`.+ /// (#819: the counter was registered but never incremented, so it read a+ /// flat zero regardless of read volume.)+ pub fn record_bytes_read(&self, n: u64) {+ if n != 0 {+ self.bytes_read.inc_by(n);+ }+ }+/// Drop the per-index label series for `index` (RC4-W4 item 5).////// Called when an index is deleted so its `queries_by_index` /diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex 07d9a23ce..20e7e3ca6 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -68,22 +68,22 @@ pub use memtable::FtsMemtable;// 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();+// The cell itself lives in `xerj_common::metrics` (#819) so `xerj-storage`+// call sites (segment open) can record into the same process-wide instance;+// these wrappers keep the engine-facing API unchanged./// 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);+ xerj_common::metrics::set_global_metrics(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()+ xerj_common::metrics::global_metrics()}// ── Ingest/flush/merge rayon pool ────────────────────────────────────────────diff --git a/engine/crates/xerj-storage/src/segment.rs b/engine/crates/xerj-storage/src/segment.rsindex 5b032cb4d..1bae7b28c 100644--- a/engine/crates/xerj-storage/src/segment.rs+++ b/engine/crates/xerj-storage/src/segment.rs@@ -552,7 +552,16 @@ impl SegmentReader {let file = File::open(path.as_ref())?;let mmap = unsafe { Mmap::map(&file) }?;let mmap = Arc::new(mmap);- Self::from_mmap(mmap)+ let reader = Self::from_mmap(mmap)?;+ // #819: `from_mmap`'s open-time whole-file CRC pass reads every+ // on-disk byte of the segment, so a validated open is the faithful+ // "bytes read from disk" site. The reader-cache hit path+ // (`from_mmap_arc`) reuses the mmap and reads nothing, so it+ // deliberately does not record.+ if let Some(m) = xerj_common::metrics::global_metrics() {+ m.record_bytes_read(reader.mmap.len() as u64);+ }+ Ok(reader)}/// Return the underlying Arc<Mmap>. Used by the cached@@ -735,6 +744,40 @@ mod tests {assert!(reader.section(SectionType::Fts).unwrap().is_none());}+ /// #819: `xerj_bytes_read_total` was registered but never incremented,+ /// so it read a flat zero regardless of read volume. A validated+ /// `SegmentReader::open` now records the opened file's on-disk length+ /// through the process-global metrics handle.+ #[test]+ fn bytes_read_metric_increments_on_segment_open() {+ // Idempotent OnceLock: installs a handle if none yet, else reads the+ // existing one. Once installed, concurrent tests in this binary may+ // also open segments, so assert a lower bound, not an exact delta.+ xerj_common::metrics::set_global_metrics(std::sync::Arc::new(+ xerj_common::metrics::Metrics::new().unwrap(),+ ));+ let m = xerj_common::metrics::global_metrics().expect("global metrics installed");++ let dir = tempfile::tempdir().unwrap();+ let mut writer = SegmentWriter::new(dir.path(), 1, 0, 0).unwrap();+ writer+ .add_section(SectionType::Stored, b"{\"title\":\"bytes read 819\"}")+ .unwrap();+ let meta = writer.finish(1, 1, 1).unwrap();+ let seg_path = dir.path().join(&meta.seg_path);+ let seg_len = std::fs::metadata(&seg_path).unwrap().len();+ assert!(seg_len > 0);++ let before = m.bytes_read.get();+ let _reader = SegmentReader::open(&seg_path).unwrap();+ let after = m.bytes_read.get();+ assert!(+ after - before >= seg_len,+ "#819: bytes_read must grow by at least the segment's on-disk \+ length ({seg_len}) on a validated open, got {before} -> {after}"+ );+ }+#[test]fn segment_with_tombstones_sets_flag() {let dir = tempfile::tempdir().unwrap();