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): read a headerless number sheet as a table, not a capped document (#2720) (#2723)

Jake Elbirt5180b22905d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 99b1593e0..a1bb8a10d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -207,6 +207,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is the index name before the dataset slug", which read as a wrong `--prefix`
(#2670).
+- `xerj autoindex` reads a spreadsheet sheet with no header row and no text,
+ such as an all-numbers export, as a table: one record per row, columns named
+ `col_A`, `col_B` and so on, values keeping their cell types. It
+ used to index such a sheet as one text document, which the 4,096-section cap
+ cut off: in the #2720 reproduction a 200,000-row sheet kept rows up to
+ 72,724. A sheet whose first 20 rows hold a text cell, uneven rows, one column
+ or only one row is still indexed as a document (#2720).
+- A `--no-graph` rerun no longer aborts when a file gains a part the committed
+ generation has no dataset for, for example a new or renamed spreadsheet
+ sheet, or a sheet that gains a header row and moves from the document
+ reading to the table reading. The file is set aside with a rebuild message
+ (exit 3) and every other file is still indexed. It used to stop the whole
+ run with "frozen assignment has 0 matches for group" (#2720).
+
## [1.0.0-rc.100] - 2026-10-26
**rc.100: faster autoindex and search, shaped by your field reports.** This
diff --git a/engine/crates/xerj-autoindex/src/extract/xlsx.rs b/engine/crates/xerj-autoindex/src/extract/xlsx.rs
index 2b522ac16..f56b4d596 100644
--- a/engine/crates/xerj-autoindex/src/extract/xlsx.rs
+++ b/engine/crates/xerj-autoindex/src/extract/xlsx.rs
@@ -14,7 +14,10 @@
//! report title, a "prepared by" line) are not part of the table and are not
//! indexed. A sheet with no such row — a form, a key/value assumptions tab,
//! free-form notes — is indexed as a document instead: one line per row with
-//! cells joined by ` | `, so its text stays searchable.
+//! cells joined by ` | `, so its text stays searchable. The exception is a
+//! sheet with no text at all whose scanned rows fill the same two or more
+//! columns (an all-numbers export, #2720): it is a table whose columns are
+//! named by letter, `col_A`, `col_B`, one typed record per row.
//!
//! A cell merged DOWN over several rows (a pandas MultiIndex export, a
//! category label beside its group of line items) stores its value only in
@@ -910,6 +913,26 @@ fn is_header_candidate(row: &Row) -> bool {
&& row.cells.iter().any(|c| c.kind == Kind::Text)
}
+/// #2720: rows with no header among them that still form a table: at least
+/// two rows, each filling the same two or more columns, and not one text cell.
+/// A number grid read as a document loses its types and, past the section
+/// cap, most of its rows; a text cell anywhere keeps the document reading,
+/// since forms, key/value tabs and notes all hold text.
+fn is_headerless_grid(rows: &[Row]) -> bool {
+ let Some(first) = rows.first() else {
+ return false;
+ };
+ rows.len() >= 2
+ && first.cells.len() >= 2
+ && rows.iter().all(|r| {
+ r.cells
+ .iter()
+ .map(|c| c.col)
+ .eq(first.cells.iter().map(|c| c.col))
+ && r.cells.iter().all(|c| c.kind != Kind::Text)
+ })
+}
+
/// Index of the header row among the rows read so far, once it can be told
/// (a header needs a row after it). A candidate followed by a WIDER candidate
/// is a title line (`Prepared by | Finance`) above the real header and is
@@ -983,6 +1006,16 @@ fn group_prefixes(upper: &Row, header: &Row, merges: &[Merge]) -> HashMap<u32, S
}
impl Table {
+ /// A table without a header row (#2720): every column takes the
+ /// `col_{letter}` name an unheaded column already gets.
+ fn headerless() -> Self {
+ Table {
+ names: HashMap::new(),
+ header: Vec::new(),
+ emitted: 0,
+ }
+ }
+
/// `upper` is the row read just before the header, if any.
fn new(header: &Row, upper: Option<&Row>, merges: &[Merge]) -> Self {
let prefixes = upper
@@ -1061,12 +1094,19 @@ impl SheetState {
}
} else if rows.len() >= HEADER_SCAN_ROWS {
let rows = std::mem::take(rows);
- self.mode = Mode::Doc {
- body: String::new(),
- last_row: 0,
+ self.mode = if is_headerless_grid(&rows) {
+ Mode::Table(Table::headerless())
+ } else {
+ Mode::Doc {
+ body: String::new(),
+ last_row: 0,
+ }
};
for r in rows {
- self.push(r, sink, stats);
+ let flow = self.push(r, sink, stats);
+ if flow != Flow::Continue {
+ return flow;
+ }
}
}
Flow::Continue
@@ -1139,6 +1179,17 @@ impl SheetState {
fn finish(mut self, stem: &str, sink: Sink, stats: &mut ExtractStats) -> bool {
if let Mode::Probe(rows) = &mut self.mode {
let rows = std::mem::take(rows);
+ if is_headerless_grid(&rows) {
+ self.mode = Mode::Table(Table::headerless());
+ for r in rows {
+ match self.push(r, sink, stats) {
+ Flow::Continue => {}
+ Flow::NextSheet => break,
+ Flow::Stop => return false,
+ }
+ }
+ return true;
+ }
self.mode = Mode::Doc {
body: String::new(),
last_row: 0,
@@ -1664,7 +1715,8 @@ mod tests {
}
/// A number-only grid has no header row anywhere in the scan window, and a
- /// header-like row past the window does not count.
+ /// header-like row past the window does not count: it is a data row of the
+ /// unnamed table the grid is read as (#2720).
#[test]
fn a_header_is_only_looked_for_in_the_first_rows() {
let dir = tempfile::tempdir().unwrap();
@@ -1683,13 +1735,12 @@ mod tests {
));
let path = book(&dir, &[("Grid", rows)], &[], false);
let (stats, recs) = run(&path);
- assert_eq!(stats.records, 1);
- assert_eq!(recs[0].group, None);
- let body = recs[0].fields["body"].as_str().unwrap();
- assert!(
- body.starts_with("1 | 2\n1 | 2") && body.ends_with("x | y\n3 | 4"),
- "{body}"
- );
+ assert_eq!(stats.records, HEADER_SCAN_ROWS as u64 + 2);
+ assert!(recs.iter().all(|r| r.group.as_deref() == Some("Grid")));
+ assert_eq!(fields(&recs[0]), json!({"col_A": 1, "col_B": 2}));
+ let late = HEADER_SCAN_ROWS;
+ assert_eq!(fields(&recs[late]), json!({"col_A": "x", "col_B": "y"}));
+ assert_eq!(fields(&recs[late + 1]), json!({"col_A": 3, "col_B": 4}));
}
#[test]
@@ -2327,4 +2378,108 @@ mod tests {
assert_eq!(names(Some(10), large), plain);
assert_eq!(names(None, large), plain);
}
+
+ /// #2720: a sheet of only numbers, booleans and dates with no header row
+ /// (an all-numbers export) is a table with columns named by letter, one
+ /// typed record per row, not one text document the section cap cuts off.
+ #[test]
+ fn a_headerless_number_grid_is_a_table_named_by_column_letter() {
+ let dir = tempfile::tempdir().unwrap();
+ let total = HEADER_SCAN_ROWS as u32 + 5;
+ let rows: Vec<String> = (1..=total)
+ .map(|i| {
+ row(
+ i,
+ &[
+ n(&format!("A{i}"), &i.to_string()),
+ n(&format!("B{i}"), "2.5"),
+ b(&format!("C{i}"), i.is_multiple_of(2)),
+ ],
+ )
+ })
+ .collect();
+ let path = book(&dir, &[("Readings", rows)], &[], false);
+ let (stats, recs) = run(&path);
+ assert_eq!(stats.records, total as u64);
+ assert!(!stats.truncated);
+ assert!(recs
+ .iter()
+ .all(|r| r.group.as_deref() == Some("Readings") && r.origin == FieldOrigin::Data));
+ assert_eq!(recs[0].locator, "Readings!r1");
+ assert_eq!(
+ fields(&recs[0]),
+ json!({"col_A": 1, "col_B": 2.5, "col_C": false})
+ );
+ let last = recs.last().unwrap();
+ assert_eq!(last.locator, format!("Readings!r{total}"));
+ assert_eq!(
+ fields(last),
+ json!({"col_A": total, "col_B": 2.5, "col_C": total.is_multiple_of(2)})
+ );
+ }
+
+ /// A grid shorter than the scan window is read the same way once the sheet
+ /// ends (#2720).
+ #[test]
+ fn a_short_headerless_number_grid_is_a_table() {
+ let dir = tempfile::tempdir().unwrap();
+ let rows = vec![
+ row(1, &[n("A1", "10"), n("B1", "20")]),
+ row(2, &[n("A2", "30"), n("B2", "40")]),
+ row(3, &[n("A3", "50"), n("B3", "60")]),
+ ];
+ let path = book(&dir, &[("Short", rows)], &[], false);
+ let (stats, recs) = run(&path);
+ assert_eq!(stats.records, 3);
+ assert!(recs.iter().all(|r| r.group.as_deref() == Some("Short")));
+ assert_eq!(fields(&recs[2]), json!({"col_A": 50, "col_B": 60}));
+ }
+
+ /// Only an even grid of non-text cells is read as an unnamed table
+ /// (#2720): a text cell, uneven rows, a single column or a single row
+ /// keep the document reading meant for forms, key/value tabs and notes.
+ #[test]
+ fn text_uneven_or_single_column_sheets_stay_documents() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = book(
+ &dir,
+ &[
+ (
+ "WithText",
+ vec![
+ row(1, &[n("A1", "1"), n("B1", "2")]),
+ row(2, &[n("A2", "3"), inl("B2", "pending")]),
+ ],
+ ),
+ (
+ "Uneven",
+ vec![
+ row(1, &[n("A1", "1"), n("B1", "2")]),
+ row(2, &[n("A2", "3"), n("B2", "4"), n("C2", "5")]),
+ ],
+ ),
+ (
+ "Gap",
+ vec![
+ row(1, &[n("A1", "1"), n("B1", "2")]),
+ row(2, &[n("A2", "3"), n("C2", "4")]),
+ ],
+ ),
+ (
+ "OneColumn",
+ vec![row(1, &[n("A1", "1")]), row(2, &[n("A2", "2")])],
+ ),
+ ("OneRow", vec![row(1, &[n("A1", "1"), n("B1", "2")])]),
+ ],
+ &[],
+ false,
+ );
+ let (stats, recs) = run(&path);
+ assert_eq!(stats.records, 5);
+ assert!(
+ recs.iter().all(|r| r.group.is_none()),
+ "every sheet joins the document dataset: {:?}",
+ recs.iter().map(|r| &r.locator).collect::<Vec<_>>()
+ );
+ }
}
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index 528ab8161..2ff782b65 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -7524,3 +7524,103 @@ fn dry_run_refuses_a_changed_option_like_the_real_run() {
assert_eq!(endpoint.data_bulk_requests(), bulks);
assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);
}
+
+/// #2720: a workbook rerun whose edit gives it a part the frozen datasets do
+/// not have cannot join them. That file is set aside with the rebuild command
+/// and every other file is still indexed; it used to abort the whole run with
+/// "frozen assignment has 0 matches for group", as if the journal were corrupt.
+fn sheet_edit_is_set_aside(edited: &[(&str, Vec<Vec<String>>)], part: &str) {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());
+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let endpoint = HttpEndpoint::start();
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+ let book = corpus.path().join("book.xlsx");
+ let write = |sheets: &[(&str, Vec<Vec<String>>)]| {
+ let rows: Vec<Vec<Vec<&str>>> = sheets
+ .iter()
+ .map(|(_, rows)| {
+ rows.iter()
+ .map(|row| row.iter().map(String::as_str).collect())
+ .collect()
+ })
+ .collect();
+ let slices: Vec<Vec<&[&str]>> = rows
+ .iter()
+ .map(|rows| rows.iter().map(Vec::as_slice).collect())
+ .collect();
+ let named: Vec<(&str, &[&[&str]])> = sheets
+ .iter()
+ .zip(&slices)
+ .map(|((name, _), rows)| (*name, rows.as_slice()))
+ .collect();
+ crate::phase_a_grouping_tests::write_xlsx(&book, &named);
+ };
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();
+ write(&[("Sales", sales_rows(false))]);
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);
+
+ write(edited);
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n2,beta\n").unwrap();
+ let code = run_index(config.clone()).unwrap_or_else(|error| panic!("{error:#}"));
+ assert_eq!(code, 3, "a set-aside file is completed-with-junk");
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);
+
+ let catalog = endpoint.catalog_docs();
+ let junk: Vec<&Value> = catalog
+ .iter()
+ .filter(|doc| doc["doc_kind"] == "file" && doc["status"] == "junk")
+ .collect();
+ assert_eq!(junk.len(), 1, "{junk:#?}");
+ assert_eq!(
+ junk[0]["path"].as_str().or(junk[0]["rel"].as_str()),
+ Some("book.xlsx")
+ );
+ let reason = junk[0]["reason"].as_str().unwrap();
+ for needle in [
+ format!("part {part:?} of this file is new or changed shape"),
+ "This file was not indexed; every other file in this pass still is".to_string(),
+ "rebuild".to_string(),
+ ] {
+ assert!(
+ reason.contains(&needle),
+ "{needle:?} missing from: {reason}"
+ );
+ }
+ let docs = serde_json::to_string(&endpoint.data_docs()).unwrap();
+ assert!(docs.contains("beta"), "the edited CSV is still indexed");
+ assert!(
+ !docs.contains("region 59"),
+ "the set-aside workbook's old document is dropped with this generation"
+ );
+}
+
+/// 60 rows of text and numbers with no header: a document, not a table.
+fn sales_rows(header: bool) -> Vec<Vec<String>> {
+ let mut rows = Vec::new();
+ if header {
+ rows.push(vec!["region".to_string(), "amount".to_string()]);
+ }
+ rows.extend((0..60).map(|i| vec![format!("region {i}"), (i * 10).to_string()]));
+ rows
+}
+
+/// A header row turns the sheet from a document into a table.
+#[test]
+fn a_sheet_that_changes_shape_is_set_aside_not_fatal() {
+ sheet_edit_is_set_aside(&[("Sales", sales_rows(true))], "Sales");
+}
+
+/// A new table sheet has no frozen dataset either.
+#[test]
+fn a_new_sheet_in_an_indexed_workbook_is_set_aside_not_fatal() {
+ let q4 = vec![
+ vec!["region".to_string(), "amount".to_string()],
+ vec!["north".to_string(), "5".to_string()],
+ ];
+ sheet_edit_is_set_aside(&[("Sales", sales_rows(false)), ("Q4", q4)], "Q4");
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index d6799fb60..777325019 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -5161,7 +5161,7 @@ mod phase_a_grouping_tests {
/// A minimal Excel workbook: inline-string text, numbers, and style 1 =
/// built-in date format 14 so a serial reads as a date.
- fn write_xlsx(path: &Path, sheets: &[(&str, &[&[&str]])]) {
+ pub(super) fn write_xlsx(path: &Path, sheets: &[(&str, &[&[&str]])]) {
use std::io::Write;
let cell = |r: usize, c: usize, v: &str| {
let at = format!("{}{}", (b'A' + c as u8) as char, r + 1);
diff --git a/engine/crates/xerj-autoindex/src/reconcile_plan.rs b/engine/crates/xerj-autoindex/src/reconcile_plan.rs
index 49719464a..fd6523e07 100644
--- a/engine/crates/xerj-autoindex/src/reconcile_plan.rs
+++ b/engine/crates/xerj-autoindex/src/reconcile_plan.rs
@@ -580,6 +580,20 @@ fn retained_slug(
.iter()
.filter(|(assigned_group, _)| assigned_group == group)
.collect::<Vec<_>>();
+ // #2720: no match for a file the journal assigned is this file's content,
+ // not the journal: a new or renamed sheet, an edit (a sheet that gains a
+ // header row) or a reader change can give it a part the frozen datasets
+ // do not have. The file is set aside like a family change. An empty
+ // assignment list or two matches would be a contradictory journal.
+ if matches.is_empty() && !owner.assignments.is_empty() {
+ let part = match group {
+ Some(group) => format!("part {group:?} of this file"),
+ None => "the document part of this file".to_string(),
+ };
+ return Err(AssignFailure::File(format!(
+ "{part} is new or changed shape since it was indexed, so it has no dataset in the committed generation."
+ )));
+ }
if matches.len() != 1 {
return Err(AssignFailure::Fatal(anyhow::anyhow!(
"frozen assignment has {} matches for group {:?}",