Repository navigation
Fix virtual row materializing a non-creatable placeholder column - #113264
Conversation
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.
Internal second-model review (click to expand)An independent model reviewed this diff cold against the ClickHouse review skill, plus my own
The claim was that the randomized
In-tree corroboration: 💡 Two nits from my own read, both addressed without a code change:
No blockers. The changed function was read in full, along with both call sites in Session id: cron:clickhouse-review-slot-50:20260804-071100 |
Pre-PR validation gate (click to expand)
Updated for head Session id: cron:clickhouse-review-slot-48:20260804-200002 |
|
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. |
|
Workflow [PR], commit [f275475] Summary: ❌
AI ReviewSummaryThis PR changes Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3/4 (75.00%) · Uncovered code |
|
|
||
| ordered_columns.push_back(pk_col->column); | ||
| } | ||
| /// Types like Set cannot produce a column with a default value. The virtual row is never |
There was a problem hiding this comment.
How we end up in serVirtualRow if "The virtual row is never emitted"?
There was a problem hiding this comment.
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.
ParallelReplicas lane failure: measured out of scope, test pinned
The two errors are distinct sites. This PR fixes I reproduced it on a local three-replica parallel-replicas server. The lane randomizes It looks like a residual of the family fixed by #111919, which is already an ancestor of this I pinned Also folded in the comment reword I owed @ vdimir from 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)); |
There was a problem hiding this comment.
Can we always do cloneResized instead of createColumnConstWithDefaultValue?
There was a problem hiding this comment.
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_rowstateless 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 insideORDER 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.
There was a problem hiding this comment.
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.
Internal second-model review (click to expand)Round on Gate: 0 findings. Own cold review: 1 nit, refuted by me on re-derivation.
What I verified independently, before reading the author's evidence:
|
CI finish ledger - f275475CI fully finished on this head: 174 of 174 check-runs completed (156 success, 17 skipped, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20260805-023000 |
861a3c2
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Cannot insert element into Set(NOT_IMPLEMENTED) whenread_in_order_use_virtual_rowis enabled and aMergeTreeread-in-order query combinesWITH FILL ... INTERPOLATEwith anINorhasfilter.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:Root cause:
setVirtualRowfills every header column absent from the part's primary-key block withcol.type->createColumnConstWithDefaultValue(1), whose precondition is a creatable type. AnINpredicate keeps aSetplaceholder in the header, andINTERPOLATEpins it there by declaring every header column an input, so it survives pruning intoReadFromMergeTree.DataTypeSetoverrides bothcreateColumnandgetDefault, so the failure lands deeper, inIColumnDummy::insert.The fix reuses the header's own column, resized to one row, whenever the element carries one, falling back to
createColumnConstWithDefaultValueonly for a null-column element (ColumnWithTypeAndNamedocuments 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 wereisNotCreatable, allConst(Set), allsize() == 0). Both forms are output-identical across thevirtual_rowsuite and a 21-typeWITH FILLmatrix.Validation: reproduces deterministically on an unpatched debug build; after the fix every shape matches the
read_in_order_use_virtual_row = 0ground truth. New test04723_virtual_row_interpolate_column_setfails 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 = 0and failed at= 1before the fix; the first 8 rows are the committed test, the rest were measured locally)s IN ('8')s IN (SELECT '8')(subquery set)s NOT IN ('9')(s, s) IN (('8','8'))(tuple set)has(['8'], s)ORDER BY k DESC(reverse read)read_in_order_use_virtual_row_per_block = 1SELECT DISTINCTLowCardinality(String)columnNullable(String), incl.IN (NULL, '8')Array(String),Map(String,String)INsPREWHERE s IN ('8')