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: log the search body on slow queries and scope autoindex status (#1630)

xerj-orgabad8180b0c7
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 548838692..0d7441a84 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -13556,11 +13556,10 @@ async fn search_impl(
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(),
+ // An omitted `query` (match_all) or a top-level `knn` with no query
+ // clause used to log `query=` empty. `logged_search_query` records
+ // the clause the engine actually ran.
+ &xerj_engine::slow_query::logged_search_query(body.query.as_ref(), body.knn.as_ref()),
);
// v0.9 9-P4: append to the audit log. The subject was the literal
// "anonymous" until issue #329 — the API-key operations had been passing a
diff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rs
index 1be60269b..6406ca689 100644
--- a/engine/crates/xerj-api/src/native.rs
+++ b/engine/crates/xerj-api/src/native.rs
@@ -594,10 +594,10 @@ pub async fn search(
started.elapsed(),
result.hits.len() as u64,
"",
- &query_body
- .get("query")
- .map(|q| q.to_string())
- .unwrap_or_default(),
+ &xerj_engine::slow_query::logged_search_query(
+ query_body.get("query"),
+ query_body.get("knn"),
+ ),
);
let hits: Vec<Value> = result.hits.iter().map(native_hit_value).collect();
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 8c7764766..474bd215f 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -9900,6 +9900,104 @@ pub fn fetch_catalog_summary(url: &str, api_key: Option<String>) -> Result<Catal
// ─── status subcommand ───────────────────────────────────────────────────
+struct JournalFacts {
+ root: String,
+ files_done: u64,
+ records: u64,
+ finished: bool,
+ generation: Option<u64>,
+ generation_files: Option<u64>,
+ generation_records: Option<u64>,
+ graph_line: Option<String>,
+ /// `url` from the `kind: run` record. Empty on a journal written before
+ /// that field existed.
+ url: String,
+}
+
+fn read_journal_facts(jp: &Path) -> JournalFacts {
+ let mut facts = JournalFacts {
+ root: String::new(),
+ files_done: 0,
+ records: 0,
+ finished: false,
+ generation: None,
+ generation_files: None,
+ generation_records: None,
+ graph_line: None,
+ url: String::new(),
+ };
+ let Ok(f) = std::fs::File::open(jp) else {
+ return facts;
+ };
+ for line in std::io::BufReader::new(f).lines().map_while(|l| l.ok()) {
+ let Ok(v) = serde_json::from_str::<Value>(&line) else {
+ continue;
+ };
+ match v.get("kind").and_then(|k| k.as_str()) {
+ Some("run") => {
+ facts.root = v.get("root").and_then(|r| r.as_str()).unwrap_or("").into();
+ if let Some(url) = v.get("url").and_then(|u| u.as_str()) {
+ facts.url = url.to_string();
+ }
+ }
+ Some("file_done") => {
+ facts.files_done += 1;
+ facts.records += v.get("records").and_then(|r| r.as_u64()).unwrap_or(0);
+ }
+ Some("finish") => {
+ facts.finished = true;
+ facts.generation = v.pointer("/summary/generation").and_then(Value::as_u64);
+ facts.generation_files =
+ v.pointer("/summary/files_indexed").and_then(Value::as_u64);
+ facts.generation_records =
+ v.pointer("/summary/records_total").and_then(Value::as_u64);
+ // Latest finish wins — the summary embeds the run
+ // doc, whose `graph` block is the edge count of
+ // record for this journal.
+ if let Some(g) = v.pointer("/summary/graph").filter(|graph| !graph.is_null()) {
+ facts.graph_line = Some(format!(
+ "graph: {} edges written to {} (brain {})",
+ g.get("edges_written").and_then(Value::as_u64).unwrap_or(0),
+ g.get("edges_index").and_then(Value::as_str).unwrap_or("?"),
+ g.get("brain").and_then(Value::as_str).unwrap_or("?"),
+ ));
+ }
+ }
+ _ => {}
+ }
+ }
+ facts
+}
+
+/// Two endpoint strings name the same node when they match after trimming
+/// and stripping one trailing slash. `http://127.0.0.1:9200/` and
+/// `http://127.0.0.1:9200` are the same journal.
+fn urls_identify_same_endpoint(recorded: &str, current: &str) -> bool {
+ fn norm(s: &str) -> &str {
+ s.trim().trim_end_matches('/')
+ }
+ norm(recorded) == norm(current)
+}
+
+/// Status word for one journal line.
+///
+/// A journal whose `run` record names a different node is not this
+/// endpoint's run. Printing `in progress` or `FINISHED` there makes
+/// `autoindex status` look like another node's work is this node's.
+/// An empty recorded URL is a journal from before `url` was written;
+/// those keep the old words.
+fn journal_progress_label(finished: bool, journal_url: &str, current_url: &str) -> String {
+ let recorded = journal_url.trim().trim_end_matches('/');
+ if !recorded.is_empty() && !urls_identify_same_endpoint(recorded, current_url) {
+ return format!("other endpoint {recorded}");
+ }
+ if finished {
+ "FINISHED".to_string()
+ } else {
+ "in progress".to_string()
+ }
+}
+
fn run_status(cfg: StatusCfg) -> Result<i32> {
if let Some(note) = &cfg.xerj_url_note {
eprintln!("autoindex: {note}");
@@ -9922,64 +10020,21 @@ fn run_status(cfg: StatusCfg) -> Result<i32> {
if !jp.exists() {
continue;
}
- let mut root = String::new();
- let mut done = 0u64;
- let mut records = 0u64;
- let mut finished = false;
- let mut generation: Option<u64> = None;
- let mut generation_files: Option<u64> = None;
- let mut generation_records: Option<u64> = None;
- let mut graph_line: Option<String> = None;
- if let Ok(f) = std::fs::File::open(&jp) {
- use std::io::BufRead;
- for line in std::io::BufReader::new(f).lines().map_while(|l| l.ok()) {
- if let Ok(v) = serde_json::from_str::<Value>(&line) {
- match v.get("kind").and_then(|k| k.as_str()) {
- Some("run") => {
- root = v.get("root").and_then(|r| r.as_str()).unwrap_or("").into()
- }
- Some("file_done") => {
- done += 1;
- records += v.get("records").and_then(|r| r.as_u64()).unwrap_or(0);
- }
- Some("finish") => {
- finished = true;
- generation = v.pointer("/summary/generation").and_then(Value::as_u64);
- generation_files =
- v.pointer("/summary/files_indexed").and_then(Value::as_u64);
- generation_records =
- v.pointer("/summary/records_total").and_then(Value::as_u64);
- // Latest finish wins — the summary embeds the run
- // doc, whose `graph` block is the edge count of
- // record for this journal.
- if let Some(g) =
- v.pointer("/summary/graph").filter(|graph| !graph.is_null())
- {
- graph_line = Some(format!(
- "graph: {} edges written to {} (brain {})",
- g.get("edges_written").and_then(Value::as_u64).unwrap_or(0),
- g.get("edges_index").and_then(Value::as_str).unwrap_or("?"),
- g.get("brain").and_then(Value::as_str).unwrap_or("?"),
- ));
- }
- }
- _ => {}
- }
- }
- }
- }
+ let facts = read_journal_facts(&jp);
+ let label = journal_progress_label(facts.finished, &facts.url, &cfg.url);
println!(
"journal {} — root {} — {} files done, {} records, {}{}",
jp.display(),
- root,
- generation_files.unwrap_or(done),
- generation_records.unwrap_or(records),
- if finished { "FINISHED" } else { "in progress" },
- generation
+ facts.root,
+ facts.generation_files.unwrap_or(facts.files_done),
+ facts.generation_records.unwrap_or(facts.records),
+ label,
+ facts
+ .generation
.map(|generation| format!(" (generation {generation})"))
.unwrap_or_default()
);
- if let Some(line) = graph_line {
+ if let Some(line) = facts.graph_line {
println!(" {line}");
}
}
@@ -9998,6 +10053,77 @@ fn run_status(cfg: StatusCfg) -> Result<i32> {
Ok(0)
}
+#[cfg(test)]
+mod journal_status_tests {
+ use super::{journal_progress_label, read_journal_facts};
+ use std::fs;
+
+ fn write_journal(name: &str, body: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("xerj-status-{}-{name}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("journal.ndjson");
+ fs::write(&path, body).unwrap();
+ path
+ }
+
+ #[test]
+ fn another_endpoints_journal_is_not_in_progress() {
+ let path = write_journal(
+ "other-open",
+ "{\"v\":1,\"kind\":\"run\",\"root\":\"/repo\",\"url\":\"http://127.0.0.1:9201\",\"prefix\":\"ax\"}\n\
+ {\"kind\":\"file_done\",\"records\":3}\n",
+ );
+ let facts = read_journal_facts(&path);
+ assert_eq!(facts.root, "/repo");
+ assert_eq!(facts.files_done, 1);
+ assert_eq!(facts.records, 3);
+ assert!(!facts.finished);
+ let label = journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200");
+ assert_eq!(label, "other endpoint http://127.0.0.1:9201");
+ assert!(!label.contains("in progress"));
+ assert!(!label.contains("FINISHED"));
+
+ let finished = write_journal(
+ "other-done",
+ "{\"kind\":\"run\",\"root\":\"/other\",\"url\":\"http://10.0.0.2:9200/\"}\n\
+ {\"kind\":\"finish\",\"summary\":{\"generation\":4,\"files_indexed\":2,\"records_total\":9}}\n",
+ );
+ let facts = read_journal_facts(&finished);
+ assert!(facts.finished);
+ assert_eq!(facts.generation, Some(4));
+ assert_eq!(facts.generation_files, Some(2));
+ assert_eq!(facts.generation_records, Some(9));
+ let label = journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200");
+ assert_eq!(label, "other endpoint http://10.0.0.2:9200");
+ assert!(!label.contains("in progress"));
+ assert!(!label.contains("FINISHED"));
+ let _ = fs::remove_dir_all(path.parent().unwrap());
+ let _ = fs::remove_dir_all(finished.parent().unwrap());
+ }
+
+ #[test]
+ fn this_endpoint_and_a_legacy_journal_keep_the_old_words() {
+ assert_eq!(
+ journal_progress_label(true, "http://127.0.0.1:9200/", "http://127.0.0.1:9200"),
+ "FINISHED"
+ );
+ assert_eq!(
+ journal_progress_label(false, " http://127.0.0.1:9200 ", "http://127.0.0.1:9200/"),
+ "in progress"
+ );
+ // No `url` on the run record: a journal from before the field existed.
+ let path = write_journal("legacy", "{\"kind\":\"run\",\"root\":\"/old\"}\n");
+ let facts = read_journal_facts(&path);
+ assert!(facts.url.is_empty());
+ assert_eq!(
+ journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200"),
+ "in progress"
+ );
+ let _ = fs::remove_dir_all(path.parent().unwrap());
+ }
+}
+
#[cfg(test)]
mod section_label_tests {
use super::section_label;
diff --git a/engine/crates/xerj-engine/src/slow_query.rs b/engine/crates/xerj-engine/src/slow_query.rs
index 247996306..a2b3dc892 100644
--- a/engine/crates/xerj-engine/src/slow_query.rs
+++ b/engine/crates/xerj-engine/src/slow_query.rs
@@ -70,13 +70,36 @@ 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.
+ /// The query body (bounded to [`SLOW_QUERY_MAX_BODY`] chars). Search
+ /// callers fill this via [`logged_search_query`], so an omitted clause
+ /// is recorded as `{"match_all":{}}` (what the engine runs) and a
+ /// top-level `knn` is recorded with the query instead of an empty
+ /// `query=` field. This is what makes an entry *actionable* — the
+ /// operator sees the exact DSL that ran slow.
pub query: String,
}
+/// Text stored in [`SlowQueryEntry::query`] for one search.
+///
+/// An omitted query is match_all. A top-level `knn` with no query clause is
+/// the knn object, not an empty string — an empty `query=` on the tracing
+/// line reads as "the body was lost". Null clauses are treated as absent.
+/// When both are present the entry keeps both, because logging only `query`
+/// hides the knn that may be why the search was slow.
+pub fn logged_search_query(
+ query: Option<&serde_json::Value>,
+ knn: Option<&serde_json::Value>,
+) -> String {
+ let query = query.filter(|q| !q.is_null());
+ let knn = knn.filter(|k| !k.is_null());
+ match (query, knn) {
+ (Some(q), None) => q.to_string(),
+ (Some(q), Some(knn)) => serde_json::json!({"query": q, "knn": knn}).to_string(),
+ (None, Some(knn)) => serde_json::json!({"knn": knn}).to_string(),
+ (None, None) => r#"{"match_all":{}}"#.to_string(),
+ }
+}
+
/// Bounded ring buffer of slow query entries.
pub struct SlowQueryLog {
buf: RwLock<Vec<SlowQueryEntry>>,
@@ -255,4 +278,37 @@ mod tests {
// Body (minus the ellipsis) never exceeds the byte cap.
assert!(stored.len() <= SLOW_QUERY_MAX_BODY + '…'.len_utf8());
}
+
+ #[test]
+ fn logged_search_query_is_never_empty() {
+ let knn = serde_json::json!({"field": "embedding", "query_vector": [0.1, 0.2], "k": 10});
+ let lexical = serde_json::json!({"match": {"body": "rotate keys"}});
+
+ let omitted = logged_search_query(None, None);
+ assert_eq!(omitted, r#"{"match_all":{}}"#);
+ assert!(!omitted.is_empty());
+
+ let nulls = logged_search_query(
+ Some(&serde_json::Value::Null),
+ Some(&serde_json::Value::Null),
+ );
+ assert_eq!(nulls, r#"{"match_all":{}}"#);
+
+ assert_eq!(
+ logged_search_query(Some(&lexical), None),
+ lexical.to_string()
+ );
+
+ let knn_only = logged_search_query(None, Some(&knn));
+ assert_eq!(knn_only, serde_json::json!({"knn": knn}).to_string());
+ assert!(!knn_only.is_empty());
+
+ let both = logged_search_query(Some(&lexical), Some(&knn));
+ assert_eq!(
+ both,
+ serde_json::json!({"query": lexical, "knn": knn}).to_string()
+ );
+ assert!(both.contains("\"knn\""));
+ assert!(both.contains("rotate keys"));
+ }
}