Skip to content

fix(csv): read a repeated header label as written - #4709

Merged
cragwolfe merged 5 commits into
Unstructured-IO:mainfrom
Bensonluo:fix/csv-repeated-header-labels
Nov 13, 2026
Merged

cragwolfe merged 5 commits into
Unstructured-IO:mainfrom
Bensonluo:fix/csv-repeated-header-labels

Conversation

@Bensonluo

@Bensonluo Bensonluo commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

read_delimited_text(), which reads every CSV and TSV upload, gets its header labels from pd.read_csv(), which makes a repeated label unique as it reads it. A header row name,name,age therefore yields the labels name, name.1, age; when a genuine name.1 label is also present, Pandas names the repeated name column name.2. The fabricated labels appear in the Table element's text and metadata.text_as_html, the same class of corruption #4574 fixed for data cells.

header row main labels this PR labels
name,name,age name name.1 age name name age
name,name,name.1 name name.2 name.1 name name name.1

Fixes #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 the Unnamed: n label Pandas gives it, which is the current emitted behavior (pinned by existing tests). No pandas option can disable the renaming (mangle_dupe_cols was removed in pandas 2.0), and reassembling the read with header=None would change the index and Unnamed: n semantics, 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:

  • the header line is peeked within a bounded budget of 1 Mi decoded characters inspected, including a blank prefix and text already queued by delimiter detection. An oversized header or prefix leaves Pandas' labels in place before the new splitter allocates fields; the existing new-fill budget and unbounded delimiter-sniffing behavior are unchanged;
  • the peek skips only the lines the read itself skips, so a header record of empty tab-separated cells (\t\nA\tA\n) keeps its Unnamed labels instead of taking the data row's values — on the sniffed path the line is re-peeked with the sniffed delimiter;
  • a header line that does not hold a complete record, a quoted cell spanning lines, is left alone (its field count alone cannot tell, when the spanning cell is last);
  • the record is split by _split_header_record(), an in-module quote-aware scanner, instead of csv.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 limit partition_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.text and metadata.text_as_html for 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 keep main'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.py and test_tsv.py: 136 passed, 9 skipped, covering a repeated label (text and text_as_html), a genuine name.1 label, a repeated label beside an empty header cell (Unnamed: n kept), 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 on main with 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 sniffed partition_csv() path with large non-ASCII repeated/unique labels; those same cases produce 9 failures and 5 passes on 56c11c0 and all pass with the fix. The fourth review round's regression holds only while the unbounded sniff sample is still bound through pd.read_csv() on a headerless sniffed read (red on 5b54e9b, green with the sample back to a temporary); nothing else changes. Repository-wide ruff check . and ruff format --check . pass. The branch includes current main (ad56303); its separate detection-metrics regression test could not collect in this CSV test environment because torch is not installed.

View guided diff

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I found four issues in the header restoration path:

  1. High — Blank TSV prefixes can exhaust memory (unstructured/partition/csv.py:128). With include_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.

  2. Medium — A multiline final header can lose text (unstructured/partition/csv.py:161). For a TSV header such as name\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, losing line from table text and HTML. Please establish that the logical header record is complete before restoring labels.

  3. 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 two Unnamed labels. Please select the same header record as the parser, including records made entirely of empty tab-separated fields.

  4. Medium — Header parsing adds a process-dependent field-size limit (unstructured/partition/csv.py:161). The new csv.reader parses every nonempty header, including unique labels, and applies the global csv.field_size_limit. A TSV header field larger than that limit can now raise csv.Error even 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]>
@Bensonluo

Copy link
Copy Markdown
Contributor Author

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:

  1. Blank-prefix memory — the header peek now runs within a chunk budget (_HEADER_PEEK_MAX_CHUNKS, about 1 MiB): past it the peek gives up, leaving what it read queued and the labels as Pandas wrote them, so a compressed TSV with a long blank prefix is no longer held in memory whole (test_partition_tsv_leaves_labels_alone_when_a_blank_prefix_is_too_long_to_peek, plus a white-box budget test). The sniff peek keeps its pre-existing unbounded behavior, which this PR did not change.

  2. Multiline final header — restoration now runs only when the first line holds a complete record: _record_is_complete() tracks the quoting state, so name\tname\t"address\nline" keeps its full label and no header text is lost (test_partition_tsv_keeps_a_multiline_quoted_header_cell_whole). Field count alone cannot tell, as you note, when the spanning cell is the last one.

  3. Empty TSV header — the header peek now skips only the lines the read itself skips: a line holding a delimiter (or a quote) is a record, so \t\nA\tA\n keeps its Unnamed labels. Both engines were checked to read the tab-only line as the header record, so the re-peek applies on the sniffed path too, with the sniffed delimiter (test_partition_tsv_keeps_an_empty_header_record_off_the_data_rows and the CSV twin).

  4. Field-size limit — the header parse catches csv.Error and leaves Pandas' labels, so an over-limit header field no longer raises on an input the read accepts; the test pins it against an ambient limit, which is what this path sees since partition_tsv() never touches the global one.

On the compatibility question: the observable change to table text/text_as_html (and to any hash built from it) is the fix itself — #4708 reports exactly that mangling — but I'm happy to add release-note guidance if you'd like it spelled out.

Separately, the Measure and compare partition() runtime failure looks like infrastructure rather than this change: the job dies in Install system dependencies at apt, where the alex-p/tesseract-ocr5 PPA has no Release file for the runner's Ubuntu 26.04 image, before any checkout-dependent step runs. The same job fails the same way on other PRs, including already-merged #4703.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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]>
@Bensonluo

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review — fixed in 56c11c0.

The header record is now split by _split_header_record(), an in-module quote-aware scanner, so the restoration path no longer consults — or sets — the process-wide field-size limit: a header field past the ambient limit is restored the same as at the raised one, without touching global CSV state, which also removes the coordination concern. test_partition_tsv_restores_labels_whatever_the_ambient_field_size_limit pins your scenario: the same file partitioned at csv.field_size_limit(1024) and at the ambient limit must produce identical text and text_as_html (it fails on cb9d43a with name name.1).

To keep the hand-rolled splitter honest, test_the_header_record_splitter_agrees_with_the_csv_module checks it against csv.reader over every record it can be reached with: every string through length 7 over {a, sep, ", <space>}, with no ending, \n or \r\n, for both \t and ,, filtered to the records _record_is_complete() accepts. The only family the two disagree on is records whose quote is left open at the end of the line — there csv.reader keeps the terminator as field text — and those never reach the splitter.

partition_csv()'s own csv.field_size_limit(10 MiB) set-without-restore predates this change and is untouched; it can no longer reach the labels. The compatibility question (persisted text/HTML/IDs for consumers that upsert) stays where you put it, with the maintainer — the PR body discloses the behavior change and its bounds.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@Bensonluo

Copy link
Copy Markdown
Contributor Author

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 partition_csv(..., include_header=True) case exercises the sniffed tab-delimited path with a long non-ASCII header, for both repeated and unique labels: it verifies that the header splitter is not called and Pandas' labels remain in the text and HTML.

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 ruff check . and ruff format --check . pass. The branch also includes current main (ad56303); its separate detection-metrics regression test could not collect in this CSV test environment because torch is not installed.

The public text/HTML/ID compatibility decision remains with the maintainers, as discussed above. Please also apply the bug category label for the generated release notes.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@Bensonluo

Copy link
Copy Markdown
Contributor Author

Thanks for the review — fixed in a90a5ce.

The sniff sample is back to a temporary: read_delimited_text() passes reader.peek_first_non_blank_line() straight into _sniff_delimiter() instead of binding it to a local, so nothing holds the joined record through pd.read_csv() on a headerless read. A header read still replaces the sample with the bounded _peek_header_line() re-peek before parsing, and _restore_repeated_header_labels() restores nothing without a header, so no other behavior changes.

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 pd.read_csv and fails while any local of read_delimited_text() still holds a string the size of the record, and asserts the sniffed read still parses the record.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)

@cragwolfe
cragwolfe enabled auto-merge November 13, 2026 19:53
@cragwolfe
cragwolfe added this pull request to the merge queue Nov 13, 2026
Merged via the queue into Unstructured-IO:main with commit 7d81b40 Nov 13, 2026
52 of 53 checks passed
Bensonluo added a commit to Bensonluo/unstructured that referenced this pull request Nov 13, 2026
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.
iammanoj807 added a commit to iammanoj807/unstructured that referenced this pull request Nov 14, 2026
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.
iammanoj807 pushed a commit to iammanoj807/unstructured that referenced this pull request Nov 17, 2026
…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. -->
iammanoj807 added a commit to iammanoj807/unstructured that referenced this pull request Nov 17, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: a repeated CSV or TSV header label is read as "name.1", not as written

2 participants