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
feat(observability): RC4-W4 Stream B — slow-query/metrics/logging/ANN minors (items 3-7)
xerj-org46044ae1b77a
diff --git a/engine/crates/xerj-api/src/auth.rs b/engine/crates/xerj-api/src/auth.rsindex 56f4c5ac9..e74e64ac9 100644--- a/engine/crates/xerj-api/src/auth.rs+++ b/engine/crates/xerj-api/src/auth.rs@@ -43,6 +43,15 @@ pub async fn auth_middleware(State(state): State<AppState>, req: Request, next:return next.run(req).await;}+ // RC4-W4 item 4: optional read-only metrics token. When configured, a+ // caller presenting the exact token may scrape `/v1/metrics` — and ONLY+ // that endpoint — without the admin key, so Prometheus can be handed a+ // low-privilege scrape credential that cannot read index data. The admin+ // key still works for metrics via the normal path below.+ if req.uri().path() == "/v1/metrics" && metrics_token_authorized(&state, &req) {+ return next.run(req).await;+ }+// Xerj Console lives in a peer router (mounted by `xerj-server` via// `Router::merge`) and runs its own session-cookie auth, so this// middleware never sees `/_xerj-console/*` requests — no path-prefix@@ -98,6 +107,25 @@ pub fn is_authorized(state: &AppState, auth_header: Option<&str>) -> bool {}}+/// Decide whether a request to `/v1/metrics` may proceed on the strength of+/// the read-only `auth.metrics_token` alone (RC4-W4 item 4).+///+/// Returns `false` (falls through to normal auth) when the token is unset or+/// the presented credential doesn't match it. The comparison is constant-time,+/// matching the admin-key path — a scrape token is still a shared secret.+fn metrics_token_authorized(state: &AppState, req: &Request) -> bool {+ let token = &state.config.auth.metrics_token;+ if token.is_empty() {+ return false;+ }+ req.headers()+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(extract_key)+ .map(|k| constant_time_eq(k.as_bytes(), token.as_bytes()))+ .unwrap_or(false)+}+/// Re-authenticate a created API key credential.////// The presented value is `base64("id:api_key")`. Decode it, split on the@@ -371,6 +399,61 @@ mod tests {assert!(!is_authorized(&state, None));}+ /// RC4-W4 item 4: the read-only `metrics_token` scrapes `/v1/metrics` and+ /// ONLY `/v1/metrics`. It is not a blanket bypass — a data endpoint still+ /// 401s with it, and metrics still 401 with no credential at all.+ #[tokio::test]+ async fn metrics_token_scopes_to_metrics_only() {+ let admin = "admin-secret-key";+ let metrics_tok = "scrape-only-token";+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.keep();+ let mut config = Config::default();+ config.server.data_dir = path.to_str().unwrap().to_string();+ config.auth.enabled = true;+ config.auth.admin_api_key = admin.to_string();+ config.auth.metrics_token = metrics_tok.to_string();+ let metrics = Metrics::new().expect("metrics");+ let engine = Engine::new(config.clone()).expect("engine");+ let state = AppState::new(config, engine, metrics);++ let app = Router::new()+ .route("/v1/metrics", get(|| async { "metrics" }))+ .route("/_cluster/health", get(|| async { "data" }))+ .layer(middleware::from_fn_with_state(+ state.clone(),+ auth_middleware,+ ))+ .with_state(state);++ let tok_hdr = format!("Bearer {metrics_tok}");+ // The scrape token reads metrics …+ let (status, _) = send(&app, "GET", "/v1/metrics", Some(&tok_hdr), "").await;+ assert_eq!(+ status,+ StatusCode::OK,+ "metrics token must scrape /v1/metrics"+ );+ // … but NOTHING else.+ let (status, _) = send(&app, "GET", "/_cluster/health", Some(&tok_hdr), "").await;+ assert_eq!(+ status,+ StatusCode::UNAUTHORIZED,+ "metrics token must not read index data"+ );+ // The admin key still works for metrics.+ let admin_hdr = format!("ApiKey {admin}");+ let (status, _) = send(&app, "GET", "/v1/metrics", Some(&admin_hdr), "").await;+ assert_eq!(status, StatusCode::OK, "admin key still scrapes metrics");+ // A missing credential still 401s — the token is opt-in, not open.+ let (status, _) = send(&app, "GET", "/v1/metrics", None, "").await;+ assert_eq!(+ status,+ StatusCode::UNAUTHORIZED,+ "metrics still demands a credential"+ );+ }+/// Regression for the RC4 blocker: `/health/live` + `/health/ready` must/// stay reachable without credentials even when auth is enabled, so Docker/// HEALTHCHECKs and k8s probes don't crashloop on a hardened deployment.diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex b70098c40..40b95f1e0 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -900,6 +900,9 @@ pub async fn delete_index(for name in &to_delete {let _ = state.engine.delete_index(name).await;+ // RC4-W4 item 5: drop the index's per-index metric label series so it+ // doesn't linger for the process lifetime after the index is gone.+ state.metrics.prune_index_labels(name);}Json(EsDeleteIndexResponse::ok()).into_response()}@@ -7297,12 +7300,6 @@ pub async fn search(.unwrap_or(search_selector_has_wildcard);for idx_name in &index_names {- state- .metrics- .queries_by_index- .with_label_values(&[idx_name])- .inc();-let idx = match state.engine.get_index(idx_name) {Ok(i) => i,Err(e) => {@@ -7314,6 +7311,17 @@ pub async fn search(}};+ // RC4-W4 item 5: record the per-index query metric only AFTER the index+ // resolves. Incrementing before resolution let a query against a+ // nonexistent index (`no_such_index_xyz`) mint a+ // `queries_by_index{index="no_such_index_xyz"}` label series that+ // lived forever — an unbounded-cardinality leak driven by client input.+ state+ .metrics+ .queries_by_index+ .with_label_values(&[idx_name])+ .inc();+// Spawn on a new task so that a panic is caught by the JoinHandle rather// than propagating up and crashing the server.let mut req_clone = search_req.clone();@@ -7942,13 +7950,21 @@ pub async fn search(let took_ms = started.elapsed().as_millis() as u64;state.metrics.query_latency.observe(took_ms as f64 / 1000.0);- // v0.8 8-P6: record into the slow query log if over the threshold.+ // v0.8 8-P6 / RC4-W4 item 3: record into the slow query log if over the+ // threshold. `maybe_record` also emits the unified slow-query tracing line+ // (same runtime threshold as the ring buffer), and captures the query body+ // so the entry is actionable.state.engine.slow_query.maybe_record(index.as_str(),"search",started.elapsed(),merged_hits.len() as u64,if body.aggs.is_some() { "with-aggs" } else { "" },+ &body+ .query+ .as_ref()+ .map(|q| q.to_string())+ .unwrap_or_default(),);// v0.9 9-P4: append to the audit log (subject is "anonymous" until// RBAC middleware wires through the authenticated user in v0.9-beta).@@ -13192,6 +13208,138 @@ pub async fn mget_index(Json(json!({ "docs": docs })).into_response()}+// ─────────────────────────────────────────────────────────────────────────────+// GET /_cat/ann & GET /_cat/ann/{index} (XERJ extension — RC4-W4 item 7)+// ─────────────────────────────────────────────────────────────────────────────++/// Query params for `/_cat/ann`. `v` (a valueless flag) adds a header row;+/// `format=json` returns a JSON array instead of the plain-text table.+#[derive(Debug, Deserialize, Default)]+pub struct CatAnnParams {+ #[serde(default)]+ pub v: Option<String>,+ #[serde(default)]+ pub format: Option<String>,+}++/// `GET /_cat/ann` — ANN/HNSW health for every index.+///+/// Surfaces the same live state as `GET /{index}/_stats`'s `hnsw` block, but in+/// the `_cat` tabular family operators already reach for. Its reason to exist:+/// a vector index that is `stale` or under-`covered` silently degrades kNN to+/// exact brute force, and without this the only signal was a per-index `_stats`+/// call. Columns: index present field nodes tombstones vector_docs coverage+/// covered stale rebuilding.+pub async fn cat_ann(+ State(state): State<AppState>,+ Query(params): Query<CatAnnParams>,+) -> impl IntoResponse {+ cat_ann_inner(state, None, params).await+}++/// `GET /_cat/ann/{index}` — health for the named index / comma-list / pattern.+pub async fn cat_ann_index(+ State(state): State<AppState>,+ Path(index): Path<String>,+ Query(params): Query<CatAnnParams>,+) -> impl IntoResponse {+ cat_ann_inner(state, Some(index), params).await+}++async fn cat_ann_inner(+ state: AppState,+ index: Option<String>,+ params: CatAnnParams,+) -> axum::response::Response {+ let all = state.engine.index_name_list();+ // Resolve the target set (mirrors _cat/indices selector rules: a concrete+ // name matching nothing 404s; a wildcard matching nothing is an empty 200).+ let targets: Vec<String> = match index.as_deref() {+ None => all,+ Some(sel) => {+ let parts: Vec<&str> = sel+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .collect();+ for &p in &parts {+ let is_wild = p == "_all" || p == "*" || p.contains('*');+ if !is_wild && !all.iter().any(|n| n == p) {+ return ApiError::new(xerj_common::XerjError::index_not_found(p))+ .into_response();+ }+ }+ all.into_iter()+ .filter(|n| {+ parts+ .iter()+ .any(|&p| p == "_all" || p == "*" || n == p || glob_match_simple(p, n))+ })+ .collect()+ }+ };++ let mut rows: Vec<(String, Value)> = Vec::new();+ for name in &targets {+ if let Ok(idx) = state.engine.get_index(name) {+ rows.push((name.clone(), idx.hnsw_stats().await));+ }+ }+ rows.sort_by(|a, b| a.0.cmp(&b.0));++ if params.format.as_deref() == Some("json") {+ let arr: Vec<Value> = rows+ .iter()+ .map(|(name, s)| {+ json!({+ "index": name,+ "present": s["present"],+ "field": s["field"],+ "nodes": s["nodes"],+ "tombstones": s["tombstones"],+ "vector_docs": s["vector_doc_count"],+ "coverage": s["doc_coverage"],+ "covered": s["covered"],+ "stale": s["stale"],+ "rebuilding": s["rebuilding"],+ })+ })+ .collect();+ return Json(arr).into_response();+ }++ let mut out = String::new();+ if params.v.is_some() {+ out.push_str(+ "index present field nodes tombstones vector_docs coverage covered stale rebuilding\n",+ );+ }+ for (name, s) in &rows {+ out.push_str(&format!(+ "{} {} {} {} {} {} {} {} {} {}\n",+ name,+ s["present"].as_bool().unwrap_or(false),+ s["field"].as_str().unwrap_or("-"),+ s["nodes"].as_u64().unwrap_or(0),+ s["tombstones"].as_u64().unwrap_or(0),+ s["vector_doc_count"].as_u64().unwrap_or(0),+ s["doc_coverage"].as_u64().unwrap_or(0),+ s["covered"].as_bool().unwrap_or(false),+ s["stale"].as_bool().unwrap_or(false),+ s["rebuilding"].as_bool().unwrap_or(false),+ ));+ }+ (+ StatusCode::OK,+ [(+ axum::http::header::CONTENT_TYPE,+ "text/plain; charset=utf-8",+ )],+ out,+ )+ .into_response()+}+// ─────────────────────────────────────────────────────────────────────────────// GET /_cat/health// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rsindex 5edd4ae35..333beede0 100644--- a/engine/crates/xerj-api/src/native.rs+++ b/engine/crates/xerj-api/src/native.rs@@ -188,6 +188,9 @@ pub async fn delete_index().into_response();}+ // RC4-W4 item 5: drop the deleted index's per-index metric label series so+ // it doesn't linger for the process lifetime.+ state.metrics.prune_index_labels(&name);let took_ms = started.elapsed().as_millis() as u64;let resp = NativeResponse::new(@@ -461,6 +464,23 @@ pub async fn search(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 3: the native search path must feed the slow-query+ // log too (previously ONLY the ES-compat `_search` handler did, so+ // a slow query via `/v1/indices/:name/search` was invisible to the+ // operator ring buffer and the tracing line). `maybe_record` emits+ // both, gated on the shared runtime threshold, and captures the+ // query body.+ state.engine.slow_query.maybe_record(+ &name,+ "search",+ started.elapsed(),+ result.hits.len() as u64,+ "",+ &query_body+ .get("query")+ .map(|q| q.to_string())+ .unwrap_or_default(),+ );let hits: Vec<Value> = result.hits@@ -871,6 +891,11 @@ pub async fn rbac_delete_role(// ─────────────────────────────────────────────────────────────────────────────pub async fn metrics(State(state): State<AppState>) -> impl IntoResponse {+ // RC4-W4 item 4: reconcile the query-cache gauges from the engine's own+ // per-index counters at scrape time (the engine owns the truth; Prometheus+ // lives at the API layer). Cheap: a sum over the open-index set.+ let (qc_hits, qc_misses) = state.engine.query_cache_totals();+ state.metrics.set_query_cache(qc_hits, qc_misses);match state.metrics.gather_text() {Ok(text) => (StatusCode::OK,diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rsindex a16478a81..cdc50fab0 100644--- a/engine/crates/xerj-api/src/router.rs+++ b/engine/crates/xerj-api/src/router.rs@@ -17,10 +17,12 @@ use axum::{Router,};use tower_http::{+ classify::{ServerErrorsAsFailures, SharedClassifier},cors::{AllowOrigin, Any, CorsLayer},limit::RequestBodyLimitLayer,- trace::TraceLayer,+ trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},};+use tracing::Level;use uuid::Uuid;use xerj_common::config::CorsConfig;@@ -56,6 +58,7 @@ use crate::{auth::auth_middleware, es_compat, memory_api, native, state::AppStat/// ```pub fn build_native_router(state: AppState) -> Router {let body_limit = state.config.limits.max_body_bytes;+ let access_log = state.config.logging.access_log;// Build the CORS layer before `state` is moved into the auth middleware.let cors = cors_layer(&state.config.cors);// Note: this router does NOT serve `/_xerj-console/*` — that namespace is@@ -148,7 +151,7 @@ pub fn build_native_router(state: AppState) -> Router {// Middleware stack (applied outermost-last).layer(middleware::from_fn_with_state(state, auth_middleware)).layer(middleware::from_fn(request_id_middleware))- .layer(TraceLayer::new_for_http())+ .layer(trace_layer(access_log)).layer(cors)// Reject requests with a body larger than the configured limit (OOM guard).// Disable axum's built-in 2MB default so RequestBodyLimitLayer is the only@@ -186,6 +189,7 @@ pub fn build_native_router(state: AppState) -> Router {/// ```pub fn build_es_compat_router(state: AppState) -> Router {let body_limit = state.config.limits.max_body_bytes;+ let access_log = state.config.logging.access_log;// Build the CORS layer before `state` is moved into the auth middleware.let cors = cors_layer(&state.config.cors);Router::new()@@ -196,6 +200,12 @@ pub fn build_es_compat_router(state: AppState) -> Router {// ── See `native.rs::liveness` for design rationale..route("/health/live", get(native::liveness)).route("/health/ready", get(native::readiness))+ // ── Prometheus scrape (RC4-W4 item 4) ──────────────────────────────+ // Mounted on the ES-compat port too so `:9200`-only deployments (the+ // common Elastic-drop-in posture, where the native `:8080` listener is+ // firewalled off) can still scrape metrics. Same handler as the native+ // router; gated by the optional read-only `auth.metrics_token`.+ .route("/v1/metrics", get(native::metrics))// ── Cluster-level ──────────────────────────────────────────────────.route("/", get(es_compat::es_info)).route("/_cluster/health", get(es_compat::cluster_health))@@ -208,6 +218,12 @@ pub fn build_es_compat_router(state: AppState) -> Router {"/_cat/indices/:pattern",get(es_compat::cat_indices_pattern),)+ // XERJ extension (RC4-W4 item 7): per-index ANN/HNSW health as a _cat+ // table so a brute-force-degraded (stale / partially-covered) vector+ // index stops being silent. No ES equivalent, so it can't collide with+ // the parity surface.+ .route("/_cat/ann", get(es_compat::cat_ann))+ .route("/_cat/ann/:index", get(es_compat::cat_ann_index)).route("/_cat/health", get(es_compat::cat_health)).route("/_cat/nodes", get(es_compat::cat_nodes)).route("/_cat/aliases", get(es_compat::cat_aliases))@@ -684,7 +700,7 @@ pub fn build_es_compat_router(state: AppState) -> Router {.layer(middleware::from_fn_with_state(state, auth_middleware)).layer(middleware::from_fn(es_headers_middleware)).layer(middleware::from_fn(request_id_middleware))- .layer(TraceLayer::new_for_http())+ .layer(trace_layer(access_log)).layer(cors)// Reject requests with a body larger than the configured limit (OOM guard).// Disable axum's built-in 2MB default so RequestBodyLimitLayer is the only@@ -771,6 +787,27 @@ fn cors_layer(cfg: &CorsConfig) -> CorsLayer {.allow_headers(Any)}+/// Build the request-tracing layer (RC4-W4 item 6).+///+/// When `access_log` is true, the span + request/response events are emitted at+/// INFO, so an operator gets one access line per request (method, path, status,+/// latency) under the default `info` filter. When false they stay at DEBUG —+/// silent by default, preserving today's quiet output — without forcing the+/// global filter down to debug. Both arms produce the same concrete type (the+/// level is a runtime field on the `Default*` responders), so this returns one+/// layer regardless of the flag.+fn trace_layer(access_log: bool) -> TraceLayer<SharedClassifier<ServerErrorsAsFailures>> {+ let level = if access_log {+ Level::INFO+ } else {+ Level::DEBUG+ };+ TraceLayer::new_for_http()+ .make_span_with(DefaultMakeSpan::new().level(level))+ .on_request(DefaultOnRequest::new().level(level))+ .on_response(DefaultOnResponse::new().level(level))+}+/// Middleware that injects a UUID request ID into extensions and response headers.async fn request_id_middleware(mut req: Request, next: Next) -> Response {let request_id = Uuid::new_v4().to_string();diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex 990ed9e16..de2b4964c 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -80,12 +80,14 @@ pub struct Config {pub pit: PitConfig,/// Scroll + async-search context TTLs and open-context caps — 7 settings.pub search_context: SearchContextConfig,+ /// Structured logging + access log — 2 settings.+ pub logging: LoggingConfig,}-// Total: 5+2+2+3+10+5+3+1+6+2+4+3+4+3 = 53 fields (incl. cors: 2)-// `Default` is derived — every field is a sub-config that implements-// `Default`, so the derive produces exactly the same all-defaults value-// the manual impl used to build by hand.+// Total: 5+3+2+3+10+5+3+1+6+2+4+3+4+3+2 = 56 fields (incl. cors: 2, auth: 3,+// logging: 2). `Default` is derived — every field is a sub-config that+// implements `Default`, so the derive produces exactly the same all-defaults+// value the manual impl used to build by hand.impl Config {/// Load configuration from a TOML file.@@ -215,6 +217,14 @@ impl Config {self.engine.validate()?;+ // Logging: format must be one of the two supported line formats.+ let fmt = self.logging.format.as_str();+ if !fmt.eq_ignore_ascii_case("text") && !fmt.eq_ignore_ascii_case("json") {+ return Err(XerjError::config(format!(+ "logging.format must be \"text\" or \"json\" (got {fmt:?})"+ )));+ }+Ok(())}@@ -275,7 +285,7 @@ impl Default for ServerConfig {/// Authentication settings.///-/// **2 settings.**+/// **3 settings.**#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default, deny_unknown_fields)]pub struct AuthConfig {@@ -290,6 +300,16 @@ pub struct AuthConfig {/// Leave empty in production; the engine writes the generated key to/// `<data_dir>/admin.key` on startup.pub admin_api_key: String,+ /// Optional read-only metrics scrape token (default: `""` — disabled).+ ///+ /// When set AND auth is enabled, a caller presenting this exact token+ /// (`Authorization: Bearer <token>` or `ApiKey <token>`) may scrape+ /// `GET /v1/metrics` — and ONLY that endpoint — without the admin key.+ /// This lets an operator hand Prometheus a low-privilege scrape credential+ /// that can read metrics but cannot touch index data. The admin key still+ /// works for `/v1/metrics`; when this is empty, metrics require the admin+ /// key like any other endpoint (unchanged behavior).+ pub metrics_token: String,}impl Default for AuthConfig {@@ -297,12 +317,53 @@ impl Default for AuthConfig {Self {enabled: true,admin_api_key: String::new(),+ metrics_token: String::new(),}}}// ─────────────────────────────────────────────────────────────────────────────+/// Structured logging + access-log settings (RC4-W4 item 6).+///+/// **2 settings.**+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct LoggingConfig {+ /// Log line format:+ /// - `"text"` (default) — human-readable compact one-liners.+ /// - `"json"` — one JSON object per line, for structured log shippers+ /// (Loki / Elastic / Datadog). Field names follow tracing's JSON schema.+ ///+ /// Validated at load time; any other value is rejected.+ pub format: String,+ /// Emit an INFO-level access log line per HTTP request (method, path,+ /// status, latency) via the tower-http request-tracing layer.+ ///+ /// Default `false`: request tracing stays at DEBUG (silent under the+ /// default `info` filter), preserving today's quiet startup. Turn on for+ /// request-level observability without dropping the global filter to debug.+ pub access_log: bool,+}++impl Default for LoggingConfig {+ fn default() -> Self {+ Self {+ format: "text".into(),+ access_log: false,+ }+ }+}++impl LoggingConfig {+ /// True when JSON line format is requested (case-insensitive).+ pub fn is_json(&self) -> bool {+ self.format.eq_ignore_ascii_case("json")+ }+}++// ─────────────────────────────────────────────────────────────────────────────+/// Cross-Origin Resource Sharing (CORS) settings.////// **2 settings.**@@ -1231,9 +1292,9 @@ mod tests {#[test]fn count_user_facing_settings() {- // 47 user-facing settings:+ // 50 user-facing settings:// server: 5 (rest_port, grpc_port, es_compat_port, data_dir, bind_address)- // auth: 2 (enabled, admin_api_key)+ // auth: 3 (enabled, admin_api_key, metrics_token) ← RC4-W4 item 4// tls: 3 (enabled, cert_path, key_path)// storage: 10 (wal_sync, wal_batch_ms, wal_max_size_mb, flush_size_mb,// flush_interval_secs, backend, s3_bucket, s3_prefix,@@ -1247,9 +1308,10 @@ mod tests {// embedding: 4 (default_endpoint, default_model, batch_size, timeout_ms)// limits: 3 (max_query_memory_mb, max_concurrent_searches, max_fields_per_index)// indexing: 3 (turbo_batch_size, turbo_parallel, turbo_fast_analyzer)+ // logging: 2 (format, access_log) ← RC4-W4 item 6// ─────────- // total: 47 fields, minus 1 auto-generated (admin_api_key) = 46 meaningful user settings- let total: usize = 5 + 2 + 3 + 10 + 5 + 3 + 1 + 6 + 2 + 4 + 3 + 3;- assert_eq!(total, 47);+ // total: 50 fields, minus 1 auto-generated (admin_api_key) = 49 meaningful user settings+ let total: usize = 5 + 3 + 3 + 10 + 5 + 3 + 1 + 6 + 2 + 4 + 3 + 3 + 2;+ assert_eq!(total, 50);}}diff --git a/engine/crates/xerj-common/src/metrics.rs b/engine/crates/xerj-common/src/metrics.rsindex c74486d2b..9698856f7 100644--- a/engine/crates/xerj-common/src/metrics.rs+++ b/engine/crates/xerj-common/src/metrics.rs@@ -83,6 +83,16 @@ pub struct Metrics {pub active_searches: IntGauge,/// Size of the WAL on disk in bytes.pub wal_size_bytes: IntGauge,++ // ── Query cache (RC4-W4 item 4) ───────────────────────────────────────────+ /// Cumulative internal query-result cache hits across all indices. Exposed+ /// as a gauge because it is reconciled from the engine's own atomic counters+ /// at scrape time (Prometheus `IntCounter` has no set()); the value is+ /// monotonic across a process lifetime, so `hits / (hits + misses)` gives+ /// the cache hit ratio directly.+ pub query_cache_hits: IntGauge,+ /// Cumulative internal query-result cache misses across all indices.+ pub query_cache_misses: IntGauge,}impl Metrics {@@ -229,6 +239,18 @@ impl Metrics {)).map_err(|e| XerjError::internal(format!("metrics: {e}")))?;+ let query_cache_hits = IntGauge::with_opts(Opts::new(+ "xerj_query_cache_hits",+ "Cumulative internal query-result cache hits across all indices",+ ))+ .map_err(|e| XerjError::internal(format!("metrics: {e}")))?;++ let query_cache_misses = IntGauge::with_opts(Opts::new(+ "xerj_query_cache_misses",+ "Cumulative internal query-result cache misses across all indices",+ ))+ .map_err(|e| XerjError::internal(format!("metrics: {e}")))?;+// ── Register everything ───────────────────────────────────────────────macro_rules! reg {($metric:expr) => {@@ -255,6 +277,8 @@ impl Metrics {reg!(memory_usage);reg!(active_searches);reg!(wal_size_bytes);+ reg!(query_cache_hits);+ reg!(query_cache_misses);Ok(Self {registry,@@ -275,9 +299,18 @@ impl Metrics {memory_usage,active_searches,wal_size_bytes,+ query_cache_hits,+ query_cache_misses,})}+ /// Reconcile the query-cache gauges from the engine's cumulative counters.+ /// Called by the `/v1/metrics` handler at scrape time.+ pub fn set_query_cache(&self, hits: u64, misses: u64) {+ self.query_cache_hits.set(hits as i64);+ self.query_cache_misses.set(misses as i64);+ }+// ── Scrape helpers ────────────────────────────────────────────────────────/// Gather all metrics from the registry as a `MetricFamily` vector.@@ -308,6 +341,17 @@ impl Metrics {self.docs_indexed_by_index.with_label_values(&[index]).inc();}+ /// Drop the per-index label series for `index` (RC4-W4 item 5).+ ///+ /// Called when an index is deleted so its `queries_by_index` /+ /// `docs_indexed_by_index` label series don't linger for the lifetime of+ /// the process (unbounded metric cardinality). Removing a label that was+ /// never created is a harmless no-op — the error is ignored.+ pub fn prune_index_labels(&self, index: &str) {+ let _ = self.queries_by_index.remove_label_values(&[index]);+ let _ = self.docs_indexed_by_index.remove_label_values(&[index]);+ }+/// Record a completed query.////// Increments counters and records latency histograms.diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 7ff07a0bb..ba2fa037f 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -1019,6 +1019,20 @@ impl Engine {self.indices.iter().map(|e| e.key().clone()).collect()}+ /// Sum the internal query-result cache hit/miss counters across every open+ /// index (RC4-W4 item 4). Returns `(hits, misses)`. Reconciled into the+ /// `xerj_query_cache_{hits,misses}` gauges by the `/v1/metrics` handler at+ /// scrape time — the engine owns the truth, the API layer owns Prometheus.+ pub fn query_cache_totals(&self) -> (u64, u64) {+ let mut hits = 0u64;+ let mut misses = 0u64;+ for entry in self.indices.iter() {+ hits = hits.saturating_add(entry.value().query_cache_hit_count());+ misses = misses.saturating_add(entry.value().query_cache_miss_count());+ }+ (hits, misses)+ }+pub async fn list_indices(&self) -> Vec<IndexInfo> {let mut list = Vec::new();for entry in self.indices.iter() {diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex b2fb86a97..876239801 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -9,7 +9,7 @@ use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::Value;use tokio::sync::{RwLock, Semaphore};-use tracing::{debug, error, info, warn};+use tracing::{debug, info, warn};use uuid::Uuid;use xerj_common::config::Config;use xerj_common::schema::ManagedSchema;@@ -410,6 +410,13 @@ pub struct Index {request_cache_seen: Arc<RwLock<RequestCacheSeen>>,request_cache_hits: Arc<AtomicU64>,request_cache_misses: Arc<AtomicU64>,+ /// Internal query-result cache hit/miss counters (RC4-W4 item 4). Distinct+ /// from `request_cache_*` above (the ES `request_cache=true` seen-set):+ /// these track the `query_cache` result cache consulted on every+ /// cache-eligible search. Summed across all indices and surfaced on+ /// `/v1/metrics` as `xerj_query_cache_{hits,misses}`.+ query_cache_hits: Arc<AtomicU64>,+ query_cache_misses: Arc<AtomicU64>,registry: Arc<AnalyzerRegistry>,data_dir: PathBuf,/// Doc count threshold for auto-flush (default: 10,000).@@ -875,6 +882,8 @@ impl Index {request_cache_seen: Arc::new(RwLock::new(RequestCacheSeen::with_capacity(65_536))),request_cache_hits: Arc::new(AtomicU64::new(0)),request_cache_misses: Arc::new(AtomicU64::new(0)),+ query_cache_hits: Arc::new(AtomicU64::new(0)),+ query_cache_misses: Arc::new(AtomicU64::new(0)),registry,data_dir: index_dir,flush_doc_threshold,@@ -1114,6 +1123,8 @@ impl Index {request_cache_seen: Arc::new(RwLock::new(RequestCacheSeen::with_capacity(65_536))),request_cache_hits: Arc::new(AtomicU64::new(0)),request_cache_misses: Arc::new(AtomicU64::new(0)),+ query_cache_hits: Arc::new(AtomicU64::new(0)),+ query_cache_misses: Arc::new(AtomicU64::new(0)),registry,data_dir: index_dir,flush_doc_threshold,@@ -5480,6 +5491,17 @@ impl Index {self.request_cache_misses.load(Ordering::Relaxed)}+ /// Cumulative internal query-result cache hits/misses for this index+ /// (RC4-W4 item 4). Summed across indices by [`Engine::query_cache_totals`]+ /// and surfaced on `/v1/metrics`.+ pub fn query_cache_hit_count(&self) -> u64 {+ self.query_cache_hits.load(Ordering::Relaxed)+ }++ pub fn query_cache_miss_count(&self) -> u64 {+ self.query_cache_misses.load(Ordering::Relaxed)+ }+/// Look up the latest `seq_no` for a document by id via the version/// map. Returns `None` when the doc is unknown or tombstoned.///@@ -5995,11 +6017,16 @@ impl Index {};if let Some(key) = cache_key {if let Some(entry) = self.query_cache.get(&key) {+ // Query-cache HIT (RC4-W4 item 4).+ self.query_cache_hits.fetch_add(1, Ordering::Relaxed);let mut cloned = (**entry.value()).clone();cloned.took_ms = 0;self.metric_query_count.fetch_add(1, Ordering::Relaxed);return Ok(cloned);}+ // Query-cache MISS: eligible + keyed, but not present. The request+ // proceeds to single-flight coalescing / real execution below.+ self.query_cache_misses.fetch_add(1, Ordering::Relaxed);}// ── Single-flight coalescing ────────────────────────────────────@@ -6170,23 +6197,11 @@ impl Index {self.metric_query_count.fetch_add(1, Ordering::Relaxed);self.metric_query_total_ms.fetch_add(took_ms, Ordering::Relaxed);- // Slow query logging.- let query_summary = summarize_query(&request.query);- if took_ms >= 5_000 {- error!(- took_ms,- index = self.name.as_str(),- query = %query_summary,- "slow query"- );- } else if took_ms >= 1_000 {- warn!(- took_ms,- index = self.name.as_str(),- query = %query_summary,- "slow query"- );- }+ // Slow-query observability (tracing warn/error + the operator+ // ring buffer) is emitted once, at the API boundary, via+ // `SlowQueryLog::maybe_record` — RC4-W4 item 3 unified the two+ // so they share the single runtime threshold knob instead of+ // this path's old hardcoded 1s/5s tracing thresholds.// Populate the response cache. Bound the cache to ~1k// entries by truncating when it grows; for hot dashboards// the working set is far smaller and the cheap O(n)@@ -15187,57 +15202,6 @@ fn apply_collapse_with_inner(result}-/// Produce a short human-readable summary of a query for logging.-fn summarize_query(query: &QueryNode) -> String {- match query {- QueryNode::MatchAll => "match_all".to_string(),- QueryNode::MatchNone => "match_none".to_string(),- QueryNode::Match { field, query, .. } => {- format!("match({}:{})", field, &query[..query.len().min(50)])- }- QueryNode::Term { field, value, .. } => format!(- "term({}:{})",- field,- value.to_string().chars().take(50).collect::<String>()- ),- QueryNode::Terms { field, values, .. } => {- format!("terms({}, {} values)", field, values.len())- }- QueryNode::Range { field, .. } => format!("range({})", field),- QueryNode::Bool {- must,- should,- filter,- must_not,- ..- } => {- format!(- "bool(must={}, should={}, filter={}, must_not={})",- must.len(),- should.len(),- filter.len(),- must_not.len()- )- }- QueryNode::MultiMatch { query, fields, .. } => {- format!(- "multi_match({}, {} fields)",- &query[..query.len().min(50)],- fields.len()- )- }- QueryNode::QueryString { query, .. } => {- format!("query_string({})", &query[..query.len().min(50)])- }- QueryNode::Ids { values } => format!("ids({} ids)", values.len()),- QueryNode::Knn { field, .. } => format!("knn({})", field),- QueryNode::Nested { path, .. } => format!("nested({})", path),- QueryNode::MoreLikeThis { like, .. } => format!("more_like_this({} texts)", like.len()),- QueryNode::Pinned { ids, .. } => format!("pinned({} ids)", ids.len()),- other => format!("{:?}", other).chars().take(100).collect(),- }-}-/// Apply `_source` filtering to all hits.////// * `Enabled(true)` → return source unchanged (default).diff --git a/engine/crates/xerj-engine/src/slow_query.rs b/engine/crates/xerj-engine/src/slow_query.rsindex a28a9729c..247996306 100644--- a/engine/crates/xerj-engine/src/slow_query.rs+++ b/engine/crates/xerj-engine/src/slow_query.rs@@ -14,13 +14,18 @@//! - Append is O(1): grow until capacity, then overwrite oldest.//! - Threshold is per-process global; per-index overrides can be added//! later if needed (most cluster-debug scenarios want a single knob).-//! - We deliberately keep the entry shape small (no full query JSON) so-//! that even with 256 entries the buffer is < 64 KB and safe to-//! serialize over an HTTP admin endpoint.+//! - Each entry carries the query body, bounded to [`SLOW_QUERY_MAX_BODY`]+//! chars so an operator can see *what* was slow — not just that something+//! was. The cap keeps the ring safe to serialize over the admin endpoint+//! even at full capacity (256 × 2 KB ≈ 512 KB worst case).+//! - This is the single source of truth for slow-query observability: the+//! `tracing` warn/error line is emitted from inside [`maybe_record`] using+//! the SAME runtime threshold as the ring buffer, so the log and the buffer+//! can never disagree and both track the hot-reloadable knob.//!-//! A future v0.9 enhancement will export this as a Prometheus-//! histogram + counter (`xerj_search_slow_total`) so the operator-//! can graph slow-query rates per index in Grafana.+//! A future enhancement will export this as a Prometheus histogram + counter+//! (`xerj_search_slow_total`) so the operator can graph slow-query rates per+//! index in Grafana.use parking_lot::RwLock;use serde::{Deserialize, Serialize};@@ -32,6 +37,24 @@ use std::time::Duration;pub const DEFAULT_SLOW_QUERY_MS: u64 = 1_000;/// Default ring buffer capacity.pub const DEFAULT_SLOW_QUERY_CAPACITY: usize = 256;+/// Max chars of the query body retained per entry (and emitted on the tracing+/// line). Keeps the bounded ring small and safe to serialize even at full+/// capacity, and stops a pathological multi-megabyte query DSL from bloating+/// either the buffer or a log line.+pub const SLOW_QUERY_MAX_BODY: usize = 2_048;++/// Truncate a query body to [`SLOW_QUERY_MAX_BODY`] chars on a UTF-8 char+/// boundary, appending an ellipsis when clipped.+fn truncate_body(s: &str) -> String {+ if s.len() <= SLOW_QUERY_MAX_BODY {+ return s.to_string();+ }+ let mut end = SLOW_QUERY_MAX_BODY;+ while end > 0 && !s.is_char_boundary(end) {+ end -= 1;+ }+ format!("{}…", &s[..end])+}#[derive(Clone, Debug, Serialize, Deserialize)]pub struct SlowQueryEntry {@@ -47,6 +70,11 @@ pub struct SlowQueryEntry {pub hits: u64,/// Optional short reason (e.g. "many segments scanned", "agg fan-out").pub note: String,+ /// The query body (bounded to [`SLOW_QUERY_MAX_BODY`] chars). Empty when+ /// the caller had no structured body (e.g. a URI-only `q=` request or a+ /// `match_all`). This is what makes an entry *actionable* — the operator+ /// sees the exact DSL that ran slow.+ pub query: String,}/// Bounded ring buffer of slow query entries.@@ -83,8 +111,16 @@ impl SlowQueryLog {self.total.load(Ordering::Relaxed)}- /// If `took >= threshold`, record an entry. No-op otherwise.- /// Returns `true` if the entry was recorded.+ /// If `took >= threshold`, record an entry AND emit the slow-query+ /// tracing line. No-op otherwise. Returns `true` if the entry was+ /// recorded.+ ///+ /// This is the ONE place slow queries are surfaced. Both the ring buffer+ /// and the `tracing` warn/error line are gated on the same runtime+ /// `threshold_ms` knob (hot-reloadable via `set_threshold_ms`), so they+ /// can never drift apart — previously the ring buffer respected the knob+ /// while `Index::search` logged against hardcoded 1s/5s thresholds.+ /// `error!` fires at 5× the knob, `warn!` at 1×.pub fn maybe_record(&self,index: &str,@@ -92,12 +128,21 @@ impl SlowQueryLog {took: Duration,hits: u64,note: &str,+ query: &str,) -> bool {let took_ms = took.as_millis() as u64;- if took_ms < self.threshold_ms.load(Ordering::Relaxed) {+ let threshold = self.threshold_ms.load(Ordering::Relaxed);+ if took_ms < threshold {return false;}self.total.fetch_add(1, Ordering::Relaxed);+ let query = truncate_body(query);+ // Unified tracing — same threshold as the ring buffer above.+ if took_ms >= threshold.saturating_mul(5) {+ tracing::error!(took_ms, index, op, hits, query = %query, "slow query");+ } else {+ tracing::warn!(took_ms, index, op, hits, query = %query, "slow query");+ }let entry = SlowQueryEntry {at_ms: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -108,6 +153,7 @@ impl SlowQueryLog {took_ms,hits,note: note.to_string(),+ query,};let mut buf = self.buf.write();if buf.len() < self.capacity {@@ -141,7 +187,7 @@ mod tests {#[test]fn under_threshold_no_record() {let log = SlowQueryLog::new(8, 1000);- let recorded = log.maybe_record("idx", "search", Duration::from_millis(500), 10, "");+ let recorded = log.maybe_record("idx", "search", Duration::from_millis(500), 10, "", "");assert!(!recorded);assert!(log.snapshot().is_empty());assert_eq!(log.total_slow(), 0);@@ -150,12 +196,21 @@ mod tests {#[test]fn over_threshold_records() {let log = SlowQueryLog::new(8, 1000);- let recorded = log.maybe_record("idx", "search", Duration::from_millis(1500), 10, "test");+ let recorded = log.maybe_record(+ "idx",+ "search",+ Duration::from_millis(1500),+ 10,+ "test",+ r#"{"match_all":{}}"#,+ );assert!(recorded);let snap = log.snapshot();assert_eq!(snap.len(), 1);assert_eq!(snap[0].took_ms, 1500);assert_eq!(snap[0].index, "idx");+ // The query body is captured so the entry is actionable.+ assert_eq!(snap[0].query, r#"{"match_all":{}}"#);assert_eq!(log.total_slow(), 1);}@@ -163,7 +218,7 @@ mod tests {fn ring_rotates_at_capacity() {let log = SlowQueryLog::new(2, 100);for i in 0..5 {- log.maybe_record("idx", "search", Duration::from_millis(200 + i), i, "");+ log.maybe_record("idx", "search", Duration::from_millis(200 + i), i, "", "");}let snap = log.snapshot();assert_eq!(snap.len(), 2);@@ -178,7 +233,26 @@ mod tests {let log = SlowQueryLog::new(8, 1000);log.set_threshold_ms(50);assert_eq!(log.threshold_ms(), 50);- let recorded = log.maybe_record("idx", "search", Duration::from_millis(100), 0, "");+ let recorded = log.maybe_record("idx", "search", Duration::from_millis(100), 0, "", "");assert!(recorded);}++ #[test]+ fn long_query_body_is_truncated_on_char_boundary() {+ let log = SlowQueryLog::new(4, 100);+ // A multibyte body larger than the cap must be clipped without+ // panicking on a char boundary, and marked with an ellipsis.+ let big = "é".repeat(SLOW_QUERY_MAX_BODY); // 2 bytes each ⇒ well over the cap+ let recorded = log.maybe_record("idx", "search", Duration::from_millis(200), 1, "", &big);+ assert!(recorded);+ let snap = log.snapshot();+ assert_eq!(snap.len(), 1);+ let stored = &snap[0].query;+ assert!(+ stored.ends_with('…'),+ "clipped body should end with an ellipsis"+ );+ // Body (minus the ellipsis) never exceeds the byte cap.+ assert!(stored.len() <= SLOW_QUERY_MAX_BODY + '…'.len_utf8());+ }}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 98de7f67a..b580e9692 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -460,17 +460,24 @@ async fn build_tls_config(cfg: &Config) -> Result<Option<RustlsConfig>> {// Observability// ─────────────────────────────────────────────────────────────────────────────-fn init_tracing() {+fn init_tracing(logging: &xerj_common::config::LoggingConfig) {let filter = EnvFilter::try_from_env("XERJ_LOG").or_else(|_| EnvFilter::try_from_env("RUST_LOG")).unwrap_or_else(|_| EnvFilter::new("info"));- tracing_subscriber::fmt()+ let builder = tracing_subscriber::fmt().with_env_filter(filter).with_target(true)- .with_thread_ids(false)- .compact()- .init();+ .with_thread_ids(false);++ // RC4-W4 item 6: JSON structured logs for shippers, or compact text+ // (default). Both branches call `.init()` so the differing builder types+ // never need to unify.+ if logging.is_json() {+ builder.json().init();+ } else {+ builder.compact().init();+ }}// ─────────────────────────────────────────────────────────────────────────────@@ -714,8 +721,6 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {use std::sync::Arc as StdArc;use tokio::sync::Semaphore;- init_tracing();-// Load config but override to a minimal in-process shape.let fake_cli = CliArgs {config: cmd.config.clone(),@@ -724,6 +729,8 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {embed_mode: None,};let mut cfg = load_config(&fake_cli)?;+ // Tracing after config so the [logging] format applies (RC4-W4 item 6).+ init_tracing(&cfg.logging);cfg.tls.enabled = false;cfg.auth.enabled = false;cfg.cluster.enabled = false;@@ -1084,13 +1091,15 @@ async fn async_main() -> Result<()> {// 1. CLI argslet args = parse_args();- // 2. Tracing (must be first so startup is logged)- init_tracing();+ // 2. Config — loaded before tracing so the [logging] format (text/json)+ // governs the very first startup line (RC4-W4 item 6). A config-load+ // failure still surfaces via the returned Result → stderr.+ let mut cfg = load_config(&args)?;- info!("xerj v{} starting", env!("CARGO_PKG_VERSION"));+ // 3. Tracing+ init_tracing(&cfg.logging);- // 3. Config- let mut cfg = load_config(&args)?;+ info!("xerj v{} starting", env!("CARGO_PKG_VERSION"));// 4. Data directorystd::fs::create_dir_all(&cfg.server.data_dir)diff --git a/engine/xerj.default.toml b/engine/xerj.default.tomlindex 739704c43..cff373334 100644--- a/engine/xerj.default.toml+++ b/engine/xerj.default.toml@@ -52,6 +52,13 @@ enabled = true# filesystem permissions (chmod 600).admin_api_key = ""+# Optional read-only metrics scrape token (leave empty to disable).+# When set AND auth is enabled, a caller presenting this exact token+# (Authorization: Bearer <token>) may scrape GET /v1/metrics — and ONLY that+# endpoint — without the admin key. Hand this to Prometheus so the scraper has+# a low-privilege credential that can read metrics but not index data.+metrics_token = ""+# ── TLS (3 settings) ──────────────────────────────────────────────────────────[tls]@@ -324,3 +331,19 @@ turbo_parallel = true# This increases ingest throughput at the cost of reduced search recall# (e.g. "running" will not match "run").turbo_fast_analyzer = false++# ── Logging (2 settings) ──────────────────────────────────────────────────────++[logging]++# Log line format:+# "text" — human-readable compact one-liners (default).+# "json" — one JSON object per line, for structured log shippers+# (Loki / Elastic / Datadog).+format = "text"++# Emit an INFO-level access log line per HTTP request (method, path, status,+# latency). Default false: request tracing stays at DEBUG (silent under the+# default `info` filter). Turn on for request-level observability without+# dropping the global log filter down to debug.+access_log = false