Skip to content

Fix missing variant_discr stream for Dynamic columns after mutation - #107562

Merged
Avogar merged 10 commits into
masterfrom
fix_dynamic_mutation_variant_discr
Jul 8, 2026
Merged

Avogar merged 10 commits into
masterfrom
fix_dynamic_mutation_variant_discr

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Candidate fix for a Dynamic-column data-part corruption found by CI fuzzers.

A background merge (and any read) over a MergeTree table with a Dynamic column can fail with:

Logical error: Stream <col>.variant_discr for column <col> with type Dynamic(max_types=N) is not found

thrown in MergeTreeReaderWide::getStream, because a data part on disk has the dynamic_structure stream but is missing the variant_discr stream of a Dynamic column. It is a write-side problem: the part was produced by an earlier merge/mutation without that stream.

Root cause

getStreamCounts in src/Storages/MergeTree/MutateTask.cpp enumerated each column's streams with a default serialization->enumerateStreams(callback) call (no column / deserialization state). For columns with a dynamic structure (Dynamic, JSON, ...), SerializationDynamic::enumerateStreams short-circuits after the dynamic_structure substream when there is no column/state, so the data-dependent substreams (variant_discr, SharedVariant, the element streams, ...) are never reported. The mutation file bookkeeping (collectFilesToSkip / collectFilesForRenames) was therefore blind to those substreams for dynamic columns, which can leave a variant_discr stream neither rewritten nor hardlinked into the new part.

Fix

Use the substreams recorded in columns_substreams.txt — the ground truth of what exists in the part — for dynamic-structure columns, mirroring the approach already used by MergeTreeDataPartWide::checkConsistency. Falls back to enumeration for old parts (no columns_substreams.txt) and for the placeholder substreams of not-yet-written columns in a new part. Gated on hasDynamicSubcolumns, so regular and Nested columns keep their previous behaviour. Adds a small ColumnsSubstreams::tryGetColumnSubstreams accessor.

Verification

  • Builds cleanly.
  • Existing Dynamic merge/alter tests (03037_dynamic_merges_*, 03038_nested_dynamic_merges_*, 03040_dynamic_type_alters_*) still pass.
  • New test 04341_dynamic_mutation_variant_discr_streams exercises mutations that rewrite / leave untouched / change the type of a Dynamic column, interleaved with merges, and CHECK TABLE validates part consistency.

Caveat — please review carefully

The original failure was found only by CI fuzzers (AST fuzzer, BuzzHouse, stress) and I could not reproduce it in isolation despite extensive attempts, so I could not directly verify that this change eliminates the original crash. This is a candidate fix that addresses a real, demonstrable incompleteness in the dynamic-column stream accounting and is consistent with the symptom; it needs validation by the fuzzers in CI and review by the serialization subsystem owners.

Closes: #107561

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):

Fix a Logical error: Stream ... variant_discr ... is not found that could occur when merging or reading a MergeTree part produced by a mutation of a table with a Dynamic column.

🤖 Generated with Claude Code

Version info

  • Backported to: 26.6.2.120, 26.5.6.78, 26.3.17.78, 25.8.29.34

… mutation

`getStreamCounts` in `MutateTask` enumerated each column's streams with a
default `enumerateStreams` call (without a column or deserialization state).
For columns with a dynamic structure (`Dynamic`, `JSON`, ...),
`SerializationDynamic::enumerateStreams` stops after the `dynamic_structure`
substream in that case and never reports the data-dependent substreams such as
`variant_discr`. As a result the mutation file bookkeeping
(`collectFilesToSkip` / `collectFilesForRenames`) was blind to those
substreams, which could leave a `variant_discr` stream neither rewritten nor
hardlinked into the new part — producing a part that later fails to read or
merge with `Logical error: Stream <col>.variant_discr ... is not found` in
`MergeTreeReaderWide`.

Use the substreams recorded in `columns_substreams.txt` (the ground truth of
what exists in the part) for dynamic-structure columns, mirroring the approach
already used by `MergeTreeDataPartWide::checkConsistency`, and fall back to
enumeration for old parts and not-yet-written columns. The change is gated on
`hasDynamicSubcolumns`, so regular and `Nested` columns are unaffected.

Note: the original failure was found by CI fuzzers and could not be reproduced
in isolation, so this is a candidate fix that needs verification by the fuzzers
and review by the serialization subsystem owners.

Related: #107561

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

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6df97dc]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-26fa) FAIL cidb, issue

AI Review

Summary

This PR fixes partial-mutation stream accounting for Dynamic/JSON columns by consulting columns_substreams.txt, forcing full rewrites for old Wide parts without recorded substreams, and adding focused regressions. One correctness hole remains in that new guard/path: a Wide part whose columns_substreams.txt is present but records zero substreams for a dynamic-structure column still takes the partial path and then counts zero streams for that column, which can re-introduce the orphaned-stream corruption this change is trying to prevent.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MutateTask.cpp:181, 1040-1047] hasDynamicColumnsWithoutRecordedSubstreams only treats a missing entry as unsafe. ColumnsSubstreams::readText also accepts 0 substreams for a column, so a corrupted columns_substreams.txt can leave a Dynamic/JSON column with a non-null but empty recorded list. getStreamCounts then treats that empty list as authoritative and counts zero streams for the column, so an unrelated partial mutation can again produce a part missing variant_discr / element streams.
    Suggested fix: treat an empty recorded list as equivalent to "no recorded substreams" in both the full-rewrite guard and getStreamCounts, and ideally reject such entries when loading columns_substreams.txt.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions: handle empty recorded-substream lists as corrupted/missing metadata instead of taking the partial-mutation path, and add a focused regression for that corruption shape.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 15, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
…during mutation

Address review on #107562: `getStreamCounts` resolved every recorded substream of a
dynamic-structure column against the source part's checksums, including the placeholder
substream that `getColumnsForNewDataPart` records for a column that the mutation will write
but that is not yet present in the source part. If the table also contains an unrelated
column literally named `dummy`, the placeholder resolved to that column's real `dummy.bin`
stream, so the unchanged stream was marked as skipped and was neither rewritten nor
hardlinked into the new part, producing a part whose checksums reference a missing
`dummy.bin`/`dummy.cmrk2`.

Introduce a named `NOT_YET_WRITTEN_COLUMN_SUBSTREAM_PLACEHOLDER` sentinel for the placeholder
and skip it explicitly in `getStreamCounts`, falling back to stream enumeration as before.

Add regression test `04342_dynamic_mutation_dummy_placeholder_stream` that materializes a
newly added `Dynamic` column next to an existing column named `dummy` and validates the
resulting part with `CHECK TABLE`. Verified that the test fails before this change (the
mutated part is missing `dummy.cmrk2`) and passes after it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
…n_variant_discr

# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
…d substreams

A partial mutation accounts for a column's streams via `getStreamCounts`, which for
a column with a dynamic structure (`Dynamic`, `JSON`, ...) relies on the substreams
recorded in `columns_substreams.txt`: state-less `serialization->enumerateStreams`
stops after the `dynamic_structure` substream and never reports the data-dependent
substreams (`variant_discr`, the variant element streams, ...).

Wide parts written before `columns_substreams.txt` was introduced (in 25.8) can
contain such a column with no recorded substreams (the file is also discarded when
found corrupted). For those parts the stream accounting is incomplete again, so a
partial mutation could leave a `variant_discr` stream neither rewritten nor
hardlinked into the new part - the same write-side problem this PR addresses.

Force a full part rewrite (`MutateAllPartColumnsTask`) for that case, mirroring the
existing behaviour for direct mutations of dynamic columns. The new helper
`hasDynamicColumnsWithoutRecordedSubstreams` is added to both full-vs-partial
decision sites (`splitAndModifyMutationCommands` and the task selection in
`MutateTask::prepare`) so they stay consistent. A full rewrite re-serializes the
column, so no stream can be orphaned, and the resulting part has a
`columns_substreams.txt` again, so later mutations can take the partial path.

Add `04401_dynamic_mutation_old_part_no_substreams_file`, which simulates an old
part by deleting `columns_substreams.txt`, runs a partial mutation that does not
touch the `Dynamic` column, and validates the result with `CHECK TABLE`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's "Request changes" verdict (the missing-columns_substreams.txt dynamic-part path) and merged master.

b4 Merge origin/master (the branch was ~1180 commits behind; conflict in MutateTask.cpp was the placeholder constant added by this PR vs. shifted context — resolved by keeping the PR's addition).

Rewrite the whole part when mutating a Dynamic column without recorded substreams — closes the gap the bot flagged. A Wide part written before columns_substreams.txt existed (Dynamic shipped in 25.3; the file was added to Wide parts in 25.8 and loadColumnsSubstreams keeps it optional, also discarding it when found corrupted) can reach getStreamCounts with no recorded substreams and fall back to the incomplete state-less enumeration that misses variant_discr. Since the dynamic stream set cannot be reconstructed without a deserialization state (and hashed names make deriving from checksums unreliable), the new helper hasDynamicColumnsWithoutRecordedSubstreams forces a full part rewrite for that case at both full-vs-partial decision sites (splitAndModifyMutationCommands and MutateTask::prepare), next to the existing haveMutationsOfDynamicColumns guard. A full rewrite re-serializes the column so no stream can be orphaned, and the new part regains a complete columns_substreams.txt so later mutations use the partial path. Blast radius: only pre-25.8 parts with a dynamic column undergoing a partial mutation, once per part.

New test 04401_dynamic_mutation_old_part_no_substreams_file simulates such an old part (delete columns_substreams.txt, reattach), runs a partial mutation that does not touch the Dynamic column, and validates with CHECK TABLE, asserting the rewritten part regains a complete columns_substreams.txt (with variant_discr).

Verified locally (non-sanitizer build): 04341, 04342, and 04401 all pass; 04401 was run against a real server. The change is a no-op for parts that already have columns_substreams.txt, so existing dynamic mutation paths are unchanged.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Address the code review on PR #107562: the new
`hasDynamicColumnsWithoutRecordedSubstreams` guard (and the matching check
in `getStreamCounts`) used `hasDynamicSubcolumns`, which also returns true
for a plain `Map` (`DataTypeMap::hasDynamicSubcolumnsData` is unconditionally
true) and a plain `Variant`. As a result an upgraded Wide part with a basic
`Map` column but no `columns_substreams.txt` would force
`MutateAllPartColumnsTask` for any unrelated partial mutation, turning a cheap
single-column mutation into a full rewrite of all the `Map` data, with no
correctness need.

Only `Dynamic`/`JSON` have a data-dependent structure whose substreams
(`variant_discr`, ...) cannot be enumerated without a deserialization state
(`SerializationDynamic`/`SerializationObject::enumerateStreams` short-circuit
without a column/state). That is exactly what `hasDynamicStructure` reports:
plain `Map`/`Variant` return false, `Dynamic`/`JSON` and any composite that
contains one return true. `SerializationVariant::enumerateStreams` enumerates
all element streams from the type, so a plain `Variant` is correctly excluded.

Use `hasDynamicStructure` at both decision sites. New test
`04412_mutation_old_part_basic_map_partial` builds a Wide part with a basic
`Map` column, deletes `columns_substreams.txt` to simulate a pre-25.8 part,
runs a partial mutation that does not touch the `Map`, and asserts it stays on
the partial path (the part does not regain `columns_substreams.txt`) while
`CHECK TABLE` passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Avogar Avogar self-assigned this Jul 6, 2026
Use recorded substreams from `columns_substreams.txt` for all column
types, not only for columns with dynamic structure. The file is the
ground truth of what streams exist on disk. Fall back to
`enumerateStreams` when no recorded substreams are available (old parts)
or when the column carries the not-yet-written placeholder (to preserve
shared-stream accounting for regular columns like Nested array sizes).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
const auto & columns_substreams = data_part->getColumnsSubstreams();
for (const auto & column : data_part->getColumns())
{
if (column.type->hasDynamicStructure() && !columns_substreams.tryGetColumnSubstreams(column.name))

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.

ColumnsSubstreams::readText accepts 0 substreams for a column, so tryGetColumnSubstreams can return a non-null empty vector here even though no valid writer ever produces a Dynamic/JSON column with zero recorded streams. In that shape this guard stays false, and then getStreamCounts at MutateTask.cpp:1040-1047 treats the empty list as authoritative and counts zero streams for the column.

That re-opens the same partial-mutation corruption this PR is fixing: a Wide part whose columns_substreams.txt was corrupted to 0 substreams for column y can still take the partial path for an unrelated mutation and leave variant_discr / element streams neither rewritten nor hardlinked into the new part. Please treat an empty recorded list as "missing substreams" here (and ideally reject it in loadColumnsSubstreams) so corrupted metadata falls back to full rewrite instead of the zero-stream path.

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.

It's incorrect, there is no way to get corrupted columns_substreams.txt file with 0 substreams for a column during regular write without manual corruption. ColumnsSubstreams::addColumn throws a LOGICAL_ERROR exception if the previous column has an empty substreams vector. Or I am wrong?

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.70% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

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

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Jul 8, 2026
Merged via the queue into master with commit 6538d37 Jul 8, 2026
173 of 175 checks passed
@Avogar
Avogar deleted the fix_dynamic_mutation_variant_discr branch July 8, 2026 13:48
@Algunenano Algunenano self-assigned this Jul 27, 2026
@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 27, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 27, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Jul 27, 2026
Cherry pick #107562 to 25.8: Fix missing variant_discr stream for Dynamic columns after mutation
robot-clickhouse added a commit that referenced this pull request Jul 27, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Jul 27, 2026
Cherry pick #107562 to 26.3: Fix missing variant_discr stream for Dynamic columns after mutation
robot-clickhouse added a commit that referenced this pull request Jul 27, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Jul 27, 2026
Cherry pick #107562 to 26.5: Fix missing variant_discr stream for Dynamic columns after mutation
robot-clickhouse added a commit that referenced this pull request Jul 27, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 27, 2026
Algunenano added a commit that referenced this pull request Jul 27, 2026
Backport #107562 to 26.6: Fix missing variant_discr stream for Dynamic columns after mutation
Algunenano added a commit that referenced this pull request Jul 27, 2026
Backport #107562 to 26.5: Fix missing variant_discr stream for Dynamic columns after mutation
Algunenano added a commit that referenced this pull request Jul 27, 2026
Backport #107562 to 26.3: Fix missing variant_discr stream for Dynamic columns after mutation
Algunenano added a commit that referenced this pull request Jul 27, 2026
Backport #107562 to 25.8: Fix missing variant_discr stream for Dynamic columns after mutation
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…during mutation

Address review on ClickHouse#107562: `getStreamCounts` resolved every recorded substream of a
dynamic-structure column against the source part's checksums, including the placeholder
substream that `getColumnsForNewDataPart` records for a column that the mutation will write
but that is not yet present in the source part. If the table also contains an unrelated
column literally named `dummy`, the placeholder resolved to that column's real `dummy.bin`
stream, so the unchanged stream was marked as skipped and was neither rewritten nor
hardlinked into the new part, producing a part whose checksums reference a missing
`dummy.bin`/`dummy.cmrk2`.

Introduce a named `NOT_YET_WRITTEN_COLUMN_SUBSTREAM_PLACEHOLDER` sentinel for the placeholder
and skip it explicitly in `getStreamCounts`, falling back to stream enumeration as before.

Add regression test `04342_dynamic_mutation_dummy_placeholder_stream` that materializes a
newly added `Dynamic` column next to an existing column named `dummy` and validates the
resulting part with `CHECK TABLE`. Verified that the test fails before this change (the
mutated part is missing `dummy.cmrk2`) and passes after it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Address the code review on PR ClickHouse#107562: the new
`hasDynamicColumnsWithoutRecordedSubstreams` guard (and the matching check
in `getStreamCounts`) used `hasDynamicSubcolumns`, which also returns true
for a plain `Map` (`DataTypeMap::hasDynamicSubcolumnsData` is unconditionally
true) and a plain `Variant`. As a result an upgraded Wide part with a basic
`Map` column but no `columns_substreams.txt` would force
`MutateAllPartColumnsTask` for any unrelated partial mutation, turning a cheap
single-column mutation into a full rewrite of all the `Map` data, with no
correctness need.

Only `Dynamic`/`JSON` have a data-dependent structure whose substreams
(`variant_discr`, ...) cannot be enumerated without a deserialization state
(`SerializationDynamic`/`SerializationObject::enumerateStreams` short-circuit
without a column/state). That is exactly what `hasDynamicStructure` reports:
plain `Map`/`Variant` return false, `Dynamic`/`JSON` and any composite that
contains one return true. `SerializationVariant::enumerateStreams` enumerates
all element streams from the type, so a plain `Variant` is correctly excluded.

Use `hasDynamicStructure` at both decision sites. New test
`04412_mutation_old_part_basic_map_partial` builds a Wide part with a basic
`Map` column, deletes `columns_substreams.txt` to simulate a pre-25.8 part,
runs a partial mutation that does not touch the `Map`, and asserts it stays on
the partial path (the part does not regain `columns_substreams.txt`) while
`CHECK TABLE` passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…tion_variant_discr

Fix missing variant_discr stream for Dynamic columns after mutation
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
Dependency of the ClickHouse#109496 backport (d56fb49): its MutateTask.cpp change calls
ColumnsSubstreams::tryGetColumnSubstreams, which this change adds, so d56fb49 does not
compile without it (found by a syntax check of every file the backports change). The 26.3
branch merged this backport on 2026-07-27, before the ClickHouse#109496 backport (2026-08-13).
Fix: a part produced by a mutation of a table with a Dynamic column could miss the
variant_discr stream (LOGICAL_ERROR on read); upstream patch unchanged, with its tests
04341, 04342, 04401 and 04412 (the local triage did not reproduce the first two on the
production build; the other two need a server).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
…f upstream fixes

The stateless selection gets the upstream tests of the 34 backports of the residual audit
and of the two backports they depend on (ClickHouse#99085, ClickHouse#107562), 04627 (runnable with the gate's
loopback Keeper), and 10317/10318 (Parquet Decimal512): 152 tests. 04670 (needs pyarrow) and
00900 (a long load test whose skip list changed) run outside the gate.

known_defects.json: a fixed KD-UP entry per backport (fixed_by = its commit); KD-UP-108790
points at the ClickHouse#115705 backport, which carries its change; KD-UP-107663 records its ClickHouse#112601
dependency. Defects found by the release gate on the candidate 91efe1f244ce and fixed:
KD-D512-PERF-OVERFLOW-CHECKS (e91167f), KD-TEST-BLOCKCHAIN-TYPENAME (f006d0d),
KD-GATE-NO-KEEPER (095b89c). 80 entries, 0 open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Logical error "Stream ... variant_discr ... is not found" for a Dynamic column during merge (part written without variant_discr)

7 participants