Skip to content

fix(tsv): honor infer_table_structure when partitioning TSV files - #4513

Merged
cragwolfe merged 11 commits into
Unstructured-IO:mainfrom
feiiiiii5:fix/tsv-infer-table-structure
Oct 23, 2026
Merged

cragwolfe merged 11 commits into
Unstructured-IO:mainfrom
feiiiiii5:fix/tsv-infer-table-structure

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

partition_tsv() silently ignores infer_table_structure=False, so callers still receive Table.metadata.text_as_html. The flag is passed through by partition() but absorbed by **kwargs in the TSV partitioner.

The fix adds the explicit parameter with the same default (True) as the other table partitioners, and sets HTML metadata only when enabled. Tests cover both flag values through partition_tsv() and partition().

Disabling HTML sends the whole flattened table through the shared text splitter, which exposed latent progress and work-bound defects in that path. The branch therefore also carries the bounded-split fixes already discussed on this PR: a prefix wholly covered by overlap advances, the token window and fallback scans are bounded, the vocabulary bound is shared across HTML cells, the unread suffix is not re-encoded on every split, and a fitting input is not rejected because an earlier prefix overflowed.

This revision (f256ed23)

Both findings from the latest review:

  • Preferred-separator search: candidates inside one whitespace run all trim to the same fragment and lstrip to the same remainder. The run is now evaluated once and the remaining matches inside it are skipped, so "a" + " " * 100_000 + "print(1)" measures one candidate instead of 100,000. Covered for spaces, newlines, mixed whitespace and a configured tab separator.
  • Fallback overlap: split_pos > len(fragment) records that the cut trimmed a trailing whitespace run. That is now combined with is_whitespace_split, so the overlap tail gets a separating space when either side of the cut had whitespace. The corrupted "aprint(1)" expectation is replaced by "a print(1)"; an unbroken-word test still forbids an artificial space when the cut had no whitespace.

Test

  • pytest test_unstructured/chunking test_unstructured/partition/test_tsv.py -q → 719 passed, 2 skipped in 12.76s
  • ruff check and ruff format --check on the two changed files → clean
  • git diff --check → clean

Not run: the full partitioner/extras suites and cross-platform tests. CI is now running on this head; no green check is claimed yet.

Type of change: bug fix; no new dependency. Related #4373 changes numeric HTML generation, and #3870 fixed a duplicate auto-dispatch kwarg; neither addresses this ignored TSV flag.

@feiiiiii5
feiiiiii5 force-pushed the fix/tsv-infer-table-structure branch from 3a9ada9 to a27bf88 Compare October 1, 2026 04:41
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Merged current main (2c0c7a6c) and resolved the changelog/version and TSV-test conflicts, preserving the upstream resource-limit safeguards. The PR still changes only the original four files; the required version bump is now 0.27.18.

With frozen dependencies, TSV has 28 passing tests and adjacent CSV has 70. The new flag regressions still fail on current main (2 failed, 2 passed) and pass on this branch (4 passed). Ruff and formatting pass. Full partitioner/extras suites were not rerun.

@feiiiiii5
feiiiiii5 force-pushed the fix/tsv-infer-table-structure branch from bf6728d to 622458a Compare October 5, 2026 04:29

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

GPT Pro review of 622458a: one High-priority correctness finding. The flag handling is otherwise consistent with the intended behavior, but disabling HTML exposes a token-chunking loop that can exhaust a worker. Please repair the splitter's progress guarantee and add regression coverage before merging.

All five required branch checks and the required Socket check passed on this exact head. No tests were run locally for this review. The author-reported test counts were not independently rerun. Current main also conflicts with this branch in CHANGELOG.md and unstructured/version.py; resolve those release files and refresh CI after the update.

(authored by codex)

filename=filename,
last_modified=get_last_modified_date(filename) if filename else None,
text_as_html=html_table.html,
text_as_html=html_table.html if infer_table_structure else None,

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.

[P1] Ensure token chunking advances when HTML is disabled

This assignment newly sends TSV tables through the text-only table splitter. A supported call with a short first cell and a long unbroken second cell can then loop indefinitely:

partition_tsv(
    file=io.BytesIO(b"a\t" + b"x" * 10_000 + b"\n"),
    infer_table_structure=False,
    chunking_strategy="basic",
    max_tokens=100,
    tokenizer="cl100k_base",
    overlap=20,
)

With io imported and the tokenizer dependency installed, the table text is "a " + X. In _TextSplitter._split_by_tokens(), the space selects fragment "a"; _get_token_overlap_tail("a", 20) returns that whole fragment, reconstructing the original remainder. _iter_text_only_table_chunks() repeats without a progress check, and basic chunking accumulates chunks until interruption or memory exhaustion. The same shared path serves by_title. This scenario is established by source inspection; it was not executed during review.

The shared splitter defect already exists, but this PR exposes it to this TSV request: previously HTML was retained, and HTML cell splitting used options without the caller's overlap plus an explicit progress guard. The two-cell input passes the cell-count limit.

Keep the intended HTML omission and ensure every nonterminal token split consumes source content after overlap is applied, including the fallback branch. Do not simply break the loop and discard the remaining field. Add a bounded splitter regression for a prefix wholly covered by overlap, then direct/auto TSV coverage with HTML disabled and token overlap, verifying finite output and preserved text.

(authored by codex)

@feiiiiii5
feiiiiii5 force-pushed the fix/tsv-infer-table-structure branch from 622458a to 452d8ba Compare October 17, 2026 05:33
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review @cragwolfe.

I have updated the branch to address the token chunking loop, refreshed against origin/main, and added regression coverage:

  1. Token Splitter Progress Guarantee:

    • In _TextSplitter._split_by_tokens(), separator matches are now skipped if the fragment is wholly covered by overlap (measure(fragment) <= overlap) or if len(overlapped_remainder) >= len(s).
    • In the fallback branch, backwards whitespace search similarly checks measure(cand_fragment) > overlap to avoid selecting a boundary that cannot progress after overlap. Fallback cuts ensure the remainder strictly consumes source content after overlap is applied without injecting spurious whitespace on arbitrary character boundaries.
  2. Regression Coverage:

    • Added unit test it_makes_progress_when_prefix_is_wholly_covered_by_overlap in test_unstructured/chunking/test_base.py verifying finite chunking and non-looping remainder advancement when a prefix is wholly within the overlap budget.
    • Added direct (test_partition_tsv_with_html_disabled_and_token_overlap) and auto-dispatch (test_partition_auto_tsv_with_html_disabled_and_token_overlap) regressions in test_unstructured/partition/test_tsv.py, verifying finite chunk generation, omitted text_as_html, and preserved payload text.
  3. Rebase & Release Files:

    • Rebased onto current main (1b02b4d18), resolving CHANGELOG.md and bumping unstructured/__version__.py to 0.27.29.
    • Local validation: 466 tests passed across test_tsv.py, test_csv.py, and test_base.py; ruff check and ruff format --check passed cleanly.

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

GPT Pro follow-up review of 452d8ba: the prior High-priority infinite-loop finding is repaired. Every nonterminal token-split return now shortens the remainder, and the new regressions cover the original short-prefix/long-field case. One separate High-priority availability finding remains: disabling HTML routes whole TSV tables through an unbounded repeated-prefix token search. See the inline comment for the source-derived example and repair criteria.

The branch includes current main, and the release files consistently advance to 0.27.29. Exact-head CI is not green: CI, Security, CodeQL, and Partition Benchmark require workflow approval, and the CI and Security runs have no jobs. The five required branch checks (changelog, test_dockerfile, lint (3.12), test_unit (3.12), and test_ingest_src (3.12)) are missing on this head. The required Socket check passed, but it does not establish test coverage. A maintainer needs to approve the workflow runs and obtain fresh required-check results.

This review used source and checked-in tests; no tests or reproductions were run. The author-reported test counts were not independently verified.

(authored by codex)

filename=filename,
last_modified=get_last_modified_date(filename) if filename else None,
text_as_html=html_table.html,
text_as_html=html_table.html if infer_table_structure else None,

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.

[P1] Bound token-split search before passing whole TSV tables through it

Disabling HTML newly routes the complete flattened table through _iter_text_only_table_chunks(). For example, with io imported:

partition_tsv(
    file=io.BytesIO(b"a\tb\n" * 100_000),
    infer_table_structure=False,
    chunking_strategy="basic",
    max_tokens=100,
    tokenizer="cl100k_base",
    overlap=0,
)

This is a 400 KB, 200,000-cell input, below the default 5,000,000-cell limit. Its flattened text contains 200,000 short words. At base.py:2757–2763, _split_by_tokens() collects all separator matches, visits them from right to left, and tokenizes each whole prefix until one fits 100 tokens. Selecting the first chunk alone measures roughly 200,000 prefixes with cumulative lengths on the order of 40 billion characters; the table loop repeats that search for subsequent chunks. These are source-operation counts, not measured timings. A modest valid upload can consume excessive worker CPU even though every split eventually advances. Auto-dispatch and by_title share the path.

The expensive splitter predates this change, but this TSV request previously retained HTML and processed these short rows through the row accumulator, without whole-table prefix searches. The new long-unbroken-field tests have only one space and do not cover this separator-dense case.

Bound the prospective chunk window before searching preferred separators, preserving the unread suffix and the repaired overlap/progress guarantees. Removing list() alone does not fix repeated prefix tokenization. Add bounded regressions with many short rows and deterministic measurement-work assertions, plus ordered payload preservation and token-budget checks through direct/auto TSV and both chunking strategies.

(authored by codex)

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Done in 8f8a016 — bounded the tokenizer work along the lines you suggested:

  • _TextSplitter.__call__ now decides "fits" by measuring doubling prefixes; an overflowing prefix proves the whole text cannot fit, so the check no longer tokenizes the full remainder once per chunk.
  • The preferred-separator scan is restricted to the fitting prefix window: the window end comes from doubling probes plus binary search, padded by a short margin for partial-token effects, and finditer(s, 0, window) never visits candidates beyond it. Removing list() was not the fix; the repeated prefix tokenization is gone. The fallback still starts from the probed fitting position and the round-1 progress/overlap guarantees are unchanged.
  • Regressions: test_partition_tsv_html_disabled_bounds_token_measurement_work asserts bounded tokenizer calls and characters together with ordered-payload and token-budget checks; test_partition_tsv_html_disabled_many_short_rows_keeps_ordered_payload covers partition_tsv/partition × basic/by_title; a test_base.py unit test pins bounded work per split and fails without the bound (4,903 tokenizer calls on 10k chars of "a ", 20 with it).
  • On this machine, your b"a\tb\n" * 100_000 example now completes in ~3s (2,000 chunks, ~40k tokenizer calls); * 2_000 took 23s before this commit and 0.3s after.
  • test_unstructured/chunking + test_unstructured/partition/test_tsv.py: 402 passed; ruff clean on the touched files; CHANGELOG updated.

The required checks are awaiting workflow approval on this head.

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

GPT Pro follow-up review of 8f8a016: the prior overlap infinite loop and dense-TSV repeated-prefix tokenizer search are repaired. Two introduced shared-chunker defects remain, listed inline in severity order: a tab prefix causes quadratic fallback scanning and an oversized chunk (High), and an overflowing partial-token probe splits input that fits whole (Medium).

Exact-head CI is successful: all 51 check runs passed, including all five required branch checks. This establishes CI readiness separately from the source findings. The review used source and checked-in tests; no tests or tokenizer reproductions were run.

(authored by codex)

Comment thread unstructured/chunking/base.py Outdated
# -- exponential probe: find a prefix length whose stripped text overflows the budget --
while high < n:
high = min(n, max(2 * high, 256))
if measure(s[:high].rstrip()) > maxlen:

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.

[P1] Bound the window using the raw fragment that can be emitted

With chunk_elements([CodeSnippet("\t" * 100_000 + "print(1)")], max_tokens=100, tokenizer="cl100k_base"), code-snippet whitespace is preserved. _fits_token_budget() rejects the raw prefix, but the new window probes strip every tab-only prefix to empty, extending the window across the entire indentation. Neither default separator (newline or ASCII space) matches. The fallback then slices and strips each preceding tab prefix, rejecting all as empty: about five billion characters of prefix work for 100,000 tabs. Finally lines 2835–2837 restore the entire raw tab prefix without checking its token count and emit an oversized whitespace chunk. This is a source-derived operation count, not a measured runtime. Main's fallback measures raw prefixes and does not scan every indentation prefix.

Use a bound consistent with the actual emitted text, and bound fallback substring work as well as tokenizer calls. Keep progress and unread content; allow overflow only for an indivisible code point. Add splitter and public basic/by-title regressions with long tab indentation, checking budgets, preserved following code, and bounded slicing/scanning work. The current tokenizer counters miss the expensive empty-candidate path.

(authored by codex)

n = len(s)
end = min(n, 256)

while True:

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.

[P2] Do not reject fitting input solely because a prefix overflows

For text = "a!" * 120 + "a" + "0" * 16, chunk_elements([Text(text)], max_tokens=242, tokenizer="gpt2", overlap=0) previously returned one unchanged chunk. GPT-2 tokenization separates the first 241 characters into individual letter/punctuation pieces. OpenAI's checked-in tests/test_encoding.py::test_simple_repeated establishes that 15 zeros take two tokens and 16 zeros take one. Thus the 257-character input fits 242 tokens, while the first 256 characters take 243. This early return incorrectly rejects the whole input; the window search settles after eight zeros, and the whitespace-free fallback splits the numeric value into two chunks. The separator margin cannot correct the false fit decision. This case was derived from source and upstream assertions without executing the tokenizer.

Preserve unchanged output for fitting inputs while retaining bounded work, using a valid conservative bound before rejecting an unread suffix. Add this actual-tokenizer regression at splitter and public chunker levels, retaining the dense-TSV work tests. Upstream evidence: https://github.com/openai/tiktoken/blob/main/tests/test_encoding.py

(authored by codex)

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Addressed both findings in 225739f and merged current main (ad9e8e5), so the branch is mergeable again and the version/changelog are now 0.27.31.

Tab-prefix fallback (High). _token_window_end() now measures the text a split would actually emit: trailing whitespace is trimmed, but a prefix that is entirely whitespace is kept instead of being measured as "". A long indentation run can therefore no longer stretch the probe window across the whole input. The fallback uses the same _emitted_prefix() helper, and when the emitted fragment is whitespace-only it keeps the unread indentation in the remainder instead of lstrip()ing it away. The only remaining overflow is the existing one-code-point case.

chunk_elements([CodeSnippet("\t" * 100_000 + "print(1)")], max_tokens=100, tokenizer="cl100k_base") now produces 63 chunks, each at most 100 tokens, whose concatenation equals the original text and whose last chunk ends with print(1). The first split does less tokenizer input work than one pass over the text (counted by monkeypatching TokenCounter.count), versus roughly two full passes before.

Overflowing partial-token probe (Medium). _fits_token_budget() no longer returns False on a prefix overflow. It rejects without tokenizing the whole text only when ceil(len(s.encode()) / max_token_bytes) > max_tokens -- a valid lower bound because each token covers at most max_token_bytes bytes. Otherwise it measures the whole string and preserves it when it fits. TokenCounter.max_token_bytes is computed once from the encoding and cached.

"a!" * 120 + "a" + "0" * 16 with max_tokens=242, tokenizer="gpt2" is now returned unchanged (242 tokens); it was split into ...00000000 + 00000000 before. The dense-TSV bounded-work test is retained.

Regressions. Added splitter-level tests for the tab run (budgets, exact reconstruction, bounded tokenizer work, fitting text unchanged) and public chunk_elements / chunk_by_title tests for both cases. All 7 new tests fail on the previous head (8f8a016) and pass here.

Local results (.venv in the worktree, PYTHONPATH=.):

  • test_unstructured/chunking/test_base.py: 374 passed.
  • test_unstructured/partition/test_tsv.py: 35 passed.
  • ruff check and ruff format --check: pass on the changed files.

The full test_unstructured/chunking/ directory could not be collected locally because spacy is not installed in this environment; CI covers test_basic.py and test_title.py.

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

GPT Pro production re-review of ad9e8e5: one High and three Medium findings remain, detailed inline in severity order. The High issue is quadratic fallback work for short content followed by long whitespace with overlap. The Medium issues are repeated vocabulary scans per oversized HTML cell, whole-suffix UTF-8 conversion across text-only chunks, and a Unicode input compatibility regression.

The previously reported overlap infinite loop, separator-dense repeated-prefix tokenizer search, all-leading-tabs oversized chunk, and fitting numeric-input failure are repaired for their reported scenarios, with meaningful regressions. The mixed-prefix/overlap case and work outside tokenizer counting remain uncovered. The TSV flag handling, default HTML behavior, and existing parsing/resource-limit safeguards are otherwise consistent with the intended change.

Exact-head CI currently has 51 successful check runs and one running check: test_dockerfile. The other four required branch checks and the required Socket alert check passed. CI readiness is therefore still pending, separately from these source findings. No local tests or reproductions were run; operation counts in the findings are source-derived, not measured runtimes.

(authored by codex)

Comment thread unstructured/chunking/base.py Outdated
cand_fragment = self._emitted_prefix(s, i)
if not cand_fragment or measure(cand_fragment) == 0:
continue
if overlap > 0 and measure(cand_fragment) <= overlap:

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.

[P1] Bound fallback work for a short prefix followed by tabs

chunk_elements([CodeSnippet("a" + "\t" * 100_000 + "print(1)")], max_tokens=100, tokenizer="cl100k_base", overlap=20) still causes quadratic work before the first split. Window probes ending inside the tab run strip down to "a", so the fitting window grows past 65,536 characters. Neither default separator matches tabs. This fallback then slices and strips each tab-position prefix to "a" and rejects it because overlap covers that one-token fragment. Just positions 1 through 65,536 request over 2.1 billion characters of prefix slices, plus trimming and tokenizer calls. These are source-operation counts, not measured timings. Both public chunkers preserve CodeSnippet whitespace and reach this path.

The tab-only regression has no leading content or overlap, so it misses this case. Bound the raw candidate span and skip equivalent whitespace regions without visiting every prefix. Add splitter and basic/by-title coverage combining short content, long tabs, overlap, and following code; verify bounded candidate/slicing work, progress, budgets, and preserved payload.

(authored by codex)

Comment thread unstructured/chunking/base.py Outdated
prefix's token count is not an upper bound on the whole (see `_fits_token_budget`).
"""
longest = 1
for token_id in range(self._encoder.n_vocab):

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.

[P2] Share the vocabulary bound across HTML cell splitters

This cache is per TokenCounter, but _HtmlTableSplitter._iter_cell_splits() constructs fresh ChunkingOptions and a fresh counter for every oversized cell. For example, with io imported, use raw = (b"id\t" + b"a!" * 200 + b"\n") * 1_000 and partition_tsv(file=io.BytesIO(raw), chunking_strategy="basic", max_tokens=100, tokenizer="gpt2"). HTML remains enabled by default. Each long cell reaches a new reduced-budget splitter; its first 256-character probe overflows, so every cell independently traverses the vocabulary here.

GPT-2 has 50,257 vocabulary entries, so 1,000 cells add 50,257,000 decoder calls solely to recompute the same encoding-wide maximum. This is about 0.4 MB and 2,000 cells, below the default cell limit. These are source-derived call counts, not measured timings. Sharing tiktoken’s encoding cache does not share this counter-instance property, and the tokenizer-count tests do not observe these calls.

Cache the immutable bound by resolved encoding or share it across cell splitters. Add a public multi-cell HTML regression that counts vocabulary traversal and proves it stays independent of cell count while preserving the fitting-input repair.

(authored by codex)

Comment thread unstructured/chunking/base.py Outdated
# -- every token covers at most `max_token_bytes` bytes of the encoded text, --
# -- so this is a valid lower bound on the token count of the whole string -- #
assert token_counter is not None # token mode is the only caller
token_floor = -(-len(s.encode("utf-8")) // token_counter.max_token_bytes)

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.

[P2] Avoid encoding the entire unread table on every split

This lower-bound calculation scans and allocates UTF-8 bytes for the complete unread suffix whenever the initial probe overflows. _iter_text_only_table_chunks() repeatedly calls the splitter on a slightly shorter suffix. For an admitted input such as b"a\tb\n" * 2_000_000 with HTML disabled, max_tokens=100, cl100k_base, and zero overlap, each chunk consumes a bounded number of characters while this conversion revisits almost the whole table. Cumulative conversion work is quadratic at a fixed budget. The input has four million cells, below the five-million-cell default.

The suffix-return API already copied strings; this change adds a full-suffix byte conversion on top. The checked-in work tests count only TokenCounter.count(), so they cannot detect it. Use a conservative character-length rejection before bounded byte measurement/full tokenization, preserving fitting inputs despite overflowing prefixes. Extend full-sequence work coverage to byte conversion; do not infer a total-work bound from tokenizer counters alone.

(authored by codex)

Comment thread unstructured/chunking/base.py Outdated
# -- every token covers at most `max_token_bytes` bytes of the encoded text, --
# -- so this is a valid lower bound on the token count of the whole string -- #
assert token_counter is not None # token mode is the only caller
token_floor = -(-len(s.encode("utf-8")) // token_counter.max_token_bytes)

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.

[P2] Preserve the tokenizer’s accepted Unicode input semantics

chunk_elements([Text("a!" * 128 + "\ud800")], max_tokens=100, tokenizer="gpt2") now raises UnicodeEncodeError at this strict UTF-8 conversion. The first 256-character probe overflows and is shorter than the complete input, so it reaches this line. The existing counter uses tiktoken.Encoding.encode_ordinary(), which catches that error and normalizes paired or lone surrogate code units before counting. Text construction and the public chunker do not otherwise reject this string before splitting. This therefore introduces a new failure for previously accepted Python text.

Keep the conservative bound consistent with the tokenizer’s input handling without normalizing an unbounded suffix on every split. Add splitter/public regressions for paired and lone surrogates at overflowing probes and for fitting complete inputs. This scenario was established by source inspection, not executed.

(authored by codex)

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Addressed all four findings in cfa1f8c.

[P1] Bound fallback work for a short prefix followed by tabs. The fallback now evaluates each whitespace run once: above position zero every position in a run emits the same candidate (_emitted_prefix rstrips the whole trailing run), so only the run's rightmost in-window position is tried, then the scan skips to the run start. A position-zero run is the one case whose prefixes differ (all-whitespace content); it is still visited position by position, bounded by the window probe. For CodeSnippet("a" + "\t" * 100_000 + "print(1)"), max_tokens=100, cl100k_base, overlap=20: candidate evaluations went from 100_026 (billions of characters of prefix slices) to 27, with the split unchanged ("a" / "aprint(1)"). Regressions: it_bounds_candidate_work_for_short_content_before_long_tabs and it_keeps_short_content_before_long_tabs_with_overlap for both public chunkers (budgets, progress, payload).

[P2] Share the vocabulary bound across HTML cell splitters. The traversal moved into a module-level _max_token_bytes_for_encoding, lru_cached on the resolved encoding object, which tiktoken returns as a process-wide singleton. With raw = (b"id\t" + b"a!" * 200 + b"\n") * N, max_tokens=100, tokenizer="gpt2": 50 rows gives 2_512_850 decode calls before and 50_257 after; 5 rows gives the same 50_257 — independent of cell count. Regression: test_partition_tsv_html_cells_share_one_vocabulary_traversal.

[P2] Avoid encoding the entire unread table on every split. The bound is now character-based (ceil(len(s) / max_token_bytes); each character occupies at least one byte) and reads nothing beyond the length. Coverage extended to byte conversion directly: test_partition_tsv_html_disabled_bounds_byte_conversion_work profiles the 20k-row text-only table and asserts no str.encode caller in unstructured/chunking/base.py — 807 full-suffix conversions before, 0 after (per-chunk conversions remain only for element-id hashing).

[P2] Preserve the tokenizer's accepted Unicode input semantics. Dropping the suffix encoding removes the strict conversion that raised. Text("a!" * 128 + "\ud800") chunks within budget with the text preserved; a fitting "a!" * 10 + "\ud800" stays one chunk. Regressions at splitter and both public-chunker levels, lone and paired surrogates.

Local runs: pytest test_unstructured/chunking test_unstructured/partition/test_tsv.py → 576 passed, 2 skipped; ruff check/format clean. Each new regression fails on ad9e8e5 with only unstructured/chunking/base.py reverted: 100026 <= 64, traversal scaling with cells, 807 suffix encodes, UnicodeEncodeError at base.py:2786.

partition_tsv() had no infer_table_structure parameter, so the kwarg landed
in **kwargs and was dropped: Table.metadata.text_as_html was always set, even
for partition(..., infer_table_structure=False) or a skip_infer_table_types
list containing tsv. csv, xlsx, docx and odt all gate text_as_html on that
flag; tsv did not.

Adds the parameter with the same docstring as the other partitioners and
gates the html on it, plus the two regression tests the csv and xlsx
partitioner tests already have.
@feiiiiii5
feiiiiii5 force-pushed the fix/tsv-infer-table-structure branch from cfa1f8c to 1905a52 Compare October 21, 2026 13:42
# Conflicts:
#	CHANGELOG.md
#	unstructured/__version__.py
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Rebased the branch onto current main and removed unrelated chunking commits that had accumulated on the branch; the PR is now the four TSV-related files only. Version is 0.27.34-dev0 and the changelog entry is under the current dev section. test_unstructured/partition/test_tsv.py is the only test file changed.

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

Reviewed current head b745a6aababfda06b748a959be701d561f2f8f25 with GPT Pro. The diff now contains only the TSV flag, TSV tests and changelog. The shared-chunker implementation is identical to current main. The latest review’s one High and three Medium findings concern withdrawn code and are not retained. However, removing the intermediate progress/search repairs exposes the two original availability defects again through the newly effective HTML-disabled route:

  1. P1 — Token overlap can loop indefinitely (unstructured/partition/tsv.py:82; unstructured/chunking/base.py:1213–1221,2879–2885,2935–2937). A supported request using file=io.BytesIO(b"a\t" + b"x" * 10_000 + b"\n"), infer_table_structure=False, chunking_strategy="basic", max_tokens=100, tokenizer="cl100k_base", and overlap=20 produces flattened text beginning a . The splitter accepts fragment a; overlap returns that entire fragment and reconstructs the unchanged remainder. The text-only table loop has no progress check, so the public chunker accumulates repeated chunks indefinitely. The same request previously retained HTML, whose cell splitter omits caller overlap and has a progress guard. Require every nonterminal separator and fallback split to consume source content after overlap without losing the unread field. Restore bounded direct/auto TSV and basic/by-title coverage for finite output, payload preservation and token budgets.

  2. P1 — Dense tables cause repeated tokenization of enormous prefixes (base.py:2865–2877, plus whole-suffix measurement at 2827–2828). With the same HTML-disabled token options, zero overlap and file=io.BytesIO(b"a\tb\n" * 100_000), a 400 KB/200,000-cell input reaches whole-table text splitting. Each split visits separators from the end and tokenizes complete prefixes until one fits. The first fragment alone examines roughly 200,000 prefixes, totaling about 40 billion input characters; subsequent fragments repeat the search. These are source-derived counts, not measured timings. Bound the chunk window and complete-sequence work, including the whole-suffix fit check. Add deterministic work and payload/budget regressions for dense inputs through both dispatch and chunking routes. Removing list() alone does not address repeated prefix tokenization.

The former tab-probe, fitting-input, vocabulary-cache, suffix-encoding and surrogate findings are withdrawn with their implementations. The original overlap and dense-table protections and their tests were withdrawn too; the current flag-only tests do not exercise chunking. Default unchunked TSV behavior is not implicated by the two findings above.

Required CI remains unverified: the current workflows require action; earlier heads’ successful checks and author-reported local results do not validate this head. No local tests or reproductions were run.

(authored by codex)

feiiiiii5 and others added 6 commits October 22, 2026 20:37
…y overlap

Ensure token-based chunking advances when a separator prefix is shorter than
or equal to overlap tokens, avoiding infinite chunk loops on text-only table
chunking and large unbroken tokens. Also guarantee fallback splits consume
source content after overlap is applied without inserting spurious whitespace
on non-whitespace boundaries.
Text-only table splitting hands the whole flattened table to the token splitter, and the token splitter tokenized every prefix of the remaining text: the fit check measured the full remainder once per chunk and the preferred-separator scan measured every candidate prefix, so a separator-dense table cost quadratic tokenizer work.

- The fit check now measures doubling prefixes: an overflowing prefix proves the whole text cannot fit, keeping the check bounded by a prefix instead of the remainder.
- The separator scan is restricted to the fitting prefix window: the window end comes from doubling probes plus binary search, padded by a short margin for partial-token effects, and finditer(endpos=...) never visits candidates beyond it. The fallback still splits at the probed fitting position and keeps the progress/overlap guarantees.

Regressions: a partition_tsv test on 20k rows asserts bounded tokenizer calls/characters plus ordered payload and token budget across partition/partition_tsv and basic/by_title; a unit test pins bounded work per split and fails without the bound (4,903 calls on 10k chars, now 20).
… drop suffix encoding

- token-mode fallback evaluates each whitespace run once instead of slicing a
  prefix at every position: a short prefix before 100k tabs plus overlap took
  100_026 candidate evaluations and billions of characters of prefix slices,
  now 27 evaluations in one pass
- the encoding-wide vocabulary bound is memoized per resolved encoding, so
  oversized HTML cells share one traversal (50 cells: 2_512_850 decode calls
  before, 50_257 after, independent of cell count)
- the conservative rejection bound is character-based and needs no encoding of
  the unread suffix (removes 807 per-split UTF-8 conversions for a 20k-row
  text-only table and accepts surrogate text the tokenizer counts)
# Conflicts:
#	test_unstructured/partition/test_tsv.py
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Restored the chunking fixes in 77992d4; the flag-only revision had dropped them, which is what re-exposed both P1s.

  • Overlap progress: a separator or fallback boundary whose candidate is wholly covered by the overlap is skipped, and every nonterminal split now consumes source content after overlap. The b"a\t" + b"x" * 10_000 + b"\n", overlap=20 request terminates, and the table loop cannot return an unchanged remainder.
  • Dense-table work: the separator scan is restricted to the fitting prefix window (doubling probes plus a bounded margin), fallback candidates are evaluated once per whitespace run, the encoding-wide token bound is cached per resolved encoding and shared across HTML cells, and the unread-suffix rejection is character-based instead of encoding every suffix.

Tests: test_unstructured/partition/test_tsv.py and test_unstructured/chunking/test_base.py → 428 passed on this head (Python 3.12, tiktoken 0.12.0), including the direct/auto TSV × basic/by-title progress, ordered-payload, token-budget and measurement-work regressions. ruff check and ruff format --check clean on the four Python files. The branch includes current main (5618dca).

CI is still action_required for CI, Security, CodeQL and Partition Benchmark — the five required branch checks have not run on 77992d4. Could you approve the workflows so they execute on this head?

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

Reviewed 77992d4182c53ab1be4e6c3bb0d13252d50587ac with GPT Pro. Two actionable defects remain:

  1. P1 — Preferred-separator search still performs quadratic work across whitespace covered by overlap (unstructured/chunking/base.py:2953–2963,3065–3079). A public chunk_elements() or chunk_by_title() call with [CodeSnippet("a" + " " * 100_000 + "print(1)")], max_tokens=100, tokenizer="cl100k_base", and overlap=20 preserves the spaces. Window probes trim that run to "a", allowing the raw search window to span it. The preferred space-separator loop then constructs and trims each prefix separately, measures the same "a", and rejects it as covered by overlap. The fallback's run-skipping repair never prevents this earlier work. The 65,536 fitting-prefix positions alone imply more than 2.1 billion characters of prefix slicing, before trimming work; these are source-derived counts, not timings. Main accepted the first rightmost separator because consuming whitespace made the overlapped remainder shorter, so this is an introduced regression.

    Skip equivalent whitespace boundaries in the preferred-separator path before constructing another prefix. Establish progress from actual source consumption/resulting remainder while retaining the original unchanged-remainder protection. A shared boundary evaluator carrying trimmed-prefix end, remainder start, and next distinct boundary can keep both paths consistent. Add deterministic work coverage for spaces, newlines, mixed whitespace, and configured tab separators with overlap. Instrument candidate construction/trimming in both paths: the existing test at test_base.py:676–703 covers tabs and only wraps _emitted_prefix(), missing the expensive expression at line 2955. Retain finite progress, budgets, ordered payload, and both public chunkers.

  2. P2 — Fallback overlap fuses words across discarded whitespace (base.py:3021–3032). For the same options with CodeSnippet("a" + "\t" * 100_000 + "print(1)"), the chosen prefix ends at the tab run's end and trims to "a". The right-side character is p, so is_whitespace_split=False and the overlap tail is concatenated directly into "aprint(1)". That identifier did not exist in the source. The test at test_base.py:694–698 explicitly expects this corrupted remainder; the public tests only check a suffix and also accept it.

    Preserve whitespace provenance on both sides of the source cut. With the current helper, split_pos > len(fragment) records left-side trimming; combine it with is_whitespace_split when deciding whether overlap needs a separating space. Keep direct concatenation for true cuts inside unbroken text and retain strict progress. Replace the fused expectation with preserved separation, verify complete lexical content through both public chunkers, and retain an unbroken-word regression that prohibits artificial spaces.

Prior-round reconciliation: the original unchanged-remainder loop, ordinary dense-table prefix search, leading-tab budget case, fitting-token case, per-cell vocabulary scan, whole-suffix UTF-8 conversion, and surrogate-input regression are repaired for their reported scenarios. The fallback-specific whitespace repair does not cover finding 1, and its test currently accepts finding 2. Default HTML behavior, TSV flag propagation, and upstream resource limits remain intact.

No local tests or reproductions were run, and author claims were not treated as independent execution evidence. Exact-head changelog, lint, and ingest checks passed; the unit check is cancelled and Docker remains in progress. Required CI is not green. No workflows were changed.

(authored by codex)

…parate

Preferred-separator search evaluated every character of a whitespace run
covered by overlap; evaluate one candidate per run. In the fallback, a
cut that trimmed a trailing whitespace run now inserts the overlap
separator, so discarded tabs no longer fuse the words around them.
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Both are in at f256ed23.

1. Preferred-separator work. The preferred loop now evaluates one candidate per whitespace run. Every separator inside a run trims to the same fragment and lstrips to the same remainder, so after the first candidate fails the loop records the run's left edge and skips the rest before constructing another prefix. Candidate construction goes through a shared _trimmed_prefix(), which the fallback's _emitted_prefix() also uses, so the work test counts both paths instead of only _emitted_prefix().

For CodeSnippet("a" + " " * 100_000 + "print(1)") with max_tokens=100, cl100k_base, overlap=20, the splitter returns ("a", "a print(1)"); the deterministic test bounds candidate calls at 64 and total prefix characters at 64 * len(text). The same test is parameterized over spaces, newlines, mixed whitespace, and text_splitting_separators=("\t",).

2. Fallback overlap fusion. split_pos > len(fragment) is exactly the left-side trim signal. It is now combined with is_whitespace_split when choosing the overlap separator, so the tabs case returns ("a", "a print(1)") instead of ("a", "aprint(1)"). The old fused expectation is replaced, and a separate unbroken-word test ("a!" * 200, no whitespace at the cut) asserts no space is introduced.

The public tests are parameterized over the same four whitespace runs and both chunk_elements and chunk_by_title, checking budgets, "a print(1)", and that "aprint" does not appear in the joined payload.

Run from the worktree at f256ed23:

  • pytest test_unstructured/chunking test_unstructured/partition/test_tsv.py -q → 719 passed, 2 skipped in 12.76s
  • ruff check and ruff format --check on the two changed files → clean

Required CI still shows action_required on this head, so I am not claiming a green run.

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

Reviewed f256ed23d1089c1cc39865be8a0180025af21304 against main 803b9005f9f2406b839e9bbec603f40e6d322693 with GPT Pro. No actionable production defects remain.

The latest two findings are resolved: preferred and fallback searches skip equivalent whitespace candidates before constructing another prefix, and fallback overlap preserves separation across discarded whitespace without inserting spaces inside unbroken words. The revised regressions cover candidate construction and trimming, preserved lexical content, and both public chunkers. Earlier progress, token-budget, fitting-input, vocabulary-cache, suffix-encoding, and Unicode repairs remain in place. TSV flag propagation, default HTML behavior, and existing parsing/resource safeguards are consistent with the intended behavior.

This approval records the source-review result. Required CI is still pending: lint (3.12) and check-version passed; test_unit (3.12), test_ingest_src (3.12), and test_dockerfile are running. The required Socket alert check passed. The branch is behind main, so strict branch protection still requires it to become current and obtain the required results. No local tests or reproductions were run, and author test/performance claims were not treated as independent execution evidence.

(authored by codex)

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

Fresh GPT Pro production review of f69ddaf5d8c711e059f508a7550a8c79a66b096f against main 803b9005f9f2406b839e9bbec603f40e6d322693: no actionable production defects found.

This review covers the complete updated implementation, including the main-branch token-unit measurement fix in PreChunk.can_combine. Its combination checks measure the same assembled text subsequently passed to the splitter, preserve overlap handling, and retain table isolation. No new interaction defect was found through basic or by-title chunking. The final PR diff contains only the four chunking/TSV source and test files, with no changelog or version diff.

All prior splitter findings remain resolved: strict remainder progress, bounded candidate construction and trimming in both search paths, lexical separation across discarded whitespace, fitting-input preservation, shared vocabulary caching, and Unicode compatibility. TSV direct and automatic routing honor the flag while preserving default HTML behavior and existing parsing/resource safeguards. The checked-in regressions cover the repaired scenarios.

This approval records the source-review result. Required CI readiness is still unverified on this exact head: CI, Security, CodeQL, and Partition Benchmark require workflow approval, and the CI run has no jobs. None of the five required branch checks (test_dockerfile, lint (3.12), test_unit (3.12), test_ingest_src (3.12), and check-version) has a result. The two Socket checks passed. Earlier heads' results do not validate this head. No local tests or reproductions were run; author test/performance claims were not treated as independent execution evidence.

(authored by codex)

@cragwolfe
cragwolfe merged commit 490eeb3 into Unstructured-IO:main Oct 23, 2026
52 checks passed
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.

2 participants