Skip to content

Fix logical error reading a whole Tuple subcolumn of Dynamic or Variant from a part - #116739

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-nullable-tuple-subcolumn-wrap-for-deserialization
Sep 1, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-nullable-tuple-subcolumn-wrap-for-deserialization

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not user-visible; the defect exists only on master.

Description

Related: #111427 (introduced this), #112338.

With allow_nullable_tuple_in_extracted_subcolumns = 1, reading a whole Tuple subcolumn of a
Dynamic or Variant column out of a MergeTree part throws
LOGICAL_ERROR: Bad cast from type DB::ColumnNullable to DB::ColumnTuple:

CREATE TABLE td (id UInt64, value Dynamic) ENGINE = MergeTree ORDER BY id;
INSERT INTO td VALUES (1, CAST(tuple(1, 's'), 'Tuple(a UInt32, b String)'));
SELECT value.`Tuple(a UInt32, b String)` FROM td;

IDataType::createColumn(const ISerialization &) builds the read column from the type, so with that
setting it is a ColumnNullable, and SerializationWrapper::wrapColumnForDeserialization forwards it to
SerializationTuple, whose assert_cast<const ColumnTuple &> fires. The forward is wrong for
SerializationVariantElement and SerializationDynamicElement, which own that level: their
deserializeBinaryBulkWithMultipleStreams peels it off and fills its null map from the discriminators.
Both now override the wrap to mirror that unwrap, and SerializationDynamicElement returns a null map
subcolumn untouched, since that one is a ColumnUInt8 read through
SerializationVariantElementNullMap where the forward produced a second signature.

Introduced on master by #111427; no release branch is affected. In a release build assert_cast is a
static_cast, so the pre-fix behaviour there is undefined (unmeasured). Only a startup profile can set
the setting; the AST fuzzer jobs set it for every run, which is where this surfaced:
report.

The new test covers both types, both part formats, typed and shared variants, a Nullable element and
the .null subcolumn; its output matches the pre-regression snapshot byte for byte.

Ordering with #112338: it narrows the matching unwrap to nullable_added_by_extraction && isColumnNullable, so once it lands that bit should gate these two wraps as well. Benign in either
order today: the nested wrap is the identity in the intrinsically-nullable case.

#111427 carries v26.8-must-backport and its backport #116547 is open, so 26.8 would get the regression
too. Could a maintainer apply v26.8-must-backport here?


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

Version info

  • Backported to: 26.8.3.9

…nt from a part

`IDataType::createColumn(const ISerialization &)` builds the read column from the type and
then hands it to the serialization. With `allow_nullable_tuple_in_extracted_subcolumns = 1`
an extracted whole-`Tuple` subcolumn of a `Dynamic` or `Variant` column is typed
`Nullable(Tuple(...))`, so that column is a `ColumnNullable`.
`SerializationWrapper::wrapColumnForDeserialization` forwards it unchanged to the nested
serialization, so `SerializationTuple::wrapColumnForDeserialization` receives a
`ColumnNullable` and its `assert_cast<const ColumnTuple &>` fires: `Bad cast from type
DB::ColumnNullable to DB::ColumnTuple`.

That forward is wrong for these two wrappers because they own that `Nullable` level
themselves. `SerializationVariantElement::deserializeBinaryBulkWithMultipleStreams` peels
exactly that level off the result column, fills its null map from the discriminators, and
only then recurses into `nested_serialization`. The wrap now mirrors that unwrap.

`SerializationDynamicElement` also needs an early return for a null map subcolumn: there
the result column is a `ColumnUInt8` read through `SerializationVariantElementNullMap`,
`nested_serialization` is not used at all, and the blanket forward produced a second
signature, `Bad cast from type DB::ColumnVector<char8_t> to DB::ColumnTuple`.

`LowCardinality(Nullable(T))` results stay on the forwarding path on purpose:
`isColumnNullable` is false for them and the unwrap side keeps them whole for the same
reason. `LowCardinality` cannot hold a `Tuple`, so no non-identity nested serialization can
appear under one.

Introduced by ClickHouse#111427, commit 8fa5b9b "Deserialize const subcolumns via
ISerialization::wrapColumnForDeserialization", which replaced type-driven column
construction with serialization-driven construction. Before it the tuple rebuild lived in
`DataTypeTuple::createColumn(const ISerialization &)`, a virtual reached only when the type
itself was a `Tuple`, so a `Nullable(Tuple(...))` never entered it. Measured: master
snapshot 82cfa6a returns the correct values, 19a501b aborts.

Rejected alternatives: relaxing the `assert_cast` in `SerializationTuple`, since that class
did not add the `Nullable` and tolerating it there would mask every genuine type-against-
serialization mismatch for every caller; making `SerializationWrapper`'s default
non-forwarding, since forwarding is required by `SerializationNamed`, which is what
`SerializationTuple` calls for each element; restoring a type-side
`DataTypeNullable::createColumn(const ISerialization &)` virtual, which reintroduces the
type-side dispatch ClickHouse#111427 removed.

Reachable only with `allow_nullable_tuple_in_extracted_subcolumns = 1`, which is read from
the global context and can only be set in a startup profile. The AST fuzzer jobs set it for
every run, which is where this surfaced.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 27, 2026
@groeneai

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

Pre-publication review: my own cold pass over the resulting code (3 findings), then one
independent-model pass (engine: codex, 0 findings) against the frozen description.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description did not state how this interacts with #112338, which touches the same two classes AGREE, fixed in the published description #112338 narrows the matching unwrap to nullable_added_by_extraction && isColumnNullable, while the wrap added here tests isColumnNullable unconditionally. Benign in either merge order, because the nested wrap is the identity in the intrinsically-nullable case, so both spellings build the same column. Now said out loud, since the same reviewer sees both PRs.
2 💡 The new C++ comments do not wrap literal type and function names in inline code blocks, as .claude/CLAUDE.md asks AGREE, not blocking Cosmetic only. The test file and the commit message in the same commit do follow it, as does the description. Left for the next touch of these two files rather than an extra commit here.
3 💡 No test arm for the JSON spelling of the same read, j.c.:Tuple(a UInt32, b String)`` out of a part AGREE, no arm added It is the same carrier: DataTypeObject.cpp:721-731 builds SerializationObjectDynamicPath over the SerializationDynamicElement that IDataType::getSubcolumnData produces, so the fix reaches it through that wrapper's inherited forward. No mutation of this diff is reddened only by such an arm, so it would be redundant rather than load-bearing. 03913_tuple_inside_nullable_subcolumns already asserts that spelling in memory.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Also noticed and deliberately not raised: SerializationNullable does not override
wrapColumnForDeserialization, so a declared Nullable(Tuple(...)) column's tuple elements are
never wrapped by their element serializations. Harmless today, since every element wrap reachable
there is the identity, and unchanged by this PR.

Session id: cron:clickhouse-review-slot-8:20260827-163300

@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% not a rate. clickhouse local --allow_nullable_tuple_in_extracted_subcolumns=1 (before the bare --, or the flag is ignored) running the 3-line reproducer in the description: rc=134 every run on pristine master, rc=0 with this change. clickhouse local installs no root logger, so the signature needs --logger.console=1 --logger.level=fatal to be visible at all.
b Root cause explained? Yes. IDataType::createColumn(const ISerialization &) builds the read column from the type; with the setting on that type is Nullable(Tuple(...)), so the column is a ColumnNullable; SerializationWrapper::wrapColumnForDeserialization blanket-forwards it to the nested SerializationTuple, whose unconditional assert_cast<const ColumnTuple &> fires. The wrap disagreed with the unwrap that SerializationVariantElement::deserializeBinaryBulkWithMultipleStreams performs on the same level.
c Fix matches root cause? Yes. The wrap is made to mirror the unwrap, in the same class a few lines away. Not a guard at the assert_cast: SerializationTuple did not add the Nullable, and relaxing it there would turn the abort into silently wrong results and would mask every genuine type-against-serialization mismatch for every caller.
d Test intent preserved / new tests added? New test 05045_nullable_tuple_subcolumn_of_dynamic_variant_from_part.sh, 8 arms. No existing test weakened or removed. Every whole-tuple arm carries a second row with a different discriminator, so the re-wrapped null map is asserted to be filled correctly (\N), not merely present. One arm is a nested-subcolumn control on the changed function that must stay byte-identical, and it does.
e Both directions demonstrated? Yes, per arm and end to end. Pristine master aborts on 6 of the 8 arms; with the change all 8 return the expected values. Through the real runner: [ OK ] with the fix, [ FAIL ] return code: 134 without it. .reference matches the pre-regression master snapshot 82cfa6a421bb9c1e byte for byte (md5 365758ed62e10b1d2aadba0ab72a9bae), so the values are the correct pre-regression ones and not merely self-consistent.
f Fix is general across code paths? Yes. All twelve SerializationWrapper subclasses were enumerated; the two that own a level their nested serialization does not deserialize are both fixed. A build in which only the SerializationDynamicElement override is dropped reddens the Dynamic arms while Variant passes, and vice versa, so the two are independent carriers rather than one. Compact and wide readers both covered; NativeReader shares the same two overrides. Fixed where the Nullable is added, not at the abort site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: plain and Nullable tuple elements, LowCardinality elements, nested tuples, unnamed tuples (the exact fuzzer spelling), compact and wide parts, typed and shared variants, Dynamic and Variant. LowCardinality(Nullable(T)) results deliberately stay on the forwarding path and are verified unaffected. Nullable inside a Variant variant is impossible by construction (DataTypeVariant.cpp rejects it), which is what makes the structural isColumnNullable test exactly right here.
h Backward compatible? (maintainer-approved exception only) Yes, vacuously. No setting added, no default changed, no serialization format touched, so no SettingsChangesHistory.cpp entry. The change only affects an in-memory read-column layout that aborted before, so there is no old behaviour to preserve.
i Invariants and contracts preserved? The invariant is: a SerializationWrapper whose result column carries a level nested_serialization does not deserialize must not forward that level to it. On the Nullable path the null map column is created empty and filled by the same class that now creates it, exactly as deserializeBinaryBulkWithMultipleStreams expects; on the null map path the column is returned untouched, which is what SerializationVariantElementNullMap expects. cloneEmpty() rather than IColumn::mutate keeps the in-flight #100185 deep-ownership assertions satisfied. The function is pure and total over its input, so no lock, error path or early return is involved.

Session id: cron:clickhouse-impl-slot-7:20260827-152600

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f3f7df]

Summary: ✅


AI Review

Summary

This PR fixes a real deserialization mismatch when a whole Tuple subcolumn extracted from Dynamic or Variant is materialized as Nullable(Tuple(...)) and then read from a MergeTree part. The two new wrapColumnForDeserialization overrides correctly mirror the existing unwrap logic in the bulk readers, the Dynamic null-map special case matches its dedicated SerializationVariantElementNullMap path, and the added stateless test covers the main regression surfaces, including compact and wide parts, shared-variant reads, and nullable tuple elements. No actionable review findings remained after tracing the changed code and prior discussion.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 8f3f7df.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ, could you review this? IDataType::createColumn(const ISerialization &) builds the read column from the type, so with allow_nullable_tuple_in_extracted_subcolumns = 1 a whole-Tuple subcolumn of Dynamic or Variant arrives as a ColumnNullable and the blanket SerializationWrapper forward hands it to SerializationTuple, whose assert_cast fires. Those two element serializations own that Nullable level themselves, so the wrap now mirrors the unwrap their deserializeBinaryBulkWithMultipleStreams already performs.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f3f7df0d with master 17dd8fe39 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.35 MiB 709.30 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

16 translation units recompiled, 40 s compile time in total, 16 of them have a recent master baseline.

Job report

@Avogar Avogar self-assigned this Sep 1, 2026
@Avogar
Avogar added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit 2ea17c3 Sep 1, 2026
359 of 360 checks passed
@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 Sep 1, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 1, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 1, 2026
…column of Dynamic or Variant from a part
clickhouse-gh Bot added a commit that referenced this pull request Sep 1, 2026
Backport #116739 to 26.8: Fix logical error reading a whole Tuple subcolumn of Dynamic or Variant from a part
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 11, 2026
Both conflicts came from master renaming the dynamic-subcolumn result structure
(`res->serialization`/`res->type` -> `res->data.*`, `dynamic_subcolumn_data` ->
`dynamic_subcolumn_info->data`). Resolved by keeping this branch's semantics in master's
spelling: the ordering in `DataTypeDynamic::getDynamicSubcolumnData` that computes
`nullable_added_by_extraction` across the type wrap, and the serialization-before-type
creator order in `IDataType::getSubcolumnData`. Master's own
`ISerialization::createFromPath` already applies the creator in that same order.

ClickHouse#116739 (`8f3f7df0d3150`) landed on master after this branch was last updated, adding
`wrapColumnForDeserialization` overrides to `SerializationVariantElement` and
`SerializationDynamicElement` that peel the result column's `Nullable` level whenever
`isColumnNullable`. This branch makes the matching unwrap in
`deserializeBinaryBulkWithMultipleStreams` conditional on `nullable_added_by_extraction`, so
the wrap was checked against that flag too. Gating it changes no observable behavior: for an
intrinsic `Nullable` the peel hands the nested column to a `SerializationNullable`, which
does not override `wrapColumnForDeserialization`, so rebuilding the `ColumnNullable` around
it reproduces the input layout. Measured on this tree, 04652, 04653 and 05045 all pass both
with the gate and without it. The overrides are therefore left byte-identical to master, and
only the comment that described the unwrap as unconditional is corrected.

Validation on the merged tree (debug, build id a395d5b3272a6dd9d33e1a4bf2ee5a9ab4766540):
04652, 04653 and master's own 05045 all pass. With the six `src/` files reverted to master
(build id ed053ed21015c958), 05045 still passes while 04652 and 04653 fail with
`Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable`, so the fix
this branch carries is still load-bearing and is not superseded by anything on master.

Co-Authored-By: Claude Opus 5 <[email protected]>
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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants