perf(chunking): avoid repeated table scans while forming chunks

Merged
AF
15d ago
+58-1

Problem

With table isolation enabled (the default), PreChunkBuilder.will_fit() scans every accumulated element to decide whether a table is already present. Repeating this for every new element makes admission quadratic in the number of elements in a pre-chunk. Text-size limits do not bound a run of images without extracted text, and the default include_orig_elements=True retains those images individually.

For 300 empty images followed by one text element, the existing public chunking path performs 45,452 table-family checks.

Change

Record whether a table-family element has been added, update that flag during admission, and reset it with the rest of the builder state before flush() yields. The existing isinstance(Table) predicate also covers TableChunk subclasses. No original elements, metadata, chunk boundaries, overlap rules or table-isolation behavior are changed.

This is separate from #4517, which compacts excluded image payloads when include_orig_elements=False; the repeated scan still affects the default mode that preserves originals.

Validation

  • A deterministic linear-work budget exercises both the list and lazy public chunking APIs. On unchanged source: 2 failing work-bound regressions and 4 passing controls. The two failures perform 45,452 checks instead of meeting a 1,204-check bound.
  • Controls cover the existing compacted-image path, preserved source object identity, metadata and the reset timing for Table/TableChunk before a flush iterator is exhausted.
  • 510 tests pass across the new regressions and existing base, basic, title and table-isolation suites.
  • Ruff lint/format and git diff --check pass. An independent read-only review found no state-lifecycle regression. No complete repository suite was run.

Measurements

Local Python 3.12, seven alternating before/after pairs with collection before each call. The benchmark invokes public chunk_elements() using the exact baseline/current builder methods; input construction and result serialization are outside the timer. Images contain empty text and page-number metadata, followed by one visible text element.

InputPreserve originalsBefore medianAfter median
100 imagesYes (default)1.162 ms0.379 ms
1,000 imagesYes (default)78.745 ms2.369 ms
5,000 imagesYes (default)2,029.488 ms11.035 ms
5,000 imagesNo22.358 ms21.071 ms
5,000 short text elements, 20,000-character windowYes1,959.048 ms11.632 ms

All serialized content and metadata fingerprints match after excluding only newly generated chunk UUIDs, which differ between identical unmodified calls too. Original-element metadata remains in the comparison. These synthetic measurements cover chunking already-partitioned elements, not file parsing or whole ingestion throughput.

Suggested label: enhancement.