Repository navigation
Fix LOGICAL_ERROR on distributed ORDER BY WITH FILL INTERPOLATE - #111919
Conversation
… shards A distributed SELECT with ORDER BY ... WITH FILL ... INTERPOLATE over a Distributed table with two or more shards (or remote() over two addresses) threw LOGICAL_ERROR "Invalid number of rows in Chunk". For a query with ORDER BY, each shard is asked to process up to WithMergeableStateAfterAggregation(AndLimit), so on the shard both isFirstStage() and isSecondStage() are true and it ran addWithFillStepIfNeeded too. The shard then materialized the INTERPOLATE output column, and the initiator re-added the same column under the same name. FillingTransform locates interpolate columns by name, so it populated only the first of the two same-named columns and left the second one empty, producing a ragged chunk that fails the row-count check. WITH FILL must run only on the node that produces the final result, over the fully merged stream. Guard the filling step with !isToAggregationState() in the analyzer planner (and the equivalent !to_aggregation_stage in the legacy interpreter), mirroring the existing 'Project names' guard. This also fixes the per-shard duplication of WITH FILL suffix rows. Closes: #111728 Related: #111724 Related: #111547 Related: #111555 Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
|
|
Workflow [PR], commit [68b288d] Summary: ❌
AI ReviewSummaryThis PR moves Final Verdict✅ Approve |
Replace the WITH FILL guard's !isToAggregationState() check with a named PlannerQueryProcessingInfo::isFinalizingStage() (to_stage == Complete). The two are equivalent for every stage that can reach the guard (inside the isSecondStage()/isFromAggregationState() block to_stage is one of Complete, WithMergeableStateAfterAggregation or WithMergeableStateAfterAggregationAndLimit), but isFinalizingStage() states the actual invariant directly - 'this node produces the final result, over the fully merged stream' - instead of relying on the double negative over the deliberately inverted stage enum ordering (Complete = 2 is numerically smaller than the after-aggregation stages). Co-authored-by: Yakov Olkhovskiy <[email protected]>
…merge Issue #111547: ORDER BY ... WITH FILL ... INTERPOLATE over a network merge of two or more empty sorted streams built a ragged chunk (the shard materialized the INTERPOLATE output column, the initiator re-added it under the same name, and FillingTransform - which locates interpolate columns by name - left the duplicate unwritten). On an empty result the WITH FILL suffix then grew the other columns while that column stayed empty, so FillingTransform::saveLastRow read past the end of the empty column (debug-only PODArray out-of-bounds), and with two shards it already fails in release with 'Invalid number of rows in Chunk'. This is the same orphan-interpolate-column mechanism as #111728, surfacing on an empty result. The distributed WITH FILL fix in this PR removes it at the source (the shard no longer fills or materializes the interpolate column), so the block stays rectangular. This adds a dedicated regression test. Closes: #111547 Co-authored-by: Yakov Olkhovskiy <[email protected]>
…eter Address review feedback on the legacy WITH FILL guard: !to_aggregation_stage is weaker than the analyzer's isFinalizingStage() and still fires on an intermediate node whose from_stage is an after-aggregation state while to_stage is only WithMergeableState (e.g. nested Distributed under allow_experimental_analyzer = 0), which would run WITH FILL before the outer merge. Use the precise to_stage == Complete test, matching the analyzer. Also clarify the isFinalizingStage() doc: it means 'produces the complete result', and note that distributed_group_by_no_merge = 1 deliberately asks each shard for a Complete result (the initiator only concatenates, running no merge or FillingStep), so WITH FILL is applied per shard there by design. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…NTERPOLATE Strengthen coverage per review: two shards holding disjoint rows, so a per-shard WITH FILL / INTERPOLATE would fill gaps and interpolate against each shard's own neighbours (extra rows, wrong interpolated values), while the correct result fills once over the globally merged stream. Also runs a distributed_push_down_limit = 0 variant to exercise the WithMergeableStateAfterAggregation stage in addition to the default WithMergeableStateAfterAggregationAndLimit. Co-authored-by: Yakov Olkhovskiy <[email protected]>
The CI 'distributed plan' stateless shard turns serialize_query_plan on globally, and WITH FILL is not supported in serialized sort descriptions (serializeSortDescription throws NOT_IMPLEMENTED: 'WITH FILL is not supported in serialized sort description'), so 04628 and 04630 failed there. These tests exercise the shard read path, not query-plan serialization, so disable it locally in the test (04629 already did). Verified the tests pass with the client default serialize_query_plan = 1. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…OLATE Address review: the PR closes #111724 but no test exercised the custom-key parallel-replicas path (all others use Distributed/remote). Add a focused test covering both parallel_replicas_mode = 'custom_key_sampling' and 'custom_key_range', asserting the result matches the non-distributed query. Confirmed it throws the LOGICAL_ERROR ('Invalid number of rows in Chunk') on the unpatched binary and passes on the patched one, including with serialize_query_plan = 1 forced. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ted-with-fill-interpolate-110a Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address review: trim the explanatory comments on the WITH FILL / isFinalizingStage guards to one or two lines. Comment-only change, no behavior change. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address review: cover the intermediate-node stage shape (from_stage = WithMergeableStateAfterAggregation, to_stage = WithMergeableState) that the to_stage == Complete guard fixes but the top-level Distributed tests do not exercise. StorageMerge over a Distributed table triggers it. Confirmed on the unpatched binary it throws 'Invalid number of rows in Chunk' (analyzer) and duplicates the fill rows once per node (old analyzer), while the patched binary returns the correct result on both analyzers. Co-authored-by: Yakov Olkhovskiy <[email protected]>
StorageMerge over Distributed does not guarantee a stable global row order across configurations, so the previous reference (one specific interleaving) was flaky in CI. Wrap the WITH FILL query in an outer ORDER BY g, id so the reference is deterministic; the bug still shows as a different multiset (per-node filling yields 12 rows instead of 10) or the logical error, both independent of order. Verified: patched binary returns the 10-row reference under different prefer_localhost_replica settings; unpatched binary still throws (analyzer) or returns 12 rows (old analyzer). Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ted-with-fill-interpolate-110a Co-authored-by: Yakov Olkhovskiy <[email protected]>
Per follow-up on #111728: the distributed WITH FILL INTERPOLATE duplicate-column bug also manifests via clusterAllReplicas, where under libc++ hardening / TSan the duplicate interpolate column causes an out-of-bounds abort in FillingTransform::insertFromFillingRow (not just 'Invalid number of rows in Chunk'), with a single INTERPOLATE target. The existing tests use remote()/Distributed/custom-key/StorageMerge but not clusterAllReplicas, so add that shape. Wrapped in an outer ORDER BY a, c for a deterministic reference. Confirmed it throws (analyzer) / returns 12 rows instead of 8 (old analyzer) on the unpatched binary and passes on the patched one. Co-authored-by: Yakov Olkhovskiy <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code |
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.
Closes: #111728
Closes: #111724
Closes: #111547
Related: #111555
A
SELECT ... ORDER BY ... WITH FILL ... INTERPOLATE (...)over aDistributedtable with two or more shards (orremote()over two addresses) failed withLOGICAL_ERROR"Invalid number of rows in Chunk", at default settings and on non-empty results.Root cause
For a query with
ORDER BY, each shard is asked to process up toWithMergeableStateAfterAggregation(AndLimit). On such a shard bothisFirstStage()andisSecondStage()are true, so the shard also ranaddWithFillStepIfNeeded— it applied theFillingStepand materialized theINTERPOLATEoutput column. The initiator then re-added the same interpolate output column under the same name.FillingTransformlocates interpolate columns by name (getPositionByName), so it populated only the first of the two same-named columns and left the second one empty, producing a ragged chunk (e.g.... UInt32(size = 12), UInt32(size = 0)) that fails the row-count check.Depending on where the duplicate column lands the same duplicate-header can also surface as an out-of-bounds abort in
FillingTransform::insertFromFillingRowunder libc++ hardening / TSan (it bounds the loop byinterpolate_block.columns()but indexesinterpolate_columns, sized viagetPositionByName, which collapses both entries to one slot) — a singleINTERPOLATEtarget is enough. Same root cause; see theclusterAllReplicasfollow-up on #111728.The same orphan-column mechanism also caused:
FillingTransform::saveLastRow(PODArray out-of-bounds) onWITH FILL ... INTERPOLATEover a distributed/merged empty result #111547 — on an empty distributed result theWITH FILL FROM..TOsuffix grows every column except the orphaned interpolate column, soFillingTransform::saveLastRowreads past the end of the empty column (a debug-only PODArray out-of-bounds; with two shards it already fails in release with the same "Invalid number of rows in Chunk").WITH FILL/INTERPOLATEare order-dependent finalization operators: gaps are only meaningful over the globally merged sorted stream, andINTERPOLATE's "previous row" must be the global predecessor. They must run once, on the finalizing node, never per shard/replica.Fix
Apply
WITH FILL(and itsINTERPOLATE) only on the node that produces the complete result. The filling step is guarded with a newPlannerQueryProcessingInfo::isFinalizingStage()(to_stage == QueryProcessingStage::Complete) in the analyzer planner (Planner.cpp), and with the equivalentto_stage == QueryProcessingStage::Completein the legacy interpreter (InterpreterSelectQuery.cpp). A shard emitting a mergeable-after-aggregation state now stops at the sorted stream, and the initiator does the single merge +Before INTERPOLATE+FillingStep, matching the local plan — so the duplicate/orphan interpolate column never forms, removing both the logical error and the hardening abort at their source.isFinalizingStage()/to_stage == Completestates the intended invariant directly ("this node produces the complete result, over the fully merged stream") instead of the double negative!isToAggregationState()over the deliberately inverted stage-enum ordering (Complete = 2is numerically smaller than the after-aggregation stages3/4), and — unlike!to_aggregation_stage— it does not fire on an intermediate node whosefrom_stageis an after-aggregation state whileto_stageis onlyWithMergeableState(nestedDistributed/StorageMergeoverDistributed).distributed_group_by_no_merge = 1is intentionally unchanged: in that mode each shard is deliberately asked for aCompleteresult and the initiator only concatenates (it runs no merge and noFillingStep), soWITH FILLis applied per shard there by design — excluding it would dropWITH FILLentirely.Scope note on #111555
#111555 has two halves:
WITH FILLandLIMIT n BYboth applied per replica under custom-key parallel replicas. This PR fixes theWITH FILLhalf (verified: fill rows are no longer multiplied by the replica/shard count). TheLIMIT BYhalf is a distinct transform with its own preliminary-vs-final stage handling and is left for a follow-up, so #111555 is listed as Related, not closed.Verification
Built ClickHouse from this branch and confirmed against a running server (2-shard
remote/Distributed, distinct-shardtest_cluster_two_shards_different_databases,StorageMergeoverDistributed,clusterAllReplicas, and a 3-replica custom-key parallel-replicas cluster). On the unpatched binary each reproducer errors/aborts (or duplicates fill rows on the old analyzer); on the patched binary all return the correct result.EXPLAINno longer shows the duplicate interpolate column. No regressions on local, single-shardremote, or plain distributedORDER BY … LIMITpushdown. Both the analyzer and the legacy (allow_experimental_analyzer = 0) interpreters are correct.Tests
04628_distributed_with_fill_interpolate.sql—WITH FILL INTERPOLATEover two shards (previously threw), plus a check thatWITH FILLwithoutINTERPOLATEno longer duplicates the fill suffix per shard.04629_with_fill_interpolate_empty_distributed.sql— the Logical error inFillingTransform::saveLastRow(PODArray out-of-bounds) onWITH FILL ... INTERPOLATEover a distributed/merged empty result #111547 empty-distributed-merge reproducer.04630_distributed_with_fill_interpolate_distinct_shards.sql— two shards with disjoint rows, also covering theWithMergeableStateAfterAggregationstage viadistributed_push_down_limit = 0.04631_parallel_replicas_custom_key_with_fill_interpolate.sql— the Custom-key parallel replicas + WITH FILL INTERPOLATE: LOGICAL_ERROR "Invalid number of rows in Chunk" — INTERPOLATE column arrives empty #111724 custom-key parallel-replicas path (bothcustom_key_samplingandcustom_key_range).04648_nested_distributed_with_fill_interpolate.sql—StorageMergeover aDistributedtable (intermediate-node stage shape); reproduces as a crash on the planner path and duplicated fill rows on the old-analyzer path.04652_cluster_all_replicas_with_fill_interpolate.sql—clusterAllReplicas+INTERPOLATE, the shape that triggers theinsertFromFillingRowout-of-bounds abort under hardening (single INTERPOLATE target).Order-sensitive nested/replica cases wrap the
WITH FILLquery in an outerORDER BYso the reference is deterministic; the bug still shows through as a different multiset or the logical error/abort. All tests setserialize_query_plan = 0where needed (WITH FILLis not serializable in a sort description; custom-key parallel replicas rejects the setting; the CIdistributed planshard forces it on). Confirmed the tests fail on the unpatched binary and pass on the patched one.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
LOGICAL_ERROR("Invalid number of rows in Chunk") — and, under hardened builds, a related out-of-bounds abort — forORDER BY ... WITH FILL ... INTERPOLATEover aDistributedtable with two or more shards, overclusterAllReplicas, or over custom-key parallel replicas, including on empty results.WITH FILLis now applied only on the node producing the final result, which also fixes duplication of the generated fill rows across shards/replicas.Version info
26.8.1.426(included in26.8and later)