Repository navigation
fix(csv): read a repeated header label as written - #4709
Conversation
Signed-off-by: Benson LUO <[email protected]>
cragwolfe
left a comment
There was a problem hiding this comment.
I found four issues in the header restoration path:
-
High — Blank TSV prefixes can exhaust memory (
unstructured/partition/csv.py:128). Withinclude_header=True, the new peek retains every decoded chunk before the first nonblank line. A compressed TSV containing a large blank prefix, or only blank lines, can therefore use memory proportional to its decompressed size even though the cell-count limit does not bound that prefix. The explicit-tab path previously consumed these chunks as it read. Please keep header inspection bounded in memory, including for compressed and nonseekable input. -
Medium — A multiline final header can lose text (
unstructured/partition/csv.py:161). For a TSV header such asname\tname\t"address\nline", the first physical line already has three fields, so the field-count check passes even though the quoted last field is incomplete. Restoration then replaces the complete Pandas label with the truncated field, losinglinefrom table text and HTML. Please establish that the logical header record is complete before restoring labels. -
Medium — An empty TSV header can be replaced by data values (
unstructured/partition/csv.py:128). For\t\nA\tA\n, the peek treats the tab-only header as whitespace and selects the first data row. Its repeated values then replace the twoUnnamedlabels. Please select the same header record as the parser, including records made entirely of empty tab-separated fields. -
Medium — Header parsing adds a process-dependent field-size limit (
unstructured/partition/csv.py:161). The newcsv.readerparses every nonempty header, including unique labels, and applies the globalcsv.field_size_limit. A TSV header field larger than that limit can now raisecsv.Erroreven though the Pandas path accepted it before; the effective limit also depends on whether an earlier CSV partition changed it. Please avoid imposing this incidental limit on accepted inputs.
Maintainer decision needed: Restoring repeated labels changes the public table text and HTML for affected inputs. It can also change deterministic element IDs when id_to_hash() is used, because the hash includes the text. Please decide whether that compatibility impact is acceptable and whether users need migration or release guidance. The correction restores source labels, but the impact is observable by consumers.
This is a static review of head 9498e6d528289b571f209898b695b46e72b864e0 against base c47ef65e827f2b3d80a4bf246909d029dc8b4fe8. The exact-head runtime-comparison check was failing when checked; I did not determine its cause. Local tests were not run.
(authored by codex)
- the header-line peek now gives up past a bounded number of chunks (about 1 MiB) instead of holding a long blank prefix in memory, leaving the labels as Pandas wrote them; - the peek skips only the lines the read itself skips, so a header record of empty tab-separated cells is no longer replaced by data-row values, on both the explicit-sep and the sniffed path; - a header record that spans lines, a quoted cell holding a line break, is detected and left alone, so none of its text is lost; - a header field longer than the csv module's field-size limit no longer raises: the restoration gives up and Pandas' labels stand. Signed-off-by: Benson LUO <[email protected]>
|
Thanks for the review — all four issues are fixed in cb9d43a, each pinned by a new test that fails on the first commit of this PR:
On the compatibility question: the observable change to table Separately, the |
cragwolfe
left a comment
There was a problem hiding this comment.
I rechecked the four earlier findings and the author's reply against the full diff at cb9d43ab5ef4d810e6c635ec4b99971927b7a8fb.
Medium — TSV header output still depends on process-wide CSV state (unstructured/partition/csv.py:171–181). Catching csv.Error prevents the earlier exception, but it leaves Pandas' suffixed labels when any header field exceeds csv.field_size_limit. The same header is restored when the limit is higher. partition_csv() sets that process-wide limit to 10 MiB, while partition_tsv() uses the same restoration path without setting it. A TSV with repeated labels and a field between the ambient limit and the peek budget can therefore produce different table text and HTML depending on whether an unrelated CSV was processed first. Default element IDs also change because they include the text. This can affect retries, deduplication, and upserts across workers. Please make restoration independent of the ambient field limit; changing and restoring a global limit without coordination would still leave a concurrency risk.
The bounded header peek resolves the newly introduced blank-prefix memory issue. The complete-record check resolves multiline header truncation, and the delimiter-aware peek resolves the empty TSV header substitution. The prior field-size exception is resolved, but the output dependency above remains. The existing delimiter-sniffing memory behavior predates this change.
Maintainer decision still needed: Restoring duplicate headers intentionally changes public table text and HTML and, for ordinary calls, default text-derived element IDs. Please decide whether to accept that compatibility change and what migration guidance consumers who persist or upsert by ID need. This decision is separate from the process-history issue above.
This was a static review against base c47ef65e827f2b3d80a4bf246909d029dc8b4fe8; no local tests or reproductions were run. Exact-head CI workflows require approval, and the two Socket checks passed. This is not a merge-readiness assessment.
(authored by codex)
… limit The re-review found that reading the header record back through csv.reader left the restored labels dependent on the process-wide field-size limit: partition_csv() raises that limit to 10 MiB for its own read while partition_tsv() leaves it as it stood, so the same TSV could get different table text, HTML and element IDs depending on whether a CSV was partitioned first in the process. The record is now split by _split_header_record(), an in-module quote-aware scanner, so the restoration neither consults nor changes the process-wide limit and a field past the ambient limit is still restored. A differential test checks the scanner against the csv module over every single-line record it can be reached with, and the give-up test is rewritten into an ambient-limit-independence test pinning identical text and HTML at a 1 KiB limit and at the ambient one. Signed-off-by: Benson LUO <[email protected]>
|
Thanks for the re-review — fixed in 56c11c0. The header record is now split by To keep the hand-rolled splitter honest,
|
cragwolfe
left a comment
There was a problem hiding this comment.
I reviewed the full change at 56c11c09 and the author's reply. The previous TSV output dependency on the process-wide CSV field limit is resolved: header restoration no longer uses that limit.
Medium — A prebuffered header bypasses the restoration memory limit (unstructured/partition/csv.py:131–136, :172, :421–442). When delimiter detection uses the sniffed path, the first peek can queue a large header before the bounded header peek starts. The second peek counts only new fills, so it can return the entire already-queued header despite the limit. The new splitter then builds a list of individual characters for every field, even when labels are unique, while the parsed data frame is also live. A tab-delimited file passed through partition_csv(..., include_header=True) with a large non-ASCII header and few cells can therefore add substantial memory pressure; concurrent requests can exhaust worker memory. The pre-existing unbounded delimiter sniff is separate from this new allocation. Please apply the restoration budget to already-buffered text too, and leave Pandas' labels in place when the header exceeds that budget. A regression case should exercise a prefilled reader queue and a large header through the sniffed path.
Maintainer decision still needed: Restoring duplicate labels intentionally changes table text and HTML and can change the default text-derived element IDs. Please decide whether to accept that compatibility impact and what guidance consumers who persist or upsert by ID need.
This is a static review against base c47ef65e827f2b3d80a4bf246909d029dc8b4fe8; no local tests or reproductions were run. At the time checked, CI, Security, Partition Benchmark and CodeQL required workflow approval, and two Socket checks passed. This is not a merge-readiness assessment.
(authored by codex)
Count inspected characters before copying queued segments, including the blank prefix. Preserve input replay and unbounded delimiter sniffing. Also merge current upstream main (ad56303) without changing its metrics files.
|
Thanks for the review — the bounded header peek now charges text already queued by delimiter detection to its inspection budget, before slicing or retaining each segment. It counts the blank prefix too and leaves the queued input unchanged when it gives up. The existing limit on new fills remains in place; the unbounded delimiter-sniff path is unchanged. The regression cases prefill the reader queue, cover oversized headers and blank prefixes with and without a final newline, check the boundary immediately below/at/above the budget, and verify that the complete input can still be read after the peek. A With the same new cases, the previous implementation has 9 failures and 5 passes; the corrected implementation passes all 14. The complete CSV and TSV test files pass (135 passed, 9 skipped), and repository-wide The public text/HTML/ID compatibility decision remains with the maintainers, as discussed above. Please also apply the |
cragwolfe
left a comment
There was a problem hiding this comment.
Medium — Release the delimiter sample before parsing when there is no header. In read_delimited_text(), first_line keeps the unbounded delimiter-sniff sample alive during pd.read_csv() when header=None. The default partition_csv() call can reach this path for a tab-delimited file: the context's initial sniff only considers comma, semicolon, and pipe, so it falls back to the unrestricted sniff. For a large first data record, the joined sample remains in memory alongside the parser and dataframe allocations even after the reader drains its buffered chunks. This adds memory proportional to the whole first record for each concurrent request. Previously the sample was a temporary argument and could be released before parsing. Please keep it temporary or release it before pd.read_csv() when header restoration is disabled, and cover the headerless sniffed path with a large first record.
The previous finding about the restoration peek bypassing its budget is resolved: the peek now charges already-buffered text before retaining it and falls back without splitting an oversized header.
A separate maintainer decision remains on the intentional changes to table text, HTML, and default element IDs, including migration guidance for consumers that persist IDs. This comment does not settle that compatibility decision.
(authored by codex)
The unrestricted sniff joins a whole record of any size to read its line, and on a headerless read that sample stayed bound to a local through pd.read_csv(), holding memory proportional to the first record of the file for each concurrent request. The sample is now an argument of the sniff alone, the way it was before header restoration: a header read still re-peeks its bounded header line, and restoration is not reached without a header. The headerless sniffed path is covered by a regression that fails while any local of read_delimited_text() holds the sample as pd.read_csv() builds the data-frame.
|
Thanks for the review — fixed in a90a5ce. The sniff sample is back to a temporary: The regression covers the headerless sniffed path with a large first record (a tab-delimited file the context's ",;|" sniff falls back on): it wraps |
cragwolfe
left a comment
There was a problem hiding this comment.
I rechecked the full change at a90a5ce5d114d1ec1d0ba177a9c157033d901e2c against base ad56303cfae517612afcd5db85d3b4e303aa0d03 and the author's reply. The previous headerless sample-retention finding is resolved: the unrestricted sniff sample is now a temporary, and the header restoration sample is obtained separately with a bounded peek. The earlier restoration-budget finding remains resolved. I found no new actionable Critical, High, or Medium issue in this static review.
Maintainer decision still needed: Restoring repeated headers changes table text and HTML and can change default text-derived element IDs. A consumer that upserts by ID may need to reconcile older elements when reprocessing. Please decide whether to accept that compatibility impact and what migration or release guidance is needed. This comment does not settle that decision.
This review covered the CSV and TSV paths, surrounding callers, tests, and discussion. No local tests or reproductions were run. Exact-head CI, Security, CodeQL, and Partition Benchmark workflows require approval; two Socket checks passed when checked. This is not a merge-readiness assessment.
(authored by codex)
7d81b40
Both changes meet in unstructured/partition/csv.py and its tests: keep Unstructured-IO#4709's header-label restoration and the sniff sample as a temporary in read_delimited_text(), composed with this branch's decompressing handle and whole-line sampling in _CsvPartitioningContext; imports take the union and both test sets are kept.
Pandas sizes the table by the first record (or header). A later record with more fields, such as a data row with a trailing delimiter, made partition_csv() and partition_tsv() fail with a ParserError. With include_header=True, data rows wider than the header instead had their first fields made the row index, which to_html(index=False) dropped without an error. check_cell_count() now measures the widest record with the quoting rules it already applies to the first record, and returns that width. read_delimited_text() passes it to Pandas as the column names, so every record is read whole and shorter ones are padded with empty cells. A header becomes the first row, labeled the way Pandas labels a header, with a repeated label read as written where Unstructured-IO#4709 restores it. The cell limit now bounds the table Pandas builds by construction.
…structured-IO#4786) ## Summary The repeated-header restoration added in Unstructured-IO#4709 misses a complete quoted header when the file has no final newline. For example, a file containing only `"name","name"` produces `name name.1` even though the second label is `name`. At the end of a complete peeked line, treat a pending quote as the closing quote of its field. A line without a terminator reaches this check only at EOF: the bounded header peek returns an empty string if its budget is exhausted, rather than returning a truncated prefix. Unclosed quoted fields and multi-line header handling retain their existing guards. The shared reader fixes CSV and TSV, including escaped quotes within duplicate labels. No read budget, delimiter, field-size limit or data-row behavior changes. ## Validation - The 27 new cases produce **18 failures and 9 passing controls** on the original source. - Exercises filename and byte-stream inputs, comma/semicolon/tab separators, duplicate labels, genuine suffixed labels and escaped quotes. Controls cover LF/CRLF endings and incomplete quoted records. - A combined fork validation branch runs both changes' regressions against the pinned original source: **27 failures, 12 passing controls**. With the final source restored, the regressions plus the existing Prodigy, CSV and TSV suites report **192 passed** on Python 3.12. - The existing CSV suite includes bounded and prefilled header-peek tests, multi-line header controls and the exhaustive single-line splitter comparison with Python's CSV reader. - Repository-configured Ruff check, format check and source-integrity checks pass. - [Validation run, exact commands and JUnit artifacts](https://github.com/Afloat16/unstructured/actions/runs/43833221474). ## Checklist - [x] User-facing conventional-commit title. - [ ] Maintainer: please apply the `bug` category label. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4786?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Pandas sizes the table by the first record (or header). A later record with more fields, such as a data row with a trailing delimiter, made partition_csv() and partition_tsv() fail with a ParserError. With include_header=True, data rows wider than the header instead had their first fields made the row index, which to_html(index=False) dropped without an error. check_cell_count() now measures the widest record with the quoting rules it already applies to the first record, and returns that width. read_delimited_text() passes it to Pandas as the column names, so every record is read whole and shorter ones are padded with empty cells. A header becomes the first row, labeled the way Pandas labels a header, with a repeated label read as written where Unstructured-IO#4709 restores it. The cell limit now bounds the table Pandas builds by construction.
Summary
read_delimited_text(), which reads every CSV and TSV upload, gets its header labels frompd.read_csv(), which makes a repeated label unique as it reads it. A header rowname,name,agetherefore yields the labelsname,name.1,age; when a genuinename.1label is also present, Pandas names the repeatednamecolumnname.2. The fabricated labels appear in theTableelement'stextandmetadata.text_as_html, the same class of corruption #4574 fixed for data cells.mainlabelsname,name,agename name.1 agename name agename,name,name.1name name.2 name.1name name name.1Fixes #4708.
Change
read_delimited_text()peeks the first header line once (the delimiter sniff already reads it) and, after the read,_restore_repeated_header_labels()gives the data-frame back the labels the file holds when they repeat. An empty header cell keeps theUnnamed: nlabel Pandas gives it, which is the current emitted behavior (pinned by existing tests). No pandas option can disable the renaming (mangle_dupe_colswas removed in pandas 2.0), and reassembling the read withheader=Nonewould change the index andUnnamed: nsemantics, so the labels are restored after the read.The restoration is best-effort and gives up (leaving Pandas' labels) rather than mis-read or fail, per the review:
\t\nA\tA\n) keeps itsUnnamedlabels instead of taking the data row's values — on the sniffed path the line is re-peeked with the sniffed delimiter;_split_header_record(), an in-module quote-aware scanner, instead ofcsv.reader, so a field past the csv module's field-size limit is restored too and the labels no longer depend on the process-wide limitpartition_csv()raises for its own read — no global CSV state is read or set on this path (per the re-review).Compatibility
Restoring the file's repeated labels changes
Table.textandmetadata.text_as_htmlfor any file whose header row repeats a label — that is the fix. For documents re-processed after this change, the changed text also changes any default element ID derived from that text, so a consumer that upserts by ID may need to reconcile or re-ingest the older elements (raised in review). Files whose header labels do not repeat keepmain's output, pinned by the existing tests. Whether to accept this behavior change, and what release or migration guidance to attach, is for the maintainers to decide.Validation
test_unstructured/partition/test_csv.pyandtest_tsv.py: 136 passed, 9 skipped, covering a repeated label (text andtext_as_html), a genuinename.1label, a repeated label beside an empty header cell (Unnamed: nkept), a quoted repeated label, CRLF endings, and — from the review rounds — a quoted header cell spanning lines (labels left alone, no text lost), a header record of empty cells (explicit and sniffed delimiter), a blank prefix past the peek budget, the budget itself (white-box), label restoration independent of the ambient field-size limit (same text and HTML at a 1 KiB limit and at the ambient one), and a differential test checking the in-module splitter against the csv module over every single-line record it can be reached with (strings through length 7 over a four-symbol alphabet, three line endings, both delimiters). The first seven fail onmainwith the fabricated label; the first review round's tests fail on this PR's first commit and pass on the second; the re-review's tests fail on the second and pass on the third. The latest review adds 14 parameterized cases for a prefilled header/prefix (including an unterminated line), the budget boundary, input replay after giving up, and the sniffedpartition_csv()path with large non-ASCII repeated/unique labels; those same cases produce 9 failures and 5 passes on56c11c0and all pass with the fix. The fourth review round's regression holds only while the unbounded sniff sample is still bound throughpd.read_csv()on a headerless sniffed read (red on5b54e9b, green with the sample back to a temporary); nothing else changes. Repository-wideruff check .andruff format --check .pass. The branch includes currentmain(ad56303); its separate detection-metrics regression test could not collect in this CSV test environment becausetorchis not installed.