Repository navigation
Do not propagate read-in-order through PartialMergeJoin - #110671
alexey-milovidov merged 4 commits into
Conversation
PartialMergeJoin re-sorts left blocks by the join key (once per right block), so it does not preserve the left stream's original order. The read-in-order-through-join optimisation in optimizeReadInOrder.cpp was propagating the left table's sorting-key order through it, so Aggregating/Distinct-in-order then consumed a stream they wrongly believed was sorted by the group/distinct key and mis-grouped rows. Gate the propagation on a new IJoin::preservesLeftBlockOrder() (default true), overridden to false in MergeJoin (PartialMergeJoin) and in JoinSwitcher, which can switch to PartialMergeJoin at runtime. Fixes both the swapped and non-swapped paths, and the DISTINCT-in-order variant. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260716-101500 |
|
cc @vdimir @novikd — could you review this? It stops the read-in-order-through-join optimization from propagating the left table's sorting-key order through |
|
Workflow [PR], commit [19d6b8c] Summary: ✅
AI ReviewSummaryThis PR now correctly stops Final Verdict
|
topKThroughJoin defers to optimizeReadInOrder's second pass only when that pass can actually stream read-in-order through the join. The deferral gate already rejected reordering/delayed-block joins (grace, spilling), but not partial_merge / prefer_partial_merge, which build a PartialMergeJoin that re-sorts left blocks by the join key. Since the PR now rejects such joins in the second pass via IJoin::preservesLeftBlockOrder(), an explicit join_algorithm = 'partial_merge' with ORDER BY <preserved-side key> LIMIT n took the deferral path and then lost BOTH optimizations. Mirror the preservesLeftBlockOrder() contract in second_pass_can_apply so the deferral fires only for order-preserving joins; otherwise topKThroughJoin injects its own Sort + Limit. Cover it with the partial_merge variant of 04209_top_k_through_join_read_in_order_gate.sql. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Done in 5d859b9. The deferral gate now mirrors the order-preservation contract: added Covered by a |
full_sorting_merge builds a FullSortingMergeJoin. It preserves left block order, but its physicalization inserts a Sort before JOIN on the preserved input (addSortingForMergeJoin), and optimizeReadInOrder's findReadingStep does not descend through a SortingStep, so read-in-order is never installed. As with partial_merge, deferring to the second pass would silently disable both topKThroughJoin and read-in-order for explicit full_sorting_merge queries with ORDER BY <preserved-side key> LIMIT n. Generalize joinMayNotPreserveLeftBlockOrder into joinDefeatsReadInOrderThroughJoin, which also flags FULL_SORTING_MERGE (logical) and FullSortingMergeJoin (physical). Add the full_sorting_merge EXPLAIN and result-equivalence variants to 04209_top_k_through_join_read_in_order_gate. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed in 45e9ace. Extended the deferral gate to reject full_sorting_merge as well. Mechanism differs from partial_merge: FullSortingMergeJoin preserves left block order (preservesLeftBlockOrder() == true), so the existing check does not catch it. But its physicalization inserts a Renamed the helper to joinDefeatsReadInOrderThroughJoin and generalized it: physical branch flags !preservesLeftBlockOrder() OR FullSortingMergeJoin; logical branch flags PARTIAL_MERGE / PREFER_PARTIAL_MERGE / FULL_SORTING_MERGE. Verified via clickhouse-local (EXPLAIN gate on 04209):
Added the full_sorting_merge EXPLAIN + result-equivalence variants to 04209_top_k_through_join_read_in_order_gate. |
CI finish ledger — 45e9aceEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260717-003000 |
CI finish ledger — 45e9aceEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260717-070000 |
|
Fixing PR for the `test_keeper_zookeeper_converter::test_multi_and_failed_requests[True]` flaky failure: #110631 (merged 2026-07-16 15:00 UTC, "Fix flaky genuine ZooKeeper startup in test_keeper_zookeeper_converter"). That check failed because this branch (45e9ace) was forked before #110631 merged, so the run predates the fix. Root cause: |
… left key Strengthens the 04500 regression with @ zlareb1's reported shape: uniqExact(l.k) within GROUP BY l.k must equal 1 for every group. Directly detects mis-grouping on the non-swap (query_plan_join_swap_table='false') path without relying on an ordered reference. Issue ClickHouse#110662. Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 32/38 (84.21%) · Uncovered code |
CI finish ledger - 19d6b8cCI fully finished on this head (Config Workflow = SUCCESS, Finish Workflow = SUCCESS, Mergeable Check = SUCCESS; 0 checks queued/in_progress; >20-min ingest buffer elapsed). CIDB shows ZERO failing tests for this commit (the strengthened zlareb1 plain-LEFT regression case is green).
All checks green except the private CH Inc sync (exempt). No PR-caused failure. Session id: cron:our-pr-ci-monitor:20260718-003000 |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRDo not propagate read-in-order through PartialMergeJoin ClickGap verified: reproduced it with the script below on ReproductionCREATE TABLE l (k Int32, j Int32) ENGINE = MergeTree ORDER BY k;
CREATE TABLE r (j Int32) ENGINE = MergeTree ORDER BY j;
INSERT INTO l SELECT number % 50, number % 5 FROM numbers(4000);
INSERT INTO r SELECT number % 4 FROM numbers(3000);
-- Correct result is `1\t1\t50`; before the fix max(u) > 1 (rows mis-grouped
-- because read-in-order is wrongly propagated through PartialMergeJoin).
SELECT max(u), min(u), count() FROM (
SELECT l.k, uniqExact(l.k) AS u FROM l LEFT JOIN r ON l.j = r.j GROUP BY l.k
)
SETTINGS join_algorithm = 'partial_merge', optimize_aggregation_in_order = 1, max_threads = 1;Bisect
Affects
Suggested next stepThe bug reproduces as far back as the oldest tested release ( Component: cc fix PR author: @groeneai ClickGap · Finding: Triage metadata
|
|
Hi — could this be a backport candidate for Affected code: Why this might apply: Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider |
Follow-up to #110671. The existing test covers the aggregation-in-order and distinct-in-order read-in-order consumers through PartialMergeJoin, but not the plain top-level ORDER BY consumer reported on #110662 as a no-aggregation manifestation of the same bug (the ORDER BY was elided because the plan wrongly trusted the partial_merge join output to be sorted by the left key). The new case is self-checking: the 1:1 self-join over keys 0..499 must emit range(500) when correctly sorted. It returns 0 on the pre-fix binary and 1 on fixed master. The read-in-order planner gates are pinned on so the defective path is always exercised; otherwise a run that randomizes them off would sort correctly and pass without testing the fix. Related: #110662 Related: #110671 Co-Authored-By: Claude Opus 4.8 <[email protected]>
The master merge in 58472f0 resolved src/Interpreters/IJoin.h by keeping both declarations of the same virtual: the one that came in from master with ClickHouse#110671 (default true) and this branch's fail-closed one (default false). That is a redeclaration of a class member, so every translation unit that reaches IJoin.h failed to compile: src/Interpreters/IJoin.h:187:18: error: class member cannot be redeclared src/Interpreters/IJoin.h:153:18: note: previous definition is here Fast test and Build (arm_tidy) stopped at Dictionaries/DictionaryFactory.cpp.o (reached via IDictionary.h -> JoinUtils.h -> IJoin.h) and every other job was dropped. Drop the inherited default and keep the fail-closed one, which is what this branch generalizes ClickHouse#110671 to: a join advertises left-block-order preservation only by opting in. The opt-ins (HashJoin, DirectKeyValueJoin, PasteJoin, ConcurrentHashJoin when it does not scatter) and the explicit false overrides that master kept on MergeJoin and JoinSwitcher are unchanged, so the resolved behaviour is identical to this branch before the merge. Also remove the two comment fragments the merge left stranded next to unrelated declarations: the doc comment for preservesLeftBlockOrder ended up above MergeJoin::addBlockToJoin, and the IJoin doc text now describes the actual opt-in set instead of implying MergeJoin and JoinSwitcher rely on the default.
The comment claimed the partial_merge assertion returned 1 before the fix. Measured on a current master build, which already contains ClickHouse#110671, it returns 0, so that shape is no longer the one this PR changes. Described as the coverage guard it actually is.
Follow-up to ClickHouse#110671. The existing test covers the aggregation-in-order and distinct-in-order read-in-order consumers through PartialMergeJoin, but not the plain top-level ORDER BY consumer reported on ClickHouse#110662 as a no-aggregation manifestation of the same bug (the ORDER BY was elided because the plan wrongly trusted the partial_merge join output to be sorted by the left key). The new case is self-checking: the 1:1 self-join over keys 0..499 must emit range(500) when correctly sorted. It returns 0 on the pre-fix binary and 1 on fixed master. The read-in-order planner gates are pinned on so the defective path is always exercised; otherwise a run that randomizes them off would sort correctly and pass without testing the fix. Related: ClickHouse#110662 Related: ClickHouse#110671 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…partial-merge-join-110662 Do not propagate read-in-order through PartialMergeJoin
Closes: #110662
Related: #109216
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results from
GROUP BY ... optimize_aggregation_in_orderandDISTINCT ... optimize_distinct_in_orderplaced over apartial_mergeJOIN. The read-in-order optimization was propagated throughPartialMergeJoin, which re-sorts its left input by the join key and therefore does not preserve the left stream's original order, so rows were grouped incorrectly.Description
PartialMergeJoinre-sorts left blocks by the join key (once per right block), so it does not preserve the left stream's original sorting-key order. The read-in-order-through-join optimization inoptimizeReadInOrder.cpppropagated the left table's sorting-key order through the join anyway.Aggregating/DistinctSortedStreamTransform(in-order) then consumed a stream they wrongly believed was sorted by the group/distinct key and mis-grouped rows.Fix: gate the propagation on a new
IJoin::preservesLeftBlockOrder()(defaulttrue), overridden tofalseinMergeJoin(PartialMergeJoin) and inJoinSwitcher(which can switch toPartialMergeJoinat runtime, so the plan-time decision must be conservative).HashJoin/DirectJoin/ConcurrentHashJoinstream the probe side and keep the order, so they are unaffected;GraceHashJoin/SpillingHashJoinwere already excluded viahasDelayedBlocks().Reproducer from #110662 (returned 3 mis-grouped rows, now returns the correct 10):
The bug is not swap-specific: a plain
LEFT JOINwithjoin_algorithm='partial_merge'+optimize_aggregation_in_order=1was equally wrong. The same defect family withoptimize_distinct_in_orderis #109216. Added04500_read_in_order_through_partial_merge_joincovering the swapped, non-swapped, and DISTINCT-in-order cases, and asserting the leftReadFromMergeTreeno longer reads in order.Version info
26.7.1.1171(included in26.7and later)