Skip to content

Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column - #112338

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-variant-element-nullable-tuple-subcolumn
Sep 13, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-variant-element-nullable-tuple-subcolumn

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed a crash when reading a subcolumn of a Variant, Dynamic or JSON column whose own type is Nullable or LowCardinality(Nullable) from a MergeTree table, for example SELECT value.`Tuple(a Nullable(UInt32), b String)`.a over a Dynamic column. Previously such a read hit a LOGICAL_ERROR in debug builds and crashed in release builds.

Description

No related open issue found (searched open issues and PRs for the crash message, the stack frames and the affected functions).

Three lines of plain SQL with default settings crash the server:

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

On master (debug) this is Logical error: 'Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable'; on 26.7.2.26, 26.6.2.120, 26.5.6.78 and 26.3.17.78 it is a segfault, because in a release build assert_cast degrades to a plain static_cast. The same query against ENGINE = Memory returns the correct value.

SerializationVariantElement recurses into the serialization of the on-disk element, and the extraction framework exposes such an element to the user as Nullable(T) even though it is stored non-nullable (DataTypeDynamic::getDynamicSubcolumnInfo, VariantSubcolumnCreator::create). To keep the type it hands down consistent with that nested serialization, SerializationVariantElement unconditionally stripped nullability off the type and the column.

That strip cannot tell nullability that the extraction added from nullability intrinsic to the requested subcolumn. When the requested subcolumn is a tuple element that is itself Nullable, the nested serialization is a SerializationNullable and the strip removes exactly the nullability it requires: SerializationNullable::enumerateStreams then casts a UInt32 type to DataTypeNullable, and deserializeBinaryBulkWithMultipleStreams casts a ColumnUInt32 to ColumnNullable.

The fix records at the site that performs the wrap whether the wrap actually changed the type, and strips only then. The flag is also part of the serialization's pooling key, so that two serializations differing only in it can never share a pooled instance. That is defence in depth rather than a fix for a reachable case: the two are already distinguished by their nested serialization, and dropping the flag from getHash leaves the tests green.

  • SerializationVariantElement gains nullable_added_by_extraction, which gates the strip in enumerateStreams and both unwraps in deserializeBinaryBulkWithMultipleStreams. Gating only the first would move the crash into deserialization instead of removing it. On the gated path the element's own null map is read by the nested serialization, and the NULLs for rows belonging to other variants come from insertDefault/insertManyDefaults.
  • Dynamic computes the flag in DataTypeDynamic::getDynamicSubcolumnInfo against the type before the wrap and forwards it through SerializationDynamicElement. Variant derives it inside VariantSubcolumnCreator::create(prev, prev_type), where prev_type is the selected subcolumn's pre-wrap type. Deciding it once per variant alternative instead is not sufficient: with allow_nullable_tuple_in_extracted_subcolumns = 1 the alternative's own wrap does change the type, so the strip would still fire on the intrinsically nullable element and the Variant case would keep crashing.
  • The shared-variant branch of SerializationDynamicElement keeps an unconditional strip. Its column is always Nullable over the shared variant type while its nested serialization is a plain String serialization, so forwarding the flag there would break a case that works today.
  • IDataType::getSubcolumnInfo now applies a creator to the serialization before the type, so that a creator reading its prev_type argument sees the type its prev serialization actually serializes. ISerialization::createFromPath already had that order; this branch was the only place with the other one, which made prev_type mean "pre-wrap" on one path and "post-wrap" on the other. It is behaviour-neutral: the creator here is tmp_subpath[i].creator for an i that satisfies hasSubcolumnForPath, and of the creator-attachment sites in src/ only SerializationNamed (for a TupleElement substream) and SerializationSparse (for SparseNullMap) attach to a substream type that predicate accepts - both take an unnamed second parameter and ignore it. It is in this PR because the two orders disagreeing is what would make the Variant predicate's meaning depend on which path resolved the subcolumn, not because anything reachable today changes.

Covered by 04652_nullable_tuple_element_subcolumn_of_dynamic_variant (Variant, Dynamic, LowCardinality(Nullable), a nested tuple element, an unnamed tuple element, wide and compact parts, PREWHERE, an aggregate, the null-map subcolumn, mixed rows against a Memory oracle, plus the controls that must keep working - above all a non-nullable top-level element, whose nullability really is added by the extraction) and by 04653_nullable_tuple_element_subcolumn_nullable_tuple_setting for allow_nullable_tuple_in_extracted_subcolumns = 1, which is read from the global context and so needs a command-line setting.

JSON reaches the same extraction through a typed path whose type is a Variant, so the covering case is JSON(t Variant(Tuple(a Nullable(UInt32), b String), String)). A dynamic path is not affected: an untyped object value is decomposed into one dynamic path per leaf, so a nested tuple never becomes a single dynamic value there. The test keeps a dynamic-path read as a control for the same route.

The part thresholds are pinned per table in the test so that the compact and wide readers, which resolve the subcolumn through different code, are both covered on every run rather than depending on what the runner randomizes.

No on-disk format change, no new or changed setting, so no SettingsChangesHistory.cpp entry. Parts written before this change are read correctly afterwards; before it they could not be read at all.


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

Version info

  • Merged into: 26.9.1.1392 (included in 26.9 and later)
  • Backported to: 26.8.4.7, 26.7.8.14, 26.6.6.15, 26.3.33.75

groeneai and others added 2 commits July 28, 2026 12:51
… column

Reading a subcolumn whose own type is Nullable or LowCardinality(Nullable) out
of a Variant, Dynamic or JSON column stored in a MergeTree table crashed the
server. Three lines of plain SQL with default settings are enough:

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

On a debug build this is a LOGICAL_ERROR ("Bad cast from type
DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable"); on a release build
assert_cast degrades to a plain static_cast, so it is a segfault. Reproduced on
26.7.2.26, 26.6.2.120, 26.5.6.78 and 26.3.17.78. The same query against
ENGINE = Memory returns the correct value.

SerializationVariantElement recurses into the serialization of the on-disk
element, and the extraction framework exposes such an element as Nullable(T)
even though it is stored non-nullable. To keep the type it hands down consistent
with that nested serialization, it stripped nullability unconditionally. That
strip cannot distinguish nullability added by the extraction from nullability
intrinsic to the requested subcolumn: for a Nullable tuple element the nested
serialization is a SerializationNullable, and the strip removes exactly the
nullability it requires.

Strip only when the extraction's wrap actually changed the type. The decision is
made where the wrap happens and passed down as an explicit flag, which is also
part of the serialization's pooling key so that two serializations differing only
in it cannot share a pooled instance.

Both methods that recurse into the nested serialization are gated: gating only
enumerateStreams would move the crash into deserializeBinaryBulkWithMultipleStreams
instead of removing it. On the gated deserialization path the element's own null
map is read by the nested serialization, and the NULLs of rows belonging to other
variants come from insertDefault/insertManyDefaults.

Dynamic computes the flag in DataTypeDynamic::getSubcolumnData against the type
before the wrap. Variant derives it inside VariantSubcolumnCreator::create, where
prev_type is the selected subcolumn's pre-wrap type; deciding it once per variant
alternative is not sufficient, because with
allow_nullable_tuple_in_extracted_subcolumns = 1 the alternative's own wrap does
change the type and the strip would still fire on the intrinsically nullable
element. The shared-variant branch keeps an unconditional strip: its column is
always Nullable over the shared variant type while its nested serialization is a
plain String serialization.

IDataType::getSubcolumnData now applies a creator to the serialization before the
type, matching ISerialization::createFromPath, so the Variant predicate sees a
pre-wrap prev_type on both read paths. This is a prerequisite of the fix and is
behaviour-neutral for every creator that ignores its prev_type argument.

No on-disk format change and no new or changed setting. Parts written before this
change are read correctly afterwards; before it they could not be read at all.
Three lines of the test read as coverage but would pass byte-identically with
the fix reverted, so the suite was weaker than the PR description.

The JSON coverage only requested a non-nullable typed path, whose nullability is
added by the extraction, i.e. the pre-existing always-correct path. A JSON object
value is decomposed into one dynamic path per leaf, so a nested tuple never
materialises as a single dynamic value and no untyped JSON path can carry the
bug. A typed path keeps its declared type intact, so a path declared as a Variant
whose alternative is the nullable-element tuple is the reachable route; it aborts
on unfixed master. The original non-nullable line is kept as a control.

The runner draws min_bytes_for_wide_part = 0 with about 30% probability, and only
the wide table pinned its part thresholds, so on such a run every table was wide
and the compact reader - the one whose stack produced the original report - was
not covered at all. All the other tables now pin compact thresholds explicitly,
so the split no longer depends on the draw.

The paired query meant to build both serializations in one pool requested a type
that was not an alternative of that column, so it silently took the shared
variant branch instead. An extra row makes the type a real alternative. The two
instances are still discriminated by their nested serialization, which no
reachable query can make agree, so the comment now says that rather than claiming
a pool collision the query cannot produce.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 9 findings adjudicated) - click to expand

Before opening this PR I ran two independent review rounds against the diff: a cold
code-reading pass plus a second-model reviewer that had not seen the implementation notes.
Findings are listed with the verdict I reached and the evidence behind it.

Round 1 - 4 findings, all accepted and fixed

All four were in the test suite, and all four were the same class: something the PR claims
was asserted by a line that would have passed byte-identically with the fix reverted.

Finding Verdict
❌ The JSON line read a dynamic path whose nullability is added by the extraction, i.e. the always-correct path. JSON is named in the changelog, so the claim needed a line that goes red without the fix. AGREE. Fixed
❌ Only one table pinned its part-type thresholds. min_bytes_for_wide_part is randomized with ~30% probability of 0, so the compact reader, whose stack produced the original report, could go unexercised on any given run. 100 green runs prove no run failed, not that a compact run happened. AGREE. Fixed
❌ An in-code comment claimed both serializations were built in one pool, but the requested type was not an alternative of that table, so the read took the shared-variant branch instead. The reference's \N second column confirmed it. AGREE. Fixed
⚠️ My own draft description enumerated every ISubcolumnCreator in the tree rather than those reachable at the reordered call site, and named a function that does not exist. AGREE. Corrected
💡 The test sets the obsolete enable_variant_type. DISAGREE. Obsolete since Settings.cpp:8693, default true, harmless, and it matches 03365/03314/03289.

The fixes: the JSON coverage is now a typed Variant path
(JSON(t Variant(Tuple(a Nullable(UInt32), b String), String))), which aborts on master with
the exact Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable and
returns Nullable(UInt32) / 1 / \N / \N with the fix; the dynamic-path read is kept as
a control for the same route. Worth recording that the obvious shapes are not carriers: an
untyped JSON value is decomposed into one dynamic path per leaf, so a nested Tuple never
materialises as a single dynamic value.

All seven tables now pin both min_bytes_for_wide_part and min_rows_for_wide_part, measured
against system.parts to give an identical part-type layout with no injection and under a
hostile --min_bytes_for_wide_part=0 --min_rows_for_wide_part=0 draw. No
no-random-merge-tree-settings tag was needed: an explicit per-DDL SETTINGS already wins
over the runner's injection.

The pooling case is now genuinely reached (an added row makes the nullable tuple a real
alternative, visible in the reference), and the comment no longer claims a mechanism the query
cannot produce.

Round 1 found no defect in the src/ diff. I enumerated the invariant carriers
independently (all three strip sites, both producers, the shared-variant literal, both
getHash overloads, the untouched null-map serialization, the JSON route) and reached the
same list as the implementation, with no divergence.

Round 2 - 4 findings, src/ unchanged from round 1

Finding Verdict
❌ The changelog entry nested a backslash-escaped backtick pair inside a single-backtick code span. Backslash escapes are not processed inside code spans, so the span closed early and the entry would have rendered as a truncated fragment plus a dangling backtick, in CHANGELOG.md. AGREE. Fixed with a double-backtick span
⚠️ The description asserted the pooling-key change as a necessity, while the implementation had measured the opposite and softened the in-code comment accordingly. Leaving the two inconsistent on the same page. AGREE. Description now matches
⚠️ The description named JSON without naming the route, which is the part that makes the claim checkable. AGREE. Route now stated
💡 The getHash field has no live test. DISAGREE. Unreachable by construction: covering it needs two requests identical in nested serialization, element name, discriminator and variant count but differing in the flag, and the flag is a deterministic function of the same pre-wrap type that selects the nested serialization. Correct as a pooling-key invariant, now honestly described.

Round 2's second-model pass returned zero findings after reading all changed files and
tests in full and tracing the Variant/Dynamic/JSON/Nullable/LowCardinality/shared-data
siblings.

Verified independently rather than accepted

  • prev_type == nullptr fails the new predicate closed (do not strip). I traced whether a
    null type can reach a read: the type-less path is the part's own serialization map, whose
    consumers are stream-name and kind-stack only; the reader builds its serializations through
    getSubcolumnSerialization, which always passes a type. The flag affects only the recursion
    payload and the read path, never a stream name.
  • Every caller of the four changed signatures, repo-wide. Both create overloads lost their
    default arguments, so an omitted flag is a compile error rather than a silent false.
  • The behaviour-neutrality argument for the creator-order change, against
    hasSubcolumnForPath's accepted substream types and all ten creator-attachment sites.
  • That a row of another variant still reads as NULL on the gated paths, via
    ColumnNullable::insertDefault and ColumnLowCardinality::insertDefault resolving to the
    dictionary's null index.
  • That the pinned thresholds keep canUsePolymorphicParts true, so no warning is logged.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --path=<tmp> --queries-file repro.sql with the three-line reproducer aborts on every run (rc=134, Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable). No fuzzer, no randomization, default settings. The 4 release binaries from builds.clickhouse.com segfault (rc=139).
b Root cause explained? Yes. The extraction framework exposes a variant/dynamic element subcolumn as Nullable(T) although the element is stored non-nullable, so SerializationVariantElement stripped nullability off the type and column it passes to its nested serialization. That strip cannot distinguish an added wrapper from nullability intrinsic to the requested subcolumn: when the request is a Nullable tuple element, the nested serialization is a SerializationNullable and the strip removes exactly the nullability it requires, so SerializationNullable::enumerateStreams casts UInt32 to DataTypeNullable (debug: LOGICAL_ERROR; release: assert_cast degrades to static_cast, hence UB and SIGSEGV).
c Fix matches root cause? Yes. The strip is now gated on whether the extraction's wrap actually changed the type, decided at the site that performs the wrap. Guarding the assert_cast instead was rejected: the (type, serialization) pair would stay inconsistent, the element's null-map substream would never be enumerated, and a loud crash would become silently wrong results.
d Test intent preserved / new tests added? New tests added, none weakened. 04652_nullable_tuple_element_subcolumn_of_dynamic_variant (.sql) and 04653_nullable_tuple_element_subcolumn_nullable_tuple_setting (.sh, the setting is read from the global context). Both parallel-safe, no no-parallel, no no-random-settings. 03913, 03915 and 03918 re-run byte-identical to master.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. 04652: pristine origin/master snapshot rc=134, fix build rc=0 matching its reference. 04653: master rc=134, fix rc=0. Every carrier including the JSON one aborts on the pristine master snapshot. Five mutations, each rebuilt and each red in the predicted place: unconditional strip → every carrier aborts, the JSON one on its own and the whole test kills the server; flag inverted → the non-nullable-element control aborts (ColumnNullable → ColumnVector); flag dropped from the pooling key together with the nested hash → collision aborts, proving the pool is reached; the rejected per-alternative predicate → the Variant carrier aborts under allow_nullable_tuple_in_extracted_subcolumns=1 while the plain Variant carrier stays green; the flag forwarded into the shared-variant branch → that control aborts (ColumnNullable → ColumnString).
f Fix is general across code paths? Yes. Fixed in the serialization layer, not at either reader that surfaced it (both the size-predictor path and MergeTreeReaderCompact::initSubcolumnsDeserializationOrder reach the same defect). Both methods of SerializationVariantElement that recurse into the nested serialization are gated - enumeration alone would relocate the crash into deserialization. Both producers are covered (Dynamic via DataTypeDynamic, Variant via VariantSubcolumnCreator), so Variant, Dynamic and JSON are all fixed. serializeBinaryBulk* throw NOT_IMPLEMENTED and SerializationVariantElementNullMap ignores SubstreamData, so neither carries the invariant.
g Fix generalizes across inputs? Yes, matrix in the test: Nullable(UInt32), Nullable(String), LowCardinality(Nullable(String)), a nested tuple element (.a.x), an unnamed tuple element (.1), two nullable elements, the null-map subcolumn, wide and compact parts, PREWHERE, an aggregate, allow_nullable_tuple_in_extracted_subcolumns on and off, and all three of Variant, Dynamic and JSON as failing-without-the-fix carriers. Part thresholds are pinned on every table, so the compact and wide readers are each covered on every run rather than on whatever the runner draws. The JSON carrier goes through a typed Variant path, which is the reachable route: an untyped JSON object value is decomposed into one dynamic path per leaf, so a nested tuple never materialises as a single dynamic value. Controls asserting the strip is not over-narrowed: a non-nullable top-level element (whose nullability really is added), a non-nullable tuple element, Array(Nullable) and Map(String, Nullable) elements, a non-nullable JSON typed path, the shared-variant branch, and the values checked against a Memory oracle over element-value / element-NULL / other-variant rows.
h Backward compatible? Yes. No on-disk format change, no serialization version bump, no new or changed setting, so no SettingsChangesHistory.cpp entry. Parts written before the change read correctly afterwards; before it they could not be read at all.
i Invariants and contracts preserved? The invariant restored is exactly the one that was broken: the (type, column, serialization) triple handed to a nested serialization must be mutually consistent. Type and column are gated together, so the mismatch cannot move from the type to the column one frame later. On the gated deserialization path the element's own null map is read by the nested serialization and the NULLs for rows of other variants come from insertDefault/insertManyDefaults, which is asserted by the mixed-row oracle rather than assumed. The new member is also part of the pooling key, so two serializations differing only in it can never share a pooled instance; that is defence in depth rather than a fix for a reachable case, since the two are already distinguished by their nested serialization. IDataType::getSubcolumnData now applies a creator to the serialization before the type, matching ISerialization::createFromPath; behaviour-neutral for every creator that ignores its prev_type argument, and NullableSubcolumnCreator already assumed the pre-wrap reading.

Session id: cron:clickhouse-impl-slot-45:20260728-155800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @KochetovNicolai - could you review this? SerializationVariantElement unconditionally stripped nullability off the type and column it hands to its nested serialization, which is correct when the extraction framework added that Nullable wrapper but wrong when the requested subcolumn is intrinsically Nullable (a Nullable tuple element): the nested SerializationNullable then gets a non-nullable type, so three lines of plain SQL with default settings segfault on every active release branch. The strip is now gated on whether the wrap actually changed the type, decided at the wrap site.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20f4427]

Summary: ✅


AI Review

Summary

This PR fixes the SerializationVariantElement / SerializationDynamicElement mismatch when a requested subcolumn is intrinsically Nullable or LowCardinality(Nullable) and preserves the separate case where nullability is added by extraction via nullable_added_by_extraction. I did not find a remaining correctness, compatibility, or test-coverage issue in the current code, and the added regression coverage is focused on the previously failing Variant, Dynamic, and typed-JSON read paths.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 20f4427.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 92/92 (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 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6d6f615

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 03394_distributed_shuffle_join_with_filter flaky under randomized settings - the runner's own diagnosis pins it to query_plan_optimize_join_order_randomize (184/184 fail with the drawn settings, 249/249 pass without) #111691 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) / test_odbc_interaction (21 rows) one fixture failure with 21 victims - the module-scoped started_cluster dies in cluster.start() -> wait_mysql8_to_start() -> Cannot wait MySQL 8 container; 97 rows / 3 unrelated PRs / 0 master in 30 days, 75 of them today across two unrelated PRs on two different sanitizer shards a fix task is created (investigating at full effort - fixing-PR link to follow here)
Finish Workflow / Post Hooks not a defect in the regression test: new_tests_check.py reports "No per-arch Bugfix Validation job validated the bug", but result_pr.json shows all three functional/unit Bugfix validation (*) nodes DROPPED and both integration ones SKIPPED ("no integration tests updates"), so the validators never ran and the test's master-HEAD behaviour was never measured. 108 of 174 nodes are DROPPED in the same result tree. per-PR gate, nothing to fix in the diff - the validators need to run

The diff here is 6 src/DataTypes/** serialization files plus the two new stateless tests; it contains
no integration-test, compose, ODBC or JOIN-planner surface, so none of the above is PR-caused.

One note on the MySQL 8 line: #96252 is the only
existing fix for that symptom, and it is already an ancestor of this branch
(git merge-base --is-ancestor 3aa25fba18c772 HEAD succeeds), so the failure happened with it present.
I am not linking it as the owner for that reason.

Session id: cron:our-pr-ci-monitor:20260728-223000

@PedroTadim

Copy link
Copy Markdown
Member

cc @Avogar

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

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_odbc_interaction / Cannot wait MySQL 8 container line of the CI finish ledger for 6d6f6157b52d0580f7b793af3a6beec106675102: #112967.

Root cause is in the MySQL 8 test image, not in this pull request: the container's entrypoint runs mysql_ssl_rsa_setup under set -e before the step that applies the MYSQL_ROOT_HOST=% grant, so a non-zero exit there aborts initialization, restart: always relaunches into an already-initialized datadir, and the grant never runs. The server then knows only root@localhost and refuses every connection from the docker gateway with error 1130, which is permanent, so wait_mysql8_to_start exhausts its full budget and fails the whole module.

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
master rewrote SerializationVariantElement::deserializeBinaryBulkWithMultipleStreams
twice since the branch point ("Remove rows_offset from the deserialization API" and
"Deserialize columns into IColumn& to fix substreams-cache clone regression"): the
discriminators and variant columns no longer live in the deserialization state, and
the result column is an IColumn& instead of a ColumnPtr &.

Both guards this branch adds to that function are conditions on expressions master
rewrote, so master's body is kept and only the conditions carry the
nullable_added_by_extraction test:

* the null map fill and the descent into the nested column now guard master's
  isColumnNullable(result_column) / inner_column = &nullable_column.getNestedColumn();
* the LowCardinality(Nullable) strip now guards master's unconditional
  isColumnLowCardinalityNullable(*inner_column) on the fresh variant clone.

The hand resolution touches one file: the two conditions, removal of the enclosing
block master deleted, and one comment compressed from 5 lines to 3. enumerateStreams,
the getHash and create signatures, and VariantSubcolumnCreator::create merged
unchanged, as did the other five files.
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 20f44271b with master f5dae6afa (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6b38945eb; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +4.7 s (+10%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted, old_compatibility) line of the CI ledger for d5ac8d5d2b91f08ff8f746113b2fcdad37555b54: #116739. That abort is Bad cast from type DB::ColumnNullable to DB::ColumnTuple in SerializationTuple::wrapColumnForDeserialization, a master regression from #111427 and independent of this PR: reverting the six src/ files here to master leaves it firing identically.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d5ac8d5

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
AST fuzzer (amd_debug, targeted, old_compatibility) / STID 3227-52fd, Bad cast from DB::ColumnNullable to DB::ColumnTuple in SerializationTuple::wrapColumnForDeserialization master regression, not caused by this PR #116739 (ours, open)
AST fuzzer (amd_debug, targeted) / STID 1559-1b3e, Bad cast from DB::ColumnNullable to DB::ColumnDecimal<Decimal256> in SingleValueDataFixed::set pre-existing master defect, not caused by this PR a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run
(33074618821), and Config Workflow, Style check and Finish Workflow all success. The praktika
report has 178 nodes, 0 DROPPED. CIDB returns 306k+ rows at this commit, of which exactly the two
failures above are ownable, so the classification is a measurement and not an empty read.

Neither red is caused by this PR, and both were measured rather than assumed.

STID 3227-52fd was settled with a 4-arm matrix against a master snapshot proven to lack this fix:
reverting the six src/ files here to master leaves the abort firing identically, and the whole-tuple
subcolumn shape it needs is Nullable(Tuple(...)) produced by SerializationTuple::wrapColumnForDeserialization,
which master introduced independently of this branch.

STID 1559-1b3e was reproduced on the same master snapshot with none of this PR's changes present
(GIT_HASH 82cfa6a421bb9c1e99185e960e92565543455b3c, which does not contain this head): the reduced
query below aborts there with the byte-identical message and the same SingleValueData.cpp:208 /
AggregateFunctionSingleValueOrNull.cpp:61 frames.

SET enable_nullable_tuple_type = 1;
CREATE TABLE probe (`key` Int128, `t` Tuple(m Map(LowCardinality(String), Decimal(76, 11))) NULL)
ENGINE = MergeTree ORDER BY key SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO probe SELECT number, tuple(map(concat('k', toString(number % 4)), number)) FROM numbers(1000);
SELECT count(), singleValueOrNull(t.m['%']) FROM probe;

The fuzzer reached it by mutating 04695_tuple_element_serialization_version_per_part, a test that
already exists on master, not anything this PR adds. #116739 is deliberately not linked for this
second line: it only changes SerializationDynamicElement and SerializationVariantElement, and the
query above has no Dynamic and no Variant column, so that fix cannot reach this path.

Session id: cron:our-pr-ci-monitor:20260827-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) / STID 1559-1b3e line of the CI finish ledger for d5ac8d5d2b91f08ff8f746113b2fcdad37555b54: #115777 (external, open).

The cause is optimize_functions_to_subcolumns, which is on by default, and not this PR. optimizeFunctionArrayElementForMap (src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:317) rewrites m['key'] to the subcolumn m.key_<key> and hardcodes its type as the map's value type V, checking only that a subcolumn of that name exists. For a Map nested in a Nullable(Tuple(...)) the real subcolumn is Nullable(V): Map cannot be inside Nullable so t.m stays bare, but one level down V can be, so t.m.key_k is wrapped in both type and column. The rewritten node then declares V while the read delivers Nullable(V), the aggregate is instantiated for V, and SingleValueDataFixed<V>::set fails its assert_cast. #115777 replaces that existence-only check with canOptimizeToExpectedSubcolumn(..., column.type), which resolves the subcolumn with withSubcolumns() and requires its exact type, so the rewrite is refused here.

Minimal repro on master, no fuzzer, none of this PR's files, and none of the fuzzed fixture's map or serialization settings:

SET enable_nullable_tuple_type = 1;
CREATE TABLE f (key Int64, t Tuple(m Map(String, UInt64)) NULL)
ENGINE = MergeTree ORDER BY key SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO f SELECT number, tuple(map('k', number)) FROM numbers(10);
SELECT singleValueOrNull(t.m['k']) FROM f;

With optimize_functions_to_subcolumns = 0 this returns \N; with the default 1 it aborts with Bad cast from type DB::ColumnNullable to DB::ColumnVector<unsigned long>. On the same table plus one genuinely NULL tuple row, the default also aborts min, max, any, argMax and sum over t.m['k'], and silently returns \N instead of 0 for t.m['k'], length(t.m) and length(t.a). All of them are covered by #115777, whose description documents the length half.

Measured on the shared master debug snapshot 82cfa6a421bb9c1e99185e960e92565543455b3c, which d5ac8d5d is not an ancestor of.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Dear @Avogar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
@Avogar Avogar self-assigned this Sep 4, 2026
@Avogar
Avogar added this pull request to the merge queue Sep 9, 2026
@Avogar Avogar added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 9, 2026
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Sep 9, 2026
Merged via the queue into ClickHouse:master with commit 6214c60 Sep 13, 2026
348 of 349 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 Sep 13, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 13, 2026
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
Cherry pick #112338 to 26.8: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
alexey-milovidov pushed a commit that referenced this pull request Sep 14, 2026
…column crash

Reading a subcolumn whose own type is Nullable out of a Variant or Dynamic column
segfaults on 26.7: SerializationVariantElement could not tell a Nullable level that
subcolumn extraction had added (whose null map it must fill from the discriminators
and peel off before recursing) from a Nullable level intrinsic to the requested type
(which belongs to nested_serialization), so it stripped the latter and handed the
nested serialization a column shape it does not read.

The robot cherry-pick conflicts because 26.7 predates two master refactors. Neither is
imported here; the fix is re-expressed in 26.7's own naming.

Axis A, the SubcolumnInfo refactor is master-only:
  - res->data.{type,serialization} spelled res->{type,serialization};
  - dynamic_subcolumn_info->data.X spelled dynamic_subcolumn_data->X;
  - nested_name_to_store (a separate master PR's zero-array-level renaming) spelled
    with the branch's inline String(subcolumn_nested_name).

Axis B, deserializeBinaryBulkWithMultipleStreams still has the older
(ColumnPtr & result_column, size_t rows_offset, ...) signature with the
mutable_column idiom and a persisted variant_element_state->variant. The branch's two
conditions are kept line for line and only gated with nullable_added_by_extraction,
which is semantically identical to master's inner_column form: when the flag is false
both trees leave the still-Nullable column with nested_serialization, and the later
insertManyDefaults/insertRangeFrom/insertFrom calls operate on the same column level.

wrapColumnForDeserialization does not exist on 26.7 (zero hits in the .cpp and the .h),
and #112338's only change to it was replacing three comment lines with three others, so
that hunk is dropped: no semantics are lost and no absent symbol is referenced. The
serialization pool does exist here, so the getHash update that threads the new flag
into the pooling key is kept, otherwise two serializations differing only in the flag
would collide.

Validated on this branch: the three-line reproducer segfaults on the official
26.7.8.5 build (rc=139, 3/3) and returns 1 here; 04652 and 04653 pass, both .reference
files byte-identical to master's blobs; forcing the flag to a constant false or true
reddens 04652 in either direction.

Related: #112338
Related: #119802
robot-ch-test-poll4 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #112338 to 26.7: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #112338 to 26.3: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #112338 to 26.6: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #112338 to 26.8: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #112338 to 26.6: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #112338 to 26.7: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Backport #112338 to 26.3: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @Avogar @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 19, 2026
…criminators

For a Variant/Dynamic/JSON element that is a tuple, the null map of a Nullable
field of that element returned 0 on every row holding a different alternative,
although the field itself reads NULL there. Since optimize_functions_to_subcolumns
is enabled by default and rewrites isNull(x) to x.null, a plain

    SELECT count() FROM t WHERE value.`Tuple(a Nullable(UInt32), b String)`.a IS NULL

silently dropped the matching rows: 1 instead of 2 on a three-row merged part.

SerializationVariantElement fills rows whose discriminator is not the element's
with the result column's default. For the value read that default IS NULL, so it
is correct; a null map is a bare UInt8 whose default 0 means "not null", which
makes it the one subcolumn whose value for an absent element is not its default.
Nothing on the path could distinguish the two: SerializationVariant::enumerate
Streams attaches one subcolumn creator per alternative, while the selection
happens per subcolumn beneath it, and ISerialization::createFromPath hands a
creator only the selected subcolumn's (serialization, type, column) - where a
null map's type is plain UInt8, indistinguishable from a genuine UInt8 element.
prev_type, which ClickHouse#112338 used to derive nullable_added_by_extraction, therefore
carries one bit too few for this case.

So ISubcolumnCreator gains one virtual with a default no-op,
specializeForSelectedSubcolumn, which names the selected substream to the
enclosing creators. VariantSubcolumnCreator uses it to learn that the selection
is a null map and then writes 1 for absent rows at all four read sites and in
both in-memory creator paths. SerializationVariantElementNullMap already does
exactly this for the top-level x.<Elem>.null, and cannot serve the nested case
because all three of its create() overloads discard prev and would throw away
the field's own on-disk null map. Nine of the ten creators inherit the no-op.
createFromPath and makeSubcolumnInfo also pass the true selected terminal, since
on the dynamically-resolved-descendant arm the leaf lives in the nested path and
path[prefix_len - 1] is only the prefix the dynamic type matched.

Two guards keep the change to the case where the null map is the only place the
information can live: the extraction must not have wrapped the element in
Nullable, where absence is already NULL, and the selection must still be a bare
UInt8, since an Array or Map below has already made it Array(UInt8), whose value
for an absent element is the correct default []. That leaves the fix orthogonal
to ClickHouse#119222, which flips allow_nullable_tuple_in_extracted_subcolumns to true.

No on-disk or format change: the same streams are requested and only the value
written into rows where the element is absent changes. This is not a regression -
released 26.8.3.105 already returns 0 there; our ClickHouse#112338 removed a SIGSEGV on the
sibling value read, which is what makes the contradiction observable and puts the
IS NULL rewrite on a completing path.

Closes: ClickHouse#119935

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 comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix 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.

8 participants