Skip to content

Fix in-place mutation of shared Variant subcolumn when converting Variant to a column - #107374

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-variant-to-column-inplace-mutation-101415
Jun 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-variant-to-column-inplace-mutation-101415

Conversation

@groeneai

@groeneai groeneai commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fix a LOGICAL_ERROR (Variant N (T) has size X, but expected Y) when a function such as toString or concat is applied to a Variant or Dynamic column that holds a single non-empty variant together with NULLs, and the function returns its input column unchanged.

Description

Related: #101415

Found by the msan function_prop_fuzzer (FunctionsStress) and the AST fuzzer. Related to the same ColumnVariant::validateState error family as #101415, but a distinct code path (no join, no runtime filter).

Root cause

When a function is applied to a Variant column that contains a single non-empty variant plus NULLs, both ConvertImplFromVariantToColumn::execute (the toString / CAST-to-column path) and FunctionVariantAdaptor::executeImpl follow the same pattern: filter the variant to its non-NULL rows, run the function on the compact subcolumn, then expand the result back to the original size, filling the filtered-out rows with defaults/NULLs. FunctionDynamicAdaptor::executeImpl has the same fast path, since Dynamic is backed by a ColumnVariant.

The expand was done with nested_result->assumeMutable()->expand(filter, false). assumeMutable() is a const_cast that does not clone shared columns. When the nested function returns one of its input columns unchanged (toString of a String variant, or concat of a single String argument both return that argument), the result aliases the input Variant's subcolumn, which is still referenced by the source ColumnVariant (use_count > 1). Expanding it in place grows that shared subcolumn, so the source Variant ends up with a subcolumn larger than the number of discriminators pointing at it. The next operation that validates the variant (arraySort -> ColumnVariant::permute, native serialization via blockSerializedSize, DISTINCT/PREWHERE filtering) then aborts in ColumnVariant::validateState.

Fix

Replace assumeMutable()->expand() with IColumn::mutate()->expand(), which clones the column first when it is shared, so the in-place expand never touches a column still owned by the source Variant. Applied to all six expand-after-filter sites: one in ConvertImplFromVariantToColumn, three in FunctionVariantAdaptor, and two in FunctionDynamicAdaptor.

Reproducers (all aborted before the fix)

SET enable_variant_type = 1, allow_suspicious_variant_types = 1;

SELECT arraySort(x -> toString(x), [NULL, CAST('hi', 'Variant(Int32, String)')]);

CREATE TABLE t (id UInt32, v Variant(Int32, String)) ENGINE = Memory;
INSERT INTO t VALUES (1, NULL), (2, 'hi');
SELECT toString(v), blockSerializedSize(v) FROM t ORDER BY id;
SELECT concat(v),   blockSerializedSize(v) FROM t ORDER BY id;

SET enable_dynamic_type = 1;
CREATE TABLE td (id UInt32, d Dynamic) ENGINE = Memory;
INSERT INTO td VALUES (1, NULL), (2, 'hi');
SELECT concat(d), blockSerializedSize(d) FROM td ORDER BY id;

Regression test: tests/queries/0_stateless/04337_variant_to_column_inplace_mutation.sql.

CI signal: Unit tests (msan, function_prop_fuzzer) -> FunctionsStress, e.g. report https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107246&sha=d470f64aa201323633aa44d3d78ef31b74356954&name_0=PR&name_1=Unit%20tests%20%28msan%2C%20function_prop_fuzzer%29

Version info

  • Merged into: 26.6.1.758

…iant to a column

When a function is applied to a Variant column that contains a single non-empty
variant plus NULLs, both ConvertImplFromVariantToColumn::execute (the toString /
CAST-to-column path) and FunctionVariantAdaptor::executeImpl filter the variant to
its non-NULL rows, run the function, then expand the result back to the original
size, filling the filtered-out rows with defaults/NULLs.

The expand was done via nested_result->assumeMutable()->expand(filter, false).
assumeMutable() is a const_cast that does not clone shared columns. When the nested
function returns one of its input columns unchanged (e.g. toString of a String
variant, or concat of a single String argument returns that argument), the result
aliases the input Variant's subcolumn, which is still referenced by the source
ColumnVariant (use_count > 1). Expanding it in place grows that shared subcolumn,
so the source Variant ends up with a subcolumn larger than the number of
discriminators pointing at it. The next operation that validates the Variant
(arraySort -> ColumnVariant::permute, native serialization via blockSerializedSize,
DISTINCT/PREWHERE filtering, ...) then aborts with
"Variant N (T) has size X, but expected Y".

Fix: replace assumeMutable()->expand() with IColumn::mutate()->expand(), which
clones the column first when it is shared, so the in-place expand never touches a
column still owned by the source Variant. Applied to all four expand-after-filter
sites (one in ConvertImplFromVariantToColumn, three in FunctionVariantAdaptor).

Reproducers (all aborted before the fix):
  SELECT arraySort(x -> toString(x), [NULL, CAST('hi', 'Variant(Int32, String)')]);
  SELECT toString(v), blockSerializedSize(v) FROM (single-variant-plus-NULL column);
  SELECT concat(v), blockSerializedSize(v) FROM (single-variant-plus-NULL column);

Found by the msan function_prop_fuzzer (FunctionsStress) and the AST fuzzer.

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

groeneai commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT arraySort(x -> toString(x), [NULL, CAST('hi', 'Variant(Int32, String)')]) aborts 100% of the time on a debug build, as does SELECT toString(v), blockSerializedSize(v) / SELECT concat(v), blockSerializedSize(v) over a single-variant-plus-NULL Variant(Int32, String) column.
b Root cause explained? Yes. For a single-non-empty-variant-plus-NULLs Variant, the convert/adaptor paths filter to non-NULL rows, run the function, then nested_result->assumeMutable()->expand(filter, false). assumeMutable() is a const_cast that does not clone. When the function returns its input unchanged (toString of a String variant, concat of one String arg), nested_result aliases the source Variant's subcolumn (use_count > 1); the in-place expand grows that shared subcolumn, so the source Variant has a subcolumn larger than the discriminators pointing at it, and the next validating op (permute/serialization) aborts in ColumnVariant::validateState. Confirmed with instrumentation: ALIASED=1, use_count=3, input_sub.size 1 -> 2 across expand.
c Fix matches root cause? Yes. Replaces assumeMutable()->expand() with IColumn::mutate()->expand(), which clones when the column is shared (use_count > 1) and only then mutates, so the source Variant's subcolumn is never grown in place. This targets the aliasing mechanism directly, not the validateState symptom.
d Test intent preserved / new tests added? New regression test tests/queries/0_stateless/04337_variant_to_column_inplace_mutation.sql covers both the conversion path (toString) and the adaptor path (concat), const and table-backed, and asserts the source Variant survives a following blockSerializedSize. No existing tests removed or weakened.
e Both directions demonstrated? Yes. The regression test aborts (exit 134) on a stash-reverted pre-fix binary and passes (diff-clean against the reference) on the fixed binary; both binaries Build-ID-verified.
f Fix is general, not a narrow patch? Yes. The identical assumeMutable()->expand() anti-pattern existed at four expand-after-filter sites: one in ConvertImplFromVariantToColumn::execute and three in FunctionVariantAdaptor::executeImpl. All four are fixed (the three adaptor sites share a small expandColumnByFilter helper). The adaptor site was independently confirmed reachable via concat. The fix is at the source of the corruption (the unsafe in-place mutation), not a guard on the validation check.

Session id: cron:clickhouse-worker-slot-0:20260612-230500

@groeneai

groeneai commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @rschu1ze - could you review this? It fixes a ColumnVariant::validateState LOGICAL_ERROR (Variant N has size X, but expected Y) where converting a single-variant-plus-NULLs Variant with a function that returns its input unchanged (toString of a String variant, concat of one String arg) expanded a shared subcolumn in place via assumeMutable()->expand(), corrupting the source Variant. Switched the four expand-after-filter sites in ConvertImplFromVariantToColumn and FunctionVariantAdaptor to IColumn::mutate()->expand(), which clones when shared.

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

clickhouse-gh Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e3b04f]

Summary: ✅


AI Review

Summary

This PR fixes a ColumnVariant/Dynamic aliasing bug by replacing expand-after-filter mutation of nested function results with IColumn::mutate before expand, and adds focused stateless regressions for the conversion, Variant adaptor, and Dynamic adaptor paths. I found no current-code issues that need inline comments; the previously raised Dynamic sibling-path issue is fixed in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 13, 2026
FunctionDynamicAdaptor has the same aliasing bug as FunctionVariantAdaptor:
Dynamic is backed by a ColumnVariant, and the single-type-plus-NULL fast path
expanded the (possibly shared) nested function result in place via
assumeMutable()->expand(). When the nested function returns an input column
unchanged (e.g. concat over one Dynamic argument returns the String subcolumn),
the result still aliases a subcolumn of the source Dynamic's backing
ColumnVariant; expanding it in place grows that shared subcolumn past its
discriminator count, leaving the source ColumnVariant malformed. A following
operation that re-validates it (here blockSerializedSize during Dynamic
statistics serialization) then aborts with
"Variant N (T) has size X, but expected Y".

Route both expand-after-filter sites through expandColumnByFilter, which uses
IColumn::mutate (clone-if-shared) instead of assumeMutable (const_cast that
never clones), mirroring the FunctionVariantAdaptor fix. Extend
04337_variant_to_column_inplace_mutation with Dynamic regressions covering the
adaptor const-array and table-backed paths.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (Dynamic adaptor extension)

# Question Answer
a Deterministic repro? Yes. On the unfixed binary, clickhouse-local -q "SET enable_dynamic_type=1; CREATE TABLE t(id UInt32, d Dynamic) ENGINE=Memory; INSERT INTO t VALUES (1,NULL),(2,'hi'); SELECT concat(d), blockSerializedSize(d) FROM t ORDER BY id" aborts every time (SIGABRT, exit 134).
b Root cause explained? concat(d) over a single-String-plus-NULL Dynamic hits the Dynamic adaptor fast path, which replaces the arg with the variant subcolumn and returns it unchanged. nested_result therefore aliases a subcolumn of the source Dynamic's backing ColumnVariant (use_count>1). assumeMutable()->expand() grows that shared subcolumn in place to 2 rows while only 1 discriminator points at it; blockSerializedSize(d) then re-validates the source via ColumnVariant::validateState and aborts with Variant 1 (String) has size 2, but expected 1.
c Fix matches root cause? Yes. Both expand-after-filter sites now use expandColumnByFilter, which calls IColumn::mutate (clone-if-shared) instead of assumeMutable (const_cast that never clones), so a shared subcolumn is cloned before expand and the source ColumnVariant stays intact. Identical mechanism to the FunctionVariantAdaptor fix in this PR.
d Test intent preserved / new tests added? Added Dynamic regressions to 04337_variant_to_column_inplace_mutation: const-array adaptor path, table-backed concat(d) (crash driver), and toString(d), each followed by blockSerializedSize(d) to force source re-validation. No existing assertions weakened.
e Both directions demonstrated? Yes. Unfixed binary (Build ID 0ac7d2e7e8): new scenario aborts via ColumnVariant::validateState. Fixed binary (Build ID 1fab5a0080): test passes 40/40 with randomization through clickhouse-test.
f Fix is general, not a narrow patch? Yes. This commit closes the last sibling of the bug class: both assumeMutable()->expand() aliasing sites in FunctionDynamicAdaptor.cpp are converted, matching the FunctionVariantAdaptor.cpp (3 sites) and FunctionsConversion.cpp (1 site) fixes. grep -rn "assumeMutable()->expand" src/Functions/Function{Variant,Dynamic}Adaptor.cpp src/Functions/FunctionsConversion.cpp now returns nothing. Not a symptom guard: the fix is at the in-place mutation that produces the malformed state, not at the validation that detects it.

Session id: cron:clickhouse-worker-slot-4:20260613-090000

@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.80% +0.10%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

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

Full report · Diff report

if (!isDynamic(result_type))
{
/// Expand filtered result. If it's already Nullable, it will be filled with NULLs.
nested_result->assumeMutable()->expand(filter, false);

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.

This is a very good change. Because assumeMutable should never be used in normal code. CC @Avogar

@alexey-milovidov alexey-milovidov left a comment

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.

Amazing, thanks!

@alexey-milovidov alexey-milovidov self-assigned this Jun 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary — head 8e3b04f3ffa1 (master-merge)

CI fully finished (Finish Workflow SUCCESS @ 17:50:07Z). 146 pass / 16 skipping, 0 test-level failures on this head.

The fix (extend the IColumn::mutate-before-expand clone-if-shared fix to the two FunctionDynamicAdaptor.cpp expand-after-filter sites, plus the Dynamic regression added to 04337_variant_to_column_inplace_mutation) is green across all stateless + sanitizer jobs.

The two Fast test (arm_darwin) reds (04336_parallel_blocks_marshalling_low_cardinality_native_format, 04327_rewrite_aggregate_function_with_if_distributed) were on the prior commit 288cb5f54285 only — known macOS arm_darwin infra flakes, unrelated to this Variant/Dynamic change, and absent on the current head.

CH Inc sync (private internal) and the aggregator nones never block merge.

Awaiting review from @Avogar and @rschu1ze.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants