8000 feat(autoindex): extract Excel workbooks (.xlsx), one dataset per sheet by thomas-villani · Pull Request #1120 · xerj-org/xerj · GitHub
[go: up one dir, main page]

Skip to content

feat(autoindex): extract Excel workbooks (.xlsx), one dataset per sheet - #1120

Closed
thomas-villani wants to merge 4 commits into
xerj-org:mainfrom
thomas-villani:feat/xlsx-extractor
Closed

thomas-villani wants to merge 4 commits into
xerj-org:mainfrom
thomas-villani:feat/xlsx-extractor

Conversation

@thomas-villani
Copy link
Copy Markdown
Contributor

Written by an AI coding agent (Claude Code, Claude Opus 5.5), run by @thomas-villani, who has reviewed this change.

Draft: stacked on #1117. This branch is built on feat/pptx-extractor, so until #1117 merges this diff also shows its two commits. The XLSX work is the last two commits: 84a288ba (shared OPC helpers) and 2d81c444 (the extractor). I'll rebase and mark this ready once #1117 lands.

What this changes, and why

Since #1114, autoindex recognizes a .xlsx but junks it with "export each sheet as CSV". Spreadsheets are where data-science and business/finance users keep their data. An exported CSV also loses what the workbook knows: which numbers are dates, which are booleans, and which sheet a row came from.

This PR adds extract/xlsx.rs and a Family::Xlsx. It follows the CSV/SQLite record model, not the DOCX one: a workbook is tables, not prose.

Record shape:

Dataset One per worksheet: RawRecord.group = sheet name, as a SQLite table. The same sheet schema in several workbooks (e.g. q1.xlsx, q2.xlsx) clusters into one dataset.
Record One per row under the header, keyed by the header cells. Names are sanitized and deduplicated the way CSV does it; columns with no header are col_<letter>. FieldOrigin::Data.
Locator <sheet>!r<row>, using Excel's own row number.

Values keep their stored type:

  • Numbers and booleans stay JSON numbers and booleans.
  • A formula contributes its cached value. Error cells, and formulas with no cached value, are absent.
  • A number whose cell format is a date format becomes an ISO-8601 string. Inference then elects date with real min/max ranges, instead of long over serials like 45839. This matters for /_ask (agents: POST /_ask + xerj_plan MCP tool — prompt in, validated DSL out #1056), which plans from those ranges.
  • Both the 1900 and the 1904 date systems are handled, including the fictitious 1900-02-29.
  • Time-only formats become HH:MM:SS. Elapsed durations ([h]:mm) and percents stay numbers.

Header detection. Real sheets often have a title above the table.

  • The header is the first of the first 20 non-empty rows that has two or more cells, holds text and no numbers or booleans, and is not followed by a wider row of the same kind.
  • Title lines above it ("Q3 Sales Report", "Prepared by | Finance") are skipped. A repeated header row is dropped.
  • A sheet with no such row (a form, a key/value assumptions tab, notes) is indexed as a document: title "<file> — <sheet>", a sheet field, and a body with one line per row and cells joined by |. Its text stays searchable.
  • So one workbook can feed both a data dataset and the document dataset. FileAssignment.assignments already routes records by group, and this is covered by a planner test.

Bounds:

  • Workbook, relationships, styles and shared strings are held whole, with a 64 MiB cap per part.
  • Worksheets are streamed row by row: 1 GiB per sheet and 2 GiB per container.
  • A document sheet keeps at most 16 MiB of text.
  • Any cap sets ExtractStats.truncated.

Wiring:

  • Family::Xlsx is not in is_document, because its rows are data.
  • It is sniffed from xl/workbook.xml.
  • When sampling, dispatch passes a 500-row cap per sheet, like SQLite's per-table cap (sample_limit_bytes returns Some(1)).
  • It is a grouped family in scan_file, in the Data band in both band functions, and not timeable in exact_scan_bytes.
  • unsupported_document_advice drops xlsx, and now tells .xlsb and .ods owners to save as .xlsx.

Shared helpers (84a288ba). The OPC container helpers from #1117 move into extract/opc.rs instead of being copied. Two changes beyond the move:

  • Budget::stream charges the budget for the bytes actually read, so worksheets can be streamed.
  • attr now resolves entity references, so a sheet named P&L (stored as P&amp;L) reads correctly.

Evidence

All of the following ran in a rust:latest Linux container (cargo 1.98.1). The crate's test build does not compile on Windows; see #1114.

cargo test -p xerj-autoindex --lib
test result: ok. 1189 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 60.76s

That is 1170 on #1117's branch, plus 19 new tests:

  • 17 extract::xlsx tests:
    • the title row skipped and typed records
    • date, time, percent and duration formats in both date systems
    • serial-date edge cases
    • format-code classification
    • tab order, unescaped sheet names and skipped chart sheets
    • the fallback when the workbook part is missing
    • form sheet → document
    • the 20-row header window
    • rich text, phonetic runs, entities, formulas and errors
    • header sanitizing, dedup, unheaded columns and repeated headers
    • a title line above a wider header
    • the per-sheet sample cap
    • an empty workbook is junk
    • both truncation caps
    • column letters
    • the logical-name title
  • 1 extract::opc streaming-budget test.
  • 1 planner test, workbooks_plan_a_dataset_per_sheet_schema_and_documents_for_form_sheets. It runs two quarterly workbooks plus a README through build_phase_a. The result is one Sales dataset with Month elected date (from 2026-01-01) and Revenue elected double. The form sheets land in the docs dataset next to the README, and q1.xlsx is assigned to both datasets.

Fail-before for the document-title test: under durable preparation the extractor reads a snapshot blob, so the title must come from Sniffed::logical_name. With dispatch passing the blob path, the test fails:

left: String("00000000 — Notes")
right: String("q1 — Notes")

The same bug existed in #1117's deck-title fallback; it is fixed there in ac108d0e.

Real-file check. I wrote workbooks with openpyxl and pandas and ran them through sniff() and xlsx::extract with a temporary test that is not committed. Output, trimmed:

== orders.xlsx sniffed family=Xlsx kind=None
orders!r2 group=Some("orders") origin=Data {"order_id":1001,"placed_at":"2026-01-05T10:00:00","amount":19.99,"customer":"Ann"}
orders!r4 group=Some("orders") origin=Data {"order_id":1003,"placed_at":"2026-02-01","amount":120.25,"customer":"Cy"}
== report.xlsx sniffed family=Xlsx kind=None
Sales!r4 group=Some("Sales") origin=Data {"Region":"EMEA","Month":"2026-07-01","Revenue":1250000,"Margin":0.21,"Closed":true,"Updated":"2026-08-02T09:30:00"}
Sales!r6 group=Some("Sales") origin=Data {"Region":"P&L adj.","Month":"2026-08-01","Revenue":-1200,"Margin":0,"Closed":true,"Updated":"2026-09-01"}
Assumptions-s0 group=None origin=Extractor {"sheet":"Assumptions","title":"report — Assumptions","body":"Discount rate | 0.08\nTax rate | 0.21\n\nOwner | Finance team"}
Lookup!r2 group=Some("Lookup") origin=Data {"code":"A","label":"Active"}

In this run:

  • The title row "Q3 Sales Report" is skipped.
  • Margin (formatted 0.00%) keeps its stored fraction.
  • The hidden Lookup sheet is indexed.

A column that mixes date-only and date-time strings (Updated) is safe: coerce_to_date parses each value's own encoding and normalizes it to RFC 3339.

Checks

  • cargo fmt -p xerj-autoindex -- --check: clean. Only this crate is touched.
  • cargo clippy -p xerj-autoindex --all-targets -- -D warnings: clean on Linux. CI runs it workspace-wide; I ran it on this crate only.
  • Scoped release build: cargo build --release -j 32 -p xerj-autoindex finished (2m 04s, Linux).
  • cargo test -p xerj-autoindex --lib: 1189 passed, 0 failed. The intermediate commit 84a288ba alone passes the extract:: tests (264 passed).
  • ES-YAML conformance suite: not run. This change only touches autoindex extraction, not the engine or the API.
  • Docs: not updated. landing/llms.txt and the README format lists would gain .pptx/.xlsx. I'll send that as one docs PR after this and feat(autoindex): extract PowerPoint decks (.pptx), one record per slide #1117 land (one-open-PR rule on llms.txt).

Not run:

  • The integration tests under crates/xerj-autoindex/tests/.
  • An end-to-end xerj autoindex run against a server.
  • A workbook saved by Excel itself, as opposed to openpyxl or pandas.

Known limits

These are deliberate for a first version:

  • One table per sheet. A second table lower on the same sheet becomes rows under the first header.
  • Merged cells are not expanded.
  • Stored values, not displayed ones. A cell showing 21% is 0.21.
  • A two-column, all-text form sheet (e.g. Name | John) reads as a table with odd field names. A form with any numeric value is correctly treated as a document.
  • Formulas without a cached value are absent. openpyxl and pandas write formulas without one; Excel and LibreOffice store it on save.
  • Chart sheets are skipped. .xlsb is still unsupported.
  • Financial statements (P&L, balance sheets) are read as ordinary tables. They may deserve dedicated handling later; nothing here precludes it.

Provenance

  • Written by: AI agent (Claude Code, Claude Opus 5.5), run by @thomas-villani, who has reviewed it.
  • Verified (commands run, output observed):
    • The test, clippy, fmt and release-build results above.
    • The fail-before output above.
    • The openpyxl and pandas extraction output above.
  • Assumed (not tested):
    • That Excel-saved workbooks match the ECMA-376 layout these fixtures and openpyxl use: shared strings, cellXfs→numFmtId date styles, and cached <v> beside <f>.
    • That the header heuristic is right for most real sheets. I have no corpus measurement of how often it picks the wrong row.
    • That rendering header-less sheets as documents beats skipping them for retrieval. Not measured.

🤖 Generated with Claude Code

Motivation: since xerj-org#1114, autoindex recognizes a .pptx but junks it as an
unsupported document. Decks are a common carrier of business content
(reviews, plans, figures) and, like PDF/DOCX, are exactly what grep cannot
read, which is where the document-folder recipe measured XERJ's largest
margin over grep (6/7 vs 0/7 on PDF/DOCX-only answers).

What it does (extract/pptx.rs, new):
- One record per slide: `title` (deck title = first slide title, else the
  file stem), `slide` (1-based position in p:sldIdLst — the number
  PowerPoint shows; part names do not change when slides are reordered),
  `slide_title` (title/ctrTitle placeholder), `body`; a long slide is
  sectioned like a PDF page (`section`, locator `slide{n}-s{k}`).
  Falls back to ppt/slides/slideN.xml in numeric order when the
  presentation part or its rels are unusable.
- Text is read shape by shape from DrawingML: `a:p` paragraphs, `a:br`
  breaks; tables as one line per row with ` | `-joined cells, so a value
  keeps its row and column (DOCX tables currently lose this).
- Speaker notes, reached through the slide's notesSlide relationship, are
  appended to the body under "Speaker notes:" so both BM25 and the
  semantic field see them.
- Skipped: dt/ftr/hdr/sldNum/sldImg placeholders and `a:fld` field text —
  boilerplate repeated on every slide.
- Matching is on local names, so strict-OOXML namespaces read the same.
- Bounds: 32 MiB per part, 256 MiB decompressed per container, 64 MiB of
  extracted text, and MAX_RECORDS_PER_FILE. Hitting any of them sets
  `truncated` (reported, not silent). A deck with no text is junk.

Wiring: Family::Pptx (as_str "pptx", is_document), sniffed from
ppt/presentation.xml in zip_container_kind; dispatch in extract/mod.rs;
SourceAndDocs band in both order.rs band functions; full-read family in
estimate::exact_scan_bytes; whole-file size cap in scan_file. "pptx" is
removed from unsupported_document_advice.

Evidence (rust:latest container, cargo 1.98.1, Linux):
- 7 new extract::pptx tests (order vs part names, numeric fallback,
  titles/tables/notes/placeholder skipping, empty slides and decks,
  sectioning, decompression budget, OPC target resolution) pass; the
  updated sniff test asserts ppt/presentation.xml -> Family::Pptx.
- cargo test -p xerj-autoindex --lib: 1167 passed, 0 failed, 2 ignored.
- cargo clippy -p xerj-autoindex --all-targets -- -D warnings: clean.
- A deck written by python-pptx (real PowerPoint template parts, slides
  reordered in sldIdLst) sniffed as Pptx and extracted 3 records in
  display order with the table rows and speaker notes intact (temporary
  probe test, not committed).

Not covered: a deck saved by PowerPoint itself; an end-to-end
`xerj autoindex` run against a server. Charts, SmartArt and images
contribute no text.

Written by an AI coding agent (Claude Code, Claude Opus 5.5), run and
reviewed by Tom Villani (@thomas-villani).
… blob

Motivation: under durable preparation (`--no-graph`), `sync_executor`
extracts a sealed snapshot blob (`prepared/00000000`) and carries the
file's own name only in `Sniffed::logical_name`. The PPTX extractor fell
back to `path.file_stem()` for a deck with no title placeholder, so such
a deck was titled "00000000" — the xerj-org#722 failure class that
`extract_as_document_with_name` and the stub name card already guard
against.

Fix: `pptx::extract` takes the logical name, and dispatch passes
`sn.logical_name` (falling back to `path`), as `code.rs` does.

Evidence: new test `an_untitled_deck_is_titled_from_the_logical_name_not_the_blob`
sniffs a deck stored as `00000000` with logical name `decks/kickoff.pptx`
and extracts it through `extract::extract`. With dispatch passing `path`
(the old behaviour) it fails with left: "00000000", right: "kickoff";
with the fix it passes. `cargo test -p xerj-autoindex --lib`: 1170
passed, 0 failed (Linux container); clippy -D warnings and fmt clean.
Motivation: the XLSX extractor reads the same Open Packaging Conventions
container as PPTX — a decompression budget across many parts, `.rels`
relationship parsing and target resolution. Rather than copy them, move
them from `extract/pptx.rs` into `extract/opc.rs`.

Changes beyond the move:
- `Budget::stream` hands a part to a closure as a bounded reader and
  charges the budget for the bytes actually pulled through it, so a
  worksheet can be parsed row by row instead of held whole. `read` is
  now `stream` + `read_to_end`; its behaviour is unchanged.
- `attr` resolves entity references (`normalized_value`) instead of
  returning the raw bytes, so a sheet named `P&L` (stored `P&amp;L`) or
  a relationship target with an escaped character reads correctly. A
  value that fails to unescape is still returned raw.

Evidence: the moved `relationship_targets_resolve_like_opc` test and a
new `streaming_charges_only_what_was_read_and_flags_a_cap_hit` test in
`extract::opc`; every existing `extract::pptx` test passes unchanged.
Motivation: since xerj-org#1114 a `.xlsx` is recognised but junked with "export
each sheet as CSV". Spreadsheets are where data-science and
business/finance users keep their data, and an exported CSV loses what
the workbook knows: which numbers are dates, booleans, and which sheet a
row came from.

Record model — CSV/SQLite, not DOCX:
- Each worksheet is its own group (`RawRecord.group` = sheet name, like a
  SQLite table), so it clusters into its own data dataset; the same sheet
  schema in several workbooks (q1.xlsx, q2.xlsx) merges into one.
- Each row under the header is one record keyed by the header cells
  (`sanitize_field_name`, `_2` dedup as in CSV; unheaded columns are
  `col_<letter>`). Locator `<sheet>!r<row>` uses Excel's own row number.
  `FieldOrigin::Data`.
- Typed values: numbers and booleans as JSON numbers/booleans; formula
  cells contribute their cached value; error cells and formulas with no
  cached value are absent. A number whose cell style (`xl/styles.xml`
  cellXfs -> numFmt) is a date format becomes an ISO-8601 string, so
  inference elects `date` with real min/max ranges instead of `long`
  over serials like 45839. Handles the 1900 and 1904 date systems and the
  fictitious 1900-02-29; time-only formats become `HH:MM:SS`; elapsed
  durations (`[h]:mm`) and percents stay numbers.

Header detection (a sheet is not always a clean table):
- The header is the first of the first 20 non-empty rows with >= 2
  cells, some text, no numbers/booleans, that is not followed by a wider
  row of the same kind. Title rows above it ("Q3 Sales Report",
  "Prepared by | Finance") are skipped; repeated header rows are dropped.
- A sheet with no such row (a form, a key/value assumptions tab, notes)
  is indexed as a document: `title` "<file> — <sheet>", `sheet`, body one
  line per row with cells joined by ` | `, blank sheet rows as paragraph
  breaks. One workbook can therefore feed a data dataset and the
  document dataset; `FileAssignment.assignments` already routes by group.

Bounds: workbook/rels/styles/shared strings are held whole under a 64 MiB
per-part cap; worksheets are streamed row by row (1 GiB per sheet, 2 GiB
per container); a document sheet keeps at most 16 MiB of text. Hitting
any cap sets `ExtractStats.truncated`.

Wiring: `Family::Xlsx` (not `is_document`: rows are data), sniffed from
`xl/workbook.xml`; dispatch passes the logical name for document titles
and a 500-row per-sheet cap when sampling (like SQLite's per-table cap,
`sample_limit_bytes` -> Some(1)); grouped family in `scan_file`; Data
band in both band functions; not timeable in `exact_scan_bytes`.
`unsupported_document_advice` drops `xlsx` and now tells `.xlsb`/`.ods`
owners to save as `.xlsx`.

Known limits: one table per sheet; merged cells not expanded; stored
values, not displayed ones (a cell showing 21% is 0.21); a two-column
all-text form sheet reads as a table; chart sheets skipped.

Evidence (Linux container, cargo 1.98.1):
- 17 new `extract::xlsx` tests plus a planner test
  `workbooks_plan_a_dataset_per_sheet_schema_and_documents_for_form_sheets`
  (two workbooks -> one `Sales` dataset with `Month` elected `date`,
  form sheets in the docs dataset, one file assigned to both).
- The logical-name title test fails with "00000000 — Notes" when
  dispatch passes the blob path, and passes with the fix.
- `cargo test -p xerj-autoindex --lib`: 1189 passed, 0 failed, 2 ignored.
- Workbooks written by openpyxl and pandas extracted as expected.
@cla-bot
cla-bot Bot commented Oct 2, 2026
Copy link
Copy Markdown

Thanks for this contribution — we'd like to merge it.

Before we can, we need a signed Contributor License Agreement from: @thomas-villani

It is a one-time thing per contributor, not per pull request. Read CLA.md, then open a small pull request adding your GitHub username to .contributors — that pull request is your signature, since it is made from your own account.

Once it is merged, comment @cla-bot check here and this check will go green. If you believe you are already covered, comment @cla-bot check and it will re-verify.

@xerj-org
xerj-org commented Oct 3, 2026
Copy link
Copy Markdown
Owner

The stack parent #1117 has landed, so this is rebased onto main as #1124 (same two commits, your authorship preserved) — the fork branch can't be pushed to from here. Thank you for the contribution!

@thomas-villani
thomas-villani deleted the feat/xlsx-extractor branch October 4, 2026 01:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0