Repository navigation
Fix wrong results and a crash in partial merge join with totals - #113936
alexey-milovidov merged 2 commits into
Conversation
MergeJoin finalized its entire right side as a side effect of setTotals(): that method called mergeRightBlocks() (its only caller in src/) and allocated used_rows_bitmap. Its comment, "Has to be called even if totals are empty", documented how fragile that coupling was. FillingRightJoinSideTransform::prepare only reaches setTotals() through two else-if chained branches: pull a chunk from the totals port, or, when there is no totals port at all, synthesize an empty totals block. A totals port that exists but delivers zero chunks satisfies neither, so prepare falls through with setTotals() never called. RemoteTotalsSource::generate() returns an empty chunk when a remote sends no totals, and it is attached exactly when the port is created, so the state is reachable rather than hypothetical. Finalization being skipped leaves three states wrong at once. loaded_right_blocks is empty, so the probe sees zero right blocks and drops every right row; min_max_right_blocks is empty; and used_rows_bitmap is null. LEFT joins therefore emit default values instead of real matches, INNER and RIGHT joins return no rows, and the RIGHT/FULL ALL non-joined path dereferences the null bitmap in NotJoinedMerge::fillColumns, which UBSan reports as a null reference binding to DB::RowBitmaps and which crashes a build without a sanitizer. Finalize on the post build phase instead. FillingRightJoinSideTransform always reaches it: prepare calls onBuildPhaseFinish() after both totals branches and, when the join reports hasPostBuildPhase(), returns Ready so the executor runs runPostBuildPhase() from work(). That strictly dominates setTotals() in reachability, and work() is also the correct context for this body, because mergeRightBlocks() drives a nested pipeline (a MergeSortingTransform over the whole right side, or SortedBlocksWriter::finishMerge for a spilled one) and IProcessor documents prepare as O(1) work only, run under the executor's graph scheduling lock. This is the same seam HashJoin uses for its own heavy build steps in runPostBuildPhase(), so no sibling does long work in the hook itself. Ordering is preserved: prepare sets post_build_phase and returns Ready without finishing its output, so the output is only finished on the following prepare, and JoiningTransform cannot build the non-joined stream until that input is finished. Measured on the in-memory, spilled, JoinSwitcher and RIGHT paths, finalization completes before the non-joined stream is constructed, exactly once per query, and not at all for a query without a join. setTotals() keeps its IJoin part, so totals results are unchanged. This fixes the wrong-results and the crash halves with one change, and removes an outlier rather than adding a mechanism. Closes ClickHouse#109637
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings this round, plus 7 from
Severity: ❌ blocker / One note for whoever reviews this: pull request 110892 edits the exact block this change relocates, Session id: cron:clickhouse-review-slot-8:20260808-080002 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260808-070200 |
|
cc @KochetovNicolai @yariks5s, could you review this? |
|
Workflow [PR], commit [6883f7e] Summary: ✅
AI ReviewSummaryThis PR moves Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 56/58 (96.55%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units
|
CI finish ledger - 18fe490CI is fully finished on this head: 175 check runs, 0 queued or in progress. Every failure below has an owner.
Session id: cron:our-pr-ci-monitor:20260808-230000 |
`Bugfix validation` reported that `04821_partial_merge_join_build_finalization` passes on the merge-base binary on both arches, so no per-arch validation was recorded and the `Finish Workflow` post-hook (`new_tests_check.py`) reddened. That report is correct: every shape 04821 can express delivers its totals chunk, because `TotalsHavingTransform::prepare` pushes it unconditionally, so 04821 pins the fix as a guard rather than reproducing the bug. The missing ingredient is a totals port that exists and delivers nothing. The `remote_query_executor_cancel_before_send` fail point already produces exactly that: it sets `was_cancelled` before the query is sent, so the shard never sends a Totals packet while `right->hasTotals` has already created the port in `QueryPipelineBuilder`. That is the same state `RemoteTotalsSource::generate` reaches when a remote sends no totals, so the test needs no fault injection and uses only master's own machinery. `04151_remote_query_executor_cancel_null_connections` uses this fail point the same way, including the `no-parallel` tag, which this test needs for the same reason. The reproduction is defined by absences, so the test asserts its ingredients instead of assuming them. The join and its settings live in a view, so the assertions and the query that reproduces the bug are the same SQL by construction: the plan must report `Algorithm: PartialMergeJoin` and `FillingRightJoinSide` must have two inputs, which happens only when the right pipeline has totals. The join result is printed rather than discarded, since `8 0` means the shard was cancelled while `8 8` would mean the right rows arrived and the starved path was never taken. The once-only fail point is asserted to have disabled itself, which is what proves the injection was consumed, and the timeout throws so a truncated execution cannot read as success. Measured on the pristine master asan_ubsan snapshot: red in 3 of 3 restart cycles, symbolized frame-for-frame to the CI stack. Fixed binary: green in 20 of 20 fresh databases, no fail point left enabled. Mutants on the fixed binary, each reddening a different arm: dropping `WITH TOTALS` from the view, dropping `join_algorithm`, and dropping `SYSTEM ENABLE FAILPOINT`. 04821's spilled-right-side arm produces the same result as the in-memory arm above it, so removing its `max_rows_in_join` left it green while covering nothing. It now asserts `ProfileEvents['ExternalJoinWritePart']` through a `log_comment`, following `04546_constant_join_spill_non_joined`, and dropping the spill trigger reddens it. Also retargets 04821's leading comment, which still named the old hook, and writes literal names in the touched comments as inline code per `.claude/CLAUDE.md`.
Bugfix validation was right: the regression test did not reproduce the bug
The reason is structural. Pushed Because the reproduction is defined by absences, the test asserts its ingredients rather than Measured on a pristine master One more thing this turned up: 04821's spilled-right-side arm produced the same output as the The other red check on the previous head, |
CI finish ledger - 6883f7eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 175 check-runs, 0 queued/in_progress,
The previously ledgered Session id: cron:our-pr-ci-monitor:20260809-080000 |
Closes: #109637
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results in
JOINwithjoin_algorithm = 'partial_merge'when the right side carries totals: the right side could be left unmerged, soLEFTjoins substituted default values for real matches andINNER/RIGHTjoins returned no rows at all. In theRIGHT/FULLnon-joined path the same state dereferenced a null pointer, which crashed the server.Description
MergeJoinfinalized its whole right side as a side effect ofsetTotals(): that methodcalled
mergeRightBlocks()and allocatedused_rows_bitmap, and its comment ("Has to becalled even if totals are empty") documented the fragility.
FillingRightJoinSideTransform::prepareonly callssetTotals()when it pulls a chunk fromthe totals port, or, when there is no totals port, through the synthesized-empty-totals branch.
Those two branches are chained by
else if, so a totals port that exists but delivers zerochunks reaches neither, and
setTotals()never runs.RemoteTotalsSource::generate()returnsan empty chunk when a remote sends no totals, and it is attached exactly when the port is
created, so the state is reachable rather than hypothetical.
With finalization skipped, three things are wrong at once:
loaded_right_blocksis empty (theprobe sees zero right blocks and drops every right row),
min_max_right_blocksis empty, andused_rows_bitmapis null.LEFTtherefore emits defaults instead of matches,INNER/RIGHTreturn nothing, and
FULL/RIGHT ALLdereference the null bitmap inNotJoinedMerge::fillColumns, which UBSan reports asreference binding to null pointer of type 'DB::RowBitmaps'.The fix finalizes the right side on the post build phase instead.
preparecallsonBuildPhaseFinish()after both totals branches and, when the join reportshasPostBuildPhase(), returnsReadyso the executor runsrunPostBuildPhase()fromwork().That strictly dominates
setTotals()in reachability, andwork()is the correct context forthis body:
mergeRightBlocks()drives a nested pipeline, whileIProcessordocumentsprepareas O(1) work only.
HashJoinuses the same seam for its own heavy build steps inrunPostBuildPhase().setTotals()keeps itsIJoinpart, so totals results are unchanged.Validation
Both directions on ASAN+UBSan builds, with the totals port starved:
shared_ptr.h:574:12: runtime error: reference binding to null pointer of type 'element_type' (aka 'DB::RowBitmaps'), symbolized stackoperator*->NotJoinedMerge::fillColumns->NotJoinedBlocks::nextImpl->IBlocksStream::next->JoiningTransform::work, matching the CI report frame for frame.LEFTreturned0 0 | 1 0 | 2 0 | 3 0 | 4 0and
INNER/RIGHTreturned no rows, wherehashreturns0 0 | 1 1 | 2 2 | 3 3 | 4 4.hashexactly.New gtest
MergeJoinStarvedTotals.FullJoinKeepsRightRowswires the starved-totals state atprocessor level and asserts the join result: on code byte-identical to unmodified master it
fails, losing every right value and the right-only key, and it passes on the fix. New stateless
test
04821_partial_merge_join_build_finalizationis a regression guard that assertspartial_mergeequalshashforINNER/LEFT/RIGHT/FULLover a right side with totals,including non-joined right rows, a spilled right side and a right-only totals column. Mutants
confirm each half is pinned independently: dropping
mergeRightBlocks()reddens the resultrows, dropping the bitmap allocation crashes the server, and making
setTotals()a no-opreddens only the totals arm. 50/50 randomized runs pass. A 349-test join/totals regression run
against pristine master gives identical failure sets and identical reason buckets, so there are
no regressions. Finalization is measured to run exactly once per query, and to complete before
the non-joined stream is constructed, on the in-memory, spilled,
JoinSwitcherandRIGHTpaths.
Version info
26.8.1.1539(included in26.8and later)