Skip to content

Fix LOGICAL_ERROR on distributed ORDER BY WITH FILL INTERPOLATE - #111919

Merged
yakov-olkhovskiy merged 13 commits into
masterfrom
cursor/fix-distributed-with-fill-interpolate-110a
Jul 30, 2026
Merged

yakov-olkhovskiy merged 13 commits into
masterfrom
cursor/fix-distributed-with-fill-interpolate-110a

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Closes: #111728
Closes: #111724
Closes: #111547
Related: #111555

A SELECT ... ORDER BY ... WITH FILL ... INTERPOLATE (...) over a Distributed table with two or more shards (or remote() over two addresses) failed with LOGICAL_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 to WithMergeableStateAfterAggregation(AndLimit). On such a shard both isFirstStage() and isSecondStage() are true, so the shard also ran addWithFillStepIfNeeded — it applied the FillingStep and materialized the INTERPOLATE output column. The initiator then re-added the same interpolate output column under the same name. FillingTransform locates 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::insertFromFillingRow under libc++ hardening / TSan (it bounds the loop by interpolate_block.columns() but indexes interpolate_columns, sized via getPositionByName, which collapses both entries to one slot) — a single INTERPOLATE target is enough. Same root cause; see the clusterAllReplicas follow-up on #111728.

The same orphan-column mechanism also caused:

WITH FILL/INTERPOLATE are order-dependent finalization operators: gaps are only meaningful over the globally merged sorted stream, and INTERPOLATE'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 its INTERPOLATE) only on the node that produces the complete result. The filling step is guarded with a new PlannerQueryProcessingInfo::isFinalizingStage() (to_stage == QueryProcessingStage::Complete) in the analyzer planner (Planner.cpp), and with the equivalent to_stage == QueryProcessingStage::Complete in 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 == Complete states 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 = 2 is numerically smaller than the after-aggregation stages 3/4), and — unlike !to_aggregation_stage — it does not fire on an intermediate node whose from_stage is an after-aggregation state while to_stage is only WithMergeableState (nested Distributed / StorageMerge over Distributed).

distributed_group_by_no_merge = 1 is intentionally unchanged: in that mode each shard is deliberately asked for a Complete result and the initiator only concatenates (it runs no merge and no FillingStep), so WITH FILL is applied per shard there by design — excluding it would drop WITH FILL entirely.

Scope note on #111555

#111555 has two halves: WITH FILL and LIMIT n BY both applied per replica under custom-key parallel replicas. This PR fixes the WITH FILL half (verified: fill rows are no longer multiplied by the replica/shard count). The LIMIT BY half 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-shard test_cluster_two_shards_different_databases, StorageMerge over Distributed, 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. EXPLAIN no longer shows the duplicate interpolate column. No regressions on local, single-shard remote, or plain distributed ORDER BY … LIMIT pushdown. Both the analyzer and the legacy (allow_experimental_analyzer = 0) interpreters are correct.

Tests

Order-sensitive nested/replica cases wrap the WITH FILL query in an outer ORDER BY so the reference is deterministic; the bug still shows through as a different multiset or the logical error/abort. All tests set serialize_query_plan = 0 where needed (WITH FILL is not serializable in a sort description; custom-key parallel replicas rejects the setting; the CI distributed plan shard forces it on). Confirmed the tests fail on the unpatched binary and pass on the patched one.

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 a LOGICAL_ERROR ("Invalid number of rows in Chunk") — and, under hardened builds, a related out-of-bounds abort — for ORDER BY ... WITH FILL ... INTERPOLATE over a Distributed table with two or more shards, over clusterAllReplicas, or over custom-key parallel replicas, including on empty results. WITH FILL is now applied only on the node producing the final result, which also fixes duplication of the generated fill rows across shards/replicas.

Open in Web Open in Cursor 

Version info

  • Merged into: 26.8.1.426 (included in 26.8 and later)

… 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]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [68b288d]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-36d8) FAIL cidb

AI Review

Summary

This PR moves ORDER BY ... WITH FILL / INTERPOLATE to the finalizing node for distributed and parallel-replica reads, and adds focused regressions for the failing Distributed, nested StorageMerge, custom-key parallel-replicas, empty-result, and clusterAllReplicas shapes. I checked the current diff, the existing review threads and replies, and the relevant stage-selection paths in the planner, legacy interpreter, StorageDistributed, StorageMerge, and IStorageCluster; the current code matches the intended contract, and I did not find a new actionable issue.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 25, 2026
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]>
cursoragent and others added 3 commits July 26, 2026 00:46
…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]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review July 26, 2026 12:41
…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]>
Comment thread src/Planner/Planner.cpp Resolved
cursoragent and others added 2 commits July 27, 2026 11:32
…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]>
cursoragent and others added 3 commits July 29, 2026 04:35
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.50% -0.10%

Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code

Full report · Diff report

@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Jul 30, 2026
Merged via the queue into master with commit d30efb3 Jul 30, 2026
177 of 179 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the cursor/fix-distributed-with-fill-interpolate-110a branch July 30, 2026 12:57
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 4, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment