perf(layout): Bound region grouping memory

Merged
CY
1mo ago
+143-8

Grouping N OCR regions currently builds an N×N intersection graph and scans all N labels again for each component. Large pages can exhaust memory even when the boxes scarcely overlap. Use a sweep and disjoint-set components with linear retained storage, then split a single stable ordering of the labels. Small inputs retain the existing dense fast path; non-finite/inverted coordinates retain the original comparison rules.

Validation:

  • Full local inference suite: 299 passed, 1 skipped; Ruff and lock/version checks pass.
  • Regression oracle covers threshold boundaries, ordering, touching/nested boxes, NaN/Inf/inverted bounds and reversed chains. Independent review ran another 500 randomized baseline/candidate comparisons with identical groups and associated arrays.
  • Dedicated nick-oom-perf-oct01 SND, same core-product API image digest and two-core Linux pod limits, three matched trials: 8,000 sparse regions take a median 1.126 → 0.128 seconds, peak RSS 619 → 141 MiB; 5,000 densely overlapping regions take 0.933 → 0.460 seconds, RSS 726 → 132 MiB. Output hashes match in every trial. These measure grouping, not end-to-end partition latency.
  • At a 768 MiB pod limit, the baseline is OOMKilled (exit 137) on 20,000 sparse regions; the final candidate completes with the expected 20,000 groups and matching output hash. All 35 SND grouping/layout regressions pass. A real three-page YOLOX+OCR PDF partition returned nine identical elements and executed the changed grouping function six times on each side.

Dense overlap can still require quadratic comparison time; the improvement bounds retained graph memory and removes repeated per-component scans. Returned groups still require memory proportional to their content.

Targets 1.6.15, one patch above main (1.6.14), independently of the other open PRs. After another PR merges, update this PR to the next patch version on main before merging. Downstream consumers receive the change after publication and adoption of that release.