From 2b60db53853ce5e50a5674df43f88196561548a3 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:13:19 -0500 Subject: [PATCH 01/17] AI-4053: Read a workbook row by row with a column and cell limit Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/documents.go | 12 +++-- .../internal/knowledge/extract/extract.go | 9 ++-- .../internal/knowledge/extract/xlsx.go | 53 ++++++++++++++++++- 3 files changed, 65 insertions(+), 9 deletions(-) diff --git a/acceleration/internal/api/documents.go b/acceleration/internal/api/documents.go index 82a736b291..720a8cfe05 100644 --- a/acceleration/internal/api/documents.go +++ b/acceleration/internal/api/documents.go @@ -122,14 +122,20 @@ func (s *Server) readDocument(ctx context.Context, found *session.Session, sourc if retry { return sentDocument{file: sandbox.File{Name: name, MIME: http.DetectContentType(data), Data: data}, sha: hex.EncodeToString(digest[:])}, nil } - read, err := s.documents.Extract(ctx, name, data) + // A format that is refused is refused before it is read: reading a workbook is work the + // person's file has no use for. + format, err := extract.Detect(data) if err != nil { return sentDocument{}, documentFailure(err) } - mime, accepted := documentFormats[read.Format] + mime, accepted := documentFormats[format] if !accepted { return sentDocument{}, newAPIError(ErrorTypeUnsupportedMediaType, - fmt.Sprintf("the file is %s: a PDF or a Word document (DOCX or DOC) can be sent", read.Format)) + fmt.Sprintf("the file is %s: a PDF or a Word document (DOCX or DOC) can be sent", format)) + } + read, err := s.documents.Extract(ctx, name, data) + if err != nil { + return sentDocument{}, documentFailure(err) } if failure := s.readDocumentPictures(ctx, spec, &read); failure != nil { return sentDocument{}, failure diff --git a/acceleration/internal/knowledge/extract/extract.go b/acceleration/internal/knowledge/extract/extract.go index 547ae0b4d2..ac7d374e2a 100644 --- a/acceleration/internal/knowledge/extract/extract.go +++ b/acceleration/internal/knowledge/extract/extract.go @@ -276,7 +276,7 @@ func (e *Extractor) Extract(ctx context.Context, name string, data []byte) (Docu ctx, cancel := context.WithTimeout(ctx, e.options.Timeout) defer cancel() - format, err := detect(data) + format, err := Detect(data) if err != nil { return Document{}, err } @@ -315,9 +315,10 @@ var ( utf8BOM = []byte{0xEF, 0xBB, 0xBF} ) -// detect reads what a file is from its first bytes and, for the formats that are zip or -// OLE containers, from what the container holds. -func detect(data []byte) (Format, error) { +// Detect reads what a file is from its first bytes and, for the formats that are zip or +// OLE containers, from what the container holds. Extract reads it the same way, so a caller +// that takes only some formats can refuse the rest before any of them is read. +func Detect(data []byte) (Format, error) { // A PDF may carry junk before its header, and readers accept one within the first // kilobyte of the file. if bytes.Contains(data[:min(len(data), 1024)], pdfMagic) { diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 4b243b3b96..57470af1a2 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -13,6 +13,18 @@ import ( // times the size of the values in it, so this is far more than a sheet anybody reads. const maxWorkbook = 4 * maxUnzipped +// maxSheetColumns is the widest a row may be, counted to its last value. Excel's sheet is +// 16,384 columns wide, but a table a person reads is far narrower, and a row is held as wide +// as its last value's column: one value in the last column of a few thousand rows is millions +// of cells from a file of a few kilobytes. 1,024 is sixteen times the 64 columns the ODT +// reader (odt.go) keeps of a repeated or spanned cell. +const maxSheetColumns = 1024 + +// maxSheetCells is the most cells one sheet may hold at once, the empty ones in a row counted. +// A cell is a 16-byte string header, so a million is 16 MiB before its text, and a table of +// that many cells is more than a conversation or a knowledge passage can take in. +const maxSheetCells = 1_000_000 + // readXLSX reads a workbook as a table per sheet, each under its sheet's name, with its // values as the sheet shows them: a price formatted as money reads as money. A hidden // sheet is left out, since nobody reading the workbook sees it. A sheet's pictures follow @@ -36,9 +48,9 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { if visible, err := book.GetSheetVisible(sheet); err == nil && !visible { continue } - rows, err := book.GetRows(sheet) + rows, err := sheetRows(ctx, book, sheet) if err != nil { - return Document{}, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + return Document{}, err } start := 0 for start < len(rows) && strings.TrimSpace(strings.Join(rows[start], "")) == "" { @@ -62,6 +74,43 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { return Document{Pages: []Page{{Text: strings.Join(sections, "\n\n")}}, Pictures: kept.kept}, nil } +// sheetRows reads a sheet row by row, as excelize's GetRows does, but refuses it as too large +// when a row is wider than maxSheetColumns or the sheet holds more than maxSheetCells, and +// stops at the deadline between rows. The iterator pads a row with empty strings up to its +// last value (excelize rows.go, appendSpace), so a row is at most 16,384 cells before it is +// checked, and is dropped when it is refused. +func sheetRows(ctx context.Context, book *excelize.File, sheet string) ([][]string, error) { + iterator, err := book.Rows(sheet) + if err != nil { + return nil, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + } + var rows [][]string + cells := 0 + for iterator.Next() { + if ctx.Err() != nil { + iterator.Close() + return nil, unreadable(ctx, XLSX, ctx.Err()) + } + row, err := iterator.Columns() + if err != nil { + break + } + if len(row) > maxSheetColumns { + 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 { + iterator.Close() + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q has more than the %d cells allowed", sheet, maxSheetCells)) + } + rows = append(rows, row) + } + if err := iterator.Close(); err != nil { + return nil, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + } + return rows, nil +} + // sheetPictures keeps the pictures of a sheet, by the cells they are placed at, and // returns their markers. func sheetPictures(book *excelize.File, sheet string, kept *pictures) ([]string, error) { From b5856892921ae65096848f34669a568e0cfc3eff Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:14:48 -0500 Subject: [PATCH 02/17] AI-4053: Test the workbook limits and the format check --- acceleration/internal/api/documents_test.go | 26 ++++ .../knowledge/extract/extract_test.go | 140 ++++++++++++++++++ 2 files changed, 166 insertions(+) diff --git a/acceleration/internal/api/documents_test.go b/acceleration/internal/api/documents_test.go index 15eaea7a7a..8d0f4baea6 100644 --- a/acceleration/internal/api/documents_test.go +++ b/acceleration/internal/api/documents_test.go @@ -17,6 +17,8 @@ import ( "testing" + "github.com/xuri/excelize/v2" + "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" ) @@ -268,6 +270,30 @@ func (s *DocumentsSuite) TestAPictureSentAsAFileIsRefused() { s.Equal("unsupported_media_type", failure.Code) } +// A workbook is no format a question takes, and it is refused for that before it is read: one that +// the reader would refuse as too large is answered as the wrong format all the same. +func (s *DocumentsSuite) TestAWorkbookIsRefusedAsTheWrongFormatWithoutBeingRead() { + opened := s.opening(s.client) + for name, column := range map[string]int{"menu.xlsx": 1, "wide.xlsx": 16384} { + book := excelize.NewFile() + for row := 1; row <= 1500; row++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "v")) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + s.Require().NoError(book.Close()) + file := FileSource{Url: "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(out.Bytes()), Name: &name} + + status, failure := s.refused(opened, CreateResponseRequest{Text: "What is this?", Files: &[]FileSource{file}}) + + s.Equal(http.StatusUnsupportedMediaType, status, name) + s.Equal("unsupported_media_type", failure.Code, name) + s.Contains(failure.Message, "the file is xlsx", name) + } +} + func (s *DocumentsSuite) TestAnEncryptedFileIsRefusedAsUnreadable() { opened := s.opening(s.client) encrypted, err := os.ReadFile("../knowledge/extract/testdata/encrypted.docx") diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index d0c47ab3a5..0f9cfdd261 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -11,6 +11,7 @@ import ( "image/png" "os" "path/filepath" + "runtime" "strconv" "strings" "testing" @@ -20,6 +21,7 @@ import ( "github.com/klippa-app/go-pdfium/requests" "github.com/klippa-app/go-pdfium/responses" "github.com/stretchr/testify/suite" + "github.com/xuri/excelize/v2" ) type ExtractSuite struct { @@ -675,3 +677,141 @@ func (k *killedAt) FPDFFormObj_GetObject(request *requests.FPDFFormObj_GetObject k.reach("FPDFFormObj_GetObject") return k.Pdfium.FPDFFormObj_GetObject(request) } + +// workbook is a workbook whose rows each hold one value, in the given column. +func (s *ExtractSuite) workbook(rows, column int) []byte { + book := excelize.NewFile() + defer book.Close() + for row := 1; row <= rows; row++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "v"+strconv.Itoa(row))) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + return out.Bytes() +} + +// A row is held as wide as its last value, so a workbook of a few kilobytes with a value in the +// last column of every row would be millions of cells. The read is refused before it holds them. +func (s *ExtractSuite) TestAWorkbookWithAValueInItsLastColumnOfEveryRowIsRefusedWithinABudget() { + const lastColumn = 16384 + data := s.workbook(1500, lastColumn) + s.Less(len(data), 32<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "wide.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // The refused row is the first, at most 16,384 cells of 16 bytes. Reading every row as wide + // allocates gigabytes. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(16<<20)) +} + +func (s *ExtractSuite) TestARowMayBeAsWideAsTheLimitAndNoWider() { + for _, test := range []struct { + column int + reason Reason + }{ + {maxSheetColumns, ""}, + {maxSheetColumns + 1, TooLarge}, + } { + _, err := s.extractor.Extract(context.Background(), "wide.xlsx", s.workbook(3, test.column)) + + if test.reason == "" { + s.Require().NoError(err, "column %d", test.column) + continue + } + s.requireReason(err, test.reason) + } +} + +func (s *ExtractSuite) TestASheetMayHoldAsManyCellsAsTheLimitAndNoMore() { + const column = 1000 + rows := maxSheetCells / column + + read, err := s.extractor.Extract(context.Background(), "tall.xlsx", s.workbook(rows, column)) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "v"+strconv.Itoa(rows)) + + _, err = s.extractor.Extract(context.Background(), "tall.xlsx", s.workbook(rows+1, column)) + s.requireReason(err, TooLarge) +} + +// Cells are counted for each sheet: a workbook of sheets that are each within the limit is read. +func (s *ExtractSuite) TestTheCellLimitIsOfOneSheetNotOfTheWorkbook() { + book := excelize.NewFile() + defer book.Close() + second, err := book.NewSheet("Second") + s.Require().NoError(err) + s.Require().NotZero(second) + for _, sheet := range []string{"Sheet1", "Second"} { + for row := 1; row <= maxSheetCells/1000; row++ { + cell, err := excelize.CoordinatesToCellName(1000, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue(sheet, cell, "v")) + } + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + read, err := s.extractor.Extract(context.Background(), "two.xlsx", out.Bytes()) + + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "## Second") +} + +// A table of many rows of an ordinary width reads as it did before the limits. +func (s *ExtractSuite) TestAWorkbookOfManyRowsOfOrdinaryWidthIsReadInFull() { + book := excelize.NewFile() + defer book.Close() + var want strings.Builder + want.WriteString("## Sheet1\n\n| A | B | C |\n| --- | --- | --- |") + for row := 1; row <= 20000; row++ { + values := []any{"a" + strconv.Itoa(row), row, "c" + strconv.Itoa(row)} + if row == 1 { + values = []any{"A", "B", "C"} + } else { + want.WriteString("\n| " + values[0].(string) + " | " + strconv.Itoa(row) + " | " + values[2].(string) + " |") + } + cell, err := excelize.CoordinatesToCellName(1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetSheetRow("Sheet1", cell, &values)) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + read, err := s.extractor.Extract(context.Background(), "table.xlsx", out.Bytes()) + + s.Require().NoError(err) + s.Equal(want.String(), read.Pages[0].Text) +} + +// stopsAfter is a context that is done once Err has been asked this many times. +type stopsAfter struct { + context.Context + left int +} + +func (c *stopsAfter) Err() error { + if c.left--; c.left < 0 { + return context.DeadlineExceeded + } + return nil +} + +// The deadline is checked between the rows of a sheet, not only between sheets. +func (s *ExtractSuite) TestASheetIsReadOnlyUntilTheDeadline() { + data := s.workbook(500, 1) + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded) + _, ok := ReasonOf(err) + s.False(ok, "a workbook stopped at the deadline is not called corrupt or too large") +} From c4f06cd8ab60e05dbab2b89d3fe9990b81af1535 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:16:04 -0500 Subject: [PATCH 03/17] AI-4053: Test a sheet whose rows cannot be read --- .../knowledge/extract/extract_test.go | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index 0f9cfdd261..d91e073a5a 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -764,18 +764,19 @@ func (s *ExtractSuite) TestTheCellLimitIsOfOneSheetNotOfTheWorkbook() { s.Contains(read.Pages[0].Text, "## Second") } -// A table of many rows of an ordinary width reads as it did before the limits. +// A table of many rows of an ordinary width reads as it did before the limits. Its last column is +// the tenth, so each row holds ten cells for three values. func (s *ExtractSuite) TestAWorkbookOfManyRowsOfOrdinaryWidthIsReadInFull() { book := excelize.NewFile() defer book.Close() var want strings.Builder want.WriteString("## Sheet1\n\n| A | B | C |\n| --- | --- | --- |") for row := 1; row <= 20000; row++ { - values := []any{"a" + strconv.Itoa(row), row, "c" + strconv.Itoa(row)} - if row == 1 { - values = []any{"A", "B", "C"} - } else { - want.WriteString("\n| " + values[0].(string) + " | " + strconv.Itoa(row) + " | " + values[2].(string) + " |") + number := strconv.Itoa(row) + values := []any{"A", "B", nil, nil, nil, nil, nil, nil, nil, "C"} + if row > 1 { + values = []any{"a" + number, row, nil, nil, nil, nil, nil, nil, nil, "c" + number} + want.WriteString("\n| a" + number + " | " + number + " | c" + number + " |") } cell, err := excelize.CoordinatesToCellName(1, row) s.Require().NoError(err) @@ -815,3 +816,26 @@ func (s *ExtractSuite) TestASheetIsReadOnlyUntilTheDeadline() { _, ok := ReasonOf(err) s.False(ok, "a workbook stopped at the deadline is not called corrupt or too large") } + +// sheet is a workbook whose only sheet is the given XML, rows of inline strings. +func (s *ExtractSuite) sheet(sheetData string) []byte { + return s.rezip(s.workbook(1, 1), map[string][]byte{"xl/worksheets/sheet1.xml": []byte( + `` + sheetData + ``)}) +} + +func (s *ExtractSuite) TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt() { + row := func(number, cell string) string { + return `` + cell + `` + } + for name, test := range map[string]struct { + data []byte + reason Reason + }{ + "a row past the last row a sheet has": {data: s.sheet(row("1", "A1") + row("1048577", "A1048577")), reason: Corrupt}, + "a cell named by no column": {data: s.sheet(row("1", "A1") + row("2", "ZZZZ2")), reason: Corrupt}, + } { + _, err := s.extractor.Extract(context.Background(), name+".xlsx", test.data) + + s.requireReason(err, test.reason) + } +} From 367db79e9709dee6ecb7b8facee45c031e97949c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:21:17 -0500 Subject: [PATCH 04/17] AI-4053: Cover a sheet whose part is missing --- .../internal/knowledge/extract/extract_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index d91e073a5a..495df42fb2 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -832,6 +832,7 @@ func (s *ExtractSuite) TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt() { reason Reason }{ "a row past the last row a sheet has": {data: s.sheet(row("1", "A1") + row("1048577", "A1048577")), reason: Corrupt}, + "a sheet whose part is missing": {data: s.withoutPart(s.workbook(1, 1), "xl/worksheets/sheet1.xml"), reason: Corrupt}, "a cell named by no column": {data: s.sheet(row("1", "A1") + row("2", "ZZZZ2")), reason: Corrupt}, } { _, err := s.extractor.Extract(context.Background(), name+".xlsx", test.data) @@ -839,3 +840,18 @@ func (s *ExtractSuite) TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt() { s.requireReason(err, test.reason) } } + +// withoutPart is a copy of an archive without one of its parts. +func (s *ExtractSuite) withoutPart(data []byte, name string) []byte { + archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + s.Require().NoError(err) + var out bytes.Buffer + writer := zip.NewWriter(&out) + for _, file := range archive.File { + if file.Name != name { + s.Require().NoError(writer.Copy(file)) + } + } + s.Require().NoError(writer.Close()) + return out.Bytes() +} From 2fea4781c1028c0828ea41d3ecdc5dd7a2973b13 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:22:53 -0500 Subject: [PATCH 05/17] AI-4053: Say why a row that cannot be read ends the sheet --- acceleration/internal/knowledge/extract/xlsx.go | 1 + 1 file changed, 1 insertion(+) diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 57470af1a2..2b80585e1e 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -93,6 +93,7 @@ func sheetRows(ctx context.Context, book *excelize.File, sheet string) ([][]stri } row, err := iterator.Columns() if err != nil { + // As in GetRows, a row that cannot be read ends the sheet there. break } if len(row) > maxSheetColumns { From 47a6803279625a4e7db2e1f8f5c284ec6f5b4d48 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 11:58:03 -0500 Subject: [PATCH 06/17] AI-4053: count a workbook's cells once for all its sheets, a row with none as one A row between two rows of values counted no cells, so a sheet with one value in its last row was a million lines, and the limit was of each sheet, so sheets multiplied it. excelize keeps every sheet read for its pictures until the workbook is closed, so the total is the workbook's. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 118 +++++++++++++++--- .../internal/knowledge/extract/xlsx.go | 32 +++-- 2 files changed, 122 insertions(+), 28 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index 495df42fb2..7ffdaa16ee 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/binary" "errors" + "fmt" "image" "image/jpeg" "image/png" @@ -729,9 +730,9 @@ func (s *ExtractSuite) TestARowMayBeAsWideAsTheLimitAndNoWider() { } } -func (s *ExtractSuite) TestASheetMayHoldAsManyCellsAsTheLimitAndNoMore() { +func (s *ExtractSuite) TestAWorkbookMayHoldAsManyCellsAsTheLimitAndNoMore() { const column = 1000 - rows := maxSheetCells / column + rows := maxWorkbookCells / column read, err := s.extractor.Extract(context.Background(), "tall.xlsx", s.workbook(rows, column)) s.Require().NoError(err) @@ -741,27 +742,110 @@ func (s *ExtractSuite) TestASheetMayHoldAsManyCellsAsTheLimitAndNoMore() { s.requireReason(err, TooLarge) } -// Cells are counted for each sheet: a workbook of sheets that are each within the limit is read. -func (s *ExtractSuite) TestTheCellLimitIsOfOneSheetNotOfTheWorkbook() { - book := excelize.NewFile() - defer book.Close() - second, err := book.NewSheet("Second") - s.Require().NoError(err) - s.Require().NotZero(second) - for _, sheet := range []string{"Sheet1", "Second"} { - for row := 1; row <= maxSheetCells/1000; row++ { - cell, err := excelize.CoordinatesToCellName(1000, row) +// Cells are counted for the whole workbook: two sheets that each hold half the limit are read, +// and one more cell in either is refused. +func (s *ExtractSuite) TestTheCellLimitIsOfTheWholeWorkbook() { + const column = 1000 + half := maxWorkbookCells / 2 / column + for _, test := range []struct { + second int + reason Reason + }{ + {half, ""}, + {half + 1, TooLarge}, + } { + book := excelize.NewFile() + _, err := book.NewSheet("Second") + s.Require().NoError(err) + for sheet, rows := range map[string]int{"Sheet1": half, "Second": test.second} { + for row := 1; row <= rows; row++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue(sheet, cell, "v")) + } + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + s.Require().NoError(book.Close()) + + read, err := s.extractor.Extract(context.Background(), "two.xlsx", out.Bytes()) + + if test.reason == "" { s.Require().NoError(err) - s.Require().NoError(book.SetCellValue(sheet, cell, "v")) + s.Contains(read.Pages[0].Text, "## Second") + continue } + s.requireReason(err, test.reason) } - var out bytes.Buffer - s.Require().NoError(book.Write(&out)) +} - read, err := s.extractor.Extract(context.Background(), "two.xlsx", out.Bytes()) +// The rows between two rows of values are read as rows with no cells, and each is a line of the +// table, so each counts as a cell. +func (s *ExtractSuite) TestARowWithNoCellsCountsAsACell() { + row := func(number int) string { + cell := "A" + strconv.Itoa(number) + return `` + cell + `` + } + read, err := s.extractor.Extract(context.Background(), "gaps.xlsx", s.sheet(row(1)+row(maxWorkbookCells))) s.Require().NoError(err) - s.Contains(read.Pages[0].Text, "## Second") + s.True(strings.HasSuffix(read.Pages[0].Text, "| A"+strconv.Itoa(maxWorkbookCells)+" |")) + + _, err = s.extractor.Extract(context.Background(), "gaps.xlsx", s.sheet(row(1)+row(maxWorkbookCells+1))) + s.requireReason(err, TooLarge) +} + +// A sheet with a value in its last row is a million rows from a few hundred bytes, and a workbook +// of many such sheets is refused before it holds them: reading them all allocates gigabytes, and +// the read is refused at the first sheet's millionth row. +func (s *ExtractSuite) TestAWorkbookOfSheetsReachingTheirLastRowIsRefusedWithinABudget() { + last := `x` + for name, test := range map[string]struct { + sheets int + sheetData string + }{ + "100 sheets with a value in their last row": {100, last}, + "40 sheets with a value in their first and last row": {40, `x` + last}, + } { + data := s.sheets(test.sheets, test.sheetData) + s.Less(len(data), 64<<10, "%s: the file is a few kilobytes", name) + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "far.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(256<<20), name) + } +} + +// sheets is a workbook of n sheets, each the given rows of inline strings. +func (s *ExtractSuite) sheets(n int, sheetData string) []byte { + var out bytes.Buffer + writer := zip.NewWriter(&out) + add := func(name, body string) { + part, err := writer.Create(name) + s.Require().NoError(err) + _, err = part.Write([]byte(body)) + s.Require().NoError(err) + } + types := `` + list := `` + rels := `` + for i := 1; i <= n; i++ { + types += fmt.Sprintf(``, i) + list += fmt.Sprintf(``, i, i, i) + rels += fmt.Sprintf(``, i, i) + add(fmt.Sprintf("xl/worksheets/sheet%d.xml", i), ``+sheetData+``) + } + add("[Content_Types].xml", types+``) + add("xl/workbook.xml", list+``) + add("xl/_rels/workbook.xml.rels", rels+``) + add("_rels/.rels", ``) + s.Require().NoError(writer.Close()) + return out.Bytes() } // A table of many rows of an ordinary width reads as it did before the limits. Its last column is diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 2b80585e1e..2f86f453c8 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -20,10 +20,19 @@ const maxWorkbook = 4 * maxUnzipped // reader (odt.go) keeps of a repeated or spanned cell. const maxSheetColumns = 1024 -// maxSheetCells is the most cells one sheet may hold at once, the empty ones in a row counted. -// A cell is a 16-byte string header, so a million is 16 MiB before its text, and a table of -// that many cells is more than a conversation or a knowledge passage can take in. -const maxSheetCells = 1_000_000 +// maxWorkbookCells is the most cells one workbook may hold, the empty ones in a row counted and +// a row with no cells counted as one. The iterator returns every row up to a sheet's last, so +// one value in a sheet's last row is a million rows. A cell is a 16-byte string header, so a +// million is 16 MiB before its text, and a table of that many cells is more than a conversation +// or a knowledge passage can take in. It is counted for the whole workbook, not for each sheet: +// excelize keeps every sheet it has read for its pictures (GetPictureCells) until the workbook +// is closed, padded as the iterator pads it. +const maxWorkbookCells = 1_000_000 + +// budget is what is left of a workbook's limits as its sheets are read. +type budget struct { + cells int +} // readXLSX reads a workbook as a table per sheet, each under its sheet's name, with its // values as the sheet shows them: a price formatted as money reads as money. A hidden @@ -41,6 +50,7 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { var sections []string var kept pictures + left := budget{cells: maxWorkbookCells} for _, sheet := range book.GetSheetList() { if ctx.Err() != nil { return Document{}, unreadable(ctx, XLSX, ctx.Err()) @@ -48,7 +58,7 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { if visible, err := book.GetSheetVisible(sheet); err == nil && !visible { continue } - rows, err := sheetRows(ctx, book, sheet) + rows, err := sheetRows(ctx, book, sheet, &left) if err != nil { return Document{}, err } @@ -75,17 +85,16 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { } // sheetRows reads a sheet row by row, as excelize's GetRows does, but refuses it as too large -// when a row is wider than maxSheetColumns or the sheet holds more than maxSheetCells, and -// stops at the deadline between rows. The iterator pads a row with empty strings up to its +// when a row is wider than maxSheetColumns or the workbook's cells so far are more than left, +// and stops at the deadline between rows. The iterator pads a row with empty strings up to its // last value (excelize rows.go, appendSpace), so a row is at most 16,384 cells before it is // checked, and is dropped when it is refused. -func sheetRows(ctx context.Context, book *excelize.File, sheet string) ([][]string, error) { +func sheetRows(ctx context.Context, book *excelize.File, sheet string, left *budget) ([][]string, error) { iterator, err := book.Rows(sheet) if err != nil { return nil, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) } var rows [][]string - cells := 0 for iterator.Next() { if ctx.Err() != nil { iterator.Close() @@ -100,9 +109,10 @@ func sheetRows(ctx context.Context, book *excelize.File, sheet string) ([][]stri 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 { + // A row with no cells, one between two rows of values, is still a line of the table. + if left.cells -= max(len(row), 1); left.cells < 0 { iterator.Close() - return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q has more than the %d cells allowed", sheet, maxSheetCells)) + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d cells allowed", sheet, maxWorkbookCells)) } rows = append(rows, row) } From 6bf9e8ee3c7b68a9ee39346784574e5ad09ae474 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 12:04:08 -0500 Subject: [PATCH 07/17] AI-4053: give a workbook a text budget, and stop its tables at the deadline The cell limit counted cells, not their text: one long shared string in many cells is many copies of it, and a table pads every row to its widest. A workbook's cell text, and then its tables, now count against one budget, and a table is written only until the deadline. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 96 +++++++++++++++++++ .../internal/knowledge/extract/markdown.go | 27 +++++- .../internal/knowledge/extract/xlsx.go | 36 +++++-- 3 files changed, 152 insertions(+), 7 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index 7ffdaa16ee..d9ae7a66bf 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -821,6 +821,102 @@ func (s *ExtractSuite) TestAWorkbookOfSheetsReachingTheirLastRowIsRefusedWithinA } } +// sharedText is a workbook of the given sheets, each of rows × columns cells that all hold one +// shared string of text. +func (s *ExtractSuite) sharedText(sheets, rows, columns int, text string) []byte { + book := excelize.NewFile() + defer book.Close() + for i := 1; i <= sheets; i++ { + sheet := "S" + strconv.Itoa(i) + _, err := book.NewSheet(sheet) + s.Require().NoError(err) + for row := 1; row <= rows; row++ { + for column := 1; column <= columns; column++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue(sheet, cell, "shared")) + } + } + } + s.Require().NoError(book.DeleteSheet("Sheet1")) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + // excelize cuts a value to the 32,767 characters a cell may hold, so the one shared string is + // replaced in the file. + return s.rezip(out.Bytes(), map[string][]byte{"xl/sharedStrings.xml": []byte( + `` + text + ``)}) +} + +// One long shared string is the text of every cell it is in. A workbook whose cells are within +// the cell limit but whose text is not is refused, before its cells' copies of it are all held. +func (s *ExtractSuite) TestAWorkbookIsRefusedPastItsTextBudget() { + long := strings.Repeat("y", 100<<10) + data := s.sharedText(1, 3, 1000, long) + s.Less(len(data), 64<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "shared.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // The cells are refused at the budget, twice maxUnzipped. Holding all three thousand copies + // is more than twice that. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(4*maxUnzipped)) +} + +// The text budget is of the whole workbook: two sheets that each take less than half of it are +// read, and a third is refused. +func (s *ExtractSuite) TestTheTextBudgetIsOfTheWholeWorkbook() { + long := strings.Repeat("y", 100<<10) + + read, err := s.extractor.Extract(context.Background(), "shared.xlsx", s.sharedText(2, 3, 100, long)) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "## S2") + s.Contains(read.Pages[0].Text, long) + + _, err = s.extractor.Extract(context.Background(), "shared.xlsx", s.sharedText(3, 3, 100, long)) + s.requireReason(err, TooLarge) +} + +// A table pads every row to its widest, so one row of values in every column over rows with no +// cells is a long table from few cells. It is refused when it is longer than the text budget. +func (s *ExtractSuite) TestATableLongerThanTheTextBudgetIsRefused() { + var header strings.Builder + header.WriteString(``) + for column := 1; column <= maxSheetColumns; column++ { + cell, err := excelize.CoordinatesToCellName(column, 1) + s.Require().NoError(err) + header.WriteString(`h`) + } + header.WriteString(``) + last := `x` + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "padded.xlsx", s.sheet(header.String()+last)) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // Writing a table allocates several times its length, so the budget is a gigabyte, a few + // times the text budget. Writing the whole table allocates several gigabytes. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(1<<30)) +} + +// The deadline is checked between the rows of a table as it is written, not only as it is read. +func (s *ExtractSuite) TestATableIsWrittenOnlyUntilTheDeadline() { + const rows = 500 + data := s.workbook(rows, 1) + + // Err is asked once for the sheet and once for each row read: the deadline passes a few rows + // into writing the table. + _, err := readXLSX(&stopsAfter{Context: context.Background(), left: 1 + rows + 5}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded) +} + // sheets is a workbook of n sheets, each the given rows of inline strings. func (s *ExtractSuite) sheets(n int, sheetData string) []byte { var out bytes.Buffer diff --git a/acceleration/internal/knowledge/extract/markdown.go b/acceleration/internal/knowledge/extract/markdown.go index a98b583d8d..6d0fb0cc0b 100644 --- a/acceleration/internal/knowledge/extract/markdown.go +++ b/acceleration/internal/knowledge/extract/markdown.go @@ -1,6 +1,9 @@ package extract import ( + "context" + "errors" + "math" "strings" ) @@ -189,6 +192,17 @@ func oneLine(text string) string { // to the widest, and columns empty in every row are dropped: a spreadsheet's formatting // often reaches well past its data. func table(rows [][]string) string { + // With no deadline and no limit, the table is always written. + text, _ := tableWithin(context.Background(), rows, math.MaxInt) + return text +} + +// errTableTooLong is a table longer than its limit. +var errTableTooLong = errors.New("the table is longer than allowed") + +// tableWithin is table, stopped at the deadline between rows and refused with errTableTooLong +// once it is longer than limit bytes. +func tableWithin(ctx context.Context, rows [][]string, limit int) (string, error) { width := 0 for _, row := range rows { width = max(width, len(row)) @@ -225,10 +239,21 @@ func table(rows [][]string) string { } } b.WriteString("\n") + // Every line ends in a line break, and the table is written without its last. + long := func() bool { return b.Len()-1 > limit } for _, row := range rows[1:] { + if err := ctx.Err(); err != nil { + return "", err + } + if long() { + return "", errTableTooLong + } write(row) } - return strings.TrimSuffix(b.String(), "\n") + if long() { + return "", errTableTooLong + } + return strings.TrimSuffix(b.String(), "\n"), nil } // tableCell is a cell's text as one line, since a Markdown table row cannot break, with diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 2f86f453c8..70ddf42000 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -3,6 +3,7 @@ package extract import ( "bytes" "context" + "errors" "fmt" "strings" @@ -29,9 +30,17 @@ const maxSheetColumns = 1024 // is closed, padded as the iterator pads it. const maxWorkbookCells = 1_000_000 +// maxWorkbookText is the most text one workbook may be read to, counted once as its cells are +// read and once more as its tables are written, since a sheet's cells and its table are held at +// once. A cell's text is its own copy, so one long shared string in many cells is that string +// many times over. Twice maxUnzipped, so a workbook's tables may be about as long as one part of +// an Office file may unpack to. +const maxWorkbookText = 2 * maxUnzipped + // budget is what is left of a workbook's limits as its sheets are read. type budget struct { cells int + text int } // readXLSX reads a workbook as a table per sheet, each under its sheet's name, with its @@ -50,7 +59,7 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { var sections []string var kept pictures - left := budget{cells: maxWorkbookCells} + left := budget{cells: maxWorkbookCells, text: maxWorkbookText} for _, sheet := range book.GetSheetList() { if ctx.Err() != nil { return Document{}, unreadable(ctx, XLSX, ctx.Err()) @@ -69,7 +78,15 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { rows = trimRows(rows[start:]) var blocks []string if len(rows) > 0 { - blocks = append(blocks, table(rows)) + text, err := tableWithin(ctx, rows, left.text) + if errors.Is(err, errTableTooLong) { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d bytes of text allowed", sheet, maxWorkbookText)) + } + if err != nil { + return Document{}, unreadable(ctx, XLSX, err) + } + left.text -= len(text) + blocks = append(blocks, text) } markers, err := sheetPictures(book, sheet, &kept) if err != nil { @@ -85,10 +102,10 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { } // sheetRows reads a sheet row by row, as excelize's GetRows does, but refuses it as too large -// when a row is wider than maxSheetColumns or the workbook's cells so far are more than left, -// and stops at the deadline between rows. The iterator pads a row with empty strings up to its -// last value (excelize rows.go, appendSpace), so a row is at most 16,384 cells before it is -// checked, and is dropped when it is refused. +// when a row is wider than maxSheetColumns or the workbook's cells or text so far are more +// than left, and stops at the deadline between rows. The iterator pads a row with empty +// strings up to its last value (excelize rows.go, appendSpace), so a row is at most 16,384 +// cells before it is checked, and is dropped when it is refused. func sheetRows(ctx context.Context, book *excelize.File, sheet string, left *budget) ([][]string, error) { iterator, err := book.Rows(sheet) if err != nil { @@ -114,6 +131,13 @@ func sheetRows(ctx context.Context, book *excelize.File, sheet string, left *bud iterator.Close() return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d cells allowed", sheet, maxWorkbookCells)) } + for _, cell := range row { + left.text -= len(cell) + } + if left.text < 0 { + iterator.Close() + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d bytes of text allowed", sheet, maxWorkbookText)) + } rows = append(rows, row) } if err := iterator.Close(); err != nil { From 1d6c939186dc1258e938a9de7d07d077653aab9a Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 12:05:11 -0500 Subject: [PATCH 08/17] AI-4053: pin how a sheet ends on a row that cannot be read, and the close error Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index d9ae7a66bf..bbb4555b80 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -1010,17 +1010,34 @@ func (s *ExtractSuite) TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt() { for name, test := range map[string]struct { data []byte reason Reason + // says is what the error says, when the rows are what cannot be read. + says string }{ - "a row past the last row a sheet has": {data: s.sheet(row("1", "A1") + row("1048577", "A1048577")), reason: Corrupt}, + "a row past the last row a sheet has": {data: s.sheet(row("1", "A1") + row("1048577", "A1048577")), reason: Corrupt, says: `sheet "Sheet1" cannot be read`}, "a sheet whose part is missing": {data: s.withoutPart(s.workbook(1, 1), "xl/worksheets/sheet1.xml"), reason: Corrupt}, "a cell named by no column": {data: s.sheet(row("1", "A1") + row("2", "ZZZZ2")), reason: Corrupt}, } { _, err := s.extractor.Extract(context.Background(), name+".xlsx", test.data) s.requireReason(err, test.reason) + if test.says != "" { + s.Contains(err.Error(), test.says, name) + s.NotContains(err.Error(), "pictures", name) + } } } +// A row that cannot be read ends its sheet there, as in excelize's GetRows: a workbook whose +// shared strings are cut short reads as a sheet with no text, not as a corrupt file. +func (s *ExtractSuite) TestAWorkbookWhoseSharedStringsAreCutShortReadsWithNoText() { + data := s.rezip(s.workbook(3, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`cut`)}) + + read, err := s.extractor.Extract(context.Background(), "cut.xlsx", data) + + s.Require().NoError(err) + s.Empty(read.Pages[0].Text) +} + // withoutPart is a copy of an archive without one of its parts. func (s *ExtractSuite) withoutPart(data []byte, name string) []byte { archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) From 3f5f60e34558cf5944cbe96516fe424a1a0b886f Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 12:36:20 -0500 Subject: [PATCH 09/17] AI-4053: count a workbook's shared strings before any row is built excelize builds a row's cells at once, each a copy of its text, so the text budget checked after a row could not bound that row. The shared strings the cells name are now counted from the parts before excelize reads a cell, and the workbook is refused past the text budget. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 117 +++++++++- .../internal/knowledge/extract/xlsx.go | 216 ++++++++++++++++++ 2 files changed, 329 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index bbb4555b80..c7e0a7762e 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -10,6 +10,7 @@ import ( "image" "image/jpeg" "image/png" + "math" "os" "path/filepath" "runtime" @@ -866,6 +867,84 @@ func (s *ExtractSuite) TestAWorkbookIsRefusedPastItsTextBudget() { s.Less(after.TotalAlloc-before.TotalAlloc, uint64(4*maxUnzipped)) } +// A row's cells are each a copy of their text, built at once: one long shared string in every cell +// of one row is that string a thousand times over before the row could be counted. The cells are +// counted as they are stored before any row is built, so the read is refused within the text budget. +func (s *ExtractSuite) TestARowOfOneLongSharedStringIsRefusedBeforeItIsBuilt() { + data := s.sharedText(1, 1, maxSheetColumns, strings.Repeat("y", 2<<20)) + s.Less(len(data), 64<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "row.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // Building the row allocates two gigabytes, sixteen times the budget. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(maxWorkbookText)) +} + +// cellsNaming is a workbook of one row of cells, each the given XML, and the given shared strings, +// in a part of the given name. +func (s *ExtractSuite) cellsNaming(cells int, cell, part, shared string) []byte { + sheet := s.sheet(`` + strings.Repeat(cell, cells) + ``) + return s.rezip(s.withoutPart(sheet, "xl/sharedStrings.xml"), map[string][]byte{part: []byte( + `` + shared + ``)}) +} + +// A cell is counted as the shared string excelize reads for it, at the index it reads it at, or +// one long string in every cell of a row is counted as a short one and built before it is +// refused. excelize reads the strings that are the root's children when their part is small +// enough to hold, and every one in it when it is not, so a string nested one level down moves the +// strings after it to other indices in one way and not the other. +func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { + long := `` + strings.Repeat("y", 2<<20) + `` + short := `short` + first := `0` + for name, test := range map[string]struct { + data []byte + // budget is what the read may allocate. Counting a string allocates a few times its + // length, as the XML decoder grows its buffer, for each of the two ways it is read. + budget uint64 + }{ + "a part small enough to hold, the first string the root's child": { + data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+short+``+long), + budget: maxWorkbookText, + }, + "a part too large to hold, the first string nested": { + data: s.cellsNaming(32, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 17<<20)+``+short), + budget: 2 * maxWorkbookText, + }, + "a cell whose formula holds another index": { + data: s.cellsNaming(128, `01`, "xl/sharedStrings.xml", long+short), + budget: maxWorkbookText, + }, + "an index between spaces": { + data: s.cellsNaming(128, ` 1 `, "xl/sharedStrings.xml", short+long), + budget: maxWorkbookText, + }, + "a part named in other letters": { + data: s.cellsNaming(128, first, "XL/SharedStrings.xml", long), + budget: maxWorkbookText, + }, + "a part named with a backslash": { + data: s.cellsNaming(128, first, `xl\sharedStrings.xml`, long), + budget: maxWorkbookText, + }, + } { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "named.xlsx", test.data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // The row is two to four times the text budget. + s.Less(after.TotalAlloc-before.TotalAlloc, test.budget, name) + } +} + // The text budget is of the whole workbook: two sheets that each take less than half of it are // read, and a third is refused. func (s *ExtractSuite) TestTheTextBudgetIsOfTheWholeWorkbook() { @@ -910,9 +989,9 @@ func (s *ExtractSuite) TestATableIsWrittenOnlyUntilTheDeadline() { const rows = 500 data := s.workbook(rows, 1) - // Err is asked once for the sheet and once for each row read: the deadline passes a few rows - // into writing the table. - _, err := readXLSX(&stopsAfter{Context: context.Background(), left: 1 + rows + 5}, data) + // Err is asked as the cells are counted, then once for the sheet and once for each row read: + // the deadline passes a few rows into writing the table. + _, err := readXLSX(&stopsAfter{Context: context.Background(), left: s.countingCalls(data) + 1 + rows + 5}, data) s.Require().ErrorIs(err, context.DeadlineExceeded) } @@ -990,13 +1069,43 @@ func (s *ExtractSuite) TestASheetIsReadOnlyUntilTheDeadline() { _, err := readXLSX(context.Background(), data) s.Require().NoError(err) - _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: s.countingCalls(data) + 10}, data) s.Require().ErrorIs(err, context.DeadlineExceeded) _, ok := ReasonOf(err) s.False(ok, "a workbook stopped at the deadline is not called corrupt or too large") } +// countingCalls is how many times counting a workbook's cells asks for the deadline. +func (s *ExtractSuite) countingCalls(data []byte) int { + counted := &stopsAfter{Context: context.Background(), left: math.MaxInt} + count := cellCount{ctx: counted} + s.Require().NoError(count.workbook(data)) + return math.MaxInt - counted.left +} + +// The deadline is checked as the cells are counted: at each row of every part, and at each shared +// string. A workbook with a part that is no sheet, or with more shared strings than its cells +// name, is counted for longer than it is read. +func (s *ExtractSuite) TestTheCellsAreCountedOnlyUntilTheDeadline() { + var rows, shared strings.Builder + for i := 1; i <= 500; i++ { + rows.WriteString(`1`) + shared.WriteString(`s`) + } + for name, data := range map[string][]byte{ + "rows of a part that is no sheet": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/rows.xml": []byte(`` + rows.String() + ``)}), + "shared strings": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`` + shared.String() + ``)}), + } { + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err, name) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded, name) + } +} + // sheet is a workbook whose only sheet is the given XML, rows of inline strings. func (s *ExtractSuite) sheet(sheetData string) []byte { return s.rezip(s.workbook(1, 1), map[string][]byte{"xl/worksheets/sheet1.xml": []byte( diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 70ddf42000..233d323c5e 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -1,10 +1,14 @@ package extract import ( + "archive/zip" "bytes" "context" + "encoding/xml" "errors" "fmt" + "io" + "strconv" "strings" "github.com/xuri/excelize/v2" @@ -57,6 +61,17 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { } defer book.Close() + count := cellCount{ctx: ctx, charset: book.CharsetReader} + if err := count.workbook(data); err != nil { + if ctx.Err() != nil { + return Document{}, unreadable(ctx, XLSX, err) + } + return Document{}, fail(Corrupt, XLSX, fmt.Errorf("the workbook cannot be read: %w", err)) + } + if count.text > maxWorkbookText { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the shared strings the workbook's cells name are more than the %d bytes of text allowed", maxWorkbookText)) + } + var sections []string var kept pictures left := budget{cells: maxWorkbookCells, text: maxWorkbookText} @@ -167,3 +182,204 @@ func sheetPictures(book *excelize.File, sheet string, kept *pictures) ([]string, } return markers, nil } + +// cellCount counts the text of the shared strings a workbook's cells name, before excelize reads +// any cell. excelize builds a row's cells at once (rows.go, Columns), each its own copy of its +// text, so one long shared string in every cell of a row is that string many times over before +// the row can be counted. The workbook is refused when the shared strings its cells name are more +// than the text budget, so no row is built past it. Every part is read as a sheet, since a sheet +// may be any part the workbook names, so a hidden sheet's cells count as well. A number format +// may make a cell's text longer than it is stored, which the rows count as they are read. +type cellCount struct { + ctx context.Context + charset func(label string, input io.Reader) (io.Reader, error) + archive *zip.Reader + // shared is the length of each shared string, read at the first cell that names one. + shared []int32 + read bool + text int +} + +// workbook counts the cells of every part of a workbook. +func (c *cellCount) workbook(data []byte) error { + archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return err + } + c.archive = archive + for _, file := range archive.File { + if err := c.part(file, c.cells); err != nil { + return err + } + } + return nil +} + +// part reads one part of the workbook, handing each element to read. A part that is not XML, +// or not past its first error, is read no further, as excelize reads it. +func (c *cellCount) part(file *zip.File, read func(*xml.Decoder) error) error { + r, err := file.Open() + if err != nil { + return err + } + defer r.Close() + decoder := xml.NewDecoder(r) + decoder.CharsetReader = c.charset + return read(decoder) +} + +// cells counts the cells of a part, checking the deadline at each row, as the rows are read. +func (c *cellCount) cells(decoder *xml.Decoder) error { + for { + token, err := decoder.Token() + if err != nil { + return nil + } + start, ok := token.(xml.StartElement) + switch { + case !ok: + case start.Name.Local == "row": + if err := c.ctx.Err(); err != nil { + return err + } + case start.Name.Local == "c": + n, err := c.cell(decoder, start) + if err != nil { + return err + } + c.text += n + } + } +} + +// cell is the length of the shared string a cell names, read as excelize reads a cell (rows.go, +// cellXMLHandler; cell.go, getValueFrom). Any other text of a cell is in the file as often as the +// cell is, so it is never more than the part it is in. +func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, error) { + kind := "" + for _, attr := range start.Attr { + if attr.Name.Local == "t" { + kind = attr.Value + } + } + var value string + for done := false; !done; { + token, err := decoder.Token() + if err != nil { + break + } + switch element := token.(type) { + case xml.StartElement: + switch element.Name.Local { + case "v": + err = decoder.DecodeElement(&value, &element) + case "f", "is": + // Read whole, so a value inside them is not the cell's. + err = decoder.Skip() + } + case xml.EndElement: + done = element == start.End() + } + if err != nil { + break + } + } + if kind != "s" || value == "" { + return 0, nil + } + if err := c.readShared(); err != nil { + return 0, err + } + // As in excelize, an index that is not a number is the first string. + index, _ := strconv.Atoi(strings.TrimSpace(value)) + if index < 0 || index >= len(c.shared) { + return 0, nil + } + return int(c.shared[index]), nil +} + +// readShared reads the length of every shared string, once. excelize reads the strings that are +// the root's children when the part is small enough to hold (rows.go, sharedStringsReader), and +// every one in the part when it is not (rows.go, getFromStringItem): both are read, and a string +// is counted as the longer of the two at its index, so a cell is never counted shorter than it +// is read. +func (c *cellCount) readShared() error { + if c.read { + return nil + } + c.read = true + for _, file := range c.archive.File { + if !strings.EqualFold(strings.ReplaceAll(file.Name, `\`, "/"), "xl/sharedStrings.xml") { + continue + } + for _, everyOne := range []bool{false, true} { + if err := c.part(file, func(decoder *xml.Decoder) error { return c.sharedStrings(decoder, everyOne) }); err != nil { + return err + } + } + } + return nil +} + +// sharedStrings reads the length of the shared strings of a part: of every one in it, or of the +// root's children only. +func (c *cellCount) sharedStrings(decoder *xml.Decoder, everyOne bool) error { + depth, index := 0, 0 + for { + token, err := decoder.Token() + if err != nil { + return nil + } + switch element := token.(type) { + case xml.StartElement: + if element.Name.Local != "si" || !everyOne && depth != 1 { + depth++ + continue + } + if err := c.ctx.Err(); err != nil { + return err + } + var text sharedString + err := decoder.DecodeElement(&text, &element) + if index == len(c.shared) { + c.shared = append(c.shared, 0) + } + // A string is at most the part it is in, a few hundred megabytes. + c.shared[index] = max(c.shared[index], int32(text.length())) + index++ + if err != nil { + return nil + } + case xml.EndElement: + depth-- + } + } +} + +// sharedString is a shared string as excelize reads it (xlsxSI): its text, and the text of its +// runs. +// excelize then only shortens it, when it unescapes characters (lib.go, bstrUnmarshal). +type sharedString struct { + T *sharedText `xml:"t"` + R []struct { + T *sharedText `xml:"t"` + } `xml:"r"` +} + +// sharedText is the text of a string or of one of its runs (xlsxT). +type sharedText struct { + Val string `xml:",chardata"` +} + +func (s *sharedString) length() int { + n := 0 + if s.T != nil { + n += len(s.T.Val) + } + for _, run := range s.R { + if run.T != nil { + n += len(run.T.Val) + } + } + return n +} From 3640753082909c50d6a3e0bc18029584dec845bb Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 12:41:28 -0500 Subject: [PATCH 10/17] AI-4053: pin the text budget and a table's limit to the byte Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index c7e0a7762e..bfe177f682 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -945,6 +945,63 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { } } +// The text budget may be spent to the byte, and no further. Cells of spaces make no table, so the +// cells alone spend it. Stored, the cells are counted before they are read, and a byte past the +// budget is refused then; a number format that writes a string twice ("@@") makes them longer as +// they are read, and they are counted again. +func (s *ExtractSuite) TestTheTextBudgetMayBeSpentToTheByte() { + spaces := strings.Repeat(" ", 1<<20) + columns := maxWorkbookText / len(spaces) + + stored := `` + spaces + ` ` + read, err := s.extractor.Extract(context.Background(), "spaces.xlsx", + s.cellsNaming(columns, `0`, "xl/sharedStrings.xml", stored)) + s.Require().NoError(err, "stored, the cells are the budget") + s.Empty(read.Pages[0].Text) + + _, err = s.extractor.Extract(context.Background(), "spaces.xlsx", + s.cellsNaming(1, strings.Repeat(`0`, columns)+`1`, "xl/sharedStrings.xml", stored)) + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "shared strings", "stored, the cells are the budget and a byte, refused before they are read") + + book := excelize.NewFile() + defer book.Close() + twice := "@@" + style, err := book.NewStyle(&excelize.Style{CustomNumFmt: &twice}) + s.Require().NoError(err) + for column := 1; column <= columns/2; column++ { + cell, err := excelize.CoordinatesToCellName(column, 1) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "twice")) + s.Require().NoError(book.SetCellStyle("Sheet1", cell, cell, style)) + } + cell, err := excelize.CoordinatesToCellName(columns/2+1, 1) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "once")) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + data := s.rezip(out.Bytes(), map[string][]byte{"xl/sharedStrings.xml": []byte( + `` + spaces + ` `)}) + + _, err = s.extractor.Extract(context.Background(), "twice.xlsx", data) + + // Stored, the cells are half the budget and a byte; read, the budget and a byte. + s.requireReason(err, TooLarge) +} + +// A table may be as long as its limit and no longer, its last row counted as well as the others. +func (s *ExtractSuite) TestATableMayBeAsLongAsItsLimit() { + rows := [][]string{{"h"}, {"a"}, {"b"}} + whole := table(rows) + + text, err := tableWithin(context.Background(), rows, len(whole)) + s.Require().NoError(err) + s.Equal(whole, text) + + _, err = tableWithin(context.Background(), rows, len(whole)-1) + s.Require().ErrorIs(err, errTableTooLong) +} + // The text budget is of the whole workbook: two sheets that each take less than half of it are // read, and a third is refused. func (s *ExtractSuite) TestTheTextBudgetIsOfTheWholeWorkbook() { From a899094d031beacc25338870d7670c9ee22ea524 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 13:25:44 -0500 Subject: [PATCH 11/17] AI-4053: count a cell's text as its number format writes it, and refuse a format longer than Excel allows A text section writes a cell's text once for each of its placeholders, so the count multiplies the text of every cell (shared and inline strings, and values) by the most any format of the workbook writes it. A format longer than Excel's 255 characters ([MS-XLS] 2.4.126) is refused before any cell is read. Co-Authored-By: Claude Opus 5.5 --- acceleration/go.mod | 2 +- .../knowledge/extract/extract_test.go | 121 ++++++++++++++++- .../internal/knowledge/extract/xlsx.go | 126 +++++++++++++++--- 3 files changed, 229 insertions(+), 20 deletions(-) diff --git a/acceleration/go.mod b/acceleration/go.mod index b18fbf4f2d..a8f37b5a22 100644 --- a/acceleration/go.mod +++ b/acceleration/go.mod @@ -55,6 +55,7 @@ require ( github.com/vektah/gqlparser/v2 v2.5.64 github.com/vmihailenco/msgpack/v5 v5.4.1 github.com/xuri/excelize/v2 v2.11.1 + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 go.opentelemetry.io/otel v1.46.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 @@ -187,7 +188,6 @@ require ( github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/wlynxg/anet v0.0.5 // indirect github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec // indirect - github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index bfe177f682..ecdfd85459 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/binary" + "encoding/xml" "errors" "fmt" "image" @@ -947,8 +948,8 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { // The text budget may be spent to the byte, and no further. Cells of spaces make no table, so the // cells alone spend it. Stored, the cells are counted before they are read, and a byte past the -// budget is refused then; a number format that writes a string twice ("@@") makes them longer as -// they are read, and they are counted again. +// budget is refused then; a number format that writes a string twice ("@@") makes them twice as +// long as they are read, and they are counted so. func (s *ExtractSuite) TestTheTextBudgetMayBeSpentToTheByte() { spaces := strings.Repeat(" ", 1<<20) columns := maxWorkbookText / len(spaces) @@ -989,6 +990,122 @@ func (s *ExtractSuite) TestTheTextBudgetMayBeSpentToTheByte() { s.requireReason(err, TooLarge) } +// formatted is a workbook of one row of cells, each the given XML, with the given shared strings, +// and with one number format, of the given code, which a cell of style 1 is written in. +func (s *ExtractSuite) formatted(code string, cells int, cell, shared string) []byte { + return s.formattedBy(`formatCode="`+s.escaped(code)+`"`, "xl/styles.xml", cells, cell, shared) +} + +// formattedBy is formatted with a number format of the given attributes, in a part of the given +// name. +func (s *ExtractSuite) formattedBy(numFmt, part string, cells int, cell, shared string) []byte { + data := s.withoutPart(s.cellsNaming(cells, cell, "xl/sharedStrings.xml", shared), "xl/styles.xml") + return s.rezip(data, map[string][]byte{part: []byte( + `` + + `` + + `` + + ``)}) +} + +func (s *ExtractSuite) escaped(text string) string { + var out bytes.Buffer + s.Require().NoError(xml.EscapeText(&out, []byte(text))) + return out.String() +} + +// A number format writes a cell's text once for each text placeholder of its text section, so a +// cell's text may be many times longer read than stored, and a row of such cells is built at once. +// The cells are counted as their formats write them before any row is built. +func (s *ExtractSuite) TestACellIsCountedAsItsNumberFormatWritesIt() { + text := strings.Repeat("y", 32<<10) + ats := strings.Repeat("@", 127) + // A fourth section is the text section, and its zero placeholders write the text as "@" does. + zeros := "0;0;0;" + strings.Repeat("0 ", 120) + shared := `` + text + `` + sharedCell := `0` + for name, data := range map[string][]byte{ + "a shared string, written by 127 text placeholders": s.formatted(ats, 1000, sharedCell, shared), + "an inline string, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), + "an inline string of runs, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), + "a value that is no number, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), + "a shared string, written by 120 zero placeholders": s.formatted(zeros, 1000, sharedCell, shared), + "a format whose code is replaced by its formatCode16": s.formattedBy(`formatCode="@" x16r2:formatCode16="`+ats+`"`, "xl/styles.xml", 1000, sharedCell, shared), + "a styles part named with a backslash": s.formattedBy(`formatCode="`+ats+`"`, `xl\styles.xml`, 1000, sharedCell, shared), + } { + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "formatted.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) + // Read, the row is gigabytes, many times the budget. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(2*maxWorkbookText), name) + } +} + +// A number format may be as long as Excel allows one to be, and no longer: excelize writes a long +// one's quoted text into each cell in time that grows with its square. +func (s *ExtractSuite) TestANumberFormatMayBeAsLongAsExcelAllows() { + // A character of two bytes, since the limit is of characters. + literal := func(length int) string { return `"` + strings.Repeat("é", length-3) + `"0` } + number := `1` + + read, err := s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(maxFormatCode), 2, number, "")) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, strings.Repeat("é", maxFormatCode-3)+"1") + + _, err = s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(maxFormatCode+1), 2, number, "")) + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "number format") + + // Read, a format of a megabyte of quoted text takes a minute for each cell. + started := time.Now() + _, err = s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(1<<20), 2, number, "")) + s.requireReason(err, TooLarge) + s.Less(time.Since(started), 5*time.Second) +} + +// A workbook in the formats people use reads as it did before formats were counted: text, a code +// padded with zeros, a weight with its unit, a price, a date, and text in a number's format. +func (s *ExtractSuite) TestAWorkbookOfOrdinaryFormatsReadsAsBefore() { + book := excelize.NewFile() + defer book.Close() + styles := map[string]int{} + for _, code := range []string{"@", "0000", `0 "kg"`, "0.00", "yyyy-mm-dd"} { + custom := code + style, err := book.NewStyle(&excelize.Style{CustomNumFmt: &custom}) + s.Require().NoError(err) + styles[code] = style + } + header := []any{"Item", "Code", "Weight", "Price", "Date", "Note"} + s.Require().NoError(book.SetSheetRow("Sheet1", "A1", &header)) + var want strings.Builder + want.WriteString("## Sheet1\n\n| Item | Code | Weight | Price | Date | Note |\n| --- | --- | --- | --- | --- | --- |") + for row := 2; row <= 40; row++ { + date := time.Date(2026, 1, row, 0, 0, 0, 0, time.UTC) + values := []any{"item " + strconv.Itoa(row), row, row * 3, float64(row) + 0.5, date, "note " + strconv.Itoa(row)} + cell, err := excelize.CoordinatesToCellName(1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetSheetRow("Sheet1", cell, &values)) + for column, code := range []string{"@", "0000", `0 "kg"`, "0.00", "yyyy-mm-dd", `0 "kg"`} { + cell, err := excelize.CoordinatesToCellName(column+1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellStyle("Sheet1", cell, cell, styles[code])) + } + fmt.Fprintf(&want, "\n| item %d | %04d | %d kg | %d.50 | %s | note %d |", row, row, row*3, row, date.Format("2006-01-02"), row) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + read, err := s.extractor.Extract(context.Background(), "ordinary.xlsx", out.Bytes()) + + s.Require().NoError(err) + s.Equal(want.String(), read.Pages[0].Text) +} + // A table may be as long as its limit and no longer, its last row counted as well as the others. func (s *ExtractSuite) TestATableMayBeAsLongAsItsLimit() { rows := [][]string{{"h"}, {"a"}, {"b"}} diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 233d323c5e..b78d55e642 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -10,8 +10,10 @@ import ( "io" "strconv" "strings" + "unicode/utf8" "github.com/xuri/excelize/v2" + "github.com/xuri/nfp" ) // maxWorkbook is the most a workbook may unpack to in all. A sheet's XML is several @@ -41,6 +43,13 @@ const maxWorkbookCells = 1_000_000 // an Office file may unpack to. const maxWorkbookText = 2 * maxUnzipped +// maxFormatCode is the longest number format a workbook may define, in characters: Excel's own +// limit for one ([MS-XLS] 2.4.126 Format: stFormat "MUST be greater than or equal to 1 character +// and less than or equal to 255 characters"). excelize writes a format's quoted text into a cell's +// value one character at a time, each a new copy of the value so far, so a longer one takes time +// that grows with the square of its length for each cell it is on. +const maxFormatCode = 255 + // budget is what is left of a workbook's limits as its sheets are read. type budget struct { cells int @@ -68,8 +77,11 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { } return Document{}, fail(Corrupt, XLSX, fmt.Errorf("the workbook cannot be read: %w", err)) } - if count.text > maxWorkbookText { - return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the shared strings the workbook's cells name are more than the %d bytes of text allowed", maxWorkbookText)) + if count.longest > maxFormatCode { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the workbook has a number format of %d characters, more than the %d allowed", count.longest, maxFormatCode)) + } + if count.overBudget() { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the text of the workbook's cells, its shared strings and the rest as its number formats write them, is more than the %d bytes of text allowed", maxWorkbookText)) } var sections []string @@ -189,7 +201,9 @@ func sheetPictures(book *excelize.File, sheet string, kept *pictures) ([]string, // the row can be counted. The workbook is refused when the shared strings its cells name are more // than the text budget, so no row is built past it. Every part is read as a sheet, since a sheet // may be any part the workbook names, so a hidden sheet's cells count as well. A number format -// may make a cell's text longer than it is stored, which the rows count as they are read. +// writes a cell's text once for each text placeholder in it (numfmt.go, textHandler), so a cell's +// text is counted that many times over, for the format of the most placeholders the workbook +// defines. type cellCount struct { ctx context.Context charset func(label string, input io.Reader) (io.Reader, error) @@ -197,7 +211,24 @@ type cellCount struct { // shared is the length of each shared string, read at the first cell that names one. shared []int32 read bool - text int + // text is the length of the shared strings the cells name. + text int + // stored is the length of the cells' own text, which a number format may write more than once. + stored int + // longest is the length of the longest number format, in characters. + longest int + // repeat is the most times a number format writes a cell's text. + repeat int +} + +// overBudget is whether the workbook's cells are more text, as excelize reads them, than the text +// budget. A cell's own text is in the file as often as the cell is, so it is counted only when a +// number format writes it more than once. +func (c *cellCount) overBudget() bool { + if c.repeat <= 1 { + return c.text > maxWorkbookText + } + return c.text+c.stored > maxWorkbookText/c.repeat } // workbook counts the cells of every part of a workbook. @@ -211,10 +242,59 @@ func (c *cellCount) workbook(data []byte) error { if err := c.part(file, c.cells); err != nil { return err } + // excelize reads the number formats from this part only (styles.go, stylesReader). + if strings.ReplaceAll(file.Name, `\`, "/") == "xl/styles.xml" { + if err := c.part(file, c.formats); err != nil { + return err + } + } } return nil } +// formats reads the number formats of the styles part, as excelize reads them (xlsxNumFmt): a +// format's code, and the code that takes its place when there is one. +func (c *cellCount) formats(decoder *xml.Decoder) error { + for { + token, err := decoder.Token() + if err != nil { + return nil + } + start, ok := token.(xml.StartElement) + if !ok || start.Name.Local != "numFmt" { + continue + } + for _, attr := range start.Attr { + if attr.Name.Local == "formatCode" || attr.Name.Local == "formatCode16" { + c.format(attr.Value) + } + } + } +} + +// format notes the length of a number format and how many times it writes a cell's text: once for +// each text or zero placeholder of a text section, parsed as excelize parses it (numfmt.go, format). +func (c *cellCount) format(code string) { + length := utf8.RuneCountInString(code) + c.longest = max(c.longest, length) + if length > maxFormatCode { + return + } + parser := nfp.NumberFormatParser() + for _, section := range parser.Parse(code) { + if section.Type != nfp.TokenSectionText { + continue + } + placeholders := 0 + for _, item := range section.Items { + if item.TType == nfp.TokenTypeTextPlaceHolder || item.TType == nfp.TokenTypeZeroPlaceHolder { + placeholders++ + } + } + c.repeat = max(c.repeat, placeholders) + } +} + // part reads one part of the workbook, handing each element to read. A part that is not XML, // or not past its first error, is read no further, as excelize reads it. func (c *cellCount) part(file *zip.File, read func(*xml.Decoder) error) error { @@ -243,19 +323,20 @@ func (c *cellCount) cells(decoder *xml.Decoder) error { return err } case start.Name.Local == "c": - n, err := c.cell(decoder, start) + shared, stored, err := c.cell(decoder, start) if err != nil { return err } - c.text += n + c.text += shared + c.stored += stored } } } -// cell is the length of the shared string a cell names, read as excelize reads a cell (rows.go, -// cellXMLHandler; cell.go, getValueFrom). Any other text of a cell is in the file as often as the -// cell is, so it is never more than the part it is in. -func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, error) { +// cell is the length of the shared string a cell names and of the cell's own text, read as excelize +// reads a cell (rows.go, cellXMLHandler; cell.go, getValueFrom): an inline string's text, or the +// cell's value. Every kind of cell but a formula's string goes through its number format. +func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, int, error) { kind := "" for _, attr := range start.Attr { if attr.Name.Local == "t" { @@ -263,6 +344,7 @@ func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, err } } var value string + inline, hasInline := 0, false for done := false; !done; { token, err := decoder.Token() if err != nil { @@ -273,8 +355,13 @@ func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, err switch element.Name.Local { case "v": err = decoder.DecodeElement(&value, &element) - case "f", "is": - // Read whole, so a value inside them is not the cell's. + case "is": + // Read whole, so a value inside it is not the cell's. + var text sharedString + err = decoder.DecodeElement(&text, &element) + inline, hasInline = inline+text.length(), true + case "f": + // Read whole, so a value inside it is not the cell's. err = decoder.Skip() } case xml.EndElement: @@ -284,18 +371,23 @@ func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, err break } } - if kind != "s" || value == "" { - return 0, nil + switch { + case kind == "str": + return 0, 0, nil + case kind == "inlineStr" && hasInline: + return 0, inline, nil + case kind != "s" || value == "": + return 0, len(value), nil } if err := c.readShared(); err != nil { - return 0, err + return 0, 0, err } // As in excelize, an index that is not a number is the first string. index, _ := strconv.Atoi(strings.TrimSpace(value)) if index < 0 || index >= len(c.shared) { - return 0, nil + return 0, 0, nil } - return int(c.shared[index]), nil + return int(c.shared[index]), 0, nil } // readShared reads the length of every shared string, once. excelize reads the strings that are From ef0c3fce13763258f89524799ed128db5dc52c3c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 13:30:22 -0500 Subject: [PATCH 12/17] AI-4053: pin that a shared string of runs is counted before its row is built Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/knowledge/extract/extract_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index ecdfd85459..530a8f92b1 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -933,6 +933,10 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { data: s.cellsNaming(128, first, `xl\sharedStrings.xml`, long), budget: maxWorkbookText, }, + "a string of runs": { + data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), + budget: maxWorkbookText, + }, } { var before, after runtime.MemStats runtime.GC() @@ -941,7 +945,8 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { runtime.ReadMemStats(&after) s.requireReason(err, TooLarge) - // The row is two to four times the text budget. + s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) + // The row is two to eight times the text budget. s.Less(after.TotalAlloc-before.TotalAlloc, test.budget, name) } } From 626520a3cedec7d93f9e67bcc17547e2e476eccb Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 13:30:53 -0500 Subject: [PATCH 13/17] AI-4053: pin that a cell of two values is counted at the last, as excelize reads it Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/knowledge/extract/extract_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index 530a8f92b1..fc605e8b56 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -937,6 +937,10 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), budget: maxWorkbookText, }, + "a cell of two values, the last naming the long string": { + data: s.cellsNaming(128, `10`, "xl/sharedStrings.xml", long+short), + budget: maxWorkbookText, + }, } { var before, after runtime.MemStats runtime.GC() From 5ca3897d22b6e326ca1840cd141ce79195ca8a8f Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 13:32:15 -0500 Subject: [PATCH 14/17] AI-4053: check the deadline every 4,096 XML tokens as the cells are counted A part of elements that are no row, cell or string was read to its end before the deadline was seen. The number formats are now read in the same pass as the cells, so the styles part is read once. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 21 +++++++ .../internal/knowledge/extract/xlsx.go | 62 ++++++++++++------- 2 files changed, 60 insertions(+), 23 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index fc605e8b56..faac970f69 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -1289,6 +1289,27 @@ func (s *ExtractSuite) TestTheCellsAreCountedOnlyUntilTheDeadline() { } } +// The deadline is checked every few thousand XML tokens as the cells are counted, not only at a +// row or a string: a part of many elements that are none of them is not read to its end past it. +func (s *ExtractSuite) TestAPartOfOtherElementsIsCountedOnlyUntilTheDeadline() { + junk := strings.Repeat(``, 100_000) + for name, data := range map[string][]byte{ + "a part that is no sheet": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/junk.xml": []byte(`` + junk + ``)}), + // Inside a formula, which the count of a part's cells skips whole, so the elements are + // read one by one only as the shared strings are read. + "the shared strings": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`s` + junk + ``)}), + "a cell": s.sheet(`0` + junk + ``), + "the styles": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/styles.xml": []byte(`` + junk + ``)}), + } { + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err, name) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded, name) + } +} + // sheet is a workbook whose only sheet is the given XML, rows of inline strings. func (s *ExtractSuite) sheet(sheetData string) []byte { return s.rezip(s.workbook(1, 1), map[string][]byte{"xl/worksheets/sheet1.xml": []byte( diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index b78d55e642..1816dfde88 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -219,6 +219,24 @@ type cellCount struct { longest int // repeat is the most times a number format writes a cell's text. repeat int + // tokens is how many XML tokens have been read, of every part. + tokens int + // styles is whether the part being read is the one of the number formats. + styles bool +} + +// tokensPerDeadlineCheck is how many XML tokens are read between two checks of the deadline, so a +// part of elements that are no row, cell or string is not read to its end past it. A token is at +// least a few bytes and costs more to read than a check, so this is a few tens of kilobytes of a +// part between checks, at a cost too small to measure. +const tokensPerDeadlineCheck = 4096 + +// tick counts one token read, and is the deadline's error at every tokensPerDeadlineCheck tokens. +func (c *cellCount) tick() error { + if c.tokens++; c.tokens%tokensPerDeadlineCheck != 0 { + return nil + } + return c.ctx.Err() } // overBudget is whether the workbook's cells are more text, as excelize reads them, than the text @@ -239,35 +257,21 @@ func (c *cellCount) workbook(data []byte) error { } c.archive = archive for _, file := range archive.File { + // excelize reads the number formats from this part only (styles.go, stylesReader). + c.styles = strings.ReplaceAll(file.Name, `\`, "/") == "xl/styles.xml" if err := c.part(file, c.cells); err != nil { return err } - // excelize reads the number formats from this part only (styles.go, stylesReader). - if strings.ReplaceAll(file.Name, `\`, "/") == "xl/styles.xml" { - if err := c.part(file, c.formats); err != nil { - return err - } - } } return nil } -// formats reads the number formats of the styles part, as excelize reads them (xlsxNumFmt): a -// format's code, and the code that takes its place when there is one. -func (c *cellCount) formats(decoder *xml.Decoder) error { - for { - token, err := decoder.Token() - if err != nil { - return nil - } - start, ok := token.(xml.StartElement) - if !ok || start.Name.Local != "numFmt" { - continue - } - for _, attr := range start.Attr { - if attr.Name.Local == "formatCode" || attr.Name.Local == "formatCode16" { - c.format(attr.Value) - } +// numFmt reads a number format of the styles part, as excelize reads one (xlsxNumFmt): its code, +// and the code that takes its place when there is one. +func (c *cellCount) numFmt(start xml.StartElement) { + for _, attr := range start.Attr { + if attr.Name.Local == "formatCode" || attr.Name.Local == "formatCode16" { + c.format(attr.Value) } } } @@ -308,9 +312,13 @@ func (c *cellCount) part(file *zip.File, read func(*xml.Decoder) error) error { return read(decoder) } -// cells counts the cells of a part, checking the deadline at each row, as the rows are read. +// cells counts the cells of a part, and notes the number formats of the styles part, checking the +// deadline at each row, as the rows are read, and every tokensPerDeadlineCheck tokens. func (c *cellCount) cells(decoder *xml.Decoder) error { for { + if err := c.tick(); err != nil { + return err + } token, err := decoder.Token() if err != nil { return nil @@ -329,6 +337,8 @@ func (c *cellCount) cells(decoder *xml.Decoder) error { } c.text += shared c.stored += stored + case c.styles && start.Name.Local == "numFmt": + c.numFmt(start) } } } @@ -346,6 +356,9 @@ func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, int var value string inline, hasInline := 0, false for done := false; !done; { + if err := c.tick(); err != nil { + return 0, 0, err + } token, err := decoder.Token() if err != nil { break @@ -418,6 +431,9 @@ func (c *cellCount) readShared() error { func (c *cellCount) sharedStrings(decoder *xml.Decoder, everyOne bool) error { depth, index := 0, 0 for { + if err := c.tick(); err != nil { + return err + } token, err := decoder.Token() if err != nil { return nil From 7439a3f806a2346c3019e930454d80e2ecf64519 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:32:51 -0500 Subject: [PATCH 15/17] AI-4053: Build the wide test workbooks as XML, not cell by cell excelize holds a row set with SetCellValue as wide as its last column, so the test workbooks with a value in column XFD of 1,500 rows took gigabytes to build before the reader saw them, and the CI go and integration (api) jobs were killed. The extract workbook helper now writes its sheet and shared strings as XML, and the cell-limit and API tests stream their rows, as inline strings. The rows the reader is given are the same. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/documents_test.go | 6 +++- .../knowledge/extract/extract_test.go | 30 ++++++++++++++----- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/acceleration/internal/api/documents_test.go b/acceleration/internal/api/documents_test.go index 8d0f4baea6..b714c3a72a 100644 --- a/acceleration/internal/api/documents_test.go +++ b/acceleration/internal/api/documents_test.go @@ -276,11 +276,15 @@ func (s *DocumentsSuite) TestAWorkbookIsRefusedAsTheWrongFormatWithoutBeingRead( opened := s.opening(s.client) for name, column := range map[string]int{"menu.xlsx": 1, "wide.xlsx": 16384} { book := excelize.NewFile() + // Streamed, so each row is written as its one value, not held as wide as its last column. + writer, err := book.NewStreamWriter("Sheet1") + s.Require().NoError(err) for row := 1; row <= 1500; row++ { cell, err := excelize.CoordinatesToCellName(column, row) s.Require().NoError(err) - s.Require().NoError(book.SetCellValue("Sheet1", cell, "v")) + s.Require().NoError(writer.SetRow(cell, []any{"v"})) } + s.Require().NoError(writer.Flush()) var out bytes.Buffer s.Require().NoError(book.Write(&out)) s.Require().NoError(book.Close()) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index faac970f69..9e0432862c 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -681,18 +681,28 @@ func (k *killedAt) FPDFFormObj_GetObject(request *requests.FPDFFormObj_GetObject return k.Pdfium.FPDFFormObj_GetObject(request) } -// workbook is a workbook whose rows each hold one value, in the given column. +// workbook is a workbook whose rows each hold one value, in the given column. Its sheet and shared +// strings are written as excelize saves them, not set cell by cell: excelize holds a row it sets as +// wide as its last value, so a workbook of rows that reach a far column takes gigabytes to build. func (s *ExtractSuite) workbook(rows, column int) []byte { book := excelize.NewFile() defer book.Close() - for row := 1; row <= rows; row++ { - cell, err := excelize.CoordinatesToCellName(column, row) - s.Require().NoError(err) - s.Require().NoError(book.SetCellValue("Sheet1", cell, "v"+strconv.Itoa(row))) - } + s.Require().NoError(book.SetCellValue("Sheet1", "A1", "v1")) var out bytes.Buffer s.Require().NoError(book.Write(&out)) - return out.Bytes() + + name, err := excelize.ColumnNumberToName(column) + s.Require().NoError(err) + var sheetData, shared strings.Builder + for row := 1; row <= rows; row++ { + number := strconv.Itoa(row) + sheetData.WriteString(`` + strconv.Itoa(row-1) + ``) + shared.WriteString(`v` + number + ``) + } + return s.rezip(out.Bytes(), map[string][]byte{ + "xl/worksheets/sheet1.xml": []byte(`` + sheetData.String() + ``), + "xl/sharedStrings.xml": []byte(`` + shared.String() + ``), + }) } // A row is held as wide as its last value, so a workbook of a few kilobytes with a value in the @@ -759,12 +769,16 @@ func (s *ExtractSuite) TestTheCellLimitIsOfTheWholeWorkbook() { book := excelize.NewFile() _, err := book.NewSheet("Second") s.Require().NoError(err) + // Streamed, so each row is written as its one value, not held as wide as its last column. for sheet, rows := range map[string]int{"Sheet1": half, "Second": test.second} { + writer, err := book.NewStreamWriter(sheet) + s.Require().NoError(err) for row := 1; row <= rows; row++ { cell, err := excelize.CoordinatesToCellName(column, row) s.Require().NoError(err) - s.Require().NoError(book.SetCellValue(sheet, cell, "v")) + s.Require().NoError(writer.SetRow(cell, []any{"v"})) } + s.Require().NoError(writer.Flush()) } var out bytes.Buffer s.Require().NoError(book.Write(&out)) From a4688114cf18dbef2a7b042f80a48ba670fad50b Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 15:59:46 -0500 Subject: [PATCH 16/17] AI-4053: Tie the extract tests' allocation budgets to the input, not a fixed figure CI runs the backend tests with -race. Under the race detector, counting a 17 MiB shared string allocated more than the fixed 256 MiB budget, so TestASharedStringIsCountedAtTheIndexItIsReadAt failed while the reader was right. - TestASharedStringIsCountedAtTheIndexItIsReadAt: each case's budget is half its row (cells x the long string); the nested case has 128 cells. - TestATableLongerThanTheTextBudgetIsRefused: the table is four times the text budget and the budget twelve times it, between the refused write and the whole one. - TestACellIsCountedAsItsNumberFormatWritesIt: 256 cells, not 1,000 (still a gigabyte as read), so it runs in a quarter of the time. Every mutant of the counter, the formats and the table limit still fails these tests, with the reason and message checks off as well. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/extract/extract_test.go | 79 +++++++++++-------- 1 file changed, 45 insertions(+), 34 deletions(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index 9e0432862c..d24c879131 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -914,46 +914,49 @@ func (s *ExtractSuite) cellsNaming(cells int, cell, part, shared string) []byte // enough to hold, and every one in it when it is not, so a string nested one level down moves the // strings after it to other indices in one way and not the other. func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { - long := `` + strings.Repeat("y", 2<<20) + `` + const length = 2 << 20 + long := `` + strings.Repeat("y", length) + `` short := `short` first := `0` + // excelize holds a shared strings part of up to 16 MiB in memory, so a longer string makes + // it read the part as it reads one too large to hold. + const nested = 17 << 20 for name, test := range map[string]struct { data []byte - // budget is what the read may allocate. Counting a string allocates a few times its - // length, as the XML decoder grows its buffer, for each of the two ways it is read. - budget uint64 + // row is the text of the row as it is built: the long string once in every cell. + row int }{ "a part small enough to hold, the first string the root's child": { - data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+short+``+long), - budget: maxWorkbookText, + data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+short+``+long), + row: 128 * length, }, "a part too large to hold, the first string nested": { - data: s.cellsNaming(32, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 17<<20)+``+short), - budget: 2 * maxWorkbookText, + data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", nested)+``+short), + row: 128 * nested, }, "a cell whose formula holds another index": { - data: s.cellsNaming(128, `01`, "xl/sharedStrings.xml", long+short), - budget: maxWorkbookText, + data: s.cellsNaming(128, `01`, "xl/sharedStrings.xml", long+short), + row: 128 * length, }, "an index between spaces": { - data: s.cellsNaming(128, ` 1 `, "xl/sharedStrings.xml", short+long), - budget: maxWorkbookText, + data: s.cellsNaming(128, ` 1 `, "xl/sharedStrings.xml", short+long), + row: 128 * length, }, "a part named in other letters": { - data: s.cellsNaming(128, first, "XL/SharedStrings.xml", long), - budget: maxWorkbookText, + data: s.cellsNaming(128, first, "XL/SharedStrings.xml", long), + row: 128 * length, }, "a part named with a backslash": { - data: s.cellsNaming(128, first, `xl\sharedStrings.xml`, long), - budget: maxWorkbookText, + data: s.cellsNaming(128, first, `xl\sharedStrings.xml`, long), + row: 128 * length, }, "a string of runs": { - data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), - budget: maxWorkbookText, + data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), + row: maxSheetColumns << 20, }, "a cell of two values, the last naming the long string": { - data: s.cellsNaming(128, `10`, "xl/sharedStrings.xml", long+short), - budget: maxWorkbookText, + data: s.cellsNaming(128, `10`, "xl/sharedStrings.xml", long+short), + row: 128 * length, }, } { var before, after runtime.MemStats @@ -964,8 +967,10 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { s.requireReason(err, TooLarge) s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) - // The row is two to eight times the text budget. - s.Less(after.TotalAlloc-before.TotalAlloc, test.budget, name) + // Counting the long string allocates a few times its length for each of the two ways it + // is read, more under the race detector: at most a quarter of the row here. Building the + // row allocates more than the row. Half the row is between the two. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(test.row/2), name) } } @@ -1041,19 +1046,21 @@ func (s *ExtractSuite) escaped(text string) string { // The cells are counted as their formats write them before any row is built. func (s *ExtractSuite) TestACellIsCountedAsItsNumberFormatWritesIt() { text := strings.Repeat("y", 32<<10) + // Stored, the cells are 8 MiB of text, within the budget; read, a gigabyte, eight times it. + const cells = 256 ats := strings.Repeat("@", 127) // A fourth section is the text section, and its zero placeholders write the text as "@" does. zeros := "0;0;0;" + strings.Repeat("0 ", 120) shared := `` + text + `` sharedCell := `0` for name, data := range map[string][]byte{ - "a shared string, written by 127 text placeholders": s.formatted(ats, 1000, sharedCell, shared), - "an inline string, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), - "an inline string of runs, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), - "a value that is no number, written by 127 text placeholders": s.formatted(ats, 1000, ``+text+``, ""), - "a shared string, written by 120 zero placeholders": s.formatted(zeros, 1000, sharedCell, shared), - "a format whose code is replaced by its formatCode16": s.formattedBy(`formatCode="@" x16r2:formatCode16="`+ats+`"`, "xl/styles.xml", 1000, sharedCell, shared), - "a styles part named with a backslash": s.formattedBy(`formatCode="`+ats+`"`, `xl\styles.xml`, 1000, sharedCell, shared), + "a shared string, written by 127 text placeholders": s.formatted(ats, cells, sharedCell, shared), + "an inline string, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "an inline string of runs, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "a value that is no number, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "a shared string, written by 120 zero placeholders": s.formatted(zeros, cells, sharedCell, shared), + "a format whose code is replaced by its formatCode16": s.formattedBy(`formatCode="@" x16r2:formatCode16="`+ats+`"`, "xl/styles.xml", cells, sharedCell, shared), + "a styles part named with a backslash": s.formattedBy(`formatCode="`+ats+`"`, `xl\styles.xml`, cells, sharedCell, shared), } { var before, after runtime.MemStats @@ -1064,7 +1071,7 @@ func (s *ExtractSuite) TestACellIsCountedAsItsNumberFormatWritesIt() { s.requireReason(err, TooLarge) s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) - // Read, the row is gigabytes, many times the budget. + // Building the row allocates at least its gigabyte, four times this budget. s.Less(after.TotalAlloc-before.TotalAlloc, uint64(2*maxWorkbookText), name) } } @@ -1167,7 +1174,10 @@ func (s *ExtractSuite) TestATableLongerThanTheTextBudgetIsRefused() { header.WriteString(`h`) } header.WriteString(``) - last := `x` + // Each line of the table is its 1,024 cells of three bytes, a pipe and a line break. The + // table is four times the text budget. + rows := 4 * maxWorkbookText / (3*maxSheetColumns + 2) + last := `x` var before, after runtime.MemStats runtime.GC() @@ -1176,9 +1186,10 @@ func (s *ExtractSuite) TestATableLongerThanTheTextBudgetIsRefused() { runtime.ReadMemStats(&after) s.requireReason(err, TooLarge) - // Writing a table allocates several times its length, so the budget is a gigabyte, a few - // times the text budget. Writing the whole table allocates several gigabytes. - s.Less(after.TotalAlloc-before.TotalAlloc, uint64(1<<30)) + // Writing a table allocates five to six times its length: refused at the text budget, about + // six times the budget; written whole, over twenty times it. Twelve times is about twice the + // first and half the second. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(12*maxWorkbookText)) } // The deadline is checked between the rows of a table as it is written, not only as it is read. From 564d367dbe42ff01fff04a38d78b1dc954eba923 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 16:32:22 -0500 Subject: [PATCH 17/17] AI-4053: Hold the shared-strings runs case to the text budget The "a string of runs" case of TestASharedStringIsCountedAtTheIndexItIsReadAt had its budget raised to half its row. Its legit allocation is far below that, so the case gets the text budget back, and the other cases keep row/2. Co-Authored-By: Claude Haiku 5.5 --- .../internal/knowledge/extract/extract_test.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index d24c879131..3930f275b2 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -925,6 +925,8 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { data []byte // row is the text of the row as it is built: the long string once in every cell. row int + // budget overrides row/2 where the legit allocation is far under half the row. + budget uint64 }{ "a part small enough to hold, the first string the root's child": { data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+short+``+long), @@ -953,6 +955,8 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { "a string of runs": { data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), row: maxSheetColumns << 20, + // Legit allocation is about 23 MB under -race, so 128 MiB is about 5.8 times it. + budget: maxWorkbookText, }, "a cell of two values, the last naming the long string": { data: s.cellsNaming(128, `10`, "xl/sharedStrings.xml", long+short), @@ -970,7 +974,11 @@ func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { // Counting the long string allocates a few times its length for each of the two ways it // is read, more under the race detector: at most a quarter of the row here. Building the // row allocates more than the row. Half the row is between the two. - s.Less(after.TotalAlloc-before.TotalAlloc, uint64(test.row/2), name) + budget := uint64(test.row / 2) + if test.budget != 0 { + budget = test.budget + } + s.Less(after.TotalAlloc-before.TotalAlloc, budget, name) } }