Skip to content

[AI-4053] Read a workbook row by row with a column and cell limit - #2550

Draft
kanat wants to merge 6 commits into
mainfrom
kanat/ai-4053-xlsx-bounded-read
Draft

kanat wants to merge 6 commits into
mainfrom
kanat/ai-4053-xlsx-bounded-read

Conversation

@kanat

@kanat kanat commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Why

The XLSX reader pads every row with empty cells up to the column of its last value and nothing bounds rows times columns, so a small workbook with a value far to the right of many rows is held as a very large table. Two paths read workbooks inside the router process: the knowledge upload worker, and createResponse, which parsed the file first and refused its format (415) afterwards. Ticket: AI-4053.

How it works

Extract(xlsx)
  readXLSX
    └─ sheetRows: book.Rows(sheet), one row at a time
         ├─ ctx checked per row            -> deadline error
         ├─ row wider than 1,024 columns   -> TooLarge
         └─ sheet over 1,000,000 cells     -> TooLarge

createResponse file
  readDocument
    ├─ extract.Detect(bytes)  (new export)
    ├─ format not in documentFormats  -> 415, file not read
    └─ Extract

Changes

Change Where Test
Row-by-row read with a column cap and a cell cap per sheet, ctx checked per row knowledge/extract/xlsx.go TestAWorkbookWithAValueInItsLastColumnOfEveryRowIsRefusedWithinABudget, TestARowMayBeAsWideAsTheLimitAndNoWider, TestASheetMayHoldAsManyCellsAsTheLimitAndNoMore, TestASheetIsReadOnlyUntilTheDeadline
Ordinary tables read as before same TestAWorkbookOfManyRowsOfOrdinaryWidthIsReadInFull, TestTheCellLimitIsOfOneSheetNotOfTheWorkbook (pass on base too)
Unreadable sheets are still refused as corrupt same TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt (pass on base too)
detect exported as Detect; readDocument checks the format before Extract extract.go, api/documents.go TestAWorkbookIsRefusedAsTheWrongFormatWithoutBeingRead (a workbook the reader would refuse as too large still gets 415)

The knowledge upload path is unchanged: it calls Extract as before and now gets the same limits.

Both caps count the padded width of a row, since that is what is held. excelize's iterator pads one row at a time (rows.go, appendSpace), so a refused row is at most 16,384 cells and is dropped. The values are commented in code: 1,024 columns is sixteen times the 64 the ODT reader keeps of a repeated cell, and a million cells is 16 MiB of cell headers.

Validation

  • go test ./internal/knowledge/... and go test -tags integration ./internal/api/ -run 'TestDocumentsSuite|TestKnowledgeFilesSuite' pass on the branch merged onto current main.
  • The new limit tests fail on the base commit; the two control tests pass there.
  • Mutations of both caps (boundary, removed, changed value), the per-row ctx check, the unreadable-sheet refusals and the format-before-read order each fail a test.

🤖 Generated with Claude Code

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Security review, round 1, head 2fea478.

Checked and fine:

  • The format check runs before the read. Detect is pure over the same bytes that Extract detects again, so a file cannot be one format for the check and another for the read. A zip holding both Word and Excel parts resolves the same way in both calls.
  • The column cap, the cell cap and the per-row deadline check each fail a test when removed (run by me against the extract package).
  • No new place sends an error's text to a caller or a stored row. The sheet-read message is moved, not new.

Not fine: the new limits count only the cells present in a row, and only per sheet, so the reader's work is still not bounded by the size of the file. The specifics are held out of this public thread, because the same behaviour is on main today; they are in the private report to the orchestrator, with the test rows for the fix. This PR does not make it worse, and it does not yet close what AI-4053 asks.

The fix is to bound the sheet's rows and the text it produces per workbook, not per sheet, and to change TestTheCellLimitIsOfOneSheetNotOfTheWorkbook with it.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Reviewed 2fea478 merged onto main 92fcbb8. CI is skipped while the PR is a draft; CI runs at gh pr ready.

Checked and fine:

  • A legitimate workbook reads as before: five workbooks (column-A control of 1,500 rows, 30,000 rows of ordinary width with gaps, blank rows, a hidden sheet, a formula, a 1,000-column sheet, rows and cells without r, a far row) give byte-identical text on main and on this head.
  • createResponse still takes PDF, DOCX and DOC; a workbook is a 415 before it is read. TestDocumentsSuite and TestKnowledgeFilesSuite pass on the merged tree.
  • go test ./internal/knowledge/..., gofmt and both go vet runs pass on the merged tree.
  • Both caps, the per-row deadline check, the call site (sheetRows(ctx, ...), GetRows put back) and the format-before-read order each fail a test when broken (20 mutants).

Blocking:

  • R1.1 [Should fix] the limits still do not bound what the reader holds for a small workbook (inline). Same finding as the earlier security review of this head.
  • R1.2 [Should fix] two branches of sheetRows can be changed without a test failing (inline, with ready test rows).

Ticket, not fixed here:

  • R1.3 [Question] a sheet whose shared strings cannot be read is read as an empty table with no error (same on main). Making it Corrupt is the better rule; it is a behaviour change, so it is its own ticket.
  • R1.4 [Question] the cell cap counts cells, not text. A sheet inside the cap can still produce far more text than a conversation can take in, because cells may repeat one long shared string (same on main). A text budget for the reader belongs in its own ticket.

Answers to the author's questions: keep the Columns() error as a silent end of the sheet (it is what main does) and pin it with the test row in R1.2; 1,024 columns is fine as a width, the total is what needs fixing (R1.1).

iterator.Close()
return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q has a row of %d columns, more than the %d allowed", sheet, len(row), maxSheetColumns))
}
if cells += len(row); cells > maxSheetCells {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 The counts do not bound what a small workbook makes the reader hold. Two gaps, both measured on this head:

  1. An empty row adds 0 to cells, and a row number far down a sheet is iterated as one empty row per number, each appended to rows. After sheetRows returns, sheetPictures (GetPictureCells) makes excelize decode the sheet padded out to its last row and cache it on the book until defer book.Close(). That is tens of MiB held for a sheet of a few hundred bytes, and it is not freed between sheets.
  2. The cap is per sheet (TestTheCellLimitIsOfOneSheetNotOfTheWorkbook pins that). A sheet right at the cap is also cached by excelize, at a few hundred bytes a cell, and the same again for every further sheet. N sheets of a few KB each hold N times that, retained across the loop, so memory grows with the sheet count while the file stays small. Base behaves the same, and this head allocates about twice as much per far-row sheet (the per-row append of empty rows). The ticket's goal is not met yet.

Fix: count a row as max(len(row), 1) toward the cells, so empty rows count, and keep one total for the workbook that readXLSX hands to sheetRows (pass the remaining budget, return the used amount), refusing as TooLarge when it is over. The ticket asked for the workbook, not only the sheet. Size the total from what excelize keeps per cell, not from the 16 B string header in the comment; fix that comment too. Replace TestTheCellLimitIsOfOneSheetNotOfTheWorkbook with: a workbook of many small sheets, each with one far row, is TooLarge; and a workbook of a few sheets of ordinary size still reads in full (control from the main text). Mutate the total (removed, >=) and max(len(row), 1) (back to len(row)).

row, err := iterator.Columns()
if err != nil {
// As in GetRows, a row that cannot be read ends the sheet there.
break

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 Mutant survives: replace this break with return nil, fail(Corrupt, XLSX, err) and every test passes. It is not equivalent. A workbook whose xl/sharedStrings.xml is cut off makes the first Columns() fail; sheetPictures does not read shared strings, so on main and on this head the answer is no error and an empty table. Test row (add to ExtractSuite, next to TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt): take s.workbook(3, 1), replace the part xl/sharedStrings.xml with <sst><si><t>cut, Extract -> NoError, and Empty(strings.TrimSpace(read.Pages[0].Text)), with a comment that this is the behaviour of main, kept on purpose (R1.3 is the ticket to change it). I ran this row: it passes on head and fails under the mutant. continue instead of break is equivalent (every later row fails the same way).

}
rows = append(rows, row)
}
if err := iterator.Close(); err != nil {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 (second mutant) Replacing this Close() check with a bare iterator.Close() passes every test: the row past the last row a sheet has is still Corrupt, because sheetPictures fails on it later, only with a different message. Test row: in TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt, for the case "a row past the last row a sheet has", also assert s.Contains(err.Error(), sheet "Sheet1" cannot be read) and s.NotContains(err.Error(), "pictures"). Checked: passes on head (extract: corrupt xlsx: sheet "Sheet1" cannot be read: row number exceeds maximum limit), fails under the mutant. Not calling Close() at all on the success path is the same mutant.

This branch has not been deployed

No deployments
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.

1 participant