Skip to content

Keep Dynamic invariant when inserting from shared variant - #107095

Merged
Avogar merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-dynamic-shared-regular-variant-insert
Jun 17, 2026
Merged

Avogar merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-dynamic-shared-regular-variant-insert

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 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 (Expected the argument N to have X rows, but it has Y) when executing a function over a Dynamic column built by a JOIN over Dynamic (for example the non-joined rows of a RIGHT/FULL JOIN, or a correlated EXISTS subquery decorrelated into a join).

Description

ColumnDynamic keeps an invariant that a logical type is stored either as a regular variant or inside the shared variant, never both. doInsertFrom/doInsertManyFrom could break it: when a value coming from the source shared variant was inserted into a destination that still had room for a new regular variant, the type was always appended to the destination shared variant; during a row-by-row gather the same type could also become a regular variant for other rows, leaving it in both storages. Such a column then crashed ExecutableFunctionDynamicAdaptor::executeImpl with the row-count LOGICAL_ERROR above.

The fix makes the shared-variant branch of doInsertFrom/doInsertManyFrom try addNewVariant first (falling back to the shared variant only when no regular variant can be added), matching deserializeAndInsertFromArena. Found by the AST fuzzer (STID 2959-51fd). Added a ColumnDynamic unit test that reproduces the broken invariant through the public insert API.

Version info

  • Backported to: 26.3.33.29

ColumnDynamic has an invariant: a logical type is stored either as a
regular variant or inside the shared variant, never both.

doInsertFrom and doInsertManyFrom broke this. When the source value lived
in the source shared variant and the destination did not yet have that
type as a regular variant, they always appended it to the destination
shared variant, even when the destination still had room for a new
regular variant. During a row-by-row gather (for example filling the
non-joined rows of a RIGHT/FULL JOIN over a Dynamic column) the same
type could then also be added as a regular variant for other rows, so it
ended up in both storages.

A Dynamic column in that state crashes function execution: in
ExecutableFunctionDynamicAdaptor::executeImpl the shared-variant rows and
the regular-variant rows of the duplicated type collide on a single
selector slot, so the per-variant column size stops matching the
scattered arguments and checkFunctionArgumentSizes raises
"Expected the argument N to have X rows, but it has Y". This was found by
the AST fuzzer (STID 2959-51fd) over a Dynamic(max_types=2) column with a
multiIf whose else branch is a correlated EXISTS subquery (decorrelated
into a join by the analyzer).

Fix doInsertFrom and doInsertManyFrom to try addNewVariant first when the
type coming from the source shared variant is not a regular variant yet,
and only fall back to the shared variant when no regular variant can be
added. This matches deserializeAndInsertFromArena, which already followed
this logic.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Unit test ColumnDynamic.InsertFromSharedVariantKeepsInvariant deterministically reproduces the broken invariant (String ends up both as a regular variant and in the shared variant) via the public insert API; it fails on master HEAD and passes with the fix. The original AST-fuzzer SQL (Dynamic(max_types=2), multiIf with a correlated EXISTS else branch, max_threads>1) also crashes the unpatched server.
b Root cause explained? ColumnDynamic requires a type to live either as a regular variant or in the shared variant, never both. In the shared-variant-source branch of doInsertFrom/doInsertManyFrom, a value whose type was not yet a regular variant in the destination was always appended to the destination shared variant, even when there was room for a new regular variant. During a row-by-row gather (non-joined rows of a join over Dynamic) the same type also became a regular variant for other rows, leaving it in both storages. ExecutableFunctionDynamicAdaptor::executeImpl then routes the shared-variant rows and regular-variant rows of that type to one selector slot, so the per-variant column size diverges from the scattered arguments and checkFunctionArgumentSizes raises the LOGICAL_ERROR.
c Fix matches root cause? Yes. The fix is at the source of the bad state: the shared-variant branch of both methods now calls addNewVariant first and only falls back to the shared variant when no regular variant can be added, so a type is never placed in the shared variant while it is (or becomes) a regular variant. This mirrors deserializeAndInsertFromArena, which already did this. No guard added at the crash site.
d Test intent preserved / new tests added? New unit test added (ColumnDynamic.InsertFromSharedVariantKeepsInvariant, covering both insertFrom and insertManyFrom). It builds valid columns and uses the public gather API, then asserts the invariant and value correctness. No existing test weakened.
e Both directions demonstrated? Yes. The new unit test fails on unpatched master (string_is_regular && string_in_shared == true) and passes with the fix. The full ColumnDynamic/ColumnVariant/ColumnObject suites (76 tests) pass. The end-to-end fuzzer query crashes before the fix and runs clean after.
f Fix is general, not a narrow patch? Yes. The same asymmetric shared-variant branch existed in both doInsertFrom and doInsertManyFrom; both are fixed. insertRangeFrom handles shared-variant rows through its own dedicated loop and routes correctly, and deserializeAndInsertFromArena already promoted to a regular variant, so no other site needs the change. The fix targets where the malformed column is produced, not the crash site in the function adaptor.

Session id: cron:clickhouse-worker-slot-15:20260610-201800

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4582dad]

Summary: ✅


AI Review

Summary

This PR keeps the ColumnDynamic invariant that a logical type is stored either as a regular variant or in SharedVariant, not both. The current code promotes decoded source-SharedVariant values when capacity exists, including the same-layout insertFrom, insertManyFrom, and insertRangeFrom fast paths, and the added ColumnDynamic regression tests cover those paths. I did not find remaining correctness, safety, or metadata issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
Comment thread src/Columns/ColumnDynamic.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished for HEAD 0e76105eaeaa. All failures are infrastructure / aggregator noise; none are caused by this PR:

  • Stateless tests (arm_asan_ubsan, azure, sequential) -> Server died + AddressSanitizer: CHECK failed: sanitizer_allocator_secondary.h:200 (STID 0250-3c49) + 02724_show_indexes ERROR: the known 2026-06-10/11 arm_asan_ubsan Azure ASan-allocator OOM outage. Over the last 2 days this signature hit 145 times across 97 distinct PRs and 25 distinct tests, with no ClickHouse frames in the stack (internal __sanitizer::LargeMmapAllocator mmap exhaustion). Not PR-caused.
  • Performance Comparison (arm_release, master_head, 1/6): no test-level regression rows; job-level perf noise.
  • CH Inc sync, Mergeable Check, PR: aggregator rollups reflecting the above.

This PR touches only src/Columns/ColumnDynamic.cpp (doInsertFrom / doInsertManyFrom shared-variant promotion) and gtest_column_dynamic.cpp; none of the failing areas are related. Moving to review.

insertRangeFrom had the same invariant hole that doInsertFrom and
doInsertManyFrom had. Its shared-variant source loop, in the path where
the two Variant types are combined, copied a value coming from the source
shared variant into our shared variant whenever the type was not yet a
regular variant here, even when there was still room for a new regular
variant. A later range copy could then add the same type as a regular
variant, so the type ended up in both storages.

That broken state crashes function execution over Dynamic: in
ExecutableFunctionDynamicAdaptor::executeImpl the shared-variant rows and
the regular-variant rows of the duplicated type collide on a single
selector slot, the per-variant column size stops matching the scattered
arguments and checkFunctionArgumentSizes raises "Expected the argument N
to have X rows, but it has Y". This is reachable through the public
range-copy path, not only through the row-by-row insert path fixed earlier
(found by the AST fuzzer, STID 2959-51fd).

Promote the new types from the source shared variant up front, while we
still have room, before caching the destination column references (the
promotion reallocates them and reassigns global discriminators). This
matches doInsertFrom, doInsertManyFrom and deserializeAndInsertFromArena.
The other shared-variant loop runs only when no more variants can be added,
so it cannot create the duplicate and is left unchanged.

Update InsertRangeFromOverflow7: with room available, types from the
source shared variant are now promoted to regular variants, matching the
row-by-row path.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (insertRangeFrom follow-up, commit afab1ab)

# Question Answer
a Deterministic repro? Yes. ColumnDynamic.InsertRangeFromSharedVariantKeepsInvariant (gtest) follows the reviewer's exact trace and fails deterministically without the fix (String ends up both as a regular variant and in the shared variant).
b Root cause explained? The combine path of insertRangeFrom copies a value from the source shared variant straight into our shared variant whenever the type is not yet a regular variant here, even with room left. A later range copy can then add that type as a regular variant, so the type lives in both storages, and ExecutableFunctionDynamicAdaptor::executeImpl collides the shared-variant and regular-variant rows on one selector slot, tripping checkFunctionArgumentSizes.
c Fix matches root cause? Yes. A promotion pass calls addNewVariant for each new type from the source shared variant while canAddNewVariant() holds, before the loop, mirroring doInsertFrom / doInsertManyFrom / deserializeAndInsertFromArena. No symptom guard.
d Test intent preserved / new tests added? New regression test added. InsertRangeFromOverflow7 updated: it asserted the now-inconsistent "keep in shared" behavior; with room the bulk path now promotes (sharedSize 2 to 0, stronger invariant), matching the row-by-row path.
e Both directions demonstrated? Yes. New test fails without the fix, passes with it. A throwaway probe confirmed bulk and row-by-row paths produce identical structure for the same input. Full ColumnDynamic.* suite passes 39/39.
f Fix is general, not a narrow patch? Yes. All three shared-variant insertion entry points now promote-first: doInsertFrom, doInsertManyFrom (earlier commit) and insertRangeFrom combine path (this commit). The no-combine path only writes to shared after saturating max_dynamic_types, so canAddNewVariant() is false and it cannot create the duplicate (verified by a throwaway test); left unchanged.

Session id: cron:clickhouse-worker-slot-10:20260611-051200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished for HEAD afab1ab83a2e. No PR-caused failures. The only red is the Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) composite, which errored at the job level with no test failures recorded; the same job-level error hit 21 unrelated PRs in the last 24h, so it is an infra/runner issue, not this change. The full ColumnDynamic gtest suite (incl. the new InsertRangeFromSharedVariantKeepsInvariant) passes. Ready for review.

@Avogar Avogar self-assigned this Jun 15, 2026

@Avogar Avogar 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.

Is it possible to create an SQL test for that? I can suggest how to create a Dynamic column with reduced internal max_dynamic_paths and values in shared data:

create table test (id UInt64, d Dynamic) engine=MergeTree settings index_granularity=1, min_bytes_for_wide_part=100000000;
insert into test select number, NULL from numbers(10);
alter table test update d = 42::UInt64 where id > 4;
select dynamicType(d), isDynamicElementInSharedData(d), count() from test group by dynamicType(d), isDynamicElementInSharedData(d);

   ┌─dynamicType(d)─┬─isDynamicEle⋯aredData(d)─┬─count()─┐
1. │ UInt64         │ true                     │       5 │
2. │ None           │ false                    │       5 │
   └────────────────┴──────────────────────────┴─────────┘

Maybe using this way we can craft an SQL test that will use insertFrom/insertRangeFrom on fresh Dynamic column from this one. If not, it's ok to keep unit test

Comment thread src/Columns/ColumnDynamic.cpp Resolved
Comment thread src/Columns/ColumnDynamic.cpp Resolved
Address review feedback: do the addNewVariant promotion inline in the
existing combine loop via an extra else-if branch, mirroring
doInsertFrom/doInsertManyFrom, instead of the separate pre-pass loop.

This is safe because addNewVariant only reassigns global discriminators,
not local ones (ColumnVariant::extend appends new variants at the end and
remaps global_to_local). The cached local_discriminators, offsets,
shared_variant and shared_variant_local_discr references therefore stay
valid across a mid-loop addNewVariant, so the up-front shared_variant_discr
re-fetch is no longer needed.

Behavior is unchanged: the same source-shared types are promoted to
regular variants while capacity remains, in the same row order, so the
InsertRangeFromSharedVariantKeepsInvariant and InsertRangeFromOverflow7
unit tests still pass. Verified both directions: with the new branch
disabled both tests fail (type ends up in both storages), with it they
pass.

Also simplify the comment at the three promotion sites.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Columns/ColumnDynamic.cpp Resolved
The same-variants fast path at the top of insertFrom/insertRangeFrom/
insertManyFrom copied the source Variant column directly, including rows
that live in the source shared variant. Two Dynamic columns can have the
same variant layout but different max_dynamic_types, so a low-limit source
can hold a type in its shared variant while a high-limit destination with
the same layout still has room for it as a regular variant. The fast path
left that type in the destination shared variant, and a later insert could
then add the same type as a regular variant, leaving it in both storages
and reproducing the ExecutableFunctionDynamicAdaptor row-count LOGICAL_ERROR.

Skip the fast path when the source has values in its shared variant and the
destination still has room, so those rows go through the combine path that
promotes them via addNewVariant first.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 4582dad)

# Question Answer
a Deterministic repro? Yes. ColumnDynamic.SameLayoutSharedVariantKeepsInvariant reproduces on demand: a create(1) source with a type in its shared variant + a same-layout create(10) destination with room → the type lands in both storages, deterministically, for all three of insertFrom/insertManyFrom/insertRangeFrom.
b Root cause explained? The same-variants fast path (variant_name(s) equal) bulk-copies the source Variant column, including shared-variant rows. Two Dynamic columns can share a layout but differ in max_dynamic_types; a low-limit source overflows a type into shared while a high-limit, same-layout destination has room for it as a regular variant. The fast path copies the shared row into the destination shared variant, bypassing addNewVariant. A later insert then adds the same type as a regular variant → present in both storages → ExecutableFunctionDynamicAdaptor row-count LOGICAL_ERROR.
c Fix matches root cause? Yes. The fast path is taken only when it cannot create that state: source shared variant empty, or destination has no room (!canAddNewVariant()). Otherwise it falls through to the combine path whose shared-variant branch already promotes via addNewVariant. No new loops; the hot path adds one getSharedVariant().empty() check.
d Test intent preserved / new tests added? New gtest SameLayoutSharedVariantKeepsInvariant covers all three functions on the same-layout-with-room case. InsertFromOverflow3/InsertManyFromOverflow3 asserted the old leave-in-shared behavior on exactly this case (same layout, destination has room) and are updated to assert promotion, matching the row-by-row insert() path and deserializeAndInsertFromArena. No test weakened.
e Both directions demonstrated? Yes. With the guard neutralized, the new test FAILS (string_is_regular && string_in_shared == true for all three modes) and the two updated tests FAIL. With the fix, full ColumnDynamic.* suite is 40/40 (build id verified to change between runs).
f Fix is general, not a narrow patch? Yes. All three same-layout fast paths (insertFrom/insertRangeFrom/insertManyFrom) are guarded identically. The only other variant_name == site is compare (not an insert path). The combine path's shared-variant promotion was added earlier; single-value deserializeAndInsertFromArena already promotes via addNewVariant. This closes the last sibling that bypassed promotion.

Session id: cron:clickhouse-worker-slot-5:20260616-163500

@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

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

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Jun 17, 2026
Merged via the queue into ClickHouse:master with commit cf1fa30 Jun 17, 2026
165 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 17, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 18, 2026
robot-ch-test-poll added a commit that referenced this pull request Aug 18, 2026
Cherry pick #107095 to 26.3: Keep Dynamic invariant when inserting from shared variant
robot-clickhouse added a commit that referenced this pull request Aug 18, 2026
robot-ch-test-poll added a commit that referenced this pull request Aug 18, 2026
Cherry pick #107095 to 26.5: Keep Dynamic invariant when inserting from shared variant
robot-clickhouse added a commit that referenced this pull request Aug 18, 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 Aug 18, 2026
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #107095 to 26.5: Keep Dynamic invariant when inserting from shared variant
Avogar added a commit that referenced this pull request Sep 9, 2026
Backport #107095 to 26.3: Keep Dynamic invariant when inserting from shared variant
@nikitamikhaylov nikitamikhaylov added v26.2-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Sep 10, 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 10, 2026
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-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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport v26.4-must-backport v26.5-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants