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(autoindex): stop extractor-origin fields from re-homing files between datasets (#180)

xerj-orgb27651536ef9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0375d6025..68fbbaa9c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **`xerj autoindex` no longer duplicates an index when an extractor improves**
+ (#178). Datasets were inferred by comparing each file's whole field-name set,
+ including names the extractor invents rather than reads from the file
+ (`defs`, `symbols`, `symbol_count`, `title`, `page`, …). A better parser makes
+ those names appear, which moved the file into a different dataset — and the
+ dataset slug is an ingredient of every document `_id`, so the file was
+ re-indexed under a new id in a new index while its previous document stayed
+ behind, unreferenced. Measured on a 846-file Rust corpus, re-planning with an
+ improved symbol extractor grew the index from 53,873 to 53,902 documents with
+ 29 stale leftovers and exit code 0; on a 2,328-file C corpus, 7,923 to 8,023.
+ Clustering now uses only the field names that came from the file, so gaining
+ or losing extractor fields can no longer re-home a document: both re-plans
+ hold at 53,873 and 7,923.
+
+ Nothing is deleted, so the first *re-plan* after upgrading (`--fresh`, a new
+ `--state-dir`, or a lost journal) re-homes the files whose datasets merge and
+ leaves their previous documents in place — 53,873 → 58,855 on that Rust
+ corpus, a one-time cost paid once instead of once per extractor change. An
+ ordinary re-run reuses the journal's frozen plan and is unaffected. Datasets
+ inferred from real schemas are untouched: that corpus went from 9 datasets to
+ 7 (the two symbol-presence variants of one code dataset merged, likewise two
+ section-presence variants of one prose dataset), and the C corpus from 407 to
+ 405, with every document accounted for in both.
+
## [1.0.0-rc.11] - 2026-08-04
### Added
diff --git a/engine/crates/xerj-autoindex/src/dataset.rs b/engine/crates/xerj-autoindex/src/dataset.rs
index eb865455e..31065a65d 100644
--- a/engine/crates/xerj-autoindex/src/dataset.rs
+++ b/engine/crates/xerj-autoindex/src/dataset.rs
@@ -2,6 +2,16 @@
//! datasets by schema fingerprint (Jaccard on field-name sets ≥ 0.7) within
//! the same format family. Path family is a NAMING hint only — no hardcoded
//! directory semantics.
+//!
+//! Only the DATA-derived field names take part (`Sketch::key_fields`, fed from
+//! `extract::FieldOrigin`). A name the extractor invented — `defs`, `symbols`,
+//! `title`, `page` — is not evidence about the file, and letting one decide
+//! membership made every extractor improvement re-home files: the dataset slug
+//! is an ingredient of `ids::doc_id`, so a moved file is re-indexed under a new
+//! `_id` in a new index while its old document survives, unreferenced, in the
+//! old one (issue #178). Files whose names are all extractor-invented (source
+//! code, prose documents) therefore cluster by format family and group alone,
+//! which is what their sniffed shape actually says about them.
use crate::infer::FieldAcc;
use crate::sniff::Family;
@@ -13,6 +23,9 @@ pub struct Sketch {
pub group: Option<String>,
pub family: Family,
pub fields: HashMap<String, FieldAcc>,
+ /// The subset of `fields` whose NAMES were read out of the file. This, not
+ /// `fields`, is the clustering key.
+ pub key_fields: HashSet<String>,
pub records: u64,
}
@@ -22,6 +35,8 @@ pub struct Cluster {
pub group: Option<String>,
pub members: Vec<usize>, // file indices
pub fields: HashMap<String, FieldAcc>,
+ /// Union of the members' `key_fields` — what new sketches are compared to.
+ pub key_fields: HashSet<String>,
pub records: u64,
pub slug: String,
}
@@ -38,13 +53,13 @@ fn jaccard(a: &HashSet<&str>, b: &HashSet<&str>) -> f64 {
pub fn cluster(sketches: Vec<Sketch>, rels: &[String]) -> Vec<Cluster> {
let mut clusters: Vec<Cluster> = Vec::new();
for sk in sketches {
- let names: HashSet<&str> = sk.fields.keys().map(|s| s.as_str()).collect();
+ let names: HashSet<&str> = sk.key_fields.iter().map(|s| s.as_str()).collect();
let mut best: Option<(usize, f64)> = None;
for (ci, c) in clusters.iter().enumerate() {
if c.family != sk.family || c.group != sk.group {
continue;
}
- let cnames: HashSet<&str> = c.fields.keys().map(|s| s.as_str()).collect();
+ let cnames: HashSet<&str> = c.key_fields.iter().map(|s| s.as_str()).collect();
let j = jaccard(&names, &cnames);
let threshold = if sk.group.is_some() { 0.5 } else { 0.7 };
if j >= threshold && best.map(|(_, bj)| j > bj).unwrap_or(true) {
@@ -56,6 +71,7 @@ pub fn cluster(sketches: Vec<Sketch>, rels: &[String]) -> Vec<Cluster> {
let c = &mut clusters[ci];
c.members.push(sk.file_idx);
c.records += sk.records;
+ c.key_fields.extend(sk.key_fields);
for (k, acc) in sk.fields {
match c.fields.get_mut(&k) {
Some(existing) => existing.merge(&acc),
@@ -70,6 +86,7 @@ pub fn cluster(sketches: Vec<Sketch>, rels: &[String]) -> Vec<Cluster> {
group: sk.group,
members: vec![sk.file_idx],
fields: sk.fields,
+ key_fields: sk.key_fields,
records: sk.records,
slug: String::new(),
}),
@@ -220,3 +237,154 @@ fn assign_slugs(clusters: &mut [Cluster], rels: &[String]) {
clusters[i].slug = slug;
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ids;
+
+ fn acc(value: &str) -> FieldAcc {
+ let mut a = FieldAcc::default();
+ a.add(&serde_json::Value::String(value.to_string()));
+ a
+ }
+
+ /// A source file: every name comes from the extractor, so the clustering
+ /// key is empty whether or not the parser found symbols.
+ fn code_sketch(file_idx: usize, symbols: bool) -> Sketch {
+ let mut fields = HashMap::new();
+ fields.insert("title".to_string(), acc("f.rs"));
+ fields.insert("language".to_string(), acc("rust"));
+ fields.insert("body".to_string(), acc("fn main() {}"));
+ if symbols {
+ fields.insert("defs".to_string(), acc("function main"));
+ fields.insert("symbols".to_string(), acc("main"));
+ fields.insert("symbol_count".to_string(), acc("1"));
+ }
+ Sketch {
+ file_idx,
+ group: None,
+ family: Family::Code,
+ fields,
+ key_fields: HashSet::new(),
+ records: 1,
+ }
+ }
+
+ /// A data file: the names are the file's own, so they are the key.
+ fn data_sketch(file_idx: usize, family: Family, names: &[&str]) -> Sketch {
+ let mut fields = HashMap::new();
+ let mut key_fields = HashSet::new();
+ for n in names {
+ fields.insert((*n).to_string(), acc("v"));
+ key_fields.insert((*n).to_string());
+ }
+ Sketch {
+ file_idx,
+ group: None,
+ family,
+ fields,
+ key_fields,
+ records: 1,
+ }
+ }
+
+ fn doc_ids(clusters: &[Cluster], rels: &[String]) -> Vec<String> {
+ let mut out = Vec::new();
+ for c in clusters {
+ for &m in &c.members {
+ // `rel` stands in for the content key: this test changes the
+ // extractor, never the files.
+ out.push(ids::doc_id(&c.slug, &rels[m], "code"));
+ }
+ }
+ out.sort();
+ out
+ }
+
+ /// Regression for #178. Re-index the same corpus with an extractor that
+ /// now finds symbols in files that produced none before: the documents
+ /// must land on exactly the same `_id`s, so the re-index overwrites in
+ /// place instead of writing a second copy beside the first.
+ #[test]
+ fn a_better_extractor_does_not_re_home_a_single_file() {
+ let rels: Vec<String> = (0..6).map(|i| format!("src/mod{i}/f.rs")).collect();
+
+ // Before: files 4 and 5 parsed to zero symbols.
+ let before = cluster(
+ (0..6).map(|i| code_sketch(i, i < 4)).collect::<Vec<_>>(),
+ &rels,
+ );
+ // The whole point: one dataset, not one per symbol-presence variant.
+ assert_eq!(before.len(), 1, "{before:#?}");
+ assert_eq!(before[0].members.len(), 6);
+
+ // After: the improved grammar finds symbols in all six.
+ let after = cluster(
+ (0..6).map(|i| code_sketch(i, true)).collect::<Vec<_>>(),
+ &rels,
+ );
+
+ let (b, a) = (doc_ids(&before, &rels), doc_ids(&after, &rels));
+ assert_eq!(a.len(), b.len(), "document count grew: {b:?} -> {a:?}");
+ assert_eq!(a, b, "documents moved to new _ids: {b:?} -> {a:?}");
+ }
+
+ /// The same must hold when only SOME files change and the corpus also
+ /// holds data files — the data datasets must not be disturbed either.
+ #[test]
+ fn a_partial_extractor_change_leaves_the_data_datasets_alone() {
+ let rels: Vec<String> = vec![
+ "src/a.rs".into(),
+ "src/b.rs".into(),
+ "data/events.csv".into(),
+ "data/users.csv".into(),
+ ];
+ let mixed = |symbols_in_b: bool| {
+ vec![
+ code_sketch(0, true),
+ code_sketch(1, symbols_in_b),
+ data_sketch(2, Family::Csv, &["ts", "level", "msg"]),
+ data_sketch(3, Family::Csv, &["id", "email", "name"]),
+ ]
+ };
+ let before = cluster(mixed(false), &rels);
+ let after = cluster(mixed(true), &rels);
+ let slugs = |cs: &[Cluster]| {
+ let mut v: Vec<(usize, String)> = cs
+ .iter()
+ .flat_map(|c| c.members.iter().map(|&m| (m, c.slug.clone())))
+ .collect();
+ v.sort();
+ v
+ };
+ assert_eq!(slugs(&before), slugs(&after));
+ // 1 code dataset + 2 unrelated CSV schemas.
+ assert_eq!(before.len(), 3, "{before:#?}");
+ }
+
+ /// The fix must not blunt clustering: unrelated schemas stay apart, near
+ /// -identical ones still merge, and formats never mix.
+ #[test]
+ fn genuinely_different_content_still_separates() {
+ let rels: Vec<String> = (0..5).map(|i| format!("d/f{i}")).collect();
+ let clusters = cluster(
+ vec![
+ data_sketch(0, Family::Csv, &["ts", "level", "msg"]),
+ // one extra column out of four — still the same schema
+ data_sketch(1, Family::Csv, &["ts", "level", "msg", "host"]),
+ data_sketch(2, Family::Csv, &["id", "email", "name"]),
+ // same names, different format family
+ data_sketch(3, Family::Jsonl, &["ts", "level", "msg"]),
+ code_sketch(4, true),
+ ],
+ &rels,
+ );
+ assert_eq!(clusters.len(), 4, "{clusters:#?}");
+ let members: Vec<Vec<usize>> = clusters.iter().map(|c| c.members.clone()).collect();
+ assert!(members.contains(&vec![0, 1]), "{members:?}");
+ assert!(members.contains(&vec![2]), "{members:?}");
+ assert!(members.contains(&vec![3]), "{members:?}");
+ assert!(members.contains(&vec![4]), "{members:?}");
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/code.rs b/engine/crates/xerj-autoindex/src/extract/code.rs
index 44dc539e5..91e1c68bb 100644
--- a/engine/crates/xerj-autoindex/src/extract/code.rs
+++ b/engine/crates/xerj-autoindex/src/extract/code.rs
@@ -14,7 +14,7 @@
//! so adding a language is a grammar dep + one registry row. If a grammar fails
//! to parse a file, it is indexed as plain text rather than dropped.
-use super::{ExtractStats, RawRecord, Sink};
+use super::{ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::Result;
use serde_json::{Map, Value};
use std::path::Path;
@@ -213,6 +213,10 @@ fn emit_code_doc(
fields,
locator: "code".into(),
group: None,
+ // `defs`/`symbols`/`symbol_count` appear only when this extractor finds
+ // something, so a better grammar would otherwise move the file to a
+ // different dataset and orphan its old document (#178).
+ origin: FieldOrigin::Extractor,
})
}
diff --git a/engine/crates/xerj-autoindex/src/extract/csv_x.rs b/engine/crates/xerj-autoindex/src/extract/csv_x.rs
index 04495968a..984f33b98 100644
--- a/engine/crates/xerj-autoindex/src/extract/csv_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/csv_x.rs
@@ -1,6 +1,6 @@
//! CSV with sniffed dialect (delimiter / header / decimal-comma), streaming.
-use super::{sanitize_field_name, ExtractStats, RawRecord, Sink};
+use super::{sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink};
use crate::sniff::Sniffed;
use anyhow::Result;
use serde_json::{Map, Value};
@@ -73,6 +73,7 @@ pub fn extract(
fields,
locator: format!("r{i}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
break;
}
diff --git a/engine/crates/xerj-autoindex/src/extract/html.rs b/engine/crates/xerj-autoindex/src/extract/html.rs
index 5377073da..789e39c28 100644
--- a/engine/crates/xerj-autoindex/src/extract/html.rs
+++ b/engine/crates/xerj-autoindex/src/extract/html.rs
@@ -4,7 +4,9 @@
//! one record per row with header-derived field names; otherwise one
//! document record {title, headings, body}.
-use super::{emit_document, sanitize_field_name, ExtractStats, RawRecord, Sink, MAX_WHOLE_FILE};
+use super::{
+ emit_document, sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink, MAX_WHOLE_FILE,
+};
use anyhow::Result;
use serde_json::{Map, Value};
use std::path::Path;
@@ -73,6 +75,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields,
locator: format!("row{i}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
diff --git a/engine/crates/xerj-autoindex/src/extract/json.rs b/engine/crates/xerj-autoindex/src/extract/json.rs
index 7837a5133..fd4c4110d 100644
--- a/engine/crates/xerj-autoindex/src/extract/json.rs
+++ b/engine/crates/xerj-autoindex/src/extract/json.rs
@@ -4,7 +4,7 @@
//! element, remaining top-level scalars merged in as shared fields
//! - anything else → a single record
-use super::{flatten_object, ExtractStats, RawRecord, Sink, MAX_WHOLE_FILE};
+use super::{flatten_object, ExtractStats, FieldOrigin, RawRecord, Sink, MAX_WHOLE_FILE};
use anyhow::Result;
use serde_json::{Map, Value};
use std::path::Path;
@@ -60,6 +60,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields,
locator: format!("{key}:e{i}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
break;
}
@@ -94,6 +95,7 @@ fn emit(v: Value, locator: &str, sink: Sink, stats: &mut ExtractStats) -> bool {
fields,
locator: locator.to_string(),
group: None,
+ origin: FieldOrigin::Data,
})
}
diff --git a/engine/crates/xerj-autoindex/src/extract/jsonl.rs b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
index 5649deb2f..fb1bcd0a6 100644
--- a/engine/crates/xerj-autoindex/src/extract/jsonl.rs
+++ b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
@@ -1,6 +1,6 @@
//! JSONL (newline-delimited JSON) — streaming, byte-offset locators.
-use super::{flatten_object, ExtractStats, RawRecord, Sink, MAX_LINE};
+use super::{flatten_object, ExtractStats, FieldOrigin, RawRecord, Sink, MAX_LINE};
use anyhow::Result;
use serde_json::Value;
use std::path::Path;
@@ -38,6 +38,7 @@ pub fn extract(
fields: flatten_object(m),
locator: format!("b{start}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
break;
}
diff --git a/engine/crates/xerj-autoindex/src/extract/logs.rs b/engine/crates/xerj-autoindex/src/extract/logs.rs
index a07045f91..97a8ff80a 100644
--- a/engine/crates/xerj-autoindex/src/extract/logs.rs
+++ b/engine/crates/xerj-autoindex/src/extract/logs.rs
@@ -6,7 +6,7 @@
//! `key=value` pairs embedded in the message (logfmt convention) are lifted
//! into fields — names come from the DATA, not from this code.
-use super::{sanitize_field_name, ExtractStats, RawRecord, Sink};
+use super::{sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::Result;
use regex::Regex;
use serde_json::{Map, Value};
@@ -266,6 +266,7 @@ pub fn extract(
fields,
locator: format!("b{start}"),
group: None,
+ origin: FieldOrigin::Data,
});
}
None => {
diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rs
index 3f207fb0d..b18e959f6 100644
--- a/engine/crates/xerj-autoindex/src/extract/mod.rs
+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs
@@ -23,6 +23,29 @@ use serde_json::{Map, Value};
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
+/// Where a record's FIELD NAMES came from — the input to dataset clustering.
+///
+/// Clustering groups files by their field names (`dataset::cluster`), and the
+/// dataset slug is an ingredient of every `_id` (`ids::doc_id`). So a name that
+/// can appear or disappear because the EXTRACTOR changed — not because the file
+/// changed — silently moves that file's documents to a different index and
+/// orphans the ones already written under the old slug (issue #178).
+///
+/// `Data` names are read out of the file (JSON keys, CSV header, SQL columns,
+/// HTML table headers, parsed log keys): two files that share them really do
+/// share a schema, and the names change only when the file changes.
+/// `Extractor` names are the extractor's own vocabulary (`title`/`body`,
+/// `defs`/`symbols`/`symbol_count`, `page`/`section`) — they describe the tool,
+/// not the data, so they are excluded from the clustering key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FieldOrigin {
+ /// Field names read out of the file itself.
+ Data,
+ /// Field names invented by the extractor.
+ Extractor,
+}
+
/// One extracted record before coercion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawRecord {
@@ -32,6 +55,10 @@ pub struct RawRecord {
pub locator: String,
/// Sub-dataset group within a file (table name for sql/sqlite).
pub group: Option<String>,
+ /// Whether `fields`' NAMES came from the file or from this extractor.
+ /// Set it at every emit site: it decides whether those names are allowed
+ /// to move the file between datasets.
+ pub origin: FieldOrigin,
}
#[derive(Debug, Default, Clone, Copy)]
@@ -283,6 +310,9 @@ pub fn emit_document(
fields,
locator: format!("s{i}"),
group: None,
+ // title/headings/section/body are this function's vocabulary, and
+ // `headings`/`section` come and go — never a clustering key.
+ origin: FieldOrigin::Extractor,
}) {
return false;
}
diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rs
index 51e44b0f3..71ea0d19b 100644
--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs
+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs
@@ -7,7 +7,7 @@
//! also gets a process group and an address-space limit. This is crash/resource
//! isolation, not a security sandbox: the worker retains the user's authority.
-use super::{split_sections, ExtractStats, RawRecord, Sink};
+use super::{split_sections, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::{anyhow, Context, Result};
use pdf_oxide::PdfDocument;
use serde::{Deserialize, Serialize};
@@ -383,6 +383,10 @@ fn extract_in_process(path: &Path) -> Result<Vec<RawRecord>> {
fields,
locator: format!("p{}-s{}", page_index + 1, section),
group: None,
+ // title/page/section/body plus the pdf_* counters are this
+ // extractor's vocabulary; `section` and `pdf_ocr_warning`
+ // appear only sometimes.
+ origin: FieldOrigin::Extractor,
});
}
}
diff --git a/engine/crates/xerj-autoindex/src/extract/sqldump.rs b/engine/crates/xerj-autoindex/src/extract/sqldump.rs
index 201ca8937..0a60a3f1c 100644
--- a/engine/crates/xerj-autoindex/src/extract/sqldump.rs
+++ b/engine/crates/xerj-autoindex/src/extract/sqldump.rs
@@ -5,7 +5,7 @@
//! records with `''`/backslash escapes, NULL, numbers, hex literals.
//! One dataset (group) per table.
-use super::{sanitize_field_name, ExtractStats, RawRecord, Sink};
+use super::{sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::Result;
use serde_json::{Map, Value};
use std::collections::HashMap;
@@ -333,6 +333,7 @@ fn emit_tuple(
fields,
locator: loc,
group: Some(table.to_string()),
+ origin: FieldOrigin::Data,
})
}
diff --git a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
index bd05c2c43..c4aa26d19 100644
--- a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
@@ -1,7 +1,7 @@
//! SQLite databases — read-only immutable open (WAL/journal never touched);
//! one dataset (group) per table; locator = rowid where available.
-use super::{sanitize_field_name, ExtractStats, RawRecord, Sink};
+use super::{sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::{Context, Result};
use rusqlite::types::ValueRef;
use rusqlite::{Connection, OpenFlags};
@@ -101,6 +101,7 @@ pub fn extract(path: &Path, per_table_limit: Option<u64>, sink: Sink) -> Result<
fields,
locator: loc,
group: Some(table.clone()),
+ origin: FieldOrigin::Data,
}) {
break 'tables;
}
diff --git a/engine/crates/xerj-autoindex/src/extract/txt.rs b/engine/crates/xerj-autoindex/src/extract/txt.rs
index 1682f95d3..e2a18be7d 100644
--- a/engine/crates/xerj-autoindex/src/extract/txt.rs
+++ b/engine/crates/xerj-autoindex/src/extract/txt.rs
@@ -22,7 +22,7 @@
//! caller can jump straight to the source — the old per-line record only
//! carried an opaque byte locator.
-use super::{emit_document, ExtractStats, RawRecord, Sink};
+use super::{emit_document, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::Result;
use serde_json::{Map, Value};
use std::path::Path;
@@ -127,6 +127,8 @@ pub fn extract_lines(
fields,
locator: format!("b{start_byte}"),
group: None,
+ // text/start_line/end_line describe this chunker, not the file.
+ origin: FieldOrigin::Extractor,
});
if drain {
window.clear();
diff --git a/engine/crates/xerj-autoindex/src/extract/xml_x.rs b/engine/crates/xerj-autoindex/src/extract/xml_x.rs
index 26f0d9d37..defb78155 100644
--- a/engine/crates/xerj-autoindex/src/extract/xml_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/xml_x.rs
@@ -4,7 +4,9 @@
//! children), ties going to the outermost then the lowest-named tag. No
//! repeating structured tag → the whole document is one record.
-use super::{sanitize_field_name, ExtractStats, RawRecord, Sink, MAX_FIELDS_PER_RECORD};
+use super::{
+ sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink, MAX_FIELDS_PER_RECORD,
+};
use anyhow::Result;
use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;
@@ -54,6 +56,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields,
locator: loc,
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
@@ -74,6 +77,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields,
locator: loc,
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
@@ -113,6 +117,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields: st.root_fields,
locator: "doc".into(),
group: None,
+ origin: FieldOrigin::Data,
});
}
Ok(stats)
diff --git a/engine/crates/xerj-autoindex/src/extract/yaml_x.rs b/engine/crates/xerj-autoindex/src/extract/yaml_x.rs
index 91cf97165..0b17914d0 100644
--- a/engine/crates/xerj-autoindex/src/extract/yaml_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/yaml_x.rs
@@ -1,7 +1,7 @@
//! YAML — multi-document streams; each doc becomes a record (a top-level
//! sequence of mappings becomes per-element records). 16MB file cap.
-use super::{flatten_object, ExtractStats, RawRecord, Sink};
+use super::{flatten_object, ExtractStats, FieldOrigin, RawRecord, Sink};
use anyhow::Result;
use serde_json::{Map, Value};
use std::path::Path;
@@ -42,6 +42,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields: flatten_object(m),
locator: format!("d{d}e{i}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
@@ -54,6 +55,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields: flatten_object(m),
locator: format!("d{d}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
@@ -66,6 +68,7 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
fields: m,
locator: format!("d{d}"),
group: None,
+ origin: FieldOrigin::Data,
}) {
return Ok(stats);
}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index cf2e089b4..425ff5648 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -177,11 +177,20 @@ fn section_label(locator: &str) -> Option<String> {
struct FileScan {
sniffed: Option<Sniffed>,
- /// group → (field accs, sampled record count)
- sketches: Vec<(Option<String>, HashMap<String, infer::FieldAcc>, u64)>,
+ sketches: Vec<GroupSketch>,
junk: Option<(String, String)>, // (status, reason)
}
+/// One sampled group within a file: every field it produced, plus the names
+/// that came from the file rather than from the extractor (`FieldOrigin`).
+/// Only the latter may decide which dataset the file joins — see `dataset`.
+struct GroupSketch {
+ group: Option<String>,
+ fields: HashMap<String, infer::FieldAcc>,
+ key_fields: std::collections::HashSet<String>,
+ records: u64,
+}
+
fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileScan {
let mut out = FileScan {
sniffed: None,
@@ -228,14 +237,25 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileSca
Family::Sqlite => Some(1), // signals per-table row cap inside the extractor
_ => None, // whole-file extractors cap themselves
};
- let mut groups: HashMap<Option<String>, (HashMap<String, infer::FieldAcc>, u64)> =
- HashMap::new();
+ type GroupAcc = (
+ HashMap<String, infer::FieldAcc>,
+ u64,
+ std::collections::HashSet<String>,
+ );
+ let mut groups: HashMap<Option<String>, GroupAcc> = HashMap::new();
let grouped_family = matches!(sn.family, Family::SqlDump | Family::Sqlite);
let mut sink = |rec: extract::RawRecord| -> bool {
let entry = groups.entry(rec.group.clone()).or_default();
if (entry.1 as usize) < sample {
+ // Every field feeds type inference; only the ones the FILE named
+ // feed the clustering key, so an extractor that starts emitting a
+ // new field cannot re-home the file (#178).
+ let from_file = rec.origin == extract::FieldOrigin::Data;
for (k, v) in &rec.fields {
entry.0.entry(k.clone()).or_default().add(v);
+ if from_file {
+ entry.2.insert(k.clone());
+ }
}
}
entry.1 += 1;
@@ -264,12 +284,98 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileSca
}
}
}
- out.sketches = groups.into_iter().map(|(g, (f, n))| (g, f, n)).collect();
- out.sketches.sort_by(|a, b| a.0.cmp(&b.0));
+ out.sketches = groups
+ .into_iter()
+ .map(|(group, (fields, records, key_fields))| GroupSketch {
+ group,
+ fields,
+ key_fields,
+ records,
+ })
+ .collect();
+ out.sketches.sort_by(|a, b| a.group.cmp(&b.group));
out.sniffed = Some(sn);
out
}
+#[cfg(test)]
+mod clustering_key_tests {
+ use super::*;
+
+ fn scan(dir: &Path, name: &str, body: &str) -> FileScan {
+ let path = dir.join(name);
+ std::fs::write(&path, body).unwrap();
+ let size = std::fs::metadata(&path).unwrap().len();
+ scan_file(&path, size, 500, 2)
+ }
+
+ /// The #178 mechanism, from the extractor to the clustering key: a source
+ /// file that yields symbols and one that yields none produce the SAME
+ /// (empty) key, so no extractor improvement can move a file between
+ /// datasets. `defs` still reaches the mapping — it is indexed, just not
+ /// used to decide identity.
+ #[test]
+ fn symbols_never_enter_the_clustering_key() {
+ let dir = std::env::temp_dir().join("xerj-ax-178-key");
+ std::fs::create_dir_all(&dir).unwrap();
+
+ // `const` is invisible to the shipped Rust query, so this file parses
+ // to zero symbols — exactly the case #170 improves.
+ let table = scan(
+ &dir,
+ "table.rs",
+ "const BYTE_FREQUENCIES: [u8; 2] = [1, 2];\n",
+ );
+ let code = scan(&dir, "code.rs", "fn main() {}\nstruct S;\n");
+ let _ = std::fs::remove_dir_all(&dir);
+
+ for s in [&table, &code] {
+ assert_eq!(s.sketches.len(), 1, "one code record per file");
+ assert!(
+ s.sketches[0].key_fields.is_empty(),
+ "extractor-invented names leaked into the clustering key: {:?}",
+ s.sketches[0].key_fields
+ );
+ }
+ assert!(!table.sketches[0].fields.contains_key("defs"));
+ assert!(code.sketches[0].fields.contains_key("defs"));
+
+ // …so the two land in one dataset instead of one dataset each.
+ let rels = vec!["table.rs".to_string(), "code.rs".to_string()];
+ let sketches: Vec<dataset::Sketch> = [&table, &code]
+ .iter()
+ .enumerate()
+ .map(|(i, s)| dataset::Sketch {
+ file_idx: i,
+ group: s.sketches[0].group.clone(),
+ family: s.sniffed.as_ref().unwrap().family,
+ fields: s.sketches[0].fields.clone(),
+ key_fields: s.sketches[0].key_fields.clone(),
+ records: s.sketches[0].records,
+ })
+ .collect();
+ let clusters = dataset::cluster(sketches, &rels);
+ assert_eq!(clusters.len(), 1, "{clusters:#?}");
+ }
+
+ /// The other half: a data file's own column names ARE the key, so real
+ /// schemas still drive clustering.
+ #[test]
+ fn data_field_names_are_the_clustering_key() {
+ let dir = std::env::temp_dir().join("xerj-ax-178-data");
+ std::fs::create_dir_all(&dir).unwrap();
+ let csv = scan(&dir, "t.csv", "id,email\n1,[email protected]\n2,[email protected]\n");
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut names: Vec<&str> = csv.sketches[0]
+ .key_fields
+ .iter()
+ .map(String::as_str)
+ .collect();
+ names.sort();
+ assert_eq!(names, ["email", "id"]);
+ }
+}
+
// ─── mapping builder ─────────────────────────────────────────────────────
pub const PROVENANCE_FIELDS: &[&str] = &[
@@ -688,13 +794,14 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
});
continue;
}
- for (group, fields, n) in sc.sketches {
+ for gs in sc.sketches {
sketches.push(dataset::Sketch {
file_idx: i,
- group,
+ group: gs.group,
family,
- fields,
- records: n,
+ fields: gs.fields,
+ key_fields: gs.key_fields,
+ records: gs.records,
});
}
}