Skip to content

Fix wrong results and a crash in partial merge join with totals - #113936

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-mergejoin-build-finalization
Aug 17, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-mergejoin-build-finalization

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109637

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):

Fix wrong results in JOIN with join_algorithm = 'partial_merge' when the right side carries totals: the right side could be left unmerged, so LEFT joins substituted default values for real matches and INNER/RIGHT joins returned no rows at all. In the RIGHT/FULL non-joined path the same state dereferenced a null pointer, which crashed the server.

Description

MergeJoin finalized its whole right side as a side effect of setTotals(): that method
called mergeRightBlocks() and allocated used_rows_bitmap, and its comment ("Has to be
called even if totals are empty") documented the fragility.

FillingRightJoinSideTransform::prepare only calls setTotals() when it pulls a chunk from
the 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 zero
chunks
reaches neither, and setTotals() never runs. 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.

With finalization skipped, three things are wrong at once: loaded_right_blocks is empty (the
probe sees zero right blocks and drops every right row), min_max_right_blocks is empty, and
used_rows_bitmap is null. LEFT therefore emits defaults instead of matches, INNER/RIGHT
return nothing, and FULL/RIGHT ALL dereference the null bitmap in
NotJoinedMerge::fillColumns, which UBSan reports as reference binding to null pointer of type 'DB::RowBitmaps'.

The fix finalizes the right side on the post build phase instead. 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 the correct context for
this body: mergeRightBlocks() drives a nested pipeline, while IProcessor documents prepare
as O(1) work only. HashJoin uses the same seam for its own heavy build steps in
runPostBuildPhase(). setTotals() keeps its IJoin part, so totals results are unchanged.

Validation

Both directions on ASAN+UBSan builds, with the totals port starved:

  • pre-fix: shared_ptr.h:574:12: runtime error: reference binding to null pointer of type 'element_type' (aka 'DB::RowBitmaps'), symbolized stack operator* ->
    NotJoinedMerge::fillColumns -> NotJoinedBlocks::nextImpl -> IBlocksStream::next ->
    JoiningTransform::work, matching the CI report frame for frame.
  • pre-fix wrong results on the same query: LEFT returned 0 0 | 1 0 | 2 0 | 3 0 | 4 0
    and INNER/RIGHT returned no rows, where hash returns 0 0 | 1 1 | 2 2 | 3 3 | 4 4.
  • post-fix: no sanitizer report, and all four join kinds match hash exactly.

New gtest MergeJoinStarvedTotals.FullJoinKeepsRightRows wires the starved-totals state at
processor 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_finalization is a regression guard that asserts
partial_merge equals hash for INNER/LEFT/RIGHT/FULL over 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 result
rows, dropping the bitmap allocation crashes the server, and making setTotals() a no-op
reddens 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, JoinSwitcher and RIGHT
paths.

Version info

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

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
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
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
my own cold review; 1 fix round + 1 delta recheck). My cold review was done without reading the
implementation notes, and the gate ran as a delta re-review against the previous round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description named the wrong hook: it said finalization moves onto onBuildPhaseFinish, and that this was the last join not overriding it AGREE, fixed before publication The change overrides hasPostBuildPhase/runPostBuildPhase and overrides onBuildPhaseFinish nowhere. On the hook actually overridden there are three overriders (HashJoin, JoinSwitcher as a forward, and this one), not "all of them": ConcurrentHashJoin, GraceHashJoin and SpillingHashJoin override onBuildPhaseFinish only. Description rewritten to name the post build phase and the prepare to work chain; the sibling count is gone
2 ⚠️ The description cited HashJoin::onBuildPhaseFinish as the precedent AGREE, fixed before publication That is the cheap bookkeeping half. The heavy half that runs from work is HashJoin::runPostBuildPhase, which is the seam this change uses, and IProcessor documents prepare as O(1) work only. Description now cites runPostBuildPhase
3 ⚠️ The Closes reference would not have linked or closed the issue AGREE, fixed before publication It sat inside the template's HTML comment, and the copy in the changelog entry was inside a code span; GitHub parses neither. Measured over 600 recent pull requests in this repository: 7 carry a real closing keyword only inside a comment or code span and 0 of those 7 link an issue, against 33 of 35 for the plain-text control. The reference is now plain text
4 💡 The regression test's opening comment still says the right side is finalized on the build-phase-finish hook AGREE, noted Accurate finding: the shipped mechanism is the post build phase. It is the only line in the change carrying that wording; the description, the commit message and the source comment all describe the shipped mechanism. Left for a follow-up push rather than another round, since no assertion depends on it
5 💡 New comments spell functions as f() where this repository's convention is f AGREE, noted Correct per .claude/CLAUDE.md; seven added comment lines are affected. Prose only, no behavioural effect, so it is recorded here rather than spent as a round
6 💡 The changelog category should be Critical Bug Fix because a crash is described DISAGREE I do not select that category on my own judgment; it is for a maintainer to request, and I will switch it immediately if you ask. It is also not the convention for this class: of 300 recently merged pull requests whose body describes a crash and picks a bug-fix category, 12 chose Bug Fix and 7 chose Critical Bug Fix
7 💡 Own review: are the carriers of this invariant complete? DISAGREE, no gap found Enumerated independently. All three construction sites reach the pipeline through the same transform; JoinSwitcher already forwards both new methods, so the runtime hash-to-partial-merge switch is covered and is exercised by a test; the parallel non-joined path cannot be reached because this join does not support it; the join-by-layers path clones through a method this join does not implement; and the paired-pipeline path rejects a side carrying totals outright
8 💡 Own review: is finalization idempotent and correctly ordered? DISAGREE, both hold mergeRightBlocks is not idempotent, but the branch sits behind a counter that is true for exactly one caller, and the next prepare short-circuits. Ordering holds because prepare returns Ready without finishing its output, and the probe side cannot build the non-joined stream until that input is finished
9 💡 Own review: would the new tests fail if the fix were reverted? DISAGREE, they would The unit test asserts an exact result set including a right-only key that only the non-joined path can produce, and it was measured failing on code identical to unmodified master. The stateless test compares partial_merge against hash on every query rather than against a constant, and its countIf column reads zero on an unmerged right side
10 💡 Own review: comment-to-code ratio on the source diff DISAGREE, within budget Four added comment lines against five added code lines, longest run three lines, and both claims in the comment verify against the code

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

One note for whoever reviews this: pull request 110892 edits the exact block this change relocates,
widening the bitmap condition in place while leaving it inside setTotals, so it does not fix the
reachability defect. A textual conflict is likely whichever lands second, and the resolution is
mechanical: that widened condition belongs in runPostBuildPhase unchanged. Pull request 108129 is
independent but converges on the same conclusion about keeping prepare cheap.

Session id: cron:clickhouse-review-slot-8:20260808-080002

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and there are now two independent arms. At processor level the new gtest MergeJoinStarvedTotals.FullJoinKeepsRightRows constructs the state directly and deterministically: a FillingRightJoinSideTransform whose totals port is fed by NullSource, whose generate() returns an empty Chunk exactly as RemoteTotalsSource does when a remote sends no totals. End to end, forcing RemoteTotalsSource::generate() to return an empty chunk reproduces it 100% of the time. The precondition is measured exactly: prepare reaching the build-finish hook with a totals port present and set_totals == false. I could not find a plain-SQL trigger: about 30 candidate shapes (remote over an empty table, LIMIT 0, WHERE 0, HAVING, totals_mode, two-shard uniteTotals, skipped unavailable shards, the four *_overflow_mode='break' limits, outer LIMIT 1, query cache, JoinSwitcher, arrayJoin(emptyArrayInt32())) all delivered their totals chunk, and across roughly 6400 tests and 12000+ instrumented build-finishes the precondition never occurred naturally.
b Root cause explained? MergeJoin::setTotals() was the build-finalization routine, not a totals setter: it called mergeRightBlocks() (its only caller in src/) and allocated used_rows_bitmap, and its own comment said "Has to be called even if totals are empty". prepare calls setTotals() only via two else if-chained branches (pull a totals chunk, or synthesize empty totals when there is no port), so a port that exists and delivers nothing satisfies neither and falls through to the build-finish hook, which MergeJoin did not override. loaded_right_blocks, min_max_right_blocks and used_rows_bitmap are then all unset: the probe sees zero right blocks and drops every right row, and the RIGHT/FULL non-joined path dereferences the null bitmap.
c Fix matches root cause? Yes. Finalization moves onto the post build phase, which the pipeline always reaches, so the state can no longer be observed unset. It also runs in the right context: mergeRightBlocks() drives a nested pipeline, IProcessor documents prepare as O(1) work only, and the executor calls prepare under its graph scheduling lock, so the body belongs in work() - which is the seam HashJoin already uses for its own heavy build steps. No null guard was added at the dereference, alwaysReturnsEmptySet() is unchanged, and JoiningTransform.cpp is untouched: guarding the dereference would have silenced the sanitizer while leaving the wrong-results half in place.
d Test intent preserved / new tests added? No existing test weakened. 01107_join_right_table_totals, the totals regression test, passes unchanged, as do the 01010/01147/01062/04546 partial-merge tests. Two new arms: the gtest above, which asserts the join result rather than the absence of a crash and which fails on unmodified master; and 04821_partial_merge_join_build_finalization, which uses hash as the correctness oracle across the join kinds. 04821 passes on unmodified master by construction - every shape a stateless test can express delivers its totals chunk - so it is a regression guard plus a partial_merge-vs-hash differential, and the gtest is the witness.
e Both directions demonstrated? Yes, three ways. (1) The gtest fails on a full revert of this change (whose code is byte-identical to pristine master): the FULL join returns {(0,0), (1,0), (2,0)} where the correct result is {(0,0), (0,3), (1,1), (2,0)}, so every right value is lost and the right-only key is missing; it passes on the fix. (2) On ASAN+UBSan builds with the Build ID asserted against the running server, pre-fix gives shared_ptr.h:574:12: runtime error: reference binding to null pointer of type 'element_type' (aka 'DB::RowBitmaps'), symbolized to operator* -> NotJoinedMerge::fillColumns -> NotJoinedBlocks::nextImpl -> IBlocksStream::next -> JoiningTransform::work, matching the CI report frame for frame; post-fix is clean and all four join kinds equal hash. (3) A mutant that keeps the merge but drops the bitmap allocation crashes the server with Address: NULL pointer. Access: read. at the same frames, carrying that mutant's own Build ID.
f Fix is general across code paths? All 13 carriers from the plan dispositioned. Both mergeRightBlocks() dispatch arms are exercised (in-memory and spilled), and mergeRightBlocks() still has exactly one call site in src/. JoinSwitcher, the only wrapper that can hold a MergeJoin, forwards onBuildPhaseFinish, hasPostBuildPhase and runPostBuildPhase, and was measured to finalize once with correct ordering. SpillingHashJoin does not forward the post-build methods, which is harmless here: its chosen_join is only ever a GraceHashJoin, ConcurrentHashJoin or HashJoin, never a MergeJoin. joinPipelinesByShards is structurally unreachable for this join: MergeJoin overrides neither clone nor cloneNoParallel (0 occurrences in the header) and the base clone() throws UNSUPPORTED_METHOD. The concurrent right-filling path is also unreachable, since supportParallelJoin() is not overridden (0 occurrences, default false), which is why no locking is owed.
g Fix generalizes across inputs? 04821 covers INNER/LEFT/RIGHT/FULL over a right side with totals, with and without non-joined right rows, in-memory and spilled right sides, and a totals arm projecting a right-only aggregate. Finalization was separately measured on the in-memory, spilled, JoinSwitcher HASH-to-PARTIAL_MERGE and RIGHT-kind paths. MergeJoin::isSupported admits ALL INNER/LEFT/RIGHT/FULL plus ANY/SEMI INNER/LEFT, and the non-joined stream exists only for ALL RIGHT/FULL, which both tests cover.
h Backward compatible? Yes. No setting, no format, no protocol change: 0 files matching Settings or Serializ in the diff, so no SettingsChangesHistory.cpp entry is owed. setTotals() keeps its IJoin::setTotals() call, so totals results are unchanged - and that claim is now itself under test: 04821's totals arm projects an aggregate that exists only on the right, so a mutant making MergeJoin::setTotals() a no-op reddens exactly that one line while the seven other labeled blocks stay green. With the previous arm, which projected only the shared USING key, JoinCommon::joinTotals sourced the value from left_totals and the assertion could not fail.
i Invariants and contracts preserved? The invariant is that no consumer reads used_rows_bitmap, loaded_right_blocks or min_max_right_blocks before mergeRightBlocks() has run. Measured on the new call site, with the probe logging the finalized state at both ends: finalization completes exactly once per query on the in-memory, spilled, JoinSwitcher and RIGHT-kind paths, with a query carrying no join as the zero control, and its completion strictly precedes construction of the non-joined stream on every one of those paths. That matches the source: prepare sets post_build_phase and returns Ready without finishing its output, so the output is finished only on the following prepare, and JoiningTransform cannot build the non-joined stream until that input is finished. Both merge paths take rwlock exactly as before.

Session id: cron:clickhouse-impl-slot-41:20260808-070200

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @yariks5s, could you review this? MergeJoin finalized its whole right side inside setTotals, which FillingRightJoinSideTransform::prepare reaches only through two else if chained branches, so a totals port that exists but delivers zero chunks skipped finalization entirely and left the right side unmerged and the non-joined bitmap null. It now finalizes on the post build phase, which the pipeline always reaches, and in work rather than prepare because the body drives a nested pipeline.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6883f7e]

Summary: ✅


AI Review

Summary

This PR moves MergeJoin right-side finalization from setTotals into the post-build phase so the build always completes even when a totals port exists but never delivers a chunk, and it adds focused regression coverage for both the starved-totals FULL JOIN exception path and the wrong-results path with real right-side rows. I rechecked the current diff, the FillingRightJoinSideTransform/JoiningTransform lifecycle, and the prior discussion, and I did not find a remaining correctness, safety, or coverage gap in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.80% -0.10%

Changed lines: Changed C/C++ lines covered: 56/58 (96.55%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6883f7eae with master 8cb46d93b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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 ⚠️

299 translation units recompiled, 374 s compile time in total, 12 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Passes/PassBuilder.cpp: 25.4 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp: 6.5 s
  • contrib/rocksdb-cmake/__/rocksdb/table/block_based/block_based_table_reader.cc: 6.0 s
  • contrib/google-cloud-cpp-cmake/__/google-cloud-cpp/google/cloud/storage/parallel_upload.cc: 5.7 s
  • contrib/google-cloud-cpp-cmake/__/google-cloud-cpp/google/cloud/storage/internal/rest/stub.cc: 5.6 s
  • contrib/rocksdb-cmake/__/rocksdb/db/write_batch.cc: 5.5 s

Job report

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 18fe490

CI is fully finished on this head: 175 check runs, 0 queued or in progress. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Finish Workflow / Post Hooks (new_tests_check.py) + Bugfix validation (functional tests, amd64 and aarch64) / 04821_partial_merge_join_build_finalization PR-caused. The per-arch report says Bug does not reproduce on this arch: after the bugfix-validation flip, the displayed FAIL row means the new stateless test still PASSED on the merge-base binary, so it does not catch the bug it is meant to pin. The gtest half did reproduce (Bugfix validation (unit tests) OK), but the hook requires at least one per-arch functional or integration validation, and a unit test does not relax that PR-caused, fixed in this PR: I will make 04821 fail without the MergeJoin change
Stress test (arm_tsan) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID: 6726-6444) pre-existing trunk abort on the set-skip-index read path, 31 rows / 28 PRs / 3 master in 30d, first seen 2026-07-24, so it predates this branch #112484 (mine, open)

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`.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Bugfix validation was right: the regression test did not reproduce the bug

Finish Workflow / Post Hooks was red because no per-arch Bugfix validation job validated the
fix. That is not noise: 04821_partial_merge_join_build_finalization passed on the merge-base
binary on both arches, so it did not catch the bug it was meant to pin.

The reason is structural. TotalsHavingTransform::prepare pushes the totals chunk
unconditionally, so with a local WITH TOTALS right side the pre-fix code always finalized the
right side, and no query 04821 can express reaches the starved-totals path. 04821 is a useful
guard, but it was never a reproducer.

Pushed 04827_partial_merge_join_starved_totals_port, which is one. The missing ingredient is a
totals port that exists and delivers nothing, and 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 the same fail point the same way,
including the no-parallel tag this test needs for the same reason.

Because the reproduction is defined by absences, the test asserts its ingredients rather than
assuming them. The join and its settings live in a view, so the assertions and the query under test
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.

Measured on a pristine master asan_ubsan build: red in 3 of 3 restart cycles with the UBSan null
RowBitmaps reference symbolized frame-for-frame to the CI stack. On the fixed binary: green in 20
of 20 fresh databases, no fail point left enabled. Three mutants each redden a different arm:
dropping WITH TOTALS from the view, dropping join_algorithm, dropping the fail point.

One more thing this turned up: 04821's spilled-right-side arm produced the same output 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.

The other red check on the previous head, Stress test (arm_tsan) (STID 6726-6444, sizes of nested
column and null map not equal after deserialization), is a pre-existing trunk failure on the
set-skip-index read path and predates this branch. Its fix is #112484.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6883f7e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both success, Mergeable Check success, and a >20 min CIDB ingestion buffer.
158 success, 17 skipped, 0 failed, 0 cancelled. The Finish Workflow / Post Hooks
(new_tests_check.py) red from the previous head 18fe490df137 is gone.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64 + aarch64) / 04821_partial_merge_join_build_finalization not a failure: invert_bugfix_validation_status (ci/jobs/functional_tests.py:184-268) flips FAIL/OK, so a stored FAIL means the test PASSED on the master binary. 04821 is a guard, not a reproducer: TotalsHavingTransform::prepare pushes the totals chunk unconditionally, so no query it can express reaches the starved-totals path. Both jobs report check_status = success. fixed in this PR: 04827_partial_merge_join_starved_totals_port carries the validation, and it plus the STID 2928-2d1a UBSan row are both stored OK = reproduced on master HEAD on both arches
Sync private fork-sync mirror CH Inc sync (private, not actionable by me)

The previously ledgered Stress test (arm_tsan) row (Logical error: Sizes of nested column and null map ..., STID 6726-6444) did not recur here: all 12 Stress test variants are green on this
head.

Session id: cron:our-pr-ci-monitor:20260809-080000

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 9fd6305 Aug 17, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UBSan: null RowBitmaps deref in NotJoinedMerge::fillColumns (partial merge join RIGHT/FULL non-joined path)

4 participants