Skip to content

Detect stream filename collisions within a single column - #115632

Merged
Avogar merged 4 commits into
ClickHouse:masterfrom
Avogar:fix-intra-column-stream-filename-collision
Sep 17, 2026
Merged

Avogar merged 4 commits into
ClickHouse:masterfrom
Avogar:fix-intra-column-stream-filename-collision

Conversation

@Avogar

@Avogar Avogar commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

MergeTreeData::checkColumnFilenamesForCollision only compared stream file names across columns. Two streams of one column that render to the same file name were silently deduplicated before that comparison, so the column was accepted at CREATE/ALTER and the part was then written with both streams in one file:

CREATE TABLE t (c Nullable(JSON(`null` Int64))) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('{"null":1}'), (NULL);
SELECT c FROM t;
-- Code: 33. Too many marks in file .../c.null.cmrk2 ... (CANNOT_READ_ALL_DATA)

The same collision spread over two columns was already rejected, so this only removes an asymmetry. The new branch follows the existing convention: BAD_ARGUMENTS at CREATE and ALTER, a logged error on attach so an already broken table still attaches and can be repaired manually.

Columns whose streams collide only as subcolumn names, not as file names, stay allowed (Array(Tuple(`size0` UInt64)), Tuple(`a` String, `a.size` UInt64)) - they read back correctly, and such tables may already exist.

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 accepting a column whose two serialization streams map to the same file name (for example Nullable(JSON(`null` Int64)) or Tuple(`a` Tuple(`b` UInt64), `a.b` UInt64)). Such a table was created successfully, but its parts were written with both streams in one file and could not be read, merged or checked. Creating such a column now fails with BAD_ARGUMENTS, as a collision between two different columns already did. Existing tables still attach, with the collision logged.


Workflow [PR]
Sync PR [sync-upstream/pr/115632]

Version info

  • Merged into: 26.10.1.30 (included in 26.10 and later)

`MergeTreeData::checkColumnFilenamesForCollision` only compared stream file
names across columns. Two streams of the same column that render to the same
file name were silently deduplicated before that comparison, so such a column
was accepted at CREATE/ALTER and the part was then written with both streams in
one file, making it unreadable:

    CREATE TABLE t (c Nullable(JSON(`null` Int64))) ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO t VALUES ('{"null":1}'), (NULL);
    SELECT c FROM t;
    -- Code: 33. Too many marks in file .../c.null.cmrk2 ... (CANNOT_READ_ALL_DATA)

The asymmetry was directly observable: the same collision spread over two
columns (`a Tuple(b UInt64)` and `` `a.b` UInt64 ``) was already rejected.

Check the `inserted` flag of the per-column map and report the collision with
the same convention as the cross-column branch: `BAD_ARGUMENTS` at CREATE and
ALTER, a logged error on attach so an already broken table can still be
attached and repaired manually.

The `replace_long_file_name_to_hash` hint is now appended only when the two
full stream names differ, since identical names cannot have been merged by
hashing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9a77a08]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR extends MergeTreeData::checkColumnFilenamesForCollision so CREATE/ALTER can reject same-column stream filename collisions that previously only got caught across columns. The Tuple and zero-level Map coverage looks directionally correct, but the implementation still leaves one real corruption path open for JSON shared-data streams, so the advertised protection is incomplete.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:11847-11872, src/DataTypes/Serializations/SerializationObject.cpp:230-291] [dismissed by author -- https://github.com/Detect stream filename collisions within a single column #115632#discussion_r4018803270] findStreamFileNameCollision still calls SerializationObject::enumerateStreams without a column or deserialize state, and that helper only descends into ObjectSharedData when column_object || structure_state is available. As a result, a schema like JSON(\object_shared_data.paths` Int64)withobject_shared_data_serialization_version = 'map'(orobject_shared_data_serialization_version_for_zero_level_parts = 'map') is still accepted even though inserts later serialize both logical streams into c.object_shared_data%2Epaths, leaving the part unreadable. Suggested fix: either reserve the fixed shared-data carriers for the mapshared-data layout during DDL-time checking, or teach the DDL-time enumeration path to emit those shared-data streams without a data column, then add a regression test for both merged and zero-levelmap` settings.
Final Verdict

Changes requested: the PR still leaves a supported JSON shared-data configuration that can create unreadable MergeTree parts after CREATE/ALTER.

LLVM Coverage Report

Measured on commit 9a77a08.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 63/64 (98.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 9a77a0872668e0dcfa228f70e8a0e8e4ad513147 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 10, 2026
04935_optimize_functions_to_subcolumns_name_collision uses ENGINE = Memory
deliberately and says why in its own comment: "Memory, because the Map cases
collide on file names in MergeTree". It carried no tag, so a stress run that
enables --replace-log-memory-with-mergetree
(ci/jobs/scripts/stress/stress.py:487, probability 0.3) rewrote those engines to
MergeTree (tests/clickhouse-test:420-428, :539-543) and created tables the test
never intended.

For c Tuple(`a.keys` Array(String), `a` Map(String, UInt64)) two substreams of
the one column render to the same stream file name, because
getNameForSubstreamPath escapes a TupleElement name as a whole for Nested
compatibility (ISerialization.cpp:340-345): both TupleElement("a.keys") with its
array element data and TupleElement("a") with the Map's keys become
c%2Ea%2Ekeys. The Compact writer emits one mark per substream occurrence for the
data granules (MergeTreeDataPartWriterCompact.cpp:353-363, 7 for the measured
part) but the deduplicated count in the final mark row (:425), and
columns_substreams.txt dedupes by name (ColumnsSubstreams.cpp:45-47, 5 entries).
The read side takes its stride from that list
(MergeTreeDataPartCompact.cpp:209-215), so it parses a zero granularity early,
sets hasFinalMark(), and throws on the next iteration:

  Logical error: 'Cannot append mark after final'
  MergeTreeIndexGranularityAdaptive.cpp:63 <- MergeTreeDataPartCompact.cpp:194
  <- loadIndexGranularity() <- IMergeTreeDataPart.cpp:1507
  <- MergeTreeData.cpp:2651 <- :2742 <- loadDataPartsFromDisk

That loop runs at server startup, and a LOGICAL_ERROR there goes through
abortOnFailedAssertion, so every restart re-reads the same part and aborts
again: 11/11 start attempts in CI, 3/3 measured locally.

The first four rows in CIDB, within four hours on 2026-09-10, none of them
PR-caused:

  03:26:57Z  master     Stress test (amd_tsan)         divisibility spelling
  03:46:32Z  master     Stress test (azure, amd_tsan)  append-mark spelling
  05:50:43Z  master     Stress test (amd_debug)        divisibility spelling
  07:15:23Z  PR 117248  Stress test (arm_tsan)         append-mark, Wide loader

All three master rows also carry "Cannot start clickhouse-server", and the same
Compact-loader signature kept arriving on unrelated PR stress runs through the
rest of that day. The lane randomizes min_bytes_for_wide_part, which is why the
fourth trips MergeTreeDataPartWide::loadIndexGranularityImpl instead: its run
log names this test and the unreadable Wide marks file c%2Et%2Ea.cmrk2 of
t_shadowed_tuple_element. Skipping the test removes every colliding table it
creates, so the tag covers both loaders and both spellings. The divisibility
spelling, reported as "Number of marks 9 is not divisible by number of columns
in mark 4", is the same part read through the writer's own prewarm cached_marks
vector (occurrence marks plus deduplicated marks, read with the deduplicated
stride) under prewarm_mark_cache = 1, not a MarkCache keying miss; the part
measured locally gives 12 and 5 there because it also carries separate String
size streams.

The engine defect is ClickHouse#115632 "Detect stream filename collisions within a single
column", open since 2026-08-20, which refuses such a schema at CREATE. This tag
is needed regardless of it: once ClickHouse#115632 merges, the substituted
CREATE TABLE ... ENGINE = MergeTree is refused with BAD_ARGUMENTS, and 04935's
statement carries no { serverError } annotation, so an untagged 04935 would fail
the stress lane instead of aborting the server.
The check enumerated stream names for one serialization configuration only,
the one used for merged parts. Zero-level parts written by `INSERT` may use
different versions - `map_serialization_version_for_zero_level_parts` and
`object_shared_data_serialization_version_for_zero_level_parts` - and the
documented recommendation for `Map` is exactly a split one: `basic` for
inserts to keep them cheap, `with_buckets` for merged parts. A collision that
only the zero-level layout produces was therefore missed, and every inserted
part written with it was corrupt:

    CREATE TABLE t (c Tuple(`a.keys` Array(String), `a` Map(String, UInt64)))
    ENGINE = MergeTree ORDER BY tuple()
    SETTINGS map_serialization_version = 'with_buckets',
             map_serialization_version_for_zero_level_parts = 'basic';

Enumerate once per configuration the table can write, each with its own name
maps, since parts of different configurations never share a file. The second
pass is skipped when both configurations agree.

Detection moved out of `checkColumnFilenamesForCollision` into
`findStreamFileNameCollision`, which returns the first collision it finds and
leaves reporting to the caller.

`enumerate_dynamic_streams` is now set to false explicitly. It changes nothing
today, because the branch reading it needs a column or a deserialize state and
the check has neither, but it pins the contract: dynamic path names and bucket
counts are properties of the data, not of the type, so they cannot be known
before anything is written.

This also fixes the test, which asserted the `Map` collisions under whichever
`map_serialization_version` the CI randomizer picked; those assertions now pin
the versions they need.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar requested a review from Ergus September 15, 2026 17:52
Avogar and others added 2 commits September 16, 2026 12:36
The case asserting that a purely bucketed `Map` configuration stays allowed
also has to pin `serialization_info_version = 'with_types'`. Per-type
serialization versions are only recorded in `serializations.json` from that
version on, so with `basic` the nested `Map` falls back to `basic`
serialization, writes a plain `keys` stream and really does collide with the
user-supplied `a.keys` element. CI randomizes the setting, which is why the
case failed there while the check was right to reject it.

Also drop the claim that no detection is lost by not enumerating dynamic
streams. It does not hold: the shared data of `Object` renders its `paths` and
`values` components as escaped-dot names (`object_shared_data%2Epaths`), so a
declared `JSON` path of that name collides with them under
`object_shared_data_serialization_version = 'map'` and is not caught here.
`basic` stream naming is simply not injective; making it so is the subject of
ClickHouse#119329.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit e02a452 Sep 17, 2026
176 of 178 checks passed
@Avogar
Avogar deleted the fix-intra-column-stream-filename-collision branch September 17, 2026 13:17
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

3 participants