Skip to content

Fix virtual row materializing a non-creatable placeholder column - #113264

Merged
vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-111831-virtual-row-column-set
Aug 10, 2026
Merged

vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-111831-virtual-row-column-set

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 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):

Fixed Cannot insert element into Set (NOT_IMPLEMENTED) when read_in_order_use_virtual_row is enabled and a MergeTree read-in-order query combines WITH FILL ... INTERPOLATE with an IN or has filter.

Description

Closes: #111831
Related: #112344

The query below fails on master and 26.1 - 26.6, and succeeds with read_in_order_use_virtual_row = 0, so a plan optimization breaks a correct query:

CREATE TABLE t (k UInt32, s String) ENGINE = MergeTree ORDER BY k;
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (1, '8');
INSERT INTO t VALUES (2, '8');
SELECT k, s FROM t WHERE s IN ('8')
ORDER BY k WITH FILL FROM 0 TO 4 INTERPOLATE (s AS '7')
SETTINGS read_in_order_use_virtual_row = 1;
-- Code: 48. Cannot insert element into Set: While executing MergingSortedTransform.

Root cause: setVirtualRow fills every header column absent from the part's primary-key block with col.type->createColumnConstWithDefaultValue(1), whose precondition is a creatable type. An IN predicate keeps a Set placeholder in the header, and INTERPOLATE pins it there by declaring every header column an input, so it survives pruning into ReadFromMergeTree. DataTypeSet overrides both createColumn and getDefault, so the failure lands deeper, in IColumnDummy::insert.

The fix reuses the header's own column, resized to one row, whenever the element carries one, falling back to createColumnConstWithDefaultValue only for a null-column element (ColumnWithTypeAndName documents that the column may be null to represent just a header). Sound because the virtual row is never emitted (skip_last_row) and only its sort columns are compared.

An earlier revision also gated this on the type via isNotCreatable, dropped at review request: it never discriminated on any reachable shape (of 1856 recorded entries here, 18 were isNotCreatable, all Const(Set), all size() == 0). Both forms are output-identical across the virtual_row suite and a 21-type WITH FILL matrix.

Validation: reproduces deterministically on an unpatched debug build; after the fix every shape matches the read_in_order_use_virtual_row = 0 ground truth. New test 04723_virtual_row_interpolate_column_set fails pre-fix and passes after, 100/100 green over 50 randomized and 50 forced-setting runs.

Carrier matrix (each shape passes at read_in_order_use_virtual_row = 0 and failed at = 1 before the fix; the first 8 rows are the committed test, the rest were measured locally)
shape pre-fix @ vr=1 post-fix @ vr=1
s IN ('8') Code 48 matches vr=0
s IN (SELECT '8') (subquery set) Code 48 matches vr=0
s NOT IN ('9') Code 48 matches vr=0
(s, s) IN (('8','8')) (tuple set) Code 48 matches vr=0
has(['8'], s) Code 48 matches vr=0
ORDER BY k DESC (reverse read) Code 48 matches vr=0
read_in_order_use_virtual_row_per_block = 1 Code 48 matches vr=0
SELECT DISTINCT Code 48 matches vr=0
LowCardinality(String) column Code 48 matches vr=0
Nullable(String), incl. IN (NULL, '8') Code 48 matches vr=0
Array(String), Map(String,String) Code 48 matches vr=0
empty set, 10k-element set, three INs Code 48 matches vr=0
PREWHERE s IN ('8') passes (not a carrier) unchanged

Closes: ClickHouse#111831
Related: ClickHouse#112344

A MergeTree read-in-order query combining WITH FILL INTERPOLATE with an IN or
has filter failed with "Cannot insert element into Set" (NOT_IMPLEMENTED) when
read_in_order_use_virtual_row was enabled, while the same query succeeded with
the setting off. A plan optimization was breaking a correct query.

setVirtualRow fills every header column absent from the part's primary-key block
with createColumnConstWithDefaultValue(1), whose precondition is a creatable
type. The second argument of an IN predicate is a Set placeholder column, and
INTERPOLATE keeps it in the read header because the interpolate step declares
every current header column as an input, so the placeholder survives column
pruning all the way down into ReadFromMergeTree. DataTypeSet overrides both
createColumn and getDefault successfully, so the failure landed one level deeper
in IColumnDummy::insert.

Reuse the header's own placeholder column resized to one row for types that
cannot produce a default value, using the existing isNotCreatable predicate.
This is sound because the virtual row is never emitted (skip_last_row, then
removeTop without insert) and only its sort columns are ever compared. Reusing
col.column rather than building a fresh one keeps the real FutureSetPtr alive
inside the ColumnSet.

isNotCreatable is used because it is the codebase's existing name for "types
that cannot produce a default-valued column", not because Function is a carrier
of this bug. It is not: the lambda shape fails with the setting off as well, at
VirtualRowTransform rather than MergingSortedTransform, which is a pre-existing
WITH FILL defect and needs its own issue.

Validated on a debug build: the failure reproduces deterministically pre-fix,
and post-fix every shape returns results identical to the
read_in_order_use_virtual_row = 0 ground truth, including LowCardinality,
Nullable, Array, Map, an empty set and a 10000-element set. The new test fails
on the pre-fix binary and passes after, 100/100 green over 50 randomized plus 50
forced-setting runs.

The original analysis is @ zlareb1's, from the closed PR ClickHouse#112344.
@groeneai

groeneai commented Aug 4, 2026

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

An independent model reviewed this diff cold against the ClickHouse review skill, plus my own
cold read of the changed function and its callers. One finding, adjudicated below.

⚠️ max_threads = 1 could make the new test vacuous (test-liveness) - disagreed, with
evidence.

The claim was that the randomized max_threads = 1 yields a single pipeline stream, so
SortingStep::mergingSorted installs RemoveVirtualRowTransform instead of
MergingSortedTransform and the changed code is never reached. That necessary step does not
hold for a read-in-order plan: the stream count comes from the number of parts, not from
max_threads.

  • ReadFromMergeTree::readInOrder builds one Pipe per entry of parts_with_ranges and unites
    them with Pipe::unitePipes, which concatenates output ports and never collapses them.
  • The only collapse there is gated on output_streams_limit, which is non-zero only when
    max_streams_for_merge_tree_reading is set. Its default is 0 and the test runner does not
    randomize it.
  • spreadMarkRangesAmongStreamsWithOrder only ever reduces num_streams toward
    max(..., parts_with_ranges.size()), so never below the part count, and SortingStep performs
    no resize before mergingSorted.
  • The test creates two parts under SYSTEM STOP MERGES, so pipeline.getNumStreams() > 1 holds
    for any max_threads.

In-tree corroboration: 03031_read_in_order_optimization_with_virtual_row sets max_threads = 1
in seven places and still asserts virtual-row behavior. Measured corroboration: max_threads = 1
and max_threads = 64 both reproduce the failure, and every one of the eight statements was
verified red on the pre-fix binary and green after.

💡 Two nits from my own read, both addressed without a code change:

  • The collapsed carrier matrix in the description mixed shapes the committed test checks with
    shapes only measured locally. The summary line now says which is which. No extra test arms were
    added: the guard keys on the type of the placeholder column, which is always Set whatever the
    filtered column's type is, so near-duplicate wrapper arms would add size without coverage.
  • The affected-version range is now substantiated by checking both halves of the mechanism, the
    createColumnConstWithDefaultValue fill in MergeTreeReadInfo.cpp and the INTERPOLATE input
    pinning in Planner.cpp, in each of 26.1 through 26.6 rather than resting on a bot's list.

No blockers. The changed function was read in full, along with both call sites in
MergingSortedAlgorithm, the merge loops that consume the virtual row, the non-creatable type and
column implementations, and the complete new test.

Session id: cron:clickhouse-review-slot-50:20260804-071100

@groeneai

groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On an unpatched debug build (Build ID 8cd11dc5) 04723_virtual_row_interpolate_column_set fails on demand, every run, with Code: 48. Cannot insert element into Set: While executing MergingSortedTransform. (NOT_IMPLEMENTED). Two parts plus SYSTEM STOP MERGES; not a percentage repro. Reproduced under both a bare client and the real test runner.
b Root cause explained? Yes. setVirtualRow fills every header column absent from the part's primary-key block with createColumnConstWithDefaultValue(1), whose precondition is a creatable type. An IN predicate puts a Set placeholder in the header and INTERPOLATE pins it there by declaring every header column an input, so it survives pruning into ReadFromMergeTree. DataTypeSet overrides both createColumn and getDefault, so the throw lands one level deeper in IColumnDummy::insert.
c Fix matches root cause? Yes. The branch is added at the site that makes the false assumption, keyed on the property that actually governs cloneability: whether the header ELEMENT carries a column. Not a widened bound, not a no-random-* tag, not a data reduction, not a guard at the throw site. Two alternatives (pruning the placeholder out of the interpolate input set; refusing the virtual row on such headers) were rejected on blast-radius and correctness grounds. A isNotCreatable type gate shipped in an earlier revision was dropped at review request after measuring it never discriminates.
d Test intent preserved / new tests added? Yes. No existing test weakened, removed, or retagged. New 04723_virtual_row_interpolate_column_set covers 8 shapes: literal IN, subquery IN, NOT IN, tuple IN, has, ORDER BY DESC, read_in_order_use_virtual_row_per_block = 1, and SELECT DISTINCT. No no-parallel tag, since nothing here is server-global. No test was added for the predicate removal itself: it is output-identical by construction, so such a test would be vacuous.
e Both directions demonstrated? Yes. All 8 statements fail individually on the pre-fix binary and pass on the fixed one (Build ID 3119d9ca, verified moved from 569baea1). Whole-file run: Code: 48 pre-fix, byte-identical to the committed .reference post-fix. 50 randomized plus 50 forced-setting runs, 100/100 green. Server binary identity confirmed per arm by reading /proc/<pid>/exe, not by trusting the launch command.
f Fix is general across code paths? Yes. The invariant is now "the column instance can be cloned", so all IColumn subclasses reachable as a header element were enumerated over src/Columns/Column*.h: 17 header-capable classes all implement cloneResized (ColumnNothing and ColumnSet via IColumnDummy, ColumnFunction directly). Exactly two lack it and both are refuted as carriers: ColumnBLOB (overrides cloneEmpty to unwrap; BlocksMarshallingStep is appended at the end of the plan, downstream of every merge; convertColumnsToBLOBs bails at rows() <= 1 while the virtual row is 1 row) and ColumnCompressed (all 10 construction sites are compress() implementations, never a pipeline header). setVirtualRow has one definition and two call sites, both through the edited loop; no sibling implementation and no Replicated/Shared pair.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured against correctness rather than mere absence of an exception. A 21-type WITH FILL / INTERPOLATE matrix (String, FixedString, Nullable, LowCardinality, LC(Nullable), Decimal, DateTime, DateTime64, Array, Array(Array), Tuple, Map, UUID, IPv4, IPv6, Enum8, Dynamic, Variant, JSON, AggregateFunction, SimpleAggregateFunction) plus literal const, Nullable const, a lambda arrayMap, and a const column inside ORDER BY (ASC, DESC, WITH FILL, materialize), an empty set, a 10 000-element set, and three INs: all at the size() == 0 boundary, all matching the read_in_order_use_virtual_row = 0 ground truth. PREWHERE s IN (...) is not a carrier and is unchanged.
h Backward compatible? (maintainer-approved exception only) Yes, vacuously. No setting added or renamed, no default changed, no serialization or on-disk format touched, so no SettingsChangesHistory.cpp entry is required. Queries that previously succeeded are unaffected; the change only turns a thrown exception into the result the same query already returns with the setting off.
i Invariants and contracts preserved? Yes. cloneResized(1) on a size-0 column is defined for every header-capable class. Chunk structure holds: one column per header column in header order, all of size 1. The col.column guard preserves the documented ColumnWithTypeAndName contract that the column may be null to represent just a header. Reusing col.column keeps the real FutureSetPtr alive, so nothing downstream sees a null set. ColumnConst::cloneResized shares the nested value where createColumnConstWithDefaultValue defaults it, which is the more correct of the two and is normalised anyway by removeConstAndSparse immediately after setVirtualRow. The merge contract is untouched: the virtual row is never emitted (skip_last_row, then removeTop() without insert) and only sort columns are compared. No error or early-return path, locking, or durability surface is involved.

Updated for head f2754755: the earlier revision of this table described the isNotCreatable type gate, dropped at review request.

Session id: cron:clickhouse-review-slot-48:20260804-200002

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @vdimir, could you review this? setVirtualRow fills every header column absent from the part primary-key block with createColumnConstWithDefaultValue, which requires a creatable type, so an IN set placeholder that INTERPOLATE pins into the in-order read header made the query throw NOT_IMPLEMENTED from IColumnDummy::insert; the fix reuses that placeholder resized to one row. @vdimir, flagging you because #111457 edits the same function and will have a small textual conflict with whichever lands second.

@vdimir vdimir added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f275475]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue

AI Review

Summary

This PR changes setVirtualRow to reuse the header column when synthesizing non-primary-key virtual-row fields, which fixes the DataTypeSet / ColumnSet path that previously threw Cannot insert element into Set under WITH FILL ... INTERPOLATE plus IN / has on read-in-order MergeTree queries. I read the modified merge path, the virtual-row producer / consumer code, the new stateless test, the existing review threads, and the current Praktika report; I did not find a remaining correctness or compatibility issue in the current head.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 3/4 (75.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 Aug 4, 2026

ordered_columns.push_back(pk_col->column);
}
/// Types like Set cannot produce a column with a default value. The virtual row is never

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.

How we end up in serVirtualRow if "The virtual row is never emitted"?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are two stages and my comment only named the second one, which is what makes it read as a contradiction.

The row is materialized precisely so it can be compared. ReadFromMergeTree.cpp:963-977 builds pk_block from the part's index entry at the next mark and attaches it via VirtualRowTransform, so the row carries that part's next key value; :3289 calls it the "announced boundary". That is how the merge learns it does not need to pull from that part yet. MergingSortedAlgorithm::initialize (MergingSortedAlgorithm.cpp:118) and consume (:168) call setVirtualRow to turn the boundary into a real 1-row chunk, and immediately set skip_last_row = true. The row is used as a queue key and then dropped at :345-349: queue.removeTop() plus return Status(order) to pull the real block, with no insertRow on that path (the batch path does the same via insert_rows_size at :489). So it is built and compared, never emitted.

That is also why reusing the placeholder is sound rather than merely cheap: SortCursorImpl::reset puts only the description columns into sort_columns, so the merge reads just the sort key of that row, and the only readers of all_columns are insertRow/insertRows, which the skip path bypasses.

The wording is the real problem, so I will reword it to describe the row as a comparison-only boundary instead of saying it is never emitted. I will fold that into the next push rather than restart the in-flight CI for a comment.

…rately

The previous wording said the virtual row "is never emitted", which reads as a
contradiction: if it is never emitted, why does setVirtualRow build it at all?

The row IS materialized, precisely so it can be compared. ReadFromMergeTree
builds pk_block from the part's index entry at the next mark and attaches it via
VirtualRowTransform, so the row carries that part's next key value (the
"announced boundary"). MergingSortedAlgorithm materializes it into a real 1-row
chunk and sets skip_last_row, uses it as a queue key, then drops it via
removeTop() without inserting it into the merged data.

Comparison-only and skipped-before-emission are the two accurate properties;
"never emitted" only named the second. No functional change.
The ParallelReplicas CI lane failed this test with "Serialization is not
implemented for data type Set" from NativeWriter::write, reached through
TCPHandler::sendData when the pipeline output header is sent to a remote
replica. That is a different site from the bug under fix here, which throws
"Cannot insert element into Set" from IColumnDummy::insert inside
MergingSortedTransform.

Measured on a local three-replica parallel-replicas server, the remote-header
failure is not a virtual-row regression:

  - it reproduces on pristine master (no fix applied) at
    read_in_order_use_virtual_row = 0, and even at optimize_read_in_order = 0,
    where no virtual row is built at all (11 of 30 runs);
  - the CI lane randomizes parallel_replicas_local_plan (tests/clickhouse-test),
    and with it 0 the read runs on remote replicas, so the header carrying the
    IN-set placeholder must be serialized over the wire;
  - the acceptance criterion used throughout this PR - pass at
    read_in_order_use_virtual_row = 0 and fail at 1 - is not met, so it is out
    of scope by the same rule that excluded the lambda ColumnFunction shape.

It is a residual of the family fixed by ClickHouse#111919 (already an ancestor of this
branch), which gated the filling step for distributed and custom-key parallel
replicas but not for this read_tasks path.

Pinning enable_parallel_replicas = 0 keeps the test targeted at the defect it
covers. Non-vacuity is preserved: with the pin applied and the fix reverted all
eight statements still fail with "Cannot insert element into Set" (10 of 10
whole-file runs red), and with the fix they pass 20 of 20 under the same
parallel-replicas server configuration. 319 stateless tests already use this
pin.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

ParallelReplicas lane failure: measured out of scope, test pinned

Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) failed
04723_virtual_row_interpolate_column_set on 9cb62cd. I investigated it as a possible
incomplete fix and it is not one: the failure is a pre-existing defect on a different code path.

The two errors are distinct sites. This PR fixes Cannot insert element into Set from
IColumnDummy::insert, reached through MergingSortedTransform. The lane failed with
Serialization is not implemented for data type Set from NativeWriter::write
(IDataTypeDummy::throwNoSerialization), reached through TCPHandler::sendData when the
pipeline output header is sent to a remote replica.

I reproduced it on a local three-replica parallel-replicas server. The lane randomizes
parallel_replicas_local_plan (tests/clickhouse-test:1554); with it 0 the read runs on remote
replicas, so the header carrying the IN-set placeholder has to be serialized over the wire.
Measured on the pre-fix binary, it fails at read_in_order_use_virtual_row = 0 and even at
optimize_read_in_order = 0, where no virtual row is constructed at all (11 of 30 runs). So it
fails the acceptance criterion I stated for this PR - pass at
read_in_order_use_virtual_row = 0, fail at 1 - and it is out of scope by the same rule that
excluded the lambda ColumnFunction shape.

It looks like a residual of the family fixed by #111919, which is already an ancestor of this
branch: that change gated the filling step for distributed and custom-key parallel replicas, but
not for this read_tasks path.

I pinned enable_parallel_replicas = 0 in the test rather than weakening it. Non-vacuity is
preserved and measured: with the pin applied and the fix reverted, all eight statements still fail
with Cannot insert element into Set (10 of 10 whole-file runs red); with the fix they pass 20 of
20 under the same parallel-replicas server configuration. 319 stateless tests already use this pin.

Also folded in the comment reword I owed @ vdimir from
#113264 (comment), which I had held back
to avoid restarting CI that was in flight at the time.

I will report the remote-header defect separately so it does not get lost.

Session id: cron:clickhouse-maint-slot-14:20260804-131900

/// Types like Set cannot produce a column with a default value. Only the sort columns of
/// the virtual row are compared, and it is skipped before emission, so reuse the placeholder.
else if (col.column && isNotCreatable(col.type->getTypeId()))
ordered_columns.push_back(col.column->cloneResized(1));

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.

Can we always do cloneResized instead of createColumnConstWithDefaultValue?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly yes: the isNotCreatable half can go, the col.column half cannot.

The null check has to stay. ColumnWithTypeAndName.h:17 says it outright: "Column data could be nullptr - to represent just 'header' of column." cloneEmpty propagates that (ColumnWithTypeAndName.cpp:20-21 only clones when column is set), Block::cloneEmpty is built on it, and ReadFromMergeTree.cpp:344 goes through output_header->cloneEmpty(). In-tree producers of null-column headers exist (IDictionary.h:481, StorageSystemTables.cpp:219). I never reached one from this path, but unconditional deref is a segfault if it ever happens.

The type check can go. I built a variant with the unconditional cloneResized(1) and diffed it against this PR:

  • the 34-file virtual_row stateless corpus: identical stdout, 34/34;
  • a 21-type matrix under WITH FILL (String, FixedString, Nullable, LowCardinality, LC(Nullable), Decimal, DateTime64, Array, Array(Array), Tuple, Map, UUID, IPv4, IPv6, Enum8, Dynamic, Variant, JSON, AggregateFunction, SimpleAggregateFunction): identical;
  • literal const, Nullable const, lambda arrayMap, and a const column inside ORDER BY (ASC, DESC, WITH FILL): identical.

To make that negative mean something I logged every entry into the branch rather than only the suspicious ones: 1856 entries, all with size() == 0. For a size-0 column cloneResized(1) default-fills (ColumnVector.cpp:667, ColumnString.cpp:105), and ColumnNullable::cloneResized sets the new null-map byte to 1 (ColumnNullable.cpp:118-120), matching DataTypeNullable::getDefault() == Null(). No default-value drift.

So I will ship:

else if (col.column)
    ordered_columns.push_back(col.column->cloneResized(1));
else
    ordered_columns.push_back(col.type->createColumnConstWithDefaultValue(1));

One note since it touches the area of #111457: for a ColumnConst header column the two forms are not equivalent in principle, because ColumnConst::cloneResized shares the nested value (ColumnConst.h:57) where createColumnConstWithDefaultValue produces a default. Output was identical on every shape I measured, and if it ever diverges, carrying the real constant is the more correct of the two.

CI is still running on 7a4725ec, with two Stress test reds I have not triaged yet, so I will fold this into the next push alongside those rather than restarting the in-flight checks now.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed as f27547553acb7accd789f86a17fc19fb1159bd3c: the isNotCreatable gate is gone, col.column && stays.

Re-verified on the built binary rather than carried over: virtual_row suite 19/19 on both this shape and the previous one (18/19 on pristine master, the failure being the new test, so the identity is not vacuous), the 34-file corpus and the 21-type WITH FILL matrix byte-identical between the two shapes, and 04723 100/100 green over 50 randomized plus 50 forced-setting runs.

One thing I checked before dropping the predicate, since the invariant moves from "the type is creatable" to "the column instance is resizable": of the 24 concrete IColumn subclasses, only ColumnBLOB and ColumnCompressed lack cloneResized, and neither can appear in a merge header - block marshalling is appended at the end of the plan, downstream of every merge, and returns early below two rows, while ColumnCompressed is only produced by IColumn::compress.

This restarts the checks that were in flight.

Drop the isNotCreatable half of the placeholder-reuse condition, keeping
only the null check on col.column. Requested by vdimir on the PR.

The header ELEMENT, not the type, carries the placeholder, so
col.column's presence is the property that actually governs whether a
clone is possible; isNotCreatable was a proxy for it that never
discriminated on any reachable shape. Measured on the previous form: of
1856 else-branch entries recorded across the virtual_row corpus and a
21-type matrix, only 18 were isNotCreatable (all Const(Set)), and every
entry had size() == 0.

The null check stays. ColumnWithTypeAndName.h documents that the column
may be nullptr to represent just the header of a column, the struct is
default-constructible that way, and cloneEmpty propagates the null, so
an unconditional deref would be a null dereference the day that path is
reached. No such shape was reachable from this path, which proves the
corpus does not reach it, not that it is unreachable.

Output-identical to the previous form on every measured shape: the
19-test virtual_row suite (19/19 identical verdicts) and 34 files run
through a bare client (34/34 identical stdout and rc), plus a 26-script
type and shape matrix covering String, FixedString, Nullable,
LowCardinality, LC(Nullable), Decimal, DateTime, DateTime64, Array,
Array(Array), Tuple, Map, UUID, IPv4, IPv6, Enum8, Dynamic, Variant,
JSON, AggregateFunction, SimpleAggregateFunction, literal and Nullable
constants, a lambda arrayMap, and a const column inside ORDER BY.

ColumnConst is the one genuine semantic difference and it is benign:
ColumnConst::cloneResized shares the nested value where
createColumnConstWithDefaultValue produces a default. Carrying the real
constant is the more correct of the two, and it is why the Set case
works at all, since ColumnSet::cloneDummy shares the FutureSetPtr.
removeConstAndSparse normalises the chunk immediately after
setVirtualRow either way.
@groeneai

groeneai commented Aug 4, 2026

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

Round on f2754755 (drop the isNotCreatable type gate, keep the null guard). Independent cold
review plus a second-model gate, both against the resulting code rather than the write-up.

Gate: 0 findings. Own cold review: 1 nit, refuted by me on re-derivation.

Finding Verdict
💡 The new comment says only the sort columns are compared. Exact on emission, but MergedData::initialize does read every input column once, to pick the merged structure for Dynamic/JSON/Map. Disagree (mine, withdrawn). No behavioural difference: chooseDynamicStructureForMerge can only union variants the source column already declares, and a row cloned from the header declares exactly the header's variants. Left as written rather than lengthening the comment.

What I verified independently, before reading the author's evidence:

  • The invariant this round moves from "the type is creatable" to "the column instance is resizable",
    so I enumerated every concrete IColumn subclass rather than sampling shapes. 22 of 24 implement
    cloneResized; IColumn's base implementation throws NOT_IMPLEMENTED. The two that do not are
    ColumnBLOB and ColumnCompressed, and neither can reach a merge header: block marshalling is
    appended at the end of the plan, downstream of every merge, and bails below two rows, while
    ColumnCompressed is only ever produced by IColumn::compress.
  • Each surviving implementation is safe at new_size = 1 from an empty source, including the two
    that need care: ColumnNullable sets the new null-map byte, matching the type's default, and
    ColumnAggregateFunction takes its grow branch and creates the state in its own arena.
  • Keeping col.column && is required, not cautious: a header element's column may legitimately be
    null, which is a documented property of ColumnWithTypeAndName, so the literally unconditional
    form would dereference null.
  • ColumnConst::cloneResized shares the constant where the old call defaulted it. That is the one
    real semantic difference; removeConstAndSparse normalises both forms immediately after, so
    nothing downstream can observe it.
  • The regression test stays live: all eight statements assert interpolated values that throw before
    the fix, and every pinned setting arms the defect rather than hiding it.
  • Rechecked Fix for virtual row is not being applied in some cases #113291, which touches the same file: its hunks are the signature and the line after
    chunk.setColumns, so they bracket this one without touching it. Merges clean, different defect.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f275475

CI fully finished on this head: 174 of 174 check-runs completed (156 success, 17 skipped,
1 failure), 0 queued or in progress, Config Workflow and Finish Workflow both green,
past the 20-minute CIDB ingestion buffer.

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

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'notNullIn' (STID 0250-41a5) pre-existing trunk defect in set-building for a subquery under a non-equi predicate; reached here by the stress thread fuzzer, unrelated to this PR's diff a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace got LogCluster query failed with code 500. The build itself passed: the job's check_status is success and the check-run concluded success, so it gates nothing infra, not this PR. A fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

The Not-ready Set logical error is 1 failure out of 5 in that stress job and is not produced
by any statement this PR changes. No other functional, integration, fuzzer, sanitizer or
performance check failed on this head.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113264&sha=f27547553acb7accd789f86a17fc19fb1159bd3c&name_0=PR

Session id: cron:our-pr-ci-monitor:20260805-023000

@vdimir vdimir self-assigned this Aug 10, 2026
@vdimir
vdimir added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit 861a3c2 Aug 10, 2026
178 of 180 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

read_in_order_use_virtual_row + WITH FILL INTERPOLATE + IN filter throws Cannot insert element into Set (NOT_IMPLEMENTED)

3 participants