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(autoindex,code): skip catalog phrase text and parse phone syslog (#2247)
xerj-org37a521f7b757
diff --git a/engine/crates/xerj-autoindex/src/extract/logs.rs b/engine/crates/xerj-autoindex/src/extract/logs.rsindex 307cf3def..3891c134d 100644--- a/engine/crates/xerj-autoindex/src/extract/logs.rs+++ b/engine/crates/xerj-autoindex/src/extract/logs.rs@@ -1,6 +1,8 @@//! Server-log families: CLF/combined access logs, app logs-//! (`YYYY-MM-DD HH:MM:SS,ms LEVEL [thread] message`), RFC3164 syslog, and —-//! since #1504 — ISO-prefixed syslog (`journalctl -o short-iso` and friends:+//! (`YYYY-MM-DD HH:MM:SS,ms LEVEL [thread] message`), RFC3164 syslog (with an+//! optional `<PRI>`, the form desk phones actually send), RFC5424+//! (`<PRI>VERSION TS host app procid msgid SD msg`), and — since #1504 —+//! ISO-prefixed syslog (`journalctl -o short-iso` and friends://! `TS host prog[pid]: message`, with an optional `<PRI>` whose severity is//! decoded) and `xferlog` (`vsftpd`/wu-ftpd transfer records, 14 fields).//! One template is elected per file from the first 200 lines; unmatched@@ -20,6 +22,7 @@ struct Templates {clf: Regex,applog: Regex,syslog: Regex,+ rfc5424: Regex,isosyslog: Regex,xferlog: Regex,kv: Regex,@@ -36,8 +39,23 @@ fn templates() -> &'static Templates {r"^(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:[.,]\d{1,9})?)\s+(?:\[([^\]]+)\]\s+)?(TRACE|DEBUG|INFO|WARN(?:ING)?|ERROR|FATAL|CRITICAL)\s*(?:\[([^\]]+)\]\s*)?[:\-]?\s*(.*)$",).unwrap(),+ // Optional `<PRI>`: desk-phone and BSD syslog write+ // `<PRI>Mon dd hh:mm:ss host tag[pid]: msg` and the PRI-less form+ // already recognised. A single space before `[pid]` is accepted+ // (`SIP [990]:`) because that is how several phone stacks print the+ // tag; the space is part of the bracket, so `host notes: prose`+ // still parses as a tag with no pid, the same as before.syslog: Regex::new(- r"^([A-Z][a-z]{2} +\d+ \d{2}:\d{2}:\d{2}) (\S+) ([\w./-]+)(?:\[(\d+)\])?: (.*)$",+ r"^(?:<(\d{1,3})>)?([A-Z][a-z]{2} +\d+ \d{2}:\d{2}:\d{2}) (\S+) ([\w./-]+)(?: ?\[(\d+)\])?: (.*)$",+ )+ .unwrap(),+ // RFC 5424: `<PRI>VERSION SP TIMESTAMP SP HOST SP APP SP PROCID SP+ // MSGID SP STRUCTURED-DATA [SP MSG]`. VERSION is what separates this+ // from PRI-prefixed ISO syslog (`<PRI>TS host tag[pid]: msg`), which+ // has no version digit between the priority and the timestamp.+ // NILVALUE `-` is allowed for APP, PROCID, MSGID and STRUCTURED-DATA.+ rfc5424: Regex::new(+ r"^<(\d{1,3})>(\d+) (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})?) (\S+) (\S+) (\S+) (\S+) (?:-|\[(?:\\.|[^\]])*\])(?: (.*))?$",).unwrap(),// #1504: `journalctl -o short-iso` / rsyslog ISO templates —@@ -83,6 +101,7 @@ enum Kind {Clf,App,Syslog,+ Rfc5424,IsoSyslog,Xferlog,}@@ -93,18 +112,20 @@ impl Kind {/// resolves the way an ambiguous LINE does — most specific first. The app/// template demands an ISO timestamp *and* a level keyword; CLF demands a/// quoted request line *and* a 3-digit status; xferlog demands the fixed- /// 14-field record shape; the ISO-syslog template demands an ISO timestamp- /// *and* the `prog[pid]:` colon form; the RFC3164 pattern is by far the- /// loosest (`Mon dd HH:MM:SS host prog: rest`) and will claim lines the- /// others describe better. Every variant has a distinct rank, which is- /// what makes the ordering total.+ /// 14-field record shape; RFC5424 demands `<PRI>`, a version and an ISO+ /// timestamp; the ISO-syslog template demands an ISO timestamp *and* the+ /// `prog[pid]:` colon form; the RFC3164 pattern is by far the loosest+ /// (`Mon dd HH:MM:SS host prog: rest`, optional `<PRI>`) and will claim+ /// lines the others describe better. Every variant has a distinct rank,+ /// which is what makes the ordering total.fn specificity(self) -> u8 {match self {Kind::App => 0,Kind::Clf => 1,Kind::Xferlog => 2,- Kind::IsoSyslog => 3,- Kind::Syslog => 4,+ Kind::Rfc5424 => 3,+ Kind::IsoSyslog => 4,+ Kind::Syslog => 5,}}}@@ -143,6 +164,8 @@ fn parse_kind(line: &str) -> Option<Kind> {Some(Kind::Clf)} else if t.xferlog.is_match(line) {Some(Kind::Xferlog)+ } else if t.rfc5424.is_match(line) {+ Some(Kind::Rfc5424)} else if t.isosyslog.is_match(line) {Some(Kind::IsoSyslog)} else if t.syslog.is_match(line) {@@ -152,6 +175,26 @@ fn parse_kind(line: &str) -> Option<Kind> {}}+/// `<PRI>` = facility*8 + severity (RFC 5424 §6.2.1). Only call this when+/// the writer emitted a priority. The domain is 0..=191 (facility 0..=23 ×+/// 8 + severity 0..=7); `<999>` is not a priority, so it stays unrecorded+/// rather than decoding into a facility of 124. A line with no `<PRI>`+/// (journalctl short-iso, classic RFC3164) must not call this — inventing+/// a severity the file does not contain is a lie about the data.+fn record_priority(pri: u16, m: &mut Map<String, Value>) {+ if pri > 191 {+ return;+ }+ const SEVERITY: [&str; 8] = [+ "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",+ ];+ m.insert(+ "severity".into(),+ Value::String(SEVERITY[(pri & 7) as usize].to_string()),+ );+ m.insert("facility".into(), Value::Number((pri >> 3).into()));+}+fn parse_line(line: &str, kind: Kind) -> Option<Map<String, Value>> {let t = templates();let mut m = Map::new();@@ -204,41 +247,49 @@ fn parse_line(line: &str, kind: Kind) -> Option<Map<String, Value>> {}Kind::Syslog => {let c = t.syslog.captures(line)?;- m.insert("ts".into(), Value::String(c.get(1)?.as_str().to_string()));- m.insert("host".into(), Value::String(c.get(2)?.as_str().to_string()));+ if let Some(pri) = c.get(1).and_then(|p| p.as_str().parse::<u16>().ok()) {+ record_priority(pri, &mut m);+ }+ m.insert("ts".into(), Value::String(c.get(2)?.as_str().to_string()));+ m.insert("host".into(), Value::String(c.get(3)?.as_str().to_string()));m.insert("program".into(),- Value::String(c.get(3)?.as_str().to_string()),+ Value::String(c.get(4)?.as_str().to_string()),);- if let Some(pid) = c.get(4) {+ if let Some(pid) = c.get(5) {+ if let Ok(n) = pid.as_str().parse::<i64>() {+ m.insert("pid".into(), Value::Number(n.into()));+ }+ }+ let msg = c.get(6)?.as_str().to_string();+ lift_kv(&msg, &mut m);+ }+ Kind::Rfc5424 => {+ let c = t.rfc5424.captures(line)?;+ if let Some(pri) = c.get(1).and_then(|p| p.as_str().parse::<u16>().ok()) {+ record_priority(pri, &mut m);+ }+ m.insert("ts".into(), Value::String(c.get(3)?.as_str().to_string()));+ m.insert("host".into(), Value::String(c.get(4)?.as_str().to_string()));+ let program = c.get(5)?.as_str();+ if program != "-" {+ m.insert("program".into(), Value::String(program.to_string()));+ }+ if let Some(pid) = c.get(6).filter(|p| p.as_str() != "-") {if let Ok(n) = pid.as_str().parse::<i64>() {m.insert("pid".into(), Value::Number(n.into()));}}- let msg = c.get(5)?.as_str().to_string();+ if let Some(msgid) = c.get(7).filter(|p| p.as_str() != "-") {+ m.insert("msgid".into(), Value::String(msgid.as_str().to_string()));+ }+ let msg = c.get(8).map(|x| x.as_str().to_string()).unwrap_or_default();lift_kv(&msg, &mut m);}Kind::IsoSyslog => {let c = t.isosyslog.captures(line)?;- // Optional `<PRI>`: facility*8 + severity (RFC 5424 §6.2.1). Only- // recorded when the writer actually emitted one — `journalctl -o- // short-iso` has no priority field, and inventing one would be a- // lie about the data. PRI's domain is 0..=191 (facility 0..=23 × 8- // + severity 0..=7); `<999>` is not a priority, so it stays- // unrecorded rather than decoding into a facility of 124.- if let Some(pri) = c- .get(1)- .and_then(|p| p.as_str().parse::<u16>().ok())- .filter(|p| *p <= 191)- {- const SEVERITY: [&str; 8] = [- "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",- ];- m.insert(- "severity".into(),- Value::String(SEVERITY[(pri & 7) as usize].to_string()),- );- m.insert("facility".into(), Value::Number((pri >> 3).into()));+ if let Some(pri) = c.get(1).and_then(|p| p.as_str().parse::<u16>().ok()) {+ record_priority(pri, &mut m);}m.insert("ts".into(), Value::String(c.get(2)?.as_str().to_string()));m.insert("host".into(), Value::String(c.get(3)?.as_str().to_string()));@@ -711,6 +762,101 @@ mod tests {assert_eq!(elect_kind(&votes), Some(Kind::Xferlog));}+ /// #1504, still open after the ISO/xferlog templates: desk-phone syslog+ /// is `<PRI>Mon dd hh:mm:ss host tag[pid]: msg` (often with a space+ /// before the pid bracket), and modern syslog is RFC 5424. Neither+ /// matched, so the file fell through to `txt-prose` and the lines were+ /// merged into chunks with no timestamp, host or severity.+ #[test]+ fn pri_rfc3164_and_rfc5424_are_one_record_per_line() {+ let phone = "<131>Oct 16 09:06:58 192.168.1.20 SIP [990]: registration failed";+ assert_eq!(parse_kind(phone), Some(Kind::Syslog));+ let m = parse_line(phone, Kind::Syslog).unwrap();+ assert_eq!(m["ts"], serde_json::json!("Oct 16 09:06:58"));+ assert_eq!(m["host"], serde_json::json!("192.168.1.20"));+ assert_eq!(m["program"], serde_json::json!("SIP"));+ assert_eq!(m["pid"], serde_json::json!(990));+ // 131 = facility 16, severity 3 (err). Not invented when PRI is absent.+ assert_eq!(m["severity"], serde_json::json!("err"));+ assert_eq!(m["facility"], serde_json::json!(16));+ assert_eq!(m["message"], serde_json::json!("registration failed"));++ let classic = "Oct 16 09:06:58 pbx syslogd: restart.";+ let m = parse_line(classic, Kind::Syslog).unwrap();+ assert!(+ m.get("severity").is_none(),+ "a line with no <PRI> does not grow a severity"+ );+ assert_eq!(m["program"], serde_json::json!("syslogd"));++ let over = "<999>Oct 16 09:06:58 phone sipd[1]: ignored priority";+ let m = parse_line(over, Kind::Syslog).unwrap();+ assert!(m.get("severity").is_none());+ assert!(m.get("facility").is_none());++ let rfc =+ "<134>1 2026-10-16T09:06:58.123Z 10.0.0.50 sipd 4321 - - SIP engine not registered";+ assert_eq!(parse_kind(rfc), Some(Kind::Rfc5424));+ let m = parse_line(rfc, Kind::Rfc5424).unwrap();+ assert_eq!(m["ts"], serde_json::json!("2026-10-16T09:06:58.123Z"));+ assert_eq!(m["host"], serde_json::json!("10.0.0.50"));+ assert_eq!(m["program"], serde_json::json!("sipd"));+ assert_eq!(m["pid"], serde_json::json!(4321));+ // 134 = facility 16, severity 6 (info).+ assert_eq!(m["severity"], serde_json::json!("info"));+ assert_eq!(m["message"], serde_json::json!("SIP engine not registered"));+ assert!(m.get("msgid").is_none(), "`-` msgid is omitted");++ let sd = "<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"] An application event log entry";+ assert_eq!(parse_kind(sd), Some(Kind::Rfc5424));+ let m = parse_line(sd, Kind::Rfc5424).unwrap();+ assert_eq!(m["program"], serde_json::json!("evntslog"));+ assert!(m.get("pid").is_none(), "`-` procid is omitted");+ assert_eq!(m["msgid"], serde_json::json!("ID47"));+ assert_eq!(+ m["message"],+ serde_json::json!("An application event log entry")+ );++ // PRI-prefixed ISO syslog stays the ISO template, not RFC5424: there+ // is no version digit between the priority and the timestamp.+ let iso = "<50>2026-10-16T09:06:58Z pbx app[7]: message";+ assert_eq!(parse_kind(iso), Some(Kind::IsoSyslog));++ // Not a log: a priority-looking prefix without the timestamp shape.+ assert!(!probe_line("<134> this is not a timestamp host prog: msg"));+ assert!(!probe_line("Oct 16 the notes from the retro"));++ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("phones.log");+ std::fs::write(+ &p,+ "<131>Oct 16 09:06:58 192.168.1.20 SIP [990]: registration failed\n\+ <134>Oct 16 09:07:01 192.168.1.20 SIP [990]: call cleared\n\+ <131>Oct 16 09:07:02 192.168.1.21 SIP[991]: SIP engine not registered\n\+ Oct 16 09:07:03 pbx pbx-phone[990]: watchdog reconnect\n",+ )+ .unwrap();+ let mut recs = Vec::new();+ extract(&p, false, None, &mut |r| {+ recs.push(r);+ true+ })+ .unwrap();+ assert_eq!(recs.len(), 4, "each phone line is its own record");+ assert!(recs.iter().all(|r| r.fields.get("ts").is_some()));+ assert!(recs.iter().all(|r| r.fields.get("host").is_some()));+ assert_eq!(recs[0].fields["severity"], serde_json::json!("err"));+ assert!(+ recs[3].fields.get("severity").is_none(),+ "the line without <PRI> does not inherit one"+ );+ assert_eq!(+ recs[2].fields["message"],+ serde_json::json!("SIP engine not registered")+ );+ }+const APP_LINE: &str = r#"2026-03-17 00:00:13,529 INFO [ingest-svc] tenant=t-n user=u-1153 latency_ms=221 msg="Segment merge.""#;const CLF_LINE: &str = r#"198.192.155.112 - - [01/Mar/2026:00:00:03 +0000] "GET /api/v1/x HTTP/1.1" 200 20854 "-" "Mozilla/5.0""#;diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rsindex d7e76fd3e..ef07b87ef 100644--- a/engine/crates/xerj-autoindex/src/extract/mod.rs+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs@@ -181,6 +181,12 @@ pub fn extract_as_document_with_name(gzip: bool,sink: Sink,) -> Result<ExtractStats> {+ // A demoted catalog or bundle is re-sampled through this renderer. The+ // same skip as `extract` — otherwise the phrase text the code path+ // refused comes back in as `body`.+ if skip_phrase_index(logical_path, content_path, gzip) {+ return emit_phrase_skip(logical_path, sink);+ }let mut stats = ExtractStats::default();let Some(bytes) = read_whole(content_path, gzip, MAX_WHOLE_FILE)? else {stats.junk += 1;@@ -207,6 +213,93 @@ pub fn extract_as_document_with_name(Ok(stats)}+/// Bytes of a JS/CSS prefix read to decide "this is a bundle, not source".+const MINIFIED_PREFIX: u64 = 8192;+/// Below this, a one-line file is a small module, not the huge bundle the+/// #1504 report lost queries to (`quill.js`, `jssip.min.js`).+const MINIFIED_MIN_BYTES: usize = 1500;++/// Translation catalogs and minified bundles repeat every UI phrase and win+/// natural-language code queries (#1504). Named catalogs (`lang/*.php`,+/// `values*/strings.xml`, `*.lproj/*.strings`, `*.po`, `*.min.js`) are+/// decided from the logical path. A bundle that is not named `*.min.js`+/// (`quill.js`) is one enormous line; the prefix test catches that without+/// reading the rest of the file.+///+/// The phrase text is not indexed. The file still gets one title record, so+/// it stays in the corpus, and a query whose only hit would have been the+/// catalog no longer has the catalog outranking the implementing source —+/// the catalog is not a candidate. `.pyi` stubs are not skipped: `xerj def`+/// still has to resolve a name that exists only as a stub.+fn skip_phrase_index(logical: &Path, content: &Path, gzip: bool) -> bool {+ let rel = logical.to_string_lossy().replace('\\', "/");+ if xerj_common::xccode::is_translation_or_bundle(&rel) {+ return true;+ }+ js_or_css(logical) && prefix_is_minified_bundle(content, gzip)+}++fn js_or_css(logical: &Path) -> bool {+ let name = logical+ .file_name()+ .and_then(|s| s.to_str())+ .unwrap_or("")+ .to_ascii_lowercase();+ let name = name.strip_suffix(".gz").unwrap_or(&name);+ matches!(+ name.rsplit('.').next().unwrap_or(""),+ "js" | "jsx" | "mjs" | "cjs" | "css"+ )+}++fn prefix_is_minified_bundle(path: &Path, gzip: bool) -> bool {+ let Ok(mut reader) = open_reader(path, gzip, Some(MINIFIED_PREFIX)) else {+ return false;+ };+ let mut buf = Vec::new();+ if reader.read_to_end(&mut buf).is_err() {+ return false;+ }+ if buf.len() < MINIFIED_MIN_BYTES {+ return false;+ }+ let newlines = buf.iter().filter(|b| **b == b'\n').count();+ if newlines <= 2 {+ return true;+ }+ // A short banner in front of one giant line: that line is most of the+ // prefix. A source file with one long string among real lines is not.+ let max_line = buf+ .split(|b| *b == b'\n')+ .map(|line| line.len())+ .max()+ .unwrap_or(0);+ max_line >= 4000 && max_line * 4 >= buf.len() * 3+}++/// One title record and no phrase text. `title` is the file name, which a+/// natural-language query does not contain, so the record cannot outrank+/// the implementing source. No `body`: the semantic election embeds `body`,+/// and a stub sentence here would put the catalog back into the vector leg.+fn emit_phrase_skip(logical: &Path, sink: Sink) -> Result<ExtractStats> {+ let mut stats = ExtractStats::default();+ let title = logical+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("file")+ .to_string();+ let mut fields = Map::new();+ fields.insert("title".into(), Value::String(title));+ stats.records += 1;+ sink(RawRecord {+ fields,+ locator: "code".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ });+ Ok(stats)+}+/// Dispatch to the family extractor. `limit_bytes` bounds SAMPLING reads;/// `None` = full stream.pub fn extract(@@ -215,6 +308,13 @@ pub fn extract(limit_bytes: Option<u64>,sink: Sink,) -> Result<ExtractStats> {+ // Logical name, never the content path: durable preparation reads a+ // content-addressed blob (`blobs/00000000`) whose name is not the source+ // (#294). The bytes still come from `path`.+ let logical = sn.logical_name.as_deref().unwrap_or(path);+ if skip_phrase_index(logical, path, sn.gzip) {+ return emit_phrase_skip(logical, sink);+ }match sn.family {Family::Jsonl => jsonl::extract(path, sn.gzip, limit_bytes, sink),Family::Json => json::extract(path, sn.gzip, sink),@@ -1599,3 +1699,145 @@ mod slot_tests {);}}++#[cfg(test)]+mod phrase_skip_tests {+ use super::*;+ use crate::sniff::{Family, Sniffed};++ const PHRASE: &str = "push notification wait for mobile device to register before dial";++ fn sniffed(family: Family, logical: &str) -> Sniffed {+ Sniffed {+ family,+ gzip: false,+ binary_kind: None,+ csv: None,+ encoding: "utf-8",+ logical_name: Some(std::path::PathBuf::from(logical)),+ }+ }++ fn indexed_text(logical: &str, family: Family, bytes: &str) -> String {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("blob");+ std::fs::write(&path, bytes).unwrap();+ let sn = sniffed(family, logical);+ let mut recs = Vec::new();+ extract(&path, &sn, None, &mut |r| {+ recs.push(r);+ true+ })+ .unwrap();+ recs.iter()+ .flat_map(|r| r.fields.values())+ .filter_map(|v| v.as_str())+ .collect::<Vec<_>>()+ .join("\n")+ }++ /// #1504: a multilingual repo's catalogs contain every UI phrase once per+ /// language and fill the fetch window, so reordering the hits that came+ /// back cannot surface the implementing file. The phrase must not be+ /// indexed from the catalog. The service file that implements it keeps it.+ #[test]+ fn translation_catalogs_do_not_index_the_phrase_the_source_keeps() {+ let catalog = format!("<?php\nreturn [\n 'dial.wait' => '{PHRASE}',\n];\n");+ let from_catalog = indexed_text("web/lang/en.php", Family::Code, &catalog);+ assert!(+ !from_catalog.contains(PHRASE),+ "lang/*.php indexed the UI phrase: {from_catalog}"+ );+ assert!(+ from_catalog.contains("en.php"),+ "the catalog file stays in the corpus by name"+ );++ let strings = format!(+ "<?xml version=\"1.0\"?>\n<resources>\n <string name=\"dial_wait\">{PHRASE}</string>\n</resources>\n"+ );+ let from_xml = indexed_text("res/values-da/strings.xml", Family::Xml, &strings);+ assert!(+ !from_xml.contains(PHRASE),+ "strings.xml indexed the phrase: {from_xml}"+ );++ let po = format!("msgid \"{PHRASE}\"\nmsgstr \"{PHRASE}\"\n");+ let from_po = indexed_text("locale/da.po", Family::TxtProse, &po);+ assert!(+ !from_po.contains(PHRASE),+ ".po indexed the phrase: {from_po}"+ );++ let apple = format!("\"dial.wait\" = \"{PHRASE}\";\n");+ let from_strings =+ indexed_text("ios/da.lproj/Localizable.strings", Family::TxtLines, &apple);+ assert!(+ !from_strings.contains(PHRASE),+ ".strings indexed the phrase: {from_strings}"+ );++ let source = format!(+ "<?php\nfunction waitForMobile() {{\n // {PHRASE}\n return $this->dial();\n}}\n"+ );+ let from_source = indexed_text(+ "web/src/services/phones/NecTemplate.php",+ Family::Code,+ &source,+ );+ assert!(+ from_source.contains(PHRASE),+ "the implementing file must stay searchable: {from_source}"+ );+ }++ /// #1504: `quill.js` is one line and is not named `*.min.js`, so the path+ /// rule does not see it. A normal source file with the same phrase, wrapped+ /// like source, stays indexed. A named `*.min.js` is skipped even when short.+ #[test]+ fn one_line_js_bundles_are_skipped_and_source_js_is_not() {+ let pad = "x".repeat(1800);+ let bundle = format!("!function(){{var s=\"{PHRASE}\";{pad}}}();");+ assert!(+ bundle.len() > MINIFIED_MIN_BYTES,+ "fixture must clear the size floor, got {}",+ bundle.len()+ );+ assert!(!bundle.contains('\n'));+ let from_bundle = indexed_text("assets/quill.js", Family::Code, &bundle);+ assert!(+ !from_bundle.contains(PHRASE),+ "one-line quill.js indexed the phrase: {from_bundle}"+ );++ let named = format!("/* {PHRASE} */\n");+ let from_min = indexed_text("assets/jssip.min.js", Family::Code, &named);+ assert!(+ !from_min.contains(PHRASE),+ "named min.js indexed the phrase: {from_min}"+ );++ let mut source = format!("function waitForMobile() {{\n // {PHRASE}\n");+ for i in 0..40 {+ source.push_str(&format!(" var line{i} = {i};\n"));+ }+ source.push_str("}\n");+ let from_source = indexed_text("web/src/dial.js", Family::Code, &source);+ assert!(+ from_source.contains(PHRASE),+ "ordinary javascript must stay searchable: {from_source}"+ );+ }++ /// A type stub stays indexed. Query-time demotion ranks it behind the+ /// implementation; stripping it would hide a name that exists only here.+ #[test]+ fn pyi_stubs_keep_their_text() {+ let stub = "def wait_for_register() -> None:\n \"\"\"push notification wait\"\"\"\n";+ let text = indexed_text("candle/quantized.pyi", Family::Code, stub);+ assert!(+ text.contains("wait_for_register"),+ "a stub must stay indexed for xerj def: {text}"+ );+ }+}diff --git a/engine/crates/xerj-autoindex/src/infer/mod.rs b/engine/crates/xerj-autoindex/src/infer/mod.rsindex 7317ba00f..50016b805 100644--- a/engine/crates/xerj-autoindex/src/infer/mod.rs+++ b/engine/crates/xerj-autoindex/src/infer/mod.rs@@ -883,16 +883,34 @@ impl CodeAnalyzer {/// `code` wins over the stemmer (the maintainer's call on #1198): the flag is/// an explicit operator choice, sub-words already reach most of what stemming/// would in prose inside code, and layering both is unmeasured. A dataset-/// without code members keeps [`elected_default_analyzer`]'s answer either way.+/// without code members keeps [`elected_default_analyzer`]'s answer either way,+/// except a log dataset (below).+///+/// The analyzer a log-only dataset gets (#1504). `"english"` is `standard`+/// plus the Lucene English stop list plus the Snowball stemmer. Log messages+/// look like natural language, so the ordinary election picks `"stemmer"`,+/// which keeps stop words. A `match` for a phrase that never occurs then+/// hits every record containing `is`. Stop words are dropped on both sides+/// of the query, and only for this family — the global default stays+/// `"stemmer"` / `"standard"` because dropping stop words changes every+/// document's BM25 length norm (#1059).+pub const LOG_TEXT_ANALYZER: &str = "english";++/// Dataset text analyzer. `log_dataset` elects [`LOG_TEXT_ANALYZER`];+/// `--code-analyzer code` still wins when the dataset holds code.pub fn elect_dataset_analyzer(specs: &[FieldSpec],fields: &HashMap<String, FieldAcc>,has_code: bool,code_analyzer: CodeAnalyzer,+ log_dataset: bool,) -> Option<&'static str> {if has_code && code_analyzer == CodeAnalyzer::Code {return Some(CODE_TEXT_ANALYZER);}+ if log_dataset {+ return Some(LOG_TEXT_ANALYZER);+ }elected_default_analyzer(specs, fields)}@@ -1297,7 +1315,7 @@ mod tests {fn code_analyzer_flag_elects_code_for_a_code_dataset_and_the_stemmer_defers() {let (specs, fields) = stemmer_electing_sample();assert_eq!(- elect_dataset_analyzer(&specs, &fields, true, CodeAnalyzer::Code),+ elect_dataset_analyzer(&specs, &fields, true, CodeAnalyzer::Code, false),Some(CODE_TEXT_ANALYZER));}@@ -1308,15 +1326,41 @@ mod tests {fn code_analyzer_flag_leaves_a_dataset_without_code_on_todays_election() {let (specs, fields) = stemmer_electing_sample();assert_eq!(- elect_dataset_analyzer(&specs, &fields, false, CodeAnalyzer::Code),+ elect_dataset_analyzer(&specs, &fields, false, CodeAnalyzer::Code, false),Some(STEMMING_TEXT_ANALYZER));assert_eq!(- elect_dataset_analyzer(&[], &HashMap::new(), false, CodeAnalyzer::Code),+ elect_dataset_analyzer(&[], &HashMap::new(), false, CodeAnalyzer::Code, false),None);}+ /// #1504: log messages look like prose, so the ordinary election is+ /// `"stemmer"`, which keeps stop words. A `match` of `"configuration is+ /// invalid"` then hits every record that contains `is`. A log dataset+ /// elects `"english"` (stemmer + the Lucene stop list) instead. A prose+ /// dataset does not — that length-norm change stays off the global default.+ #[test]+ fn log_dataset_elects_english_so_stopwords_are_not_terms() {+ let (specs, fields) = stemmer_electing_sample();+ assert_eq!(+ elected_default_analyzer(&specs, &fields),+ Some(STEMMING_TEXT_ANALYZER),+ "the same sample is the stemmer without the log flag — that is the bug"+ );+ assert_eq!(+ elect_dataset_analyzer(&specs, &fields, false, CodeAnalyzer::Standard, true),+ Some(LOG_TEXT_ANALYZER)+ );+ assert_eq!(LOG_TEXT_ANALYZER, "english");+ // An explicit `--code-analyzer code` on a dataset that also holds+ // code still wins: the operator asked for it.+ assert_eq!(+ elect_dataset_analyzer(&specs, &fields, true, CodeAnalyzer::Code, true),+ Some(CODE_TEXT_ANALYZER)+ );+ }+/// #1198: the default (`standard`) changes nothing, code or not.#[test]fn default_code_analyzer_keeps_todays_election() {@@ -1324,7 +1368,7 @@ mod tests {assert_eq!(CodeAnalyzer::default(), CodeAnalyzer::Standard);for has_code in [true, false] {assert_eq!(- elect_dataset_analyzer(&specs, &fields, has_code, CodeAnalyzer::Standard),+ elect_dataset_analyzer(&specs, &fields, has_code, CodeAnalyzer::Standard, false),elected_default_analyzer(&specs, &fields));}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 804dfa39a..1dd6443e7 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -3884,6 +3884,53 @@ mod phase_a_grouping_tests {);}+ /// #1504: desk-phone syslog (`<PRI>Mon dd hh:mm:ss host tag[pid]: msg`)+ /// used to plan as `txt-prose`, so timestamp, host and severity were not+ /// fields and the stemmer kept the stop word `is`. It plans as `logs`+ /// with the english analyzer.+ #[test]+ fn phone_syslog_plans_as_logs_with_the_english_analyzer() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(+ root.join("phones.log"),+ "<131>Oct 16 09:06:58 192.168.1.20 SIP [990]: registration failed\n\+ <134>Oct 16 09:07:01 192.168.1.20 SIP [990]: call cleared\n\+ <131>Oct 16 09:07:02 192.168.1.21 SIP[991]: SIP engine not registered\n\+ <134>Oct 16 09:07:03 192.168.1.21 SIP[991]: watchdog reconnect\n\+ Oct 16 09:07:04 pbx pbx-phone[990]: configuration loaded\n\+ Oct 16 09:07:05 pbx pbx-phone[991]: device is online\n",+ )+ .unwrap();+ let plan = plan_for(root);+ let logs: Vec<_> = plan+ .datasets+ .iter()+ .filter(|d| d.family == "logs")+ .collect();+ assert_eq!(+ logs.len(),+ 1,+ "expected one logs dataset, got {:?}",+ plan.datasets+ .iter()+ .map(|d| (+ d.slug.as_str(),+ d.family.as_str(),+ d.text_analyzer.as_deref()+ ))+ .collect::<Vec<_>>()+ );+ assert_eq!(+ logs[0].text_analyzer.as_deref(),+ Some(infer::LOG_TEXT_ANALYZER)+ );+ let names: Vec<&str> = logs[0].specs.iter().map(|s| s.name.as_str()).collect();+ for field in ["ts", "host", "program", "message"] {+ assert!(names.contains(&field), "missing {field} in {names:?}");+ }+ }+const CODE: &str = "// The event loop dispatches every ready connection to a worker.\n\// Each worker drains its queue before polling for more sockets.\n\static void dispatch_ready_connections(struct event_loop *loop) {\n\@@ -4463,9 +4510,18 @@ fn build_phase_a(.members.iter().any(|&m| matches!(file_meta[m], Some((Family::Code, _))));- let text_analyzer =- infer::elect_dataset_analyzer(&specs, &c.fields, has_code, cfg.code_analyzer)- .map(str::to_string);+ // A pure log cluster (not a docs cluster a log file was demoted+ // into). `c.family` is the cluster's own family; docs clusters are+ // labelled `Family::Code` by `dataset::cluster`.+ let log_dataset = c.family == Family::Logs && !c.is_docs;+ let text_analyzer = infer::elect_dataset_analyzer(+ &specs,+ &c.fields,+ has_code,+ cfg.code_analyzer,+ log_dataset,+ )+ .map(str::to_string);datasets.push(PlanDataset {slug: c.slug.clone(),index: format!("{}-{}", cfg.prefix, c.slug),diff --git a/engine/crates/xerj-autoindex/src/sniff.rs b/engine/crates/xerj-autoindex/src/sniff.rsindex a3a91f54e..507b41671 100644--- a/engine/crates/xerj-autoindex/src/sniff.rs+++ b/engine/crates/xerj-autoindex/src/sniff.rs@@ -4486,6 +4486,20 @@ mod text_family_tests {Oct 16 09:07:01 pbx sshd[1235]: Accepted publickey for admin\n\Oct 16 09:07:02 pbx pbx-phone[990]: SIP engine not registered\n";assert_eq!(classify_full(rfc), Family::Logs);++ // Desk-phone syslog carries a `<PRI>` and often a space before the+ // pid bracket. RFC 5424 puts a version digit between `<PRI>` and an+ // ISO timestamp. Both used to miss every template and land in+ // `TxtProse`, so timestamp, host and severity were not fields.+ let phone = "<131>Oct 16 09:06:58 192.168.1.20 SIP [990]: registration failed\n\+ <134>Oct 16 09:07:01 192.168.1.20 SIP [990]: call cleared\n\+ <131>Oct 16 09:07:02 192.168.1.21 SIP[991]: SIP engine not registered\n";+ assert_eq!(classify_full(phone), Family::Logs);++ let rfc5424 = "<134>1 2026-10-16T09:06:58.123Z 10.0.0.50 sipd 4321 - - SIP engine not registered\n\+ <131>1 2026-10-16T09:07:01.000Z 10.0.0.50 sipd 4321 - - registration failed\n\+ <165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=\"3\"] An application event log entry\n";+ assert_eq!(classify_full(rfc5424), Family::Logs);}/// #1504 review: the ISO-syslog template must not steal files from Csv or@@ -4537,6 +4551,17 @@ mod text_family_tests {Family::Logs,"timestamped notes are prose, not Logs");++ // A `<PRI>` prefix is not enough. Without the timestamp shape these+ // stay prose — the new phone/RFC5424 templates must not claim them.+ let pri_prose = "<134> this is not a timestamp host prog: msg\n\+ <131> notes from the retro about the release\n\+ <999> hello the configuration is invalid\n";+ assert_ne!(+ classify_full(pri_prose),+ Family::Logs,+ "a priority-looking prefix without a timestamp is prose"+ );}/// Regression: a markdown document with `## Headings` averages ~50 charsdiff --git a/engine/crates/xerj-common/src/xccode/mod.rs b/engine/crates/xerj-common/src/xccode/mod.rsindex eb117ff3f..c89f00085 100644--- a/engine/crates/xerj-common/src/xccode/mod.rs+++ b/engine/crates/xerj-common/src/xccode/mod.rs@@ -721,14 +721,16 @@ pub fn demote_catalog_noise(hits: Vec<Value>) -> Vec<Value> {/// ones a multilingual repo uses for key→string tables, not a general/// "prose file" filter: `lang/*.php`, `values*/strings.xml`, `*.lproj/*.strings`,/// `*.po` / `*.pot`, and `*.min.js` / `*.min.mjs` / `*.min.css`.-pub fn is_catalog_noise(path: &str) -> bool {- let name = path.rsplit(['/', '\\']).next().unwrap_or(path);- // Type stubs repeat the public signature and outrank the implementation- // on a natural-language query (candle field report 2026-10-17: `.pyi`- // files were the top hits). They stay searchable, behind source.- if name.ends_with(".pyi") {- return true;- }+///+/// This is the index-time predicate. Autoindex does not put the phrase text+/// of these files into `body` — a post-fetch reorder cannot help when the+/// catalogs fill the whole fetch window, and a one-line bundle that is not+/// named `*.min.js` is caught separately by content. `.pyi` stubs are NOT+/// in this set: they stay indexed so `xerj def` can still resolve a name+/// that exists only as a stub, and [`is_catalog_noise`] ranks them behind+/// the implementation at query time.+pub fn is_translation_or_bundle(path: &str) -> bool {+ let name = file_name(path);if name.ends_with(".min.js") || name.ends_with(".min.mjs") || name.ends_with(".min.css") {return true;}@@ -747,6 +749,18 @@ pub fn is_catalog_noise(path: &str) -> bool {parent.ends_with(".lproj") && name.ends_with(".strings")}+/// Translation catalogs, minified bundles, and type stubs (#1504, #1651).+pub fn is_catalog_noise(path: &str) -> bool {+ // Type stubs repeat the public signature and outrank the implementation+ // on a natural-language query (candle field report 2026-10-17: `.pyi`+ // files were the top hits). They stay searchable, behind source.+ file_name(path).ends_with(".pyi") || is_translation_or_bundle(path)+}++fn file_name(path: &str) -> &str {+ path.rsplit(['/', '\\']).next().unwrap_or(path)+}+fn parent_segment(path: &str) -> Option<&str> {let cut = path.rfind(['/', '\\'])?;let head = &path[..cut];@@ -1727,6 +1741,19 @@ mod tests {assert!(is_catalog_noise("web/lang/en.php"));assert!(is_catalog_noise("res/values/strings.xml"));assert!(is_catalog_noise("assets/app.min.css"));+ // `.pyi` is query-time noise only. Stripping it at index time would+ // hide a name that exists only as a stub from `xerj def`.+ assert!(!is_translation_or_bundle("candle/quantized.pyi"));+ assert!(is_translation_or_bundle("web/lang/en.php"));+ assert!(is_translation_or_bundle("assets/jssip.min.js"));+ // A huge one-line bundle that is not named `*.min.js` (the report's+ // `quill.js`) is not a path match. Index-time content detection+ // catches it; this predicate must not pretend the name is enough.+ assert!(!is_translation_or_bundle("assets/quill.js"));+ assert!(!is_catalog_noise("assets/quill.js"));+ assert!(!is_translation_or_bundle(+ "web/src/services/phones/NecTemplate.php"+ ));}/// #1146: with a mixed mapping the fused request may only go to thediff --git a/engine/crates/xerj-fts/src/analyzer.rs b/engine/crates/xerj-fts/src/analyzer.rsindex 6c77d44a4..fecf39f81 100644--- a/engine/crates/xerj-fts/src/analyzer.rs+++ b/engine/crates/xerj-fts/src/analyzer.rs@@ -2698,6 +2698,56 @@ mod tests {assert!(texts.contains(&"fox"));}+ /// #1504: a `match` for a phrase that never occurs returned thousands of+ /// hits because the token `is` is in almost every log line. `standard`+ /// and `stemmer` keep it (ES `standard` has no stop list; the stemmer is+ /// that plus Snowball). `english` drops it, which is what a log dataset+ /// elects. Content words of the same phrase stay, so the query is no+ /// longer a search for `is`.+ #[test]+ fn english_drops_is_and_stemmer_keeps_it() {+ let registry = AnalyzerRegistry::default();+ let phrase = "configuration is invalid";+ let english = registry+ .get_analyzer("english")+ .unwrap()+ .analyze_to_terms(phrase);+ let stemmer = registry+ .get_analyzer("stemmer")+ .unwrap()+ .analyze_to_terms(phrase);+ let standard = registry+ .get_analyzer("standard")+ .unwrap()+ .analyze_to_terms(phrase);+ assert!(+ !english.iter().any(|t| t == "is"),+ "english must drop the stopword is: {english:?}"+ );+ assert!(+ stemmer.iter().any(|t| t == "is"),+ "stemmer keeps is, which is why log match hit every line: {stemmer:?}"+ );+ assert!(+ standard.iter().any(|t| t == "is"),+ "standard keeps is: {standard:?}"+ );+ assert!(+ english.iter().any(|t| t.starts_with("configur")),+ "the content word survives stemming: {english:?}"+ );+ assert!(+ english.iter().any(|t| t.starts_with("invalid")),+ "invalid is not a stop word: {english:?}"+ );+ let sip = registry+ .get_analyzer("english")+ .unwrap()+ .analyze_to_terms("SIP 403 Forbidden");+ assert!(sip.iter().any(|t| t == "sip"), "{sip:?}");+ assert!(sip.iter().any(|t| t == "403"), "{sip:?}");+ }+#[test]fn registry_standard_analyzer_e2e() {let registry = AnalyzerRegistry::default();