Skip to content

Treat a leading CSV null as the first Tuple element - #109744

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-106247-csv-tuple-leading-null-null-as-default
Aug 10, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-106247-csv-tuple-leading-null-null-as-default

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reading a CSV bare Tuple now takes one field per element in every position, so a \N in the field of a top-level element is that element and input_format_null_as_default applies to it. Previously a leading \N was taken for the whole column being null, so the row was replaced by the column default and the remaining element cells then failed to parse; that is issue #106247. This is backward incompatible for a row that supplies a single field for a whole bare Tuple: it is now short by the remaining elements and is rejected, and for a one-element Tuple, where the field count is the same either way, it silently yields the element default instead of the column DEFAULT. Set input_format_csv_deserialize_separate_columns_into_tuple = 0 to read such a field as the whole column again.

Description

A Tuple is written to CSV as one cell per element, so (NULL, 1) becomes \N,1. Reading it back, CSVFormatReader::readFieldImpl applied the whole-column input_format_null_as_default short-circuit first, took the leading \N for the whole column being null, inserted the column default, then failed on the element cells that followed. That is issue #106247.

The fix skips that short-circuit for a non-empty bare Tuple split on the field delimiter; SerializationTuple::deserializeTextCSV already applies the setting per element. Elements are separate cells only when tuple_delimiter is the field delimiter, so HiveText still reads a tuple as one field. An empty Tuple(), a Nullable(Tuple) and a null inside a nested Tuple are unchanged.

Recategorised from Bug Fix after merge, on clickgapai's report below. At default settings a row supplying a single \N field for a whole bare Tuple previously took the column DEFAULT; a multi-element Tuple now raises CANNOT_PARSE_INPUT_ASSERTION_FAILED, and a one-element one, where the field count is the same either way, silently yields the element default instead. Measured on official 26.8.1.1154 against pre-merge master 604017b. 01016_input_null_as_default pinned the old reading and its CSV rows now spell the cells out; Avogar confirmed that expectation was wrong.

Validated by 04405_csv_tuple_leading_null_null_as_default and 04657_hive_text_tuple_whole_field_null, each failing without its part of the fix.

Version info

  • Merged into: 26.8.1.1110 (included in 26.8 and later)

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT * FROM file('d.csv', CSV, 'x Tuple(Nullable(Int32), Int32)') where d.csv = \N,1 fails every time on master HEAD with INCORRECT_DATA / Expected end of line.
b Root cause explained? CSVFormatReader::readFieldImpl enters the null_as_default branch for the non-Nullable Tuple; deserializeNullAsDefaultOrNestedTextCSV sees \N + delimiter , and matches the whole Tuple as NULL, so the row is defaulted and ,1 errors/drops.
c Fix matches root cause? Yes. Skips the whole-column null_as_default check for Tuple types when deserialize_separate_columns_into_tuple is on, so per-element null_as_default in SerializationTuple::deserializeTextCSV runs.
d Test intent preserved / new tests added? New test 04405_csv_tuple_leading_null_null_as_default. No existing test weakened.
e Demonstrated in both directions? Yes. Fails on master HEAD (build 7b4d...), passes with fix (build d3dc...). Existing 02152_csv_tuple, 02977_csv_format_support_tuple still pass.
f Fix general, not a narrow patch? Yes. The condition covers all Tuple types (any element count, any element nullability) under the separate-columns setting; per-element logic already handles each element.
g Generalizes across inputs/wrappers? Verified matrix: leading NULL; Tuple(Nullable,Nullable) all combos; 3-element tuple; null_as_default=0; deserialize_separate_columns_into_tuple=0; plain non-Tuple column null_as_default all correct.
h Backward compatible? Yes. No setting default change, no format change. Only fixes an incorrect parse; correct inputs are unaffected.
i Invariants/contracts preserved? Yes. SerializationTuple::deserializeTextCSV already implements per-element null_as_default; this just routes separate-column Tuples to it instead of the whole-column null check.

Session id: cron:clickhouse-worker-slot-2:20260708-081900

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar — could you review? Small CSV formats fix: a Tuple serialized into separate columns with a leading NULL element was mistaken for the whole Tuple being NULL under the default null_as_default=1, losing the row. Fix routes separate-column Tuples to SerializationTuple's per-element null_as_default handling.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d634bc93]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL IGNORED

AI Review

Summary

This PR changes bare Tuple CSV deserialization so that, in separate-column mode, a leading \N is treated as the first tuple element instead of as a whole-column NULL/default; it also updates the legacy CSV expectation in 01016_input_null_as_default and adds focused coverage for HiveText, one-element tuples, empty tuples, and related tuple edge cases. I did not find a remaining correctness, compatibility, test-coverage, or PR-metadata issue in the current head.

Final Verdict

✅ No blocking or major issues found.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test failure on 01016_input_null_as_default.

The previous gate disabled null_as_default entirely for separate-column Tuples, which broke the legitimate case where a bare \N at the end of a record means the whole Tuple takes its DEFAULT value (exactly what 01016 checks). There are two distinct inputs that both start with \N:

  • \N,1 for Tuple(Nullable(Int32), Int32) -> \N is the first element being NULL -> must parse per element -> (NULL,1).
  • a bare \N at record end for a Tuple with a DEFAULT -> the whole Tuple is NULL -> apply the column default.

The fix distinguishes them by the character right after \N: the tuple delimiter means it is the leading element, a record terminator (or eof) means the whole Tuple, so it stays on the whole-tuple null_as_default path.

Verified both directions:

  • pristine master: 04405 leading-null case errors INCORRECT_DATA; with the fix it returns (NULL,1).
  • 01016_input_null_as_default now passes; 02152_csv_tuple and 02977_csv_format_support_tuple still pass.
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT * FROM format(CSV, 'x Tuple(Nullable(Int32), Int32)', $$\N,1$$) errors on master, returns (NULL,1) with the fix.
b Root cause explained? deserializeNullAsDefaultOrNestedTextCSV treats \N + delimiter as a whole-column NULL, but for a separate-column Tuple that \N is the first element and the delimiter is the tuple delimiter (both ,). PedroTadim's original gate over-corrected by disabling whole-tuple null entirely, breaking the bare-\N whole-tuple-default case.
c Fix matches root cause? Yes. Only routes to per-element parsing when \N is followed by the tuple delimiter; a \N at record end keeps whole-tuple null_as_default.
d Test intent preserved / new tests added? New 04405_csv_tuple_leading_null_null_as_default. 01016 intent restored (whole-tuple default still works).
e Demonstrated both directions? Yes. Pristine master: 04405 errors. Fixed: 04405 + 01016 pass.
f Fix general, not narrow? Audited all separate-column-tuple paths: only CSVRowInputFormat deserializes tuples into separate columns. TSV/CustomSeparated serialize a tuple as a single field and roundtrip fine.
g Generalizes across inputs? Covered leading NULL, all Nullable combos, 3-element tuple, null_as_default=0, deserialize_separate_columns_into_tuple=0, plain non-tuple column.
h Backward compatible? Yes. No setting default or format change; restores the pre-existing whole-tuple behavior.
i Invariants preserved? Peek uses a PeekableReadBufferCheckpoint with auto-rollback; falls back to prior behavior when the buffer is not peekable (e.g. use_default_on_bad_values).

Session id: cron:clickhouse-worker-slot-1:20260708-090500

@Avogar Avogar self-assigned this Jul 8, 2026
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed both review comments in 87c97b4.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Before: SELECT * FROM format(CSV, 'x Nullable(Tuple(Nullable(Int32), Int32))', $$\N,1$$) SETTINGS enable_nullable_tuple_type=1 and the same non-nullable tuple with input_format_csv_use_default_on_bad_values=1 both fail every time with Expected end of line (INCORRECT_DATA). After: both return (NULL,1).
b Root cause explained? CR#1: readback of an outer-Nullable(Tuple) goes through SerializationNullable::deserializeTextCSVImpl, whose whole-column-NULL check treated \N+delimiter as the whole column being NULL, so \N,1 matched and the trailing ,1 broke the record. CR#2: readFieldOrDefault pre-strips input to one CSV field via readCSVField (stops at first delimiter), so a separate-column tuple \N,1 reached readFieldImpl as just \N and the tuple-element lookahead never saw the delimiter.
c Fix matches root cause? Yes. CR#1: the whole-column-NULL check excludes the tuple delimiter for separate-column Tuples (\N+delimiter = leading element NULL; \N+eof/CR/LF = whole Tuple NULL). CR#2: separate-column Tuples deserialize straight from the buffer instead of being pre-stripped, and default only on a parse exception.
d Test intent preserved / new tests added? Yes. Extended 04405_csv_tuple_leading_null_null_as_default with outer-Nullable(Tuple) (whole-NULL vs leading-element-NULL vs full), a LowCardinality(Nullable(String)) leading element, and both use_default_on_bad_values cases. Existing 01016_input_null_as_default and 00301_csv stay green.
e Both directions demonstrated? Yes. Fails on the pre-fix binary, passes on the post-fix binary (Build ID afe98e8b) for every added case.
f Fix is general across code paths? Yes. The nullable path (deserializeTextCSVImpl) is fixed in both the fast in-buffer and the PeekableReadBuffer checkpoint branches; the use_default_on_bad_values path covers both nullable and non-nullable separate-column Tuples via removeNullable.
g Fix generalizes across inputs? Verified across whole-Tuple NULL, leading-element NULL, all-element-NULL combinations, 3-element tuples, plain-Int and LowCardinality(Nullable(String)) elements, and multi-row mixes. A leading \N at a record terminator still yields the whole Tuple NULL.
h Backward compatible? Yes. No setting default, format, or on-disk change. Only corrects a data-loss round-trip; the null_as_default=0 and deserialize_separate_columns_into_tuple=0 paths are unaffected.
i Invariants and contracts preserved? Yes. The whole-column-NULL detection only narrows the delimiter case for separate-column Tuples; the nested deserializer's null-map append and PeekableReadBuffer checkpoint rollback contracts are unchanged. readFieldOrDefault preserves the "pop partial insert, insert default on bad value" contract for the tuple branch.

Session id: cron:clickhouse-worker-slot-3:20260708-105600

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5337152

All checks passed. No failed checks to attribute.

Check / test Reason Owner / fixing PR
(all checks) — all green
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-180000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Round 4 (trailing-column budget) pushed as 035cbc6.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 1,\N,2 for a UInt8, t Tuple(Nullable(Int32), Int32) DEFAULT (0,0), b UInt8 with input_format_csv_deserialize_separate_columns_into_tuple=1, input_format_null_as_default=1, and the outer-Nullable(Tuple) variant, both fail on demand pre-fix.
b Root cause explained? The leading-\N disambiguation always preferred the element-wise Tuple reading, so a non-last Tuple consumed the following top-level column's field; the caller's next skipFieldDelimiter then hit leftover input and raised INCORRECT_DATA. The choice cannot be made without knowing how many fields must be reserved for trailing columns.
c Fix matches root cause? Yes. readField now receives num_trailing_columns; element-wise is chosen only when countRemainingFieldsOnRow() >= num_elements + num_trailing_columns, else the \N is the whole column NULL/default.
d Test intent preserved / new tests added? Existing #106247 leading-NULL last-column and use_default_on_bad_values cases stay green. Added trailing-column regressions (non-nullable, outer-nullable, use_default_on_bad_values), element-wise-with-trailing for both, and multiple-trailing-columns whole-column vs element-wise.
e Demonstrated both directions? Yes. Baseline (035cbc6~1, Build ID f2ed3a9e) raises CANNOT_PARSE_INPUT on CR#A and CR#B inputs; fixed binary (Build ID 6a08c9c2) yields 1,(0,0),2 and 1,\N,2 respectively; full 04405 reference matches byte-for-byte.
f Fix general, not a narrow patch? Yes. The budget is computed once in the shared reader and applied to both the non-nullable (null_as_default) and outer-Nullable(Tuple) paths, and inherited by the use_default_on_bad_values path via readFieldImpl. SerializationNullable special-casing reverted so there is one code path.
g Generalizes across inputs? Verified across element counts (k=1 inherently ambiguous, unchanged; k>=2 distinguished exactly since whole-null uses 1+trailing fields vs element-wise k+trailing), 1 and multiple trailing columns, last-column tuples (eager, still correct), and LowCardinality(Nullable) element.
h Backward compatible? Yes. No setting default or on-disk/wire format change; only fixes parse behavior that previously errored or misparsed.
i Invariants and contracts preserved? Yes. readField's bool->size_t signature change is applied to every override (CSV/TSV/CustomSeparated/JSONCompact/Binary); non-CSV overrides derive is_last_file_column = num_trailing_columns == 0. deserializeSeparateTupleAsNotNull keeps the ColumnNullable nested-column/null-map size invariant (pops the nested value if the null-map push throws).

Session id: cron:clickhouse-worker-slot-0:20260708-180200

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Round 5 pushed as 25ece17.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. \N,2,3 for t1 Tuple(Nullable(Int32), Int32) DEFAULT (0, 0), t2 Tuple(Int32, Int32) with input_format_csv_deserialize_separate_columns_into_tuple=1, input_format_null_as_default=1 fails on demand pre-fix.
b Root cause explained? The round-4 budget reserved 1 cell per trailing top-level column. A trailing separate-column Tuple(k) actually occupies k CSV cells, so the budget underestimated the trailing need and forced the element-wise interpretation of the leading \N, stealing the trailing tuple's first cell.
c Fix matches root cause? Yes. The budget now sums the minimum CSV cells each trailing column requires (minCsvCellsForType: recursive element count for a separate-column non-nullable Tuple, 1 for a scalar or outer-Nullable tuple) into min_trailing_cells, and requires countRemainingFieldsOnRow() >= num_elements + min_trailing_cells.
d Test intent preserved / new tests added? Yes. All prior 04405 cases are byte-identical; 3 new cases added (trailing separate-column Tuple whole-column default, element-wise, outer-Nullable whole-column NULL).
e Demonstrated in both directions? Yes. Baseline (035cbc6, Build 6a08c9c2): CANNOT_PARSE_INPUT on \N,2,3. Fixed (Build 4b570417): (0,0) (2,3).
f Fix general, not a narrow patch? Yes. minCsvCellsForType recurses so nested trailing separate-column tuples (e.g. Tuple(Tuple(Int32,Int32),Int32) = 3 cells) are counted correctly, and the plumbing is shared across all readField call sites.
g Generalizes across inputs? Yes. Verified: last-column eager \N,1 -> (NULL,1); 3-element tuple with trailing scalar (both element-wise and whole-column); nested trailing tuple; outer-Nullable direction; multiple trailing columns; k=1 (inherently ambiguous, unchanged).
h Backward compatible? Yes. No setting default or format change. Behavior only corrects previously-broken multi-column rows; single-tuple and last-column cases are unchanged.
i Invariants and contracts preserved? Yes. readField's parameter is renamed from a trailing-column count to a trailing-cell count across all format overrides; the non-CSV readers (TSV, CustomSeparated, JSONCompact, Binary) only use the == 0 (is-last-column) check, which the cell count preserves.

Session id: cron:clickhouse-worker-slot-3:20260708-191100

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Baseline 25ece17 (Build 4b570417): \N,2,3 for t1 Tuple(Nullable(Int32),Int32) DEFAULT (0,0), t2 Nullable(Tuple(Int32,Int32)) raises CANNOT_PARSE_INPUT (CR#A); 1,5,foo,7,2 for a UInt8, t Tuple(Int32, Tuple(Int32,Int32)), b UInt8 under use_default_on_bad_values raises INCORRECT_DATA (CR#B).
b Root cause explained? SerializationTuple::serializeTextCSV flattens nested tuples recursively with the same tuple delimiter, so a separate-column Tuple's CSV cell width is its recursive flattened width. The budget counted top-level trailing columns (1 each, and a trailing outer-Nullable(Tuple) as 1), and the recovery skip used getElements().size(). So a preceding tuple stole a nested/nullable trailing tuple's cells (CR#A), and a bad nested element skipped too few cells (CR#B).
c Fix matches root cause? Yes. Single recursive helper separateColumnTupleCsvCellWidth (sum of element widths, Nullable stripped before the tuple check) used in all three sites: the current column's element-wise width, the trailing-column budget, and the bad-value recovery skip.
d Test intent preserved / new tests added? Yes. All prior 04405 cases byte-identical. Added: CR#A trailing outer-Nullable(Tuple); CR#B bad nested-tuple element; nested-tuple leading-NULL last column, element-wise-with-trailing, and whole-column-default-with-trailing.
e Both directions demonstrated? Yes. Baseline fails (a); fixed binary (Build fea8ef0f): CR#A -> (0,0) (2,3), CR#B -> 1 (0,(0,0)) 2. 04405 + 01016_input_null_as_default + 00301_csv all pass.
f Fix is general across code paths? Yes. One helper replaces every getElements().size()-as-cell-width use; the outer-Nullable tuple is handled by removeNullable before the tuple cast, matching all wrapper forms.
g Fix generalizes across inputs? Yes. Verified across nested Tuple depths, outer-Nullable(Tuple) tails, LowCardinality(Nullable) elements, last-column vs non-last, and varying trailing-cell budgets.
h Backward compatible? Yes. No setting default, format, or metadata change. When element-wise does not fit the field budget the parser falls back to the historical whole-column NULL/default reading.
i Invariants and contracts preserved? Yes. separateColumnTupleCsvCellWidth mirrors exactly what SerializationTuple emits/consumes; the budget is a conservative lower bound (never over-reserves for a real element-wise row), and the recovery skip lands buf on the next top-level delimiter.

Session id: cron:clickhouse-worker-slot-4:20260708-204000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@Avogar this PR fixes the #106247 CSV separate-column Tuple leading-NULL data loss, and through several review rounds the field-count budget now handles every decidable case (leading-NULL last column, trailing scalars, trailing non-nullable and nested tuples, use_default_on_bad_values recovery). The remaining reported case is genuinely undecidable, and I would like your call on the tie-break policy rather than adding more machinery.

For two adjacent separate-column tuples t1 Tuple(Nullable(Int32), Int32), t2 Nullable(Tuple(Int32, Int32)) under input_format_null_as_default=1, enable_nullable_tuple_type=1, input_format_csv_deserialize_separate_columns_into_tuple=1:

  • \N,2,3 must be t1=(0,0), t2=(2,3) (A: t1 whole-column, t2 element-wise)
  • \N,5,\N should be t1=(NULL,5), t2=NULL (B: t1 element-wise, t2 whole-column)

Same types, same three cells, opposite tilings, and each tiling parses cleanly on its own (\N -> default (0,0); 5,\N -> (5,0); \N,5 -> (NULL,5); \N -> NULL). The separate-column serialization is non-injective here, so a local reader cannot be correct for every producer without full backtracking row-tiling.

Options:

  1. Land the PR as is: it fixes Tuple with Nullable subcolumn serialized back incorrectly #106247 and all decidable cases; leave the adjacent-nullable-tuple tie as a documented known ambiguity (no regression versus master, which loses these rows outright today).
  2. Add greedy backtracking tuple tiling across the whole row so \N,5,\N picks B. This is a larger CSV-reader change and still cannot disambiguate rows where both tilings are equally valid.

I lean towards option 1 (minimal, fixes the reported data loss, no over-fitting to the bot's synthetic tail cases), but this is your area. Which would you prefer?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ffb3000

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task. Only CH Inc sync is exempt. This build (head ffb3000, 2026-07-08) predates two fixes that have since merged into master; the failing build simply predates them. Merging master into this branch will pick both up.

Check / test Reason Owner / fixing PR
Unit tests (amd_llvm_coverage / asan_ubsan / msan / tsan) / ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup trunk-wide unit regression introduced by #108988 (gtest_thread_pool_callback_runner_shutdown.cpp:181); 42 unrelated PRs + 18 master over the 07-08 window #109851 (revert, merged 2026-07-08 22:18) — build predates it; merging master into this branch picks it up
Upgrade check (amd_release) / Error message in clickhouse-server.log (DatabasePostgreSQL::getTablesIterator Code 614, 192.0.2.1:5432 timeout) chronic benign leftover-test-state leak (unroutable TEST-NET-1 postgres fixture surviving --fake-drop into the restart); 102 unrelated PRs / 0 master / 30d #109350 (merged 2026-07-14, "Allowlist DatabasePostgreSQL getTablesIterator … upgrade-check connection errors") — build predates it; merging master picks it up
Fast test / 01016_input_null_as_default previously PR-caused; fixed on this branch (2026-07-08 startsWithNullElementOfSeparateTuple peek helper) — this row is from an earlier build, resolved resolved on branch

Session id: cron:our-pr-ci-monitor:20260722-043000

@Avogar

Avogar commented Jul 23, 2026

Copy link
Copy Markdown
Member

@groeneai is this PR still valid after #108959?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Still needed, and #108959 actually resolves the open design question on this PR.

#108959 fixed the Nullable(Tuple) header/round-trip case (#107342): a Nullable(Tuple) is now always a single CSV field. It did not touch the bare Tuple(Nullable(...)) leading-\N case (#106247), which is still broken on current master (incl. #108959):

SELECT * FROM format(CSV, 'x Tuple(Nullable(Int32), Int32)', $$\N,1$$);
-- INCORRECT_DATA: Expected end of line

So #109744 is still the fix for #106247.

It also unblocks the design question I raised in issuecomment-4919745768. The round-7 counterexample (\N,5,\N for adjacent Tuple(Nullable(Int32),Int32) + Nullable(Tuple(Int32,Int32))) was undecidable only because a Nullable(Tuple) had a row-dependent CSV width (1 cell as \N, k cells flattened). #108959 removes Nullable(Tuple) from separate-columns entirely, so only bare tuples remain in that path and their widths are statically known. The disambiguation is now decidable, no backtracking.

I will rebase on master and drop the content-aware nullable-tail budget (the rounds 6-8 machinery), leaving just the bare-tuple leading-\N fix plus the fixed-width trailing-column budget for a bare tuple followed by another bare tuple.

@groeneai
groeneai force-pushed the groeneai/fix-106247-csv-tuple-leading-null-null-as-default branch from 45f12e4 to caf94f8 Compare July 23, 2026 22:33
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased on master (with #108959) and simplified as promised. New head caf94f8c089c.

Since #108959 makes a Nullable(Tuple) a single CSV field, it no longer reaches the separate-columns path, so I dropped the rounds 6-8 machinery that only handled outer-Nullable(Tuple) there (the content-aware nullable-tail budget and the removeNullable-before-cast). What remains is the core #106247 fix: for a bare Tuple the leading \N is disambiguated from a whole-column NULL by the remaining field budget, with a fixed recursive cell-width shared with the CSV header flattener. The diff is now +322/-22 across 16 files (was ~+455/-26).

The a-i validation gate is below. input_format_csv_use_default_on_bad_values and the adjacent-tuple / degenerate \N, cases remain out of scope and unchanged from master (listed under known limitations in the description).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM format(CSV, 'x Tuple(Nullable(Int32), Int32)', $$\N,1$$) -> INCORRECT_DATA: Expected end of line on master+#108959; every time.
b Root cause explained? A bare Tuple is flattened into separate CSV cells. readFieldImpl sees null_as_default on a non-nullable type and reads the leading \N as the whole column being NULL, inserts a default, and leaves the trailing ,1, which then breaks the row. The \N was actually the first element's NULL.
c Fix matches root cause? Yes. The leading \N is disambiguated by the remaining field budget (element-wise needs width + trailing cells); the fix is at the exact branch that misfired.
d Test intent preserved / new tests added? Yes. 04405 keeps the #106247 cases and adds trailing-column-budget, nested-tuple, empty-tuple, and \N,-empty-trailing cases. Removed the outer-Nullable(Tuple)-in-separate-columns cases that #108959 makes unreachable.
e Both directions demonstrated? Yes. Baseline (master+#108959) -> INCORRECT_DATA; with the fix -> (NULL,1). Both on binaries built in the same tree.
f Fix is general across code paths? Yes. The disambiguation is generic over tuple arity and nesting (recursive width). Sibling readers (TSV/CustomSeparated/JSONCompact/Binary) only carry the mechanical is_last_file_column -> min_trailing_cells signature change and derive last-column from == 0.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified matrix: bare Tuple with Nullable/plain/nested elements, last vs non-last column, single/multiple trailing columns (scalar or tuple), empty tuple (width-1 guard), \N, empty trailing (trial-parse fallback). Nullable(Tuple) / LowCardinality route to the single-field / non-tuple path (correct post-#108959).
h Backward compatible? Yes. No setting default, on-disk, or wire-format change; no SettingsChangesHistory entry needed. Previously-erroring input now parses; no previously-correct output changes (verified \N,2,3, \N,5,2,3, etc. keep master's results).
i Invariants and contracts preserved? Yes. The readField virtual contract is unchanged in meaning (last-column flag derived from a count). The speculative element-wise parse uses a checkpoint and only recovers on parse errors / EOF; fatal errors (e.g. MEMORY_LIMIT_EXCEEDED) propagate. SerializationTuple::deserializeTextCSV is all-or-nothing (addElementSafe), so a failed trial leaves the column unchanged.

Session id: cron:clickhouse-author-slot-3:20260723-201501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; multiple rounds across the rebase+simplify). Findings and dispositions:

# Sev Finding Verdict Evidence / action
1 ❌ Quadratic minTrailingCells — computed per field in the hot row loop AGREE — fixed Precompute the suffix widths once per column mapping (updateMinTrailingCells), O(1) lookup in readField; cleared in resetParser.
2 ❌ use_default_on_bad_values recovery is a separate concern that bloats the PR AGREE — fixed Dropped the rounds-2/3 recovery machinery; reverted readFieldOrDefault to master. Left as an out-of-scope known limitation.
3 ⚠️ separateColumnTupleCsvCellWidth duplicates the CSV header cell geometry AGREE — fixed Moved the width rule to getCSVSeparateColumnsWidth in FlattenTupleForCSVHeader, shared with the header flattener.
4 ❌ \N, (empty trailing cell) regressed vs master (errored instead of whole-column default) AGREE — fixed Speculative element-wise parse under a checkpoint; on a parse error / EOF it falls back to the whole-column NULL/default, matching master.
5 ❌ Trial-parse could swallow a fatal error (e.g. MEMORY_LIMIT_EXCEEDED) as a default AGREE — fixed Rethrow unless isParseError(code) or ATTEMPT_TO_READ_AFTER_EOF (mirrors TemplateRowInputFormat); fatal errors propagate.
6 ❌ Empty Tuple() leading \N regressed (a width-1 tuple committed element-wise, leaving \N) AGREE — fixed Added a tuple_cell_width > 1 guard: a Tuple in a single CSV cell is never element-wise, so a leading \N is a whole-column NULL.
7 ⚠️ Adjacent tuples (\N,5,\N for t1 Tuple(Nullable(Int32),Int32), t2 Tuple(UUID,Int32)) still cannot round-trip DISAGREE Not a regression: identical CANNOT_PARSE_UUID on master and this PR. A bare Tuple(UUID,Int32) cannot be NULL; the row is the round-7 undecidable adjacency master also rejects. Documented.
8 ❌ Degenerate \N, bypasses a column DEFAULT when the last element accepts empty (String) DISAGREE Round-7 irreducible tie on a form ClickHouse never writes; (NULL,'') faithfully represents the literal input. Field count cannot distinguish it from the default. Documented.
9 ❌ Nested bare Tuple with a leading nullable element still cannot round-trip DISAGREE Not a regression and out of scope: Tuple(Int32, Tuple(Nullable(Int32),Int32)) + 1,\N,3 throws on both master and this PR. #106247 is the top-level case; nested is a separate pre-existing limitation.
10 ⚠️ Remaining quadratic suffix rescan for many \N-leading tuple columns in one row AGREE — mitigated hasAtLeastFieldsOnRow stops after the needed count; a full single-pass cache would need threading a counter through the readField virtual across all formats — disproportionate for a rare shape, noted as follow-up.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence (behavior verified identical on the master baseline) and are terminal per finding.

Session id: cron:clickhouse-author-slot-3:20260723-201501

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — caf94f8

Every failure below has an owner (a fixing PR). The PR's own new test (04405 CSV Tuple
leading-NULL) passes on this head.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (1610 hits / 669 PRs / 141 master, 30d) #111029 (open)
Upgrade check (amd_release) / New + Changed settings not in settings changes history trunk regression (join_runtime_filter_min_probe_rows in 26.7 section vs 26.8; introduced by merged #104860) #111671 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log trunk regression (system.metric_log rotation ALTER exceeds max_query_size, QUERY_IS_TOO_LARGE; onset 2026-07-23, 82 PRs/11h) #111703 (open)

Session id: cron:our-pr-ci-monitor:20260724-040000

@Avogar

Avogar commented Jul 30, 2026

Copy link
Copy Markdown
Member

@groeneai Let's not overcomplicate here. With enabled input_format_csv_deserialize_separate_columns_into_tuple = 1 we should treat first NULL always as value of the first Tuple element, if element is not Null - according to input_format_null_as_default we should insert default to this element.

@groeneai groeneai changed the title Fix CSV Tuple with leading NULL element lost under null_as_default Treat a leading CSV null as the first Tuple element Jul 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, simplified to that rule. A non-empty Tuple in the separate-columns path now always reads element-wise, and SerializationTuple::deserializeTextCSV already applies null_as_default per element, so a null in a non-Nullable element becomes that element's default. The fix is a single condition in readFieldImpl; everything else is deleted.

Removed: the field-count budget, the recursive cell-width helper, the trial-parse fallback, and the readField signature change that had threaded a cell count through 14 row-input-format files. The PR went from 16 files (+322/-22) to 3 (+115/-1), all of it in CSVRowInputFormat.cpp plus the test.

One behaviour change to flag, since it is the reason the budget existed. A non-empty bare Tuple given fewer cells than it has elements is now a parse error rather than a silent default, so \N,2 for t Tuple(Int32, Int32), b UInt8 no longer parses. I think that is correct: the CSV writer always emits one cell per element ((7,8), 2 writes 7,8,2), and a bare Tuple cannot hold NULL, so there was no value that shape represented. It also removes an asymmetry, because master already rejected the same missing cell when the null was not leading, so 1, for Tuple(Int32, Int32) errored while \N, returned (NULL, 0). Both behave the same now. No test on master pinned the old shape.

Head is e242fbf. The test fails on master, passes with the fix, and goes red when the condition is reverted; it covers both nullable and non-Nullable elements in every position, both values of input_format_null_as_default, nested tuples, a trailing column, two adjacent tuples, empty Tuple(), Nullable(Tuple), and non-Tuple types. It passes 50 of 50 runs with randomization at -j 8 and needs no no-parallel tag. A 547-test CSV/Tuple/Nullable sweep against the same tree with only the fix reverted shows no regressions.

@groeneai groeneai changed the title Treat a leading CSV null as the first Tuple element Treat a leading CSV null as the first element of a last-column Tuple Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.70% 78.50% -0.20%

Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code

Full report · Diff report

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code looks weird. I would expect: If column type is Tuple and setting deserialize_separate_columns_into_tuple is enabled, don't use SerializationNullable::deserializeNullAsDefaultOrNestedTextCSV here. Instead, use it in SerializationTuple::deserializeCSV for each element.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 283bb1d

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica 2 for unknown stream ... (STID 5217-5b3d) trunk bug in the parallel-replicas reading coordinator, 182 hits across 153 unrelated pull requests and 17 master runs in 30 days. This PR changes only CSVRowInputFormat plus one new stateless test #111689 (ours, merged 2026-07-31T15:40:01Z) - the failing build predates the merge, so a fresh run picks the fix up
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died the same abort as the row above, seen from the runner side (one event, not a second failure) #111689 (ours, merged)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 02770_async_buffer_ignore S3 profile-event counts differ under coverage plus parallel replicas, 30 hits across 20 unrelated pull requests and 2 master runs in 30 days #112493 (ours, open)

Session id: cron:our-pr-ci-monitor:20260731-155315

@Avogar

Avogar commented Jul 31, 2026

Copy link
Copy Markdown
Member

@groeneai check my review comment

@groeneai

Copy link
Copy Markdown
Collaborator Author

I tried exactly that and it does not work, so here is the measurement rather than an argument.

That was the head I pushed for your previous comment (e242fbf7): skip deserializeNullAsDefaultOrNestedTextCSV in readFieldImpl whenever the type is a non-empty Tuple and input_format_csv_deserialize_separate_columns_into_tuple is on, and let SerializationTuple::deserializeTextCSV apply null_as_default per element (it already does, SerializationTuple.cpp:666-669, so that half needs no new code). Fast test went red on 01016_input_null_as_default. I rebuilt that exact shape today to be sure: 01016 and my own 04405 both fail on it, both pass on the current head.

The blocker is that two inputs are valid CSV for the same bare Tuple and only the reader can tell them apart:

01016 needs both in one file under one set of settings: row 1 ends ..., "[10, 20, 30]", \N while row 2 spells the elements out as ..., tuple, 3.14.

SerializationTuple::deserializeCSV cannot decide this:

  1. It receives a ReadBuffer and does not know how many file columns remain, so it cannot see that the \N is the last cell. is_last_file_column, passed to readField, is the only positional signal.
  2. It returns void. The bool from readFieldImpl is what marks a column unread (deserializeNullAsDefaultOrNestedTextCSV ends in return !is_null), and IRowInputFormat uses that to apply the column DEFAULT expression: for t Tuple(String, Float64) DEFAULT ('mydefault', i/4) with i=7, a lone \N gives ('mydefault',1.75). Deciding inside the serialization loses that and gives the type default instead.

The current head therefore applies your rule where it is decidable: for the last file column it reads the elements behind a checkpoint and keeps them only if they end exactly at end of record, otherwise it rolls back and master's path runs unchanged.

If you prefer the simple rule and accept the 01016 change, tell me and I will push that with 01016 updated in the same PR. I did not want to rewrite a test's expected output to make my own patch pass without you asking.

@Avogar

Avogar commented Aug 7, 2026

Copy link
Copy Markdown
Member

@groeneai it's ok to change the test if it inserts default on \N for Tuple() with enabled input_format_csv_deserialize_separate_columns_into_tuple. Because it's wrong.

With input_format_csv_deserialize_separate_columns_into_tuple = 1 a Tuple is read from one CSV cell
per element, so the first cell belongs to the first element. readFieldImpl applied the whole-column
input_format_null_as_default short-circuit first, so a leading \N was taken to mean the entire Tuple
column was NULL: the row was replaced by a default and the remaining cells were misread as the next
column, failing with INCORRECT_DATA "Expected end of line". That is issue ClickHouse#106247.

Skip the whole-column branch for a non-empty Tuple whose elements are separated by the field
delimiter. SerializationTuple::deserializeTextCSV already applies null_as_default per element, so a
null in a non-Nullable element becomes that element's default, which is what it already did for every
position other than the first.

The elements are separate cells only when tuple_delimiter is the field delimiter. HiveText reuses
this reader with its own field delimiter while tuple_delimiter stays a comma, so a tuple is one field
there and a null in it is still the whole column.

A bare Tuple therefore always occupies one cell per element, so a lone \N in a tuple's cell position
is no longer read as the whole column being NULL. 01016_input_null_as_default pinned that older
reading through the setting's default value; its CSV rows now spell the tuple's cells out and expect
the element defaults. Avogar confirmed the previous expectation was wrong. An empty Tuple() has no
elements and a Nullable(Tuple) is read from a single field, so both keep the whole-column behaviour.
A null inside a nested Tuple is still read as that whole nested element, unchanged and out of scope.
@groeneai
groeneai force-pushed the groeneai/fix-106247-csv-tuple-leading-null-null-as-default branch from 283bb1d to d634bc9 Compare August 8, 2026 08:46
@groeneai groeneai changed the title Treat a leading CSV null as the first element of a last-column Tuple Treat a leading CSV null as the first Tuple element Aug 8, 2026
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Done, pushed as d634bc9.

The fix is back to the one condition you asked for: readFieldImpl skips the whole-column
input_format_null_as_default short-circuit for a non-empty bare Tuple, and
SerializationTuple::deserializeTextCSV applies the setting per element, so the second half of your
rule needed no new code. The checkpoint and rollback machinery is gone.

01016_input_null_as_default is updated as you authorised, scoped to its CSV block only: rows 1 and 4
gave t Tuple(String, Float64) a single \N field, and they now spell the two element cells out and
expect the element defaults. The other formats in that test read the tuple as one field and still take
the column DEFAULT, so their expectations are untouched.

Two things I found while validating, both fixed here:

HiveText inherits this reader and replaces csv.delimiter with its own field delimiter while
tuple_delimiter stays a comma, so a tuple is one field there. Exempting every bare Tuple broke it:
a lone \N became the first element and then failed expecting the internal comma, where before it
gave the column default. The condition now also requires tuple_delimiter to be the field delimiter,
and 04657_hive_text_tuple_whole_field_null covers it.

A one-element Tuple had no case pinning it. With a column DEFAULT the two readings differ there,
(NULL) or (0) against (7), so 04405 now covers both spellings.

I also documented the restriction on
input_format_csv_deserialize_separate_columns_into_tuple itself: a row that supplies a single field
for a whole bare Tuple is short by the remaining elements and is rejected rather than taking the
column default, and setting it to 0 restores the previous reading.

input_format_csv_use_default_on_bad_values still rejects a separate-column Tuple, with or without
a null in it, because that path buffers one cell. That is unchanged from master and I left it alone.

Validation: 01016, 04405 and 04657 pass together on the pushed tree. Reverting either half of
the condition reddens exactly its own test and leaves the other green. A sweep of the CSV, Tuple and
HiveText tests with only the fix reverted shows no regressions and 04405 as the one repaired test.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d634bc9

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) / text_index the perf test materializes a text index with mutations_sync = 0, so its own drop_query (ALTER TABLE hits_10m_single DROP INDEX idx_sp) can race the still-running mutation and raise Code: 36 ... affected by mutation with ID 'mutation_22.txt' which is not finished yet. A race inside the perf test, not in the server. 99 hits across 29 unrelated pull requests and 1 master run in 30 days a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Build (arm_release) / Post Hooks build_profile_hook.py telemetry INSERT: ERROR: No connection to LogCluster / LogCluster not ready, AssertionError at log_cluster.py:239. The is_ready() gate is the connect-side variant of the fleet-wide build-profile telemetry failure tracked in #113408. 410 hits across 223 pull requests and 145 master runs in 30 days, check_status is success throughout, so nothing is gated #113409 (external, merged 2026-08-06) is present on this build and did not resolve this variant: its retry loop sits after the early is_ready() return, so a fix task owns the residual (fixing PR link to follow on this PR)
Bugfix validation (functional tests, amd64 and aarch64) / 04657_hive_text_tuple_whole_field_null not a failure. invert_bugfix_validation_status flips FAIL and OK, so this row means the test passed on pre-fix master, which is correct: 04657 is the HiveText regression-prevention guard added during review, not a reproducer of the reported bug. 04405_csv_tuple_leading_null_null_as_default and 01016_input_null_as_default both reproduce it, so the per-arch validation contract is met and both checks are green not a failure, no owner needed

Config Workflow is success; 175 check-runs, 0 incomplete, 17 skipped, last completion
2026-08-08T13:12:25Z. No PR-caused failure on this head: the diff touches
CSVRowInputFormat, one format setting and four stateless test files, none of which can reach
the text index, mutation scheduling, or the build post-hook.

Session id: cron:our-pr-ci-monitor:20260808-133000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison text_index drop_query failure on this PR's CI ledger: #114030

@Avogar
Avogar added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit 2655f0e Aug 10, 2026
179 of 181 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @Avogar — this PR appears to contain a backward incompatible change but is categorized as Bug Fix (user-visible misbehavior in an official stable release).

Why: With default settings, SELECT * FROM format(CSV, 'a UInt8, t Tuple(Int32,Int32), b UInt8', '1,\N,2') returned 1 (0,0) 2 before the change (verified via the documented opt-out input_format_csv_deserialize_separate_columns_into_tuple = 0) and now throws CANNOT_PARSE_INPUT_ASSERTION_FAILED. The PR itself had to widen the CSV input of the six-year-old test 01016_input_null_as_default by two cells, which is direct evidence that previously-valid input no longer parses.

Suggested category: Backward Incompatible Change

Could you check if the changelog category should be updated? This helps users know what to expect when upgrading. Ignore this if the change is intentionally non-breaking.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, and done: I have recategorised this to Backward Incompatible Change and rewritten the changelog entry to lead with what breaks.

Measured on official 26.8.1.1154 (contains the merge) against pre-merge master 604017b7, at default settings:

input for t before after
1,\N,2 into a UInt8, t Tuple(Int32,Int32), b UInt8 1 (0,0) 2 CANNOT_PARSE_INPUT_ASSERTION_FAILED
7,\N,\N into i Int8, b Float64 DEFAULT 3, c Tuple(String, Float64) DEFAULT ('mydefault', b/4) ('mydefault',0.75) CANNOT_PARSE_INPUT_ASSERTION_FAILED
5,\N into i Int8, c Tuple(Int32) DEFAULT tuple(7) (7) (0)

The third row is the one I think justifies the category on its own, and it is stronger than the case you raised: a one-element Tuple has the same field count under either reading, so there is no parse error to warn the user. The row is accepted and the value silently changes from the column DEFAULT to the element default.

One correction to your repro so it reproduces as written: in a SQL string literal '1,\N,2' is 4 bytes, 1,,2, because the lexer consumes the \N. That input returns 1 (0,0) 2 on both binaries. Use '1,\\N,2' (hex() gives 312C5C4E2C32) to get the failure.

The pr-bugfix label still needs swapping for pr-backward-incompatible; I do not have rights to change labels. @Avogar could you swap it? The changelog itself reads the category from the PR body, which is now correct, so the generated 26.8 entry lands in the right section either way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants