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.

test(autoindex): cover the six untested extractors, pinning two real defects

xerj-orgc3a06f3b6c46
diff --git a/engine/crates/xerj-autoindex/src/extract/csv_x.rs b/engine/crates/xerj-autoindex/src/extract/csv_x.rs
index 8c7ca2d94..04495968a 100644
--- a/engine/crates/xerj-autoindex/src/extract/csv_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/csv_x.rs
@@ -79,3 +79,164 @@ pub fn extract(
}
Ok(stats)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sniff::{CsvDialect, Family};
+
+ fn sniffed(delim: u8, has_header: bool, decimal_comma: bool) -> Sniffed {
+ Sniffed {
+ family: Family::Csv,
+ gzip: false,
+ binary_kind: None,
+ csv: Some(CsvDialect {
+ delim,
+ has_header,
+ decimal_comma,
+ }),
+ encoding: "utf-8",
+ }
+ }
+
+ fn run(sn: &Sniffed, bytes: &[u8]) -> (Result<ExtractStats>, Vec<RawRecord>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("t.csv");
+ std::fs::write(&path, bytes).unwrap();
+ let mut recs = Vec::new();
+ let stats = extract(&path, sn, None, &mut |r| {
+ recs.push(r);
+ true
+ });
+ (stats, recs)
+ }
+
+ fn ok(sn: &Sniffed, bytes: &[u8]) -> (ExtractStats, Vec<RawRecord>) {
+ let (stats, recs) = run(sn, bytes);
+ (stats.unwrap(), recs)
+ }
+
+ #[test]
+ fn the_header_row_names_the_fields_and_every_data_row_becomes_one_record() {
+ let (stats, recs) = ok(
+ &sniffed(b',', true, false),
+ b"id,Full Name,amount\n1,Ann Lee,10.5\n2,Bob Ray,20\n",
+ );
+ assert_eq!(stats.records, 2);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(recs[0].locator, "r0");
+ assert_eq!(recs[1].locator, "r1");
+ assert_eq!(recs[0].fields["id"], serde_json::json!("1"));
+ assert_eq!(
+ recs[0].fields["Full_Name"],
+ serde_json::json!("Ann Lee"),
+ "column names are sanitized, never guessed"
+ );
+ assert_eq!(recs[1].fields["amount"], serde_json::json!("20"));
+ assert!(
+ recs.iter().all(|r| r.group.is_none()),
+ "a CSV file is one dataset"
+ );
+ }
+
+ #[test]
+ fn a_headerless_dialect_names_every_column_by_position() {
+ let (stats, recs) = ok(&sniffed(b';', false, false), b"1;Ann;10\n2;Bob;20\n");
+ assert_eq!(stats.records, 2, "the first row is data, not a header");
+ assert_eq!(recs[0].fields["col_1"], serde_json::json!("1"));
+ assert_eq!(recs[0].fields["col_2"], serde_json::json!("Ann"));
+ assert_eq!(recs[0].fields["col_3"], serde_json::json!("10"));
+ }
+
+ #[test]
+ fn a_decimal_comma_dialect_rewrites_only_whole_numeric_fields() {
+ let (_, recs) = ok(
+ &sniffed(b';', true, true),
+ "id;amount;note\n1;10,5;Ann, Lee\n2;-3,25;a,b,c\n".as_bytes(),
+ );
+ assert_eq!(recs[0].fields["amount"], serde_json::json!("10.5"));
+ assert_eq!(recs[1].fields["amount"], serde_json::json!("-3.25"));
+ assert_eq!(
+ recs[0].fields["note"],
+ serde_json::json!("Ann, Lee"),
+ "text that merely contains a comma must be left alone"
+ );
+ assert_eq!(recs[1].fields["note"], serde_json::json!("a,b,c"));
+ }
+
+ #[test]
+ fn duplicate_header_names_are_disambiguated_instead_of_overwriting_each_other() {
+ let (_, recs) = ok(&sniffed(b',', true, false), b"id,id,amount\n1,2,3\n");
+ assert_eq!(recs[0].fields["id"], serde_json::json!("1"));
+ assert_eq!(recs[0].fields["id_2"], serde_json::json!("2"));
+ assert_eq!(recs[0].fields["amount"], serde_json::json!("3"));
+ }
+
+ #[test]
+ fn quoted_fields_keep_embedded_delimiters_and_newlines() {
+ let (stats, recs) = ok(
+ &sniffed(b',', true, false),
+ b"a,b\n\"x,y\",\"line1\nline2\"\n",
+ );
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].fields["a"], serde_json::json!("x,y"));
+ assert_eq!(recs[0].fields["b"], serde_json::json!("line1\nline2"));
+ }
+
+ #[test]
+ fn ragged_rows_keep_their_extra_columns_and_all_blank_rows_are_dropped() {
+ let (stats, recs) = ok(&sniffed(b',', true, false), b"a,b\n1,2,3,4\n,,\n5\n");
+ assert_eq!(stats.records, 2, "the all-empty row yields no record");
+ assert_eq!(stats.junk, 0, "a ragged row is not junk");
+ assert_eq!(recs[0].fields["col_3"], serde_json::json!("3"));
+ assert_eq!(recs[0].fields["col_4"], serde_json::json!("4"));
+ assert_eq!(recs[1].fields["a"], serde_json::json!("5"));
+ assert!(
+ recs[1].fields.get("b").is_none(),
+ "a short row omits the missing field rather than blanking it"
+ );
+ assert_eq!(
+ recs[1].locator, "r2",
+ "locators stay positional in the file, skipped rows included"
+ );
+ }
+
+ #[test]
+ fn an_undecodable_row_is_counted_as_junk_and_the_rest_of_the_file_still_extracts() {
+ let mut bytes = b"a,b\n1,ok\n".to_vec();
+ bytes.extend_from_slice(&[b'2', b',', 0xff, 0xfe, b'\n']);
+ bytes.extend_from_slice(b"3,fine\n");
+ let (stats, recs) = ok(&sniffed(b',', true, false), &bytes);
+ assert_eq!(stats.records, 2);
+ assert_eq!(stats.junk, 1);
+ assert_eq!(recs[1].fields["b"], serde_json::json!("fine"));
+ }
+
+ /// The asymmetry is deliberate to record, not to endorse: a bad DATA row is
+ /// junk-counted and skipped, but the header is read with `?`, so a header
+ /// that will not decode fails the whole file. The caller junk-files it.
+ #[test]
+ fn an_undecodable_header_row_fails_the_file_rather_than_skipping_a_row() {
+ let mut bytes = vec![b'a', b',', 0xff, 0xfe, b'\n'];
+ bytes.extend_from_slice(b"1,2\n");
+ let (stats, recs) = run(&sniffed(b',', true, false), &bytes);
+ assert!(stats.is_err());
+ assert!(recs.is_empty());
+ }
+
+ #[test]
+ fn a_file_sniffed_without_a_dialect_falls_back_to_comma_with_a_header() {
+ let mut sn = sniffed(b',', true, false);
+ sn.csv = None;
+ let (stats, recs) = ok(&sn, b"x,y\n1,2\n");
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].fields["x"], serde_json::json!("1"));
+ }
+
+ #[test]
+ fn a_header_only_file_yields_no_records_and_no_junk() {
+ let (stats, recs) = ok(&sniffed(b',', true, false), b"a,b\n");
+ assert_eq!((stats.records, stats.junk), (0, 0));
+ assert!(recs.is_empty());
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/html.rs b/engine/crates/xerj-autoindex/src/extract/html.rs
index 68c6ef86e..ac99e57e0 100644
--- a/engine/crates/xerj-autoindex/src/extract/html.rs
+++ b/engine/crates/xerj-autoindex/src/extract/html.rs
@@ -340,3 +340,216 @@ fn decode_entities(s: &str) -> String {
.replace("&apos;", "'")
.replace("&nbsp;", " ")
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn run(name: &str, html: &str) -> (ExtractStats, Vec<RawRecord>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(name);
+ std::fs::write(&path, html).unwrap();
+ let mut recs = Vec::new();
+ let stats = extract(&path, false, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ fn body_of(rec: &RawRecord) -> &str {
+ rec.fields["body"].as_str().unwrap()
+ }
+
+ fn table_html(header: Option<[&str; 2]>, data_rows: usize) -> String {
+ let mut h = String::from("<html><body><table>");
+ if let Some([a, b]) = header {
+ h.push_str(&format!("<tr><th>{a}</th><th>{b}</th></tr>"));
+ }
+ for i in 1..=data_rows {
+ h.push_str(&format!("<tr><td>item{i}</td><td>{i}</td></tr>"));
+ }
+ h.push_str("</table></body></html>");
+ h
+ }
+
+ #[test]
+ fn a_prose_page_becomes_one_document_of_title_headings_and_tag_free_body() {
+ let (stats, recs) = run(
+ "page.html",
+ "<html><head><title>Quarterly Report</title></head><body>\
+ <h1>Revenue</h1><p>Growth was steady.</p>\
+ <h2>Costs</h2><div>Cloud costs declined.</div></body></html>",
+ );
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs.len(), 1);
+ assert_eq!(recs[0].locator, "s0");
+ assert_eq!(
+ recs[0].fields["title"],
+ serde_json::json!("Quarterly Report")
+ );
+ assert_eq!(
+ recs[0].fields["headings"],
+ serde_json::json!(["Revenue", "Costs"])
+ );
+ let body = body_of(&recs[0]);
+ assert!(body.contains("Growth was steady."));
+ assert!(body.contains("Cloud costs declined."));
+ assert!(
+ !body.contains('<') && !body.contains("div"),
+ "markup leaked into the body: {body:?}"
+ );
+ }
+
+ #[test]
+ fn attributes_and_comments_never_reach_the_body() {
+ let (_, recs) = run(
+ "attrs.html",
+ "<html><body><p class=\"lede\">visible</p><!-- hidden note -->\
+ <a href=\"https://example.com/hidden-path\" title=\"hidden title\">link text</a>\
+ </body></html>",
+ );
+ let body = body_of(&recs[0]);
+ assert!(body.contains("visible") && body.contains("link text"));
+ assert!(
+ !body.contains("hidden") && !body.contains("class") && !body.contains("href"),
+ "attribute or comment text was indexed: {body:?}"
+ );
+ }
+
+ #[test]
+ fn character_entities_are_unescaped_in_the_title_and_the_body() {
+ let (_, recs) = run(
+ "ents.html",
+ "<html><head><title>Q4 &amp; FY</title></head><body>\
+ <p>5 &lt; 10 &gt; 2, &quot;quoted&quot; &amp; &#39;single&#39;&nbsp;spaced</p>\
+ </body></html>",
+ );
+ assert_eq!(recs[0].fields["title"], serde_json::json!("Q4 & FY"));
+ let body = body_of(&recs[0]);
+ assert!(body.contains("5 < 10 > 2"), "{body:?}");
+ assert!(body.contains("\"quoted\" & 'single' spaced"), "{body:?}");
+ assert!(!body.contains("&amp;") && !body.contains("&lt;"));
+ }
+
+ /// DEFECT, pinned as CURRENT behaviour — not a contract worth keeping.
+ ///
+ /// `skip_until` suppresses the *tags* inside `<script>`/`<style>` but the
+ /// text branch of the tokenizer appends to `cur_text` unconditionally, and
+ /// the closing tag `continue`s without discarding it. The buffered CSS/JS
+ /// is therefore flushed into the body at the next tag boundary, so page
+ /// scripts and stylesheets are indexed as prose.
+ ///
+ /// When the tokenizer is fixed, this test fails: invert the assertion
+ /// rather than deleting it.
+ #[test]
+ fn script_and_style_text_still_reaches_the_body() {
+ let (_, recs) = run(
+ "skip.html",
+ "<html><head><style>.lede{color:#fff}</style>\
+ <script>var token=1;</script></head><body><p>visible</p></body></html>",
+ );
+ let body = body_of(&recs[0]);
+ assert!(body.contains("visible"));
+ assert!(
+ body.contains(".lede{color:#fff}") && body.contains("var token=1;"),
+ "script/style suppression now works — flip this assertion: {body:?}"
+ );
+ }
+
+ #[test]
+ fn a_dominant_table_becomes_one_record_per_row_named_from_its_header_cells() {
+ let (stats, recs) = run("t.html", &table_html(Some(["Product Name", "Qty"]), 5));
+ assert_eq!(stats.records, 5);
+ assert_eq!(recs.len(), 5);
+ assert_eq!(recs[0].fields["Product_Name"], serde_json::json!("item1"));
+ assert_eq!(recs[0].fields["Qty"], serde_json::json!("1"));
+ assert_eq!(recs[4].fields["Product_Name"], serde_json::json!("item5"));
+ assert!(
+ recs.iter().all(|r| r.fields.len() == 2),
+ "the header row must not become a record"
+ );
+ let locs: Vec<&str> = recs.iter().map(|r| r.locator.as_str()).collect();
+ assert_eq!(locs, ["row1", "row2", "row3", "row4", "row5"]);
+ assert!(recs.iter().all(|r| r.group.is_none()));
+ }
+
+ #[test]
+ fn a_headerless_table_gets_positional_column_names_and_keeps_its_first_row() {
+ let (stats, recs) = run("t.html", &table_html(None, 6));
+ assert_eq!(stats.records, 6, "no header row means no row is consumed");
+ assert_eq!(recs[0].locator, "row0");
+ assert_eq!(recs[0].fields["col_1"], serde_json::json!("item1"));
+ assert_eq!(recs[0].fields["col_2"], serde_json::json!("1"));
+ }
+
+ #[test]
+ fn empty_cells_are_omitted_rather_than_indexed_as_blank_values() {
+ let mut h = String::from("<html><body><table><tr><th>A &amp; B</th><th>Note</th></tr>");
+ for i in 1..=5 {
+ h.push_str(&format!("<tr><td>x&lt;{i}</td><td> </td></tr>"));
+ }
+ h.push_str("</table></body></html>");
+ let (stats, recs) = run("cells.html", &h);
+ assert_eq!(stats.records, 5);
+ assert_eq!(recs[0].fields["A_B"], serde_json::json!("x<1"));
+ assert_eq!(
+ recs[0].fields.len(),
+ 1,
+ "the blank Note cell must not be stored"
+ );
+ }
+
+ /// DEFECT, pinned as CURRENT behaviour.
+ ///
+ /// A table under the 5-row dominance threshold loses its content twice
+ /// over: it is not emitted as rows, and `flush_text` has already diverted
+ /// every cell into `cur_cell` instead of `doc.body`, so the cells are not
+ /// in the document record either. Small tables — the common case on a
+ /// documentation page — are silently unindexed.
+ #[test]
+ fn a_table_below_the_dominance_threshold_leaves_its_cells_unindexed() {
+ let (stats, recs) = run(
+ "small.html",
+ "<html><body><h1>Head</h1><p>prose</p>\
+ <table><tr><td>cellA</td><td>cellB</td></tr></table>\
+ <p>after</p></body></html>",
+ );
+ assert_eq!(stats.records, 1, "falls back to the document record");
+ let body = body_of(&recs[0]);
+ assert!(body.contains("prose") && body.contains("after"));
+ assert!(
+ !body.contains("cellA") && !body.contains("cellB"),
+ "small-table cells are now indexed — flip this assertion: {body:?}"
+ );
+ }
+
+ #[test]
+ fn a_page_without_a_title_falls_back_to_a_heading_then_to_the_file_stem() {
+ let (_, recs) = run(
+ "fallback.html",
+ "<html><body><h2>Only Heading</h2><p>x</p></body></html>",
+ );
+ assert_eq!(recs[0].fields["title"], serde_json::json!("Only Heading"));
+
+ let (_, recs) = run("stem-name.html", "<html><body><p>x</p></body></html>");
+ assert_eq!(recs[0].fields["title"], serde_json::json!("stem-name"));
+ assert!(recs[0].fields.get("headings").is_none());
+ }
+
+ #[test]
+ fn unclosed_and_nonsense_markup_is_never_fatal() {
+ let (stats, recs) = run(
+ "junk.html",
+ "<<<>>> <div class=\"unclosed <p>dangling &amp; text <script>x=1;",
+ );
+ assert_eq!(stats.junk, 0);
+ assert_eq!(stats.records, 1, "a broken page still yields a document");
+ assert_eq!(recs[0].fields["title"], serde_json::json!("junk"));
+
+ let (stats, recs) = run("empty.html", "");
+ assert_eq!(stats.records, 1);
+ assert_eq!(body_of(&recs[0]), "");
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/json.rs b/engine/crates/xerj-autoindex/src/extract/json.rs
index 65c6eea12..7837a5133 100644
--- a/engine/crates/xerj-autoindex/src/extract/json.rs
+++ b/engine/crates/xerj-autoindex/src/extract/json.rs
@@ -96,3 +96,122 @@ fn emit(v: Value, locator: &str, sink: Sink, stats: &mut ExtractStats) -> bool {
group: None,
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn run(text: &str) -> (ExtractStats, Vec<RawRecord>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("t.json");
+ std::fs::write(&path, text).unwrap();
+ let mut recs = Vec::new();
+ let stats = extract(&path, false, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ #[test]
+ fn an_array_of_objects_becomes_one_record_per_element() {
+ let (stats, recs) = run(
+ r#"[{"id":1,"user":{"name":"ann","addr":{"city":"NY"}},"tags":["a","b"]},{"id":2}]"#,
+ );
+ assert_eq!(stats.records, 2);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(recs[0].locator, "e0");
+ assert_eq!(recs[1].locator, "e1");
+ assert_eq!(recs[0].fields["id"], serde_json::json!(1));
+ assert_eq!(
+ recs[0].fields["user_name"],
+ serde_json::json!("ann"),
+ "two levels of nesting flatten into a_b keys"
+ );
+ assert_eq!(recs[0].fields["user_addr_city"], serde_json::json!("NY"));
+ assert_eq!(
+ recs[0].fields["tags"],
+ serde_json::json!(["a", "b"]),
+ "an array of scalars stays an array"
+ );
+ assert_eq!(recs[1].fields.len(), 1, "absent keys are not filled in");
+ }
+
+ #[test]
+ fn a_wrapper_object_lifts_its_largest_array_and_shares_the_outer_scalars() {
+ let (stats, recs) = run(r#"{"generated":"2026-01-01","count":2,
+ "items":[{"id":1},{"id":2,"generated":"per-item"}],
+ "errors":[{"e":1}]}"#);
+ assert_eq!(stats.records, 2, "records come from the biggest array");
+ assert_eq!(recs[0].locator, "items:e0");
+ assert_eq!(recs[0].fields["generated"], serde_json::json!("2026-01-01"));
+ assert_eq!(recs[0].fields["count"], serde_json::json!(2));
+ assert_eq!(
+ recs[1].fields["generated"],
+ serde_json::json!("per-item"),
+ "the element wins a collision with a shared field"
+ );
+ assert_eq!(
+ recs[0].fields["errors"],
+ serde_json::json!(r#"[{"e":1}]"#),
+ "the other arrays of objects travel as JSON strings"
+ );
+ }
+
+ #[test]
+ fn an_object_with_no_repeating_array_is_a_single_document_record() {
+ let (stats, recs) =
+ run(r#"{"meta":"m","nested":{"deep":{"deeper":{"x":1}}},"items":[{"id":1}]}"#);
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].locator, "doc");
+ assert_eq!(recs[0].fields["meta"], serde_json::json!("m"));
+ assert_eq!(
+ recs[0].fields["items"],
+ serde_json::json!(r#"[{"id":1}]"#),
+ "a single-element array is below the record-lifting threshold"
+ );
+ assert_eq!(
+ recs[0].fields["nested_deep_deeper"],
+ serde_json::json!(r#"{"x":1}"#),
+ "structure past two levels is stored as a JSON string"
+ );
+ }
+
+ #[test]
+ fn a_bare_scalar_document_is_wrapped_in_a_value_field() {
+ let (stats, recs) = run("42");
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].locator, "doc");
+ assert_eq!(recs[0].fields["value"], serde_json::json!(42));
+
+ let (stats, recs) = run("[1,2,3]");
+ assert_eq!(stats.records, 3, "array elements each become a record");
+ assert_eq!(recs[2].fields["value"], serde_json::json!(3));
+ }
+
+ #[test]
+ fn a_data_field_in_the_provenance_namespace_is_renamed_not_dropped() {
+ let (_, recs) = run(r#"{"ax_kind":"invoice","ok":1}"#);
+ assert_eq!(recs[0].fields["data_ax_kind"], serde_json::json!("invoice"));
+ assert!(recs[0].fields.get("ax_kind").is_none());
+ }
+
+ #[test]
+ fn truncated_json_is_junk_filed_and_emits_nothing() {
+ let (stats, recs) = run(r#"{"a":1,"#);
+ assert_eq!((stats.records, stats.junk), (0, 1));
+ assert!(recs.is_empty());
+
+ let (stats, recs) = run("not json at all");
+ assert_eq!((stats.records, stats.junk), (0, 1));
+ assert!(recs.is_empty());
+ }
+
+ #[test]
+ fn an_empty_array_yields_nothing_at_all_without_being_junk() {
+ let (stats, recs) = run("[]");
+ assert_eq!((stats.records, stats.junk), (0, 0));
+ assert!(recs.is_empty());
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/jsonl.rs b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
index 97b9464c7..5649deb2f 100644
--- a/engine/crates/xerj-autoindex/src/extract/jsonl.rs
+++ b/engine/crates/xerj-autoindex/src/extract/jsonl.rs
@@ -95,3 +95,105 @@ fn trim_ws(b: &[u8]) -> &[u8] {
.unwrap_or(start);
&b[start..end]
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn run(bytes: &[u8], limit: Option<u64>) -> (ExtractStats, Vec<RawRecord>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("t.jsonl");
+ std::fs::write(&path, bytes).unwrap();
+ let mut recs = Vec::new();
+ let stats = extract(&path, false, limit, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ fn locators(recs: &[RawRecord]) -> Vec<&str> {
+ recs.iter().map(|r| r.locator.as_str()).collect()
+ }
+
+ #[test]
+ fn every_line_is_one_record_located_at_the_byte_offset_it_starts_at() {
+ let (stats, recs) = run(b"{\"id\":1,\"m\":{\"k\":\"v\"}}\n{\"id\":2}\n", None);
+ assert_eq!(stats.records, 2);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(
+ locators(&recs),
+ ["b0", "b23"],
+ "the second line starts after the 23 bytes of the first"
+ );
+ assert_eq!(recs[0].fields["id"], serde_json::json!(1));
+ assert_eq!(
+ recs[0].fields["m_k"],
+ serde_json::json!("v"),
+ "nested objects flatten exactly as in whole-file JSON"
+ );
+ }
+
+ #[test]
+ fn blank_lines_are_skipped_without_being_counted_as_junk() {
+ let (stats, recs) = run(b"{\"id\":1}\n\n \n{\"id\":2}\n", None);
+ assert_eq!((stats.records, stats.junk), (2, 0));
+ assert_eq!(locators(&recs), ["b0", "b14"]);
+ }
+
+ #[test]
+ fn a_bad_line_is_junk_and_never_stops_the_lines_after_it() {
+ let (stats, recs) = run(b"{\"id\":1}\n[1,2]\n{oops\n{\"id\":3}\n", None);
+ assert_eq!(stats.records, 2);
+ assert_eq!(
+ stats.junk, 2,
+ "a valid non-object line is junk just like a parse failure"
+ );
+ assert_eq!(recs[1].fields["id"], serde_json::json!(3));
+ }
+
+ /// The distinction from `json::extract`: JSONL is line-framed, so a
+ /// pretty-printed document is not one record — it is one junk line per
+ /// physical line.
+ #[test]
+ fn a_pretty_printed_object_is_not_a_jsonl_stream() {
+ let (stats, recs) = run(b"{\n \"id\": 1\n}\n", None);
+ assert_eq!(stats.records, 0);
+ assert_eq!(stats.junk, 3);
+ assert!(recs.is_empty());
+ }
+
+ /// Sampling stops mid-file: the last line arrives cut in half. That is a
+ /// truncation, not corrupt data, so it must not inflate the junk count the
+ /// catalog reports for the file.
+ #[test]
+ fn a_line_cut_short_by_a_sampling_limit_is_not_counted_as_junk() {
+ let data = b"{\"id\":1}\n{\"id\":2}\n{\"id\":3}\n";
+ let (stats, recs) = run(data, Some(14));
+ assert_eq!(stats.records, 1);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(locators(&recs), ["b0"]);
+
+ let (stats, _) = run(data, Some(27));
+ assert_eq!((stats.records, stats.junk), (3, 0), "the full stream fits");
+ }
+
+ #[test]
+ fn carriage_returns_are_trimmed_but_still_counted_in_the_offset() {
+ let (stats, recs) = run(b"{\"id\":1}\r\n{\"id\":2}\r\n", None);
+ assert_eq!((stats.records, stats.junk), (2, 0));
+ assert_eq!(locators(&recs), ["b0", "b10"]);
+ }
+
+ #[test]
+ fn a_line_over_the_cap_is_junk_rather_than_a_giant_record() {
+ let mut data = vec![b'{'];
+ data.resize(MAX_LINE + 1, b' ');
+ data.extend_from_slice(b"}\n{\"id\":2}\n");
+ let (stats, recs) = run(&data, None);
+ assert_eq!(stats.junk, 1);
+ assert_eq!(stats.records, 1, "the stream continues after the cap");
+ assert_eq!(recs[0].fields["id"], serde_json::json!(2));
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
index 6187cf063..bd05c2c43 100644
--- a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs
@@ -113,3 +113,181 @@ pub fn extract(path: &Path, per_table_limit: Option<u64>, sink: Sink) -> Result<
}
Ok(stats)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Build a real database with the bundled driver the extractor itself uses.
+ fn db(dir: &tempfile::TempDir, name: &str, sql: &str) -> std::path::PathBuf {
+ let path = dir.path().join(name);
+ let conn = Connection::open(&path).unwrap();
+ conn.execute_batch(sql).unwrap();
+ path
+ }
+
+ fn run(path: &Path, per_table_limit: Option<u64>) -> (ExtractStats, Vec<RawRecord>) {
+ let mut recs = Vec::new();
+ let stats = extract(path, per_table_limit, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ #[test]
+ fn every_row_of_every_table_is_a_record_grouped_and_located_by_table_and_rowid() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = db(
+ &dir,
+ "shop.db",
+ r#"CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT);
+ INSERT INTO authors VALUES (1,'Ann'),(2,'Bob');
+ CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT);
+ INSERT INTO books VALUES (1,'First');"#,
+ );
+ let (stats, recs) = run(&path, None);
+ assert_eq!(stats.records, 3);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(
+ recs.iter()
+ .map(|r| (r.group.clone().unwrap(), r.locator.clone()))
+ .collect::<Vec<_>>(),
+ vec![
+ ("authors".into(), "tauthors:r1".to_string()),
+ ("authors".into(), "tauthors:r2".to_string()),
+ ("books".into(), "tbooks:r1".to_string()),
+ ],
+ "tables are walked in name order and each is its own dataset"
+ );
+ assert_eq!(recs[0].fields["name"], serde_json::json!("Ann"));
+ assert!(
+ recs[0].fields.get("rowid").is_none(),
+ "the rowid drives the locator and is never a field"
+ );
+ }
+
+ #[test]
+ fn column_names_are_sanitized_and_null_and_blob_cells_are_omitted() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = db(
+ &dir,
+ "types.db",
+ r#"CREATE TABLE t (id INTEGER PRIMARY KEY, "full name" TEXT, score REAL,
+ note TEXT, pic BLOB);
+ INSERT INTO t VALUES (1,'Ann Lee',9.5,NULL,x'0102');
+ INSERT INTO t VALUES (2,'Bob Ray',7.25,'hi',NULL);"#,
+ );
+ let (_, recs) = run(&path, None);
+ assert_eq!(recs[0].fields["full_name"], serde_json::json!("Ann Lee"));
+ assert_eq!(recs[0].fields["id"], serde_json::json!(1));
+ assert_eq!(recs[0].fields["score"], serde_json::json!(9.5));
+ assert!(
+ recs[0].fields.get("note").is_none(),
+ "a NULL cell is absent, not empty"
+ );
+ assert!(
+ recs[0].fields.get("pic").is_none(),
+ "a BLOB carries no text to index"
+ );
+ assert_eq!(recs[1].fields["note"], serde_json::json!("hi"));
+ }
+
+ #[test]
+ fn a_table_without_a_rowid_falls_back_to_ordinal_locators() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = db(
+ &dir,
+ "norowid.db",
+ r#"CREATE TABLE books (isbn TEXT PRIMARY KEY, title TEXT) WITHOUT ROWID;
+ INSERT INTO books VALUES ('111','First'),('222','Second');"#,
+ );
+ let (stats, recs) = run(&path, None);
+ assert_eq!(stats.records, 2);
+ assert_eq!(
+ recs.iter().map(|r| r.locator.as_str()).collect::<Vec<_>>(),
+ ["tbooks:o0", "tbooks:o1"]
+ );
+ assert_eq!(recs[0].fields["isbn"], serde_json::json!("111"));
+ }
+
+ #[test]
+ fn views_and_sqlite_internal_tables_are_never_extracted() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = db(
+ &dir,
+ "views.db",
+ r#"CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);
+ INSERT INTO t (v) VALUES ('a'),('b');
+ CREATE VIEW v_t AS SELECT * FROM t;
+ CREATE TABLE blank (x INTEGER);"#,
+ );
+ let (stats, recs) = run(&path, None);
+ assert_eq!(stats.records, 2, "an empty table contributes no records");
+ assert!(
+ recs.iter().all(|r| r.group.as_deref() == Some("t")),
+ "{recs:?}"
+ );
+ }
+
+ #[test]
+ fn the_row_limit_applies_to_each_table_independently() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = db(
+ &dir,
+ "sample.db",
+ r#"CREATE TABLE a (id INTEGER PRIMARY KEY);
+ INSERT INTO a VALUES (1),(2),(3);
+ CREATE TABLE b (id INTEGER PRIMARY KEY);
+ INSERT INTO b VALUES (1),(2),(3);"#,
+ );
+ let (stats, recs) = run(&path, Some(1));
+ assert_eq!(stats.records, 2, "one row sampled from each of two tables");
+ assert_eq!(
+ recs.iter()
+ .map(|r| r.group.clone().unwrap())
+ .collect::<Vec<_>>(),
+ ["a", "b"]
+ );
+ }
+
+ #[test]
+ fn a_zero_byte_database_yields_no_records_and_no_junk() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("empty.db");
+ std::fs::write(&path, b"").unwrap();
+ let (stats, recs) = run(&path, None);
+ assert_eq!((stats.records, stats.junk), (0, 0));
+ assert!(recs.is_empty());
+ }
+
+ /// Unlike every text extractor, a corrupt database is a hard error rather
+ /// than a junk count — there is no partial parse to salvage. The caller
+ /// junk-files the file with this message, so the failure is recorded and
+ /// never fatal, but nothing is extracted from the readable pages.
+ #[test]
+ fn a_corrupt_database_fails_the_file_instead_of_panicking() {
+ let dir = tempfile::tempdir().unwrap();
+ let good = db(
+ &dir,
+ "good.db",
+ "CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO t VALUES (1,'a');",
+ );
+ let bytes = std::fs::read(&good).unwrap();
+ let path = dir.path().join("corrupt.db");
+ std::fs::write(&path, &bytes[..bytes.len() / 2]).unwrap();
+
+ let mut seen = 0usize;
+ let err = extract(&path, None, &mut |_r| {
+ seen += 1;
+ true
+ })
+ .unwrap_err();
+ assert_eq!(seen, 0);
+ assert!(
+ err.to_string().contains("malformed") || err.to_string().contains("not a database"),
+ "unexpected error: {err}"
+ );
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/extract/xml_x.rs b/engine/crates/xerj-autoindex/src/extract/xml_x.rs
index cf3e30c38..9f20923a5 100644
--- a/engine/crates/xerj-autoindex/src/extract/xml_x.rs
+++ b/engine/crates/xerj-autoindex/src/extract/xml_x.rs
@@ -278,3 +278,192 @@ fn elect_record_tag(path: &Path, gzip: bool) -> Result<Option<String>> {
.max_by_key(|(_, (n, _))| *n)
.map(|(k, _)| k))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn run(xml: &str) -> (ExtractStats, Vec<RawRecord>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("t.xml");
+ std::fs::write(&path, xml).unwrap();
+ let mut recs = Vec::new();
+ let stats = extract(&path, false, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ #[test]
+ fn the_repeating_structured_element_becomes_one_record_per_occurrence() {
+ let (stats, recs) = run(r#"<catalog site="shop">
+ <item id="1"><name>Widget</name></item>
+ <item id="2"><name>Gadget</name></item>
+ <item id="3"><name>Doohickey</name></item>
+ <item id="4"><name>Thing</name><price cur="USD">4.50</price></item>
+ </catalog>"#);
+ assert_eq!(stats.records, 4);
+ assert_eq!(stats.junk, 0);
+ assert_eq!(
+ recs.iter().map(|r| r.locator.as_str()).collect::<Vec<_>>(),
+ ["e0", "e1", "e2", "e3"]
+ );
+ assert_eq!(
+ recs[0].fields["id"],
+ serde_json::json!("1"),
+ "attributes of the record element are top-level fields"
+ );
+ assert_eq!(
+ recs[0].fields["name"],
+ serde_json::json!("Widget"),
+ "child text is keyed by the child element path"
+ );
+ assert!(
+ recs[0].fields.get("site").is_none(),
+ "the root element is not part of a record"
+ );
+ assert_eq!(recs[3].fields["price"], serde_json::json!("4.50"));
+ assert_eq!(
+ recs[3].fields["price_cur"],
+ serde_json::json!("USD"),
+ "a child's attribute is prefixed with the child's path"
+ );
+ }
+
+ #[test]
+ fn a_self_closing_element_is_emitted_from_its_attributes_alone() {
+ let (stats, recs) =
+ run(r#"<rows><row a="1" b="x"/><row a="2" b="y"/><row a="3" b="z"/></rows>"#);
+ assert_eq!(stats.records, 3, "no End event must not lose the record");
+ assert_eq!(recs[2].fields["a"], serde_json::json!("3"));
+ assert_eq!(recs[2].fields["b"], serde_json::json!("z"));
+ }
+
+ #[test]
+ fn a_child_element_repeated_inside_a_record_becomes_a_multi_valued_field() {
+ let (stats, recs) = run(r#"<catalog>
+ <item id="1"><tag>red</tag><tag>blue</tag></item>
+ <item id="2"><tag>green</tag></item>
+ <item id="3"><tag>red</tag></item>
+ </catalog>"#);
+ assert_eq!(stats.records, 3);
+ assert_eq!(recs[0].fields["tag"], serde_json::json!(["red", "blue"]));
+ assert_eq!(
+ recs[1].fields["tag"],
+ serde_json::json!("green"),
+ "a single occurrence stays a scalar"
+ );
+ }
+
+ #[test]
+ fn a_document_with_no_repeating_element_becomes_one_record_keyed_by_path() {
+ let (stats, recs) = run(
+ r#"<config><server><host>localhost</host><port>8080</port></server><debug>true</debug></config>"#,
+ );
+ assert_eq!(stats.records, 1);
+ assert_eq!(recs[0].locator, "doc");
+ assert_eq!(
+ recs[0].fields["server_host"],
+ serde_json::json!("localhost")
+ );
+ assert_eq!(recs[0].fields["server_port"], serde_json::json!("8080"));
+ assert_eq!(
+ recs[0].fields["debug"],
+ serde_json::json!("true"),
+ "the root element is stripped from every key"
+ );
+ }
+
+ #[test]
+ fn entities_are_unescaped_and_cdata_is_kept_verbatim() {
+ let (_, recs) =
+ run(r#"<doc><p>5 &lt; 10 &amp; rising</p><p><![CDATA[<b>raw</b>]]></p></doc>"#);
+ let p = recs[0].fields["p"].as_array().unwrap();
+ assert!(p.contains(&serde_json::json!("5 < 10 & rising")));
+ assert!(p.contains(&serde_json::json!("<b>raw</b>")));
+ }
+
+ #[test]
+ fn a_truncated_document_is_junk_filed_and_keeps_what_it_parsed() {
+ let (stats, recs) =
+ run(r#"<catalog><item id="1"><name>A</name></item><item id="2"><name>B<"#);
+ assert_eq!(stats.junk, 1);
+ assert_eq!(stats.records, 1);
+ assert_eq!(
+ recs[0].fields["item_id"],
+ serde_json::json!(["1", "2"]),
+ "everything read before the break is still emitted"
+ );
+
+ let (stats, recs) = run("<a><b>1</c></a>");
+ assert_eq!(stats.junk, 1, "a mismatched end tag ends the parse");
+ assert_eq!(recs[0].fields["b"], serde_json::json!("1"));
+ }
+
+ #[test]
+ fn text_that_is_not_xml_yields_nothing_at_all() {
+ let (stats, recs) = run("not xml at all, just words");
+ assert_eq!(
+ (stats.records, stats.junk),
+ (0, 0),
+ "text outside any element is dropped; the caller junk-files the file"
+ );
+ assert!(recs.is_empty());
+ }
+
+ /// DEFECT, pinned as CURRENT behaviour.
+ ///
+ /// `elect_record_tag` picks the winner with `max_by_key` over a `HashMap`,
+ /// which breaks ties by iteration order — and that order is randomly
+ /// seeded per map. When two structured tags occur the same number of times
+ /// (here the `item` wrapper and its `price` child, three each) the elected
+ /// record element differs BETWEEN RUNS on the same file: the records carry
+ /// different fields each time, so re-indexing an unchanged file rewrites
+ /// every document under the same locator.
+ ///
+ /// A deterministic tie-break (outermost tag, or lowest name) would fix it;
+ /// when it lands this test fails and should be replaced by the
+ /// stable-election assertion.
+ #[test]
+ fn a_tied_record_tag_election_picks_an_arbitrary_winner_each_run() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("tie.xml");
+ std::fs::write(
+ &path,
+ r#"<catalog>
+ <item id="1"><price cur="USD">9.99</price></item>
+ <item id="2"><price cur="EUR">19.99</price></item>
+ <item id="3"><price cur="USD">4.50</price></item>
+ </catalog>"#,
+ )
+ .unwrap();
+
+ let mut shapes = std::collections::BTreeSet::new();
+ for _ in 0..200 {
+ let mut n = 0usize;
+ let mut first = String::new();
+ extract(&path, false, &mut |r| {
+ if n == 0 {
+ let mut keys: Vec<&str> = r.fields.keys().map(|k| k.as_str()).collect();
+ keys.sort_unstable();
+ first = keys.join(",");
+ }
+ n += 1;
+ true
+ })
+ .unwrap();
+ assert_eq!(n, 3, "the record COUNT is stable whichever tag wins");
+ shapes.insert(first);
+ }
+ assert_eq!(
+ shapes,
+ ["cur,text", "id,price,price_cur"]
+ .into_iter()
+ .map(String::from)
+ .collect::<std::collections::BTreeSet<_>>(),
+ "the tie-break became deterministic — replace this test"
+ );
+ }
+}