Skip to content

Fix CSVWithNames header column count for tuples serialized into separate columns - #107371

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-csv-with-names-tuple-header-107342
Jun 29, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-csv-with-names-tuple-header-107342

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed the CSVWithNames and CSVWithNamesAndTypes header having fewer columns than the data when output_format_csv_serialize_tuple_into_separate_columns is enabled (the default). The header (and the types row) now flattens Tuple columns into their leaf fields with dotted names (e.g. t.a, t.b), so the header column count matches the data. A new setting output_format_csv_header_serialize_tuple_into_separate_columns (default 1) controls this and can be set to 0 to restore the previous single-name header.

Description

Closes: #107342

When output_format_csv_serialize_tuple_into_separate_columns is enabled (the default), SerializationTuple::serializeTextCSV writes each tuple value as N separate CSV cells, but the header was written from the top-level column names only, so the header had fewer fields than the data. Example before the fix:

"User","Network"
123,"Sophia",1,"Net1"

After the fix (default):

"User.ID","User.Name","Network.ID","Network.Name"
123,"Sophia",1,"Net1"

The same applied to the types row of CSVWithNamesAndTypes and to CustomSeparated* with the CSV escaping rule.

The new opt-out setting output_format_csv_header_serialize_tuple_into_separate_columns (default 1) flattens the header (names and types rows) recursively, mirroring the value flattening. Nested tuples expand recursively (t.a.x), unnamed tuples use positional element names (t.1, t.2), and non-tuple columns are unchanged.

Round-trip note: a flattened header is not read back into a tuple by name when input_format_with_names_use_header = 1 (the input reader matches a tuple by its single name). Such data round-trips with the new setting set to 0 on output, or with input_format_with_names_use_header = 0 on input. This is documented on the setting.

Test: tests/queries/0_stateless/04340_csv_with_names_tuple_header.

…ate columns

With output_format_csv_serialize_tuple_into_separate_columns enabled (the
default), SerializationTuple::serializeTextCSV writes each tuple value as N
separate CSV cells, but CSVRowOutputFormat::writePrefix wrote the header from
the top-level column names only. The result was a header with fewer fields than
the data (issue ClickHouse#107342). The types row of CSVWithNamesAndTypes had the same
problem, and CustomSeparated* with the CSV escaping rule was affected too.

Add output_format_csv_header_serialize_tuple_into_separate_columns (default 1,
opt-out). When enabled together with the existing value-flattening setting, the
header (names row and types row) flattens each tuple column into its leaf fields
recursively, using dotted names (User.ID, User.Name) and the leaf type names, so
the header width matches the data width.

A flattened header is not read back into a tuple by name when
input_format_with_names_use_header = 1; such data round-trips with the setting
set to 0 on output or input_format_with_names_use_header = 0 on input. This is
documented on the setting.

Closes: ClickHouse#107342

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT (1::UInt64,'a')::Tuple(ID UInt64, Name String) AS User FORMAT CSVWithNames always emits a 1-field header ("User") over a 2-field data row on master. New setting defaults make header and data both 2 fields.
b Root cause explained? output_format_csv_serialize_tuple_into_separate_columns=1 (default) makes SerializationTuple::serializeTextCSV write each tuple value as N CSV cells, but CSVRowOutputFormat::writePrefix wrote the header from top-level column names only, so header width < data width. Same for the types row and for CustomSeparated* under the CSV escaping rule.
c Fix matches root cause? Yes. The header path now flattens tuples the same way the value path does, gated by a new opt-out setting output_format_csv_header_serialize_tuple_into_separate_columns (default 1). It is not a band-aid: it makes the names/types rows use the same recursion as the data.
d Test intent preserved / new tests added? New stateless test 04340_csv_with_names_tuple_header covering CSVWithNames, CSVWithNamesAndTypes, opt-out, nested tuples, unnamed tuples, mixed columns, no-tuple unchanged, CustomSeparated CSV/non-CSV rule, and round-trip both ways. No existing test weakened.
e Both directions demonstrated? Yes. On the pre-fix master binary the test diff is non-empty (header "User","Network", new setting UNKNOWN_SETTING). On the fixed binary the test passes via the real server using the same client-pipe+diff mechanism clickhouse-test uses.
f Fix is general, not a narrow patch? Yes. A shared helper getCSVHeaderNamesAndTypes is used by both CSVRowOutputFormat and the sibling CustomSeparatedRowOutputFormat (the only other format that flattens tuples into CSV cells). Flattening is recursive (nested tuples), handles named and unnamed tuples, and only triggers when values are actually flattened (and, for CustomSeparated, only under the CSV escaping rule). The input round-trip caveat is documented on the setting rather than silently broken.

Session id: cron:clickhouse-worker-slot-3:20260612-204200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @al13n321 could you review this? It fixes the CSVWithNames/CSVWithNamesAndTypes header having fewer columns than the data when tuples are serialized into separate columns (issue #107342), by flattening the header rows the same way the values are flattened, behind a new opt-out setting output_format_csv_header_serialize_tuple_into_separate_columns (default 1).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78e0365]

Summary: ✅


AI Review

Summary

This PR fixes CSVWithNames/CSVWithNamesAndTypes tuple headers by flattening tuple names and type names when tuple values are serialized into separate CSV columns, and adds the corresponding setting, compatibility-history entry, CustomSeparated delimiter guard, and focused stateless coverage. I found the prior inline concerns addressed in the current code and did not find new blockers or major issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 12, 2026
…s the tuple delimiter

In CustomSeparated, tuple values are flattened into separate columns under the
CSV escaping rule, and the tuple elements are joined with csv.tuple_delimiter
(format_csv_delimiter). The format itself joins fields with
custom.field_delimiter (format_custom_field_delimiter), which defaults to tab.

When those two delimiters differ (for example the default tab field delimiter,
or format_custom_field_delimiter = '|'), a Tuple(ID UInt64, Name String) value
is still written as one custom field like 1,"a", while the previous prefix
flattened the header into several fields such as User.ID|User.Name. That
reintroduced the same header/data width mismatch in the opposite direction.

Flatten the CustomSeparated header only when the custom field delimiter is the
same single character as csv.tuple_delimiter, so the flattened header matches
how the tuple value is laid out. The plain CSV path is unaffected because there
csv.delimiter and csv.tuple_delimiter are both format_csv_delimiter.

Extends the regression test with non-comma CustomSeparatedWithNames cases.

Closes: ClickHouse#107342

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d Nullable tuples

The header leaf-count logic in FlattenTupleForCSVHeader diverged from the CSV
value serializers in two cases, so the header width did not always match the
data width:

- An empty Tuple() value still occupies one field (SerializationTuple writes
  nothing between the surrounding delimiters), but the helper recursed into
  zero elements and emitted no header cell. It now emits one cell for an empty
  tuple.

- A non-null Nullable(Tuple(...)) value serializes through the nested tuple
  (SerializationNullable delegates to it) and is flattened into separate
  columns, but the helper saw the top-level Nullable and kept one header cell.
  It now unwraps Nullable and flattens the inner tuple. Scalar Nullable types
  serialize as one field and keep one cell with the full Nullable type name.

Extends the 04340 regression test with a mixed empty-tuple row, a non-null
Nullable(Tuple(...)) column, and a scalar Nullable column.

Regenerates 00300_csv and 02149_schema_inference_formats_with_schema_2
references: with output_format_csv_header_serialize_tuple_into_separate_columns
default on, CSVWithNames(AndTypes) now flattens tuple columns in the header to
match the already-flattened data.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Core/FormatFactorySettings.h Resolved
…ttening

The output_format_csv_header_serialize_tuple_into_separate_columns
description stated the flattening applies to the CSV escaping rule of
CustomSeparated* without the delimiter condition the code enforces. The
header is flattened for CustomSeparated* only when
format_custom_escaping_rule = 'CSV' and format_custom_field_delimiter is a
single character equal to format_csv_delimiter (= csv.tuple_delimiter);
otherwise the header stays unflattened so it matches the one-field tuple
value. Update the doc text so the documented contract matches the code.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on this commit. All failures are confirmed unrelated to this PR (a CSV header doc-wording change cannot cause any of them):

  • Fast test (arm_darwin) / 04336_parallel_blocks_marshalling_low_cardinality_native_format — known macOS loopback infra flake (remote('127.0.0.{1,2}'), 127.0.0.2 unbindable on Darwin). Fix in flight: Skip macOS-incompatible distributed tests 04327 and 04336 #107376 (adds it to ci/defs/darwin.skip).
  • AST fuzzer (amd_debug) / Unexpected expression in JOIN ON section. Expected boolean (UInt8), got 'Nothing' (STID 4699-43ac) — chronic analyzer trunk bug, 12+ unrelated PRs + master in 30d. Tracked separately.
  • Stateless tests (arm_asan_ubsan, azure, parallel) / 02477_single_value_data_string_regression and 04040_tpc_h_q08 — both code 241 (memory limit exceeded, host RSS ~53.7 GiB) and both Failed 0 out of 3 reruns, i.e. transient host-memory-pressure on the azure runner that did not reproduce. 0 master hits; scattered 1-hit-per-PR across unrelated PRs.

The PR change is doc-only on top of the validated fix. No PR-caused failures.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 569e75d61fc7 (auto repo-wide master-merge into the fork branch; the CSVWithNames tuple-header fix itself is unchanged). Finish Workflow / Mergeable Check / PR all green. No PR-caused failures.

CI ledger (covered SHA 569e75d):

  • Report messages — job-level praktika report warning (1 warning, no test failure, not merge-blocking). Not PR-caused.

All real test jobs pass. Ready for review.

@Avogar Avogar self-assigned this Jun 15, 2026
Rewrite the regression test from a .sql test with the no-parallel tag into a
.sh test driven by clickhouse-local. The round-trip part wrote fixed-name files
(04340_optout.csv, 04340_flat.csv) into the shared server user_files, so it
needed no-parallel to avoid colliding with a concurrent copy of itself.

clickhouse-local runs in CLICKHOUSE_TMP (unique per test run) and the round-trip
files are prefixed with CLICKHOUSE_TEST_UNIQUE_NAME, so the test no longer
touches shared state and runs in parallel with itself. The expected output is
unchanged. Per reviewer request on ClickHouse#107371.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Core/FormatFactorySettings.h Resolved
…t_with_types_use_header = 0

The output_format_csv_header_serialize_tuple_into_separate_columns note told
readers to set input_format_with_names_use_header = 0 to read a flattened
header back into a Tuple positionally. For CSVWithNamesAndTypes the types row
is flattened too, so RowInputFormatWithNamesAndTypes::readPrefix validates the
flattened types row against the single top-level Tuple input field (while
input_format_with_types_use_header stays enabled) and rejects it with
INCORRECT_DATA "The number of data types differs from the number of column
names". The positional round-trip therefore also needs
input_format_with_types_use_header = 0.

Update the setting note accordingly and add the CSVWithNamesAndTypes
positional round-trip case to 04340_csv_with_names_tuple_header.sh.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on a4f8106. The only red test check, Stateless tests (arm_asan_ubsan, targeted), is GitHub Actions runner infrastructure rather than a test failure: the job was killed during docker setup (the chown -R 1000:1000 ./ci/tmp step) before any test ran (empty job output, zero per-test rows in CIDB). The same three changed tests pass on amd asan/tsan/msan/debug/coverage and all four flaky-check jobs, and reproduce green locally. CH Inc sync is the internal fork mirror-sync status that always fails on fork PRs and does not gate. No action needed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107371&sha=a4f8106022f85f365a1f02de28701a2a10e8cfca&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

Comment thread src/Core/FormatFactorySettings.h Resolved
…dd test case

The WithNamesAndTypes round-trip caveat for
output_format_csv_header_serialize_tuple_into_separate_columns applies to
CustomSeparatedWithNamesAndTypes too, not only CSVWithNamesAndTypes. When the
setting flattens a CustomSeparatedWithNamesAndTypes header (format_custom_escaping_rule
= 'CSV' and a single-character format_custom_field_delimiter equal to
format_csv_delimiter), the types row is flattened into the leaf type fields
(UInt64, String) while the input schema still has one top-level Tuple column.
RowInputFormatWithNamesAndTypes::readPrefix validates that types row whenever
input_format_with_types_use_header = 1 and rejects it (INCORRECT_DATA), exactly
like CSVWithNamesAndTypes. So the positional read needs input_format_with_types_use_header
= 0 in addition to input_format_with_names_use_header = 0.

Doc note now names both *WithNamesAndTypes formats, and the test adds the
CustomSeparatedWithNamesAndTypes positional round-trip case next to the CSV one.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Jun 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 24, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jun 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 24, 2026
@Avogar

Avogar commented Jun 25, 2026

Copy link
Copy Markdown
Member

@groeneai merge with master and move new setting in history in new 26.7 section

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, please take a look at ^

groeneai added 2 commits June 28, 2026 17:42
…o 26.7 settings history

master bumped to 26.7.1, so the new setting's SettingsChangesHistory entry
moves from the 26.6 block to a new 26.7 block (per reviewer request).
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done. Merged fresh master into the branch (8b2ed65) and moved output_format_csv_header_serialize_tuple_into_separate_columns from the 26.6 to the new 26.7 section in SettingsChangesHistory.cpp. 02995_new_settings_history passes (the setting now resolves to version 26.7); the fix and 04340 test are unchanged.

Prior CI run on the previous head aborted in the Config Workflow bootstrap:
the praktika fetch-previously-failed-tests step hit a transient
play.clickhouse.com read timeout on all retries, the 600s job timed out
(exit -15), and all downstream jobs were dropped. CIDB is healthy again;
this empty commit re-runs the workflow on the same validated tree.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 68/68 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 29, 2026
Merged via the queue into ClickHouse:master with commit 6341c22 Jun 29, 2026
174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
@Avogar

Avogar commented Jun 30, 2026

Copy link
Copy Markdown
Member

@groeneai we have a problem:

:) select number % 2 ? NULL : toNullable(tuple(1,2,3)) as t from numbers(4) format CSVWithNamesAndTypes

SELECT if(number % 2, NULL, toNullable(tuple(1, 2, 3))) AS t
FROM numbers(4)
FORMAT CSVWithNamesAndTypes

Query id: 138dc233-60a3-44bd-a5b2-748f6e03f713

"t"
"Nullable(Tuple(UInt8, UInt8, UInt8))"
1,2,3
\N
1,2,3
\N

4 rows in set. Elapsed: 0.002 sec.

In case of Nullable(Tuple(...)) we might have wrong number of columns in CSV, because elements are serialized as separate columns while NULL only as a single column. I think for Nullable(Tuple(...)) we should not serialize it as separte columns.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar thanks, confirmed. The root cause: a Nullable(Tuple) value has a row-dependent CSV width because a non-null value is flattened into separate columns while a NULL is a single \N, so the flattened header only matched the non-null rows (and the data didn't round-trip).

Fix in #108959: a Nullable(Tuple) is now serialized as a single CSV field (not flattened), so every row is one field and the header stays one cell. A bare Tuple is still flattened as before. Input is symmetric, so it round-trips:

"t"
"Nullable(Tuple(UInt8, UInt8, UInt8))"
"(1,2,3)"
\N
"(1,2,3)"
\N

Note: Tuple(Nullable(...)) with an element NULL not reading back correctly (#106247) is a separate, pre-existing bug in the tuple-element path, out of scope here.

alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Jul 22, 2026
A Nullable(Tuple(...)) had a row-dependent CSV width: a NULL row wrote a
single \N field, while a non-null row was flattened into separate columns
(N fields) under output_format_csv_serialize_tuple_into_separate_columns.
The CSVWithNames(AndTypes) header was flattened to N columns, matching only
the non-null rows, so NULL rows desynced the column count and the data did
not round-trip (CANNOT_PARSE_INPUT).

Keep a Nullable(Tuple) as a single quoted CSV value (it is not flattened),
so every row is exactly one field and the header stays one cell. A bare
Tuple (not wrapped in Nullable) is still flattened as before. Input is made
symmetric so the value round-trips.

Follow-up to ClickHouse#107371, reported by Avogar.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
A Nullable(Tuple(...)) had a row-dependent CSV width: a NULL row wrote a
single \N field, while a non-null row was flattened into separate columns
(N fields) under output_format_csv_serialize_tuple_into_separate_columns.
The CSVWithNames(AndTypes) header was flattened to N columns, matching only
the non-null rows, so NULL rows desynced the column count and the data did
not round-trip (CANNOT_PARSE_INPUT).

Keep a Nullable(Tuple) as a single quoted CSV value (it is not flattened),
so every row is exactly one field and the header stays one cell. A bare
Tuple (not wrapped in Nullable) is still flattened as before. Input is made
symmetric so the value round-trips.

Follow-up to ClickHouse#107371, reported by Avogar.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Rewrite the regression test from a .sql test with the no-parallel tag into a
.sh test driven by clickhouse-local. The round-trip part wrote fixed-name files
(04340_optout.csv, 04340_flat.csv) into the shared server user_files, so it
needed no-parallel to avoid colliding with a concurrent copy of itself.

clickhouse-local runs in CLICKHOUSE_TMP (unique per test run) and the round-trip
files are prefixed with CLICKHOUSE_TEST_UNIQUE_NAME, so the test no longer
touches shared state and runs in parallel with itself. The expected output is
unchanged. Per reviewer request on ClickHouse#107371.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-tuple-header-107342

Fix CSVWithNames header column count for tuples serialized into separate columns
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.

CSVWithNames structure mismatch when unwrapping tuples

5 participants