Skip to content

Fix LOGICAL_ERROR in LEFT JOIN with additional filter promoted to RightAny - #111041

Merged
fm4v merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-hashjoin-additional-filter-rightany-null-map-3452-37cd
Aug 7, 2026
Merged

fm4v merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-hashjoin-additional-filter-rightany-null-map-3452-37cd

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106928
Related: #110048
Related: #112153

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

This is now a test-only PR. The source fix it originally carried was superseded by #106928, which landed the equivalent filter resize in joinRightColumnsWithAdditionalFilter on 2026-07-30. After merging master, this branch's copy of src/Interpreters/HashJoin/HashJoinMethodsImpl.h is byte-identical to master, so only the regression test remains.

The test is still worth keeping because it covers a different assertion than #106928's. Both bugs come from the same missing resize, but they surface through different columns. On a build with the resize removed, #106928's 04330_join_global_left_semi_chunk_consistency.sql raises Invalid number of rows in Chunk, while this test raises Null map of size 2 at offset 0 does not match ColumnNullable of size 1 (STID 3452-37cd) through ColumnNullable::applyNullMapImpl in HashJoinResult::generateBlock. That is the signature seen in CI on unrelated PRs #79393 and #110048, and no existing test reaches it: it needs join_use_nulls = 1 and a nullable right key, which #106928's test does not use.

The test asserts results, plus the two conditions the coverage depends on: that the strictness really was promoted to RightAny, and that the block really was split. The promotion needs its own assertion because HashJoin::onBuildPhaseFinish decides it from the data alone and reports it through no setting, profile event or result, so the profile counters cannot stand in for it: a plain LEFT ALL join on the same unique right keys reads the same build rows and splits the same way. It is asserted from the system.text_log message keyed by query_id, the pattern 04029_join_convert_to_fixed_hash_table.sql already uses. Both conditions were mutation-tested: inverting the all_values_unique gate leaves every result row and the split assertion green while turning only the promotion row from 1 to 0.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110048&sha=6f8f79fc6c7b7d0d43e2df0722a387d7d69755cc&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Version info

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

…htAny

joinRightColumnsWithAdditionalFilter builds the per-left-row filter at the full
input block size, then can shrink left_block_rows to the matched rows and returns
that reduced count, which the caller uses to scatter the block. It only resized
filter to left_block_rows under need_replication, so a LEFT RightAny join
(need_replication=false) left filter at the full block size. Downstream
copyLeftKeyColumnToRight then applied the oversized negated null map to the shrunk
left key column, aborting with 'Null map of size N does not match ColumnNullable
of size M'.

Resize filter whenever it was built (need_filter), not only under need_replication,
so it stays in the same row space as the scattered block.

Author: Groene AI <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count(), sum(coalesce(r.a,0)+coalesce(r.b,0)) FROM (SELECT number % 50 AS k FROM numbers(100000)) AS l LEFT JOIN (SELECT toNullable(number % 25) AS a, number % 30 AS b FROM numbers(2)) AS r ON (l.k = r.a) AND (l.k > r.b) SETTINGS join_algorithm='hash', join_use_nulls=1, max_joined_block_size_rows=256 raises the LOGICAL_ERROR on every run without the fix.
b Root cause explained? joinRightColumnsWithAdditionalFilter builds filter at selector.size() (full input block), then the additional filter reassigns left_block_rows to the matched-row count and returns it; the caller scatters the block to that many rows. filter was only resized to left_block_rows under if constexpr (need_replication). A LEFT ALL join whose right table has unique keys is promoted to RightAny (need_replication == false), so the resize was skipped and filter kept the full block size. Downstream copyLeftKeyColumnToRight applied the oversized negated null map to the shrunk left key column -> size mismatch.
c Fix matches root cause? Yes. Resize filter to left_block_rows whenever it was built (need_filter), not only under need_replication, so it stays in the same row space as the scattered block. Targets the exact desync, not a symptom.
d Test intent preserved / new tests added? New test added (04612_left_join_additional_filter_right_any_scatter). It asserts correct join RESULTS (including a partial-match case verifying right-key values are joined correctly), not merely that the query stops raising.
e Both directions demonstrated? Yes. Without fix: server raises the LOGICAL_ERROR (and the sibling Invalid number of rows in Chunk for the non-nullable variant). With fix: correct results, server alive. Build IDs verified distinct.
f Fix is general across code paths? Yes. This method solely owns the filter/return-size contract; the plain joinRightColumns returns 0 (processes all rows) and never scatters — confirmed an equi-only RightAny join does not reproduce. No sibling path has the same defect.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified across join_algorithm (hash/parallel_hash/grace_hash), max_joined_block_size_rows {0,1,100,256,1000,65536}, joined_block_split_single_row {0,1}, enable_lazy_columns_replication {0,1}, and both nullable (negated-null-map path) and non-nullable (Chunk-size path) right keys — all consistent, zero mismatches.
h Backward compatible? Yes. No setting/format/protocol change; a pure internal correctness fix (previously raised a LOGICAL_ERROR, now returns correct results). No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. Restores the invariant filter.size() == returned left_block_rows == scattered block rows. filter[i]/matched_rows are written in [0, left_block_rows), and the caller keeps the first left_block_rows selector positions (raw_selector.split(processed_rows)), so the truncation is exact and drops no live entry.

Session id: cron:clickhouse-author-slot-1:20260720-083700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings across 1 full pass + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 💡 Test comments described the LOGICAL_ERROR as a "crash" AGREE — fixed A LOGICAL_ERROR is an exception (release builds do not abort); reworded to "raised a LOGICAL_ERROR" / "raise" / "stops raising" (comment-only).
2 ❌ "Diff only rewords comments; the HashJoin fix is missing" DISAGREE Delta-recheck artifact. The --delta base already contained the source fix, so the recheck saw only the comment-only commit. The full PR diff includes src/Interpreters/HashJoin/HashJoinMethodsImpl.h (+8/-2) with the if (need_filter) added_columns.filter.resize(left_block_rows); change — verifiable in the PR's Files-changed.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-1:20260720-083700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @rschu1ze — could you review this? joinRightColumnsWithAdditionalFilter only resized the per-left-row filter to the matched-row count under need_replication, so a LEFT JOIN with a non-equi ON condition promoted to RightAny (need_replication=false) left filter at the full block size while the block was scattered to the matched rows, raising "Null map of size N does not match ColumnNullable of size M" downstream. Fix resizes filter whenever it was built.

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

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f95f794]

Summary: ✅


AI Review

Summary

This PR is now a test-only regression case for the LEFT JOIN additional-filter LOGICAL_ERROR. The new system.text_log check correctly restores proof of the RightAny promotion, but the split oracle still depends on the incoming probe chunk being larger than max_joined_block_size_rows, so the test can pass without exercising the truncated-prefix path that originally triggered the bug.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04612_left_join_additional_filter_right_any_scatter.sql:45] The probe_rows > 1000 assertion is still not self-contained: with unique right keys, each left row contributes at most one candidate, so if a suite-level max_block_size <= 256 reaches numbers(1000), joinRightColumnsWithAdditionalFilter never emits a follow-up block and JoinProbeTableRowCount stays exactly 1000. The result rows and the RightAny log check remain green, so the test stops covering the split/truncation path it is supposed to lock down. Pin max_block_size > 256 in the reproducer, or opt the test out of random max_block_size.
Final Verdict

⚠️ Needs one more test-hardening fix before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b682a82 (HashJoin additional-filter RightAny null-map fix)

CI fully finished (Finish Workflow SUCCESS, 20-min ingest buffer met). Every failure below has an owner; none is PR-caused (this PR touches only src/Interpreters/HashJoin/HashJoinMethodsImpl.h).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk; 102 master + 14 unrelated PRs / 21d) #111029 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize trunk bug (Code 70 Tuple->Geometry in MVTEncodeMerge state serialize; 1 master + 2 unrelated PRs / 21d) a fix task is created (investigating at full effort; fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260720-150000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04507_mvt_encode_state_serialize finish-ledger line (Code 70 Cannot convert type Tuple(Float64, Float64) to Geometry under ParallelReplicas): #111136. That is a trunk bug in the query-tree to AST conversion of folded Variant constants, unrelated to this PR's diff.

@rschu1ze

Copy link
Copy Markdown
Member

@m-selmi Like to check this one?


SET enable_analyzer = 1;

-- No matches: every left row gets defaulted right keys. Used to raise

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai Try to find a more minimal test case.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, in 220f3d1.

The bug needs four things: a LEFT JOIN whose right table has unique keys, so the strictness is promoted to RightAny; a non-equi ON condition, so joinRightColumnsWithAdditionalFilter runs; a required right key in the output, so need_filter is true at runtime; and the left block to be processed as a prefix, so the scattered block is shorter than filter. Two rows on each side with max_joined_block_size_rows = 1 satisfy all four, so the test is now 2 rows instead of 100000, and it asserts the joined values instead of aggregates over them. The large max_block_size and the cityHash64/coalesce wrappers came from the CI query and were not needed.

Both queries were re-verified in both directions on a debug build: each one alone raises before the fix, the first with Null map of size 2 at offset 0 does not match ColumnNullable of size 1 and the second with the sibling Invalid number of rows in Chunk, and both return the asserted values with the fix, matching an unscattered hash join and grace_hash.

Minimizing did surface something the previous version was also missing. Two of those four conditions are invisible in the results, because with unique right keys the rows are the same whether or not they hold, and if either stops holding the queries quietly stop covering the fixed path: without the promotion the join stays Left ALL, which has need_replication and so was already resized by the guard this fixes. So the test now also asserts them, the promotion from the client log at debug level and the prefix split from JoinProbeTableRowCount, which is 3 for 2 left rows when the split happens. Both assertions were checked to be load-bearing: forcing query_plan_join_swap_table = true reports NOT PROMOTED and dropping max_joined_block_size_rows reports NOT SPLIT: 2. That needs the client log, hence the .sql became a .sh.

query_plan_join_swap_table and use_query_cache are pinned for the same reason: the stress runner randomizes both, swapping makes this a RIGHT join that is never promoted, and a cached result skips the join entirely, so either would make the test pass while testing nothing.

50 runs green, and also green with query_plan_join_swap_table=true, use_query_cache=1 and the block-size settings injected on the command line.

groeneai and others added 8 commits July 29, 2026 19:33
The bug needs only four things: a LEFT JOIN whose right table has unique
keys (so the strictness is promoted to RightAny), a non-equi ON condition
(so joinRightColumnsWithAdditionalFilter runs), a required right key in the
output (so need_filter is true at runtime), and one unmatched left row
ahead of a matched one so the additional filter shrinks the block below
selector.size().

Two rows on each side with max_joined_block_size_rows = 1 satisfy all four,
so the row counts drop from 100000 to 2 and the aggregate wrappers are gone
in favour of the joined values themselves. The large max_block_size and the
cityHash64/coalesce aggregates in the previous version were incidental to
the CI query, not required by the bug.

Both queries were re-verified in both directions on a debug build: each one
alone aborts before the fix (the first with "Null map of size 2 does not
match ColumnNullable of size 1", the second with the sibling "Invalid
number of rows in Chunk") and both return the values asserted here with the
fix, matching an unscattered hash join and grace_hash.

Co-Authored-By: Claude Fable 5 <[email protected]>
The comments said the additional filter drops trailing left rows. It does
not: the loop breaks once the pre-filter candidate count reaches
max_joined_block_size_rows, before buildAdditionalFilter runs, and the
caller splits the remaining left rows into a following block rather than
discarding them. Say that instead, and shorter.

Comments only, no behaviour change.

Co-Authored-By: Claude Fable 5 <[email protected]>
The two result assertions are identical with and without the split, so on
their own they would keep passing if the join stopped splitting the block
and the queries silently stopped covering the fixed path. Add an oracle for
it: the deferred left row is probed again in the following block, so
JoinProbeTableRowCount is 3 for 2 left rows when the split happens and 2
when it does not. Verified load-bearing by dropping
max_joined_block_size_rows from the first query, which turns it into
"fail: 2".

The RightAny promotion itself is decided after the build phase and is not
exposed through EXPLAIN, a ProfileEvent or a system table, so it has no SQL
oracle; the promotion is what makes need_replication false, which is the
condition the resize guard turned on, so it stays covered only in the sense
that the queries abort without the fix.

Also quote the diagnostic in full, including "at offset 0".

Co-Authored-By: Claude Fable 5 <[email protected]>
Swapping the tables makes this a RIGHT join. Promotion to RightAny only
happens for inner and left joins, and RIGHT ALL has need_replication, which
the guard already resized, so with the swap neither query reproduces: on a
pre-fix build they return the expected rows instead of raising. The stress
runner injects query_plan_join_swap_table=true, so without the pin the test
would silently pass in that configuration while covering nothing.

Verified in both directions on a pre-fix build: with the pin the test still
raises even when query_plan_join_swap_table=true is passed on the command
line, and with the pin removed the same run returns the expected rows.

Co-Authored-By: Claude Fable 5 <[email protected]>
The bug needs two conditions that the results themselves cannot show, since
they are the same either way: the strictness has to be promoted to RightAny,
and the block has to be split. The previous version asserted only the split,
so the test would still pass if promotion stopped happening, and then it
would cover nothing: without promotion the join stays Left ALL, which has
need_replication and so was already resized by the guard this fixes.

Promotion is decided after the build phase and is not in EXPLAIN, a
ProfileEvent or a system table, but it is logged, so assert it from the
client log at debug level. That needs a shell test, hence the .sql becomes
a .sh.

Each assertion was checked to be load-bearing: forcing
query_plan_join_swap_table = true reports "NOT PROMOTED", and dropping
max_joined_block_size_rows reports "NOT SPLIT: 2".

Co-Authored-By: Claude Fable 5 <[email protected]>
The probe-count assertion runs the first query a second time, and the query
cache key does not include the query id, so with use_query_cache = 1 the
second run is served from the cache, never reaches the join, and reports
"NOT SPLIT: 0". The stress runner enables the cache, so pin it off. The
assertion itself also needs the pin, because reading a system table with the
cache on throws unless query_cache_system_table_handling is set.

Verified by removing the pin with the cache enabled, which reports
"NOT SPLIT: 0", and with it in place the test passes both with the cache
enabled bare and with the settings the stress runner passes alongside it.

Co-Authored-By: Claude Fable 5 <[email protected]>
shell_config.sh always puts --send_logs_level into $CLICKHOUSE_CLIENT, and
the client rejects the option given twice, so appending a second one made
the promotion query fail with "Bad arguments" and the pipeline read that as
"NOT PROMOTED". It happened to pass locally only because the test runner
adds --allow_repeated_settings, which it does not always do.

Replace the existing option instead, as 00653_verification_monotonic_data_load.sh
does. Checked at every log level the runner can pass (warning, error, fatal,
information) with a client built by shell_config.sh and no
--allow_repeated_settings: the previous form reports "NOT PROMOTED" and this
one reports "promoted".

Co-Authored-By: Claude Fable 5 <[email protected]>
The Style check requires every query to system.query_log to carry a
current_database = currentDatabase() predicate, and the split assertion
added in the previous commit read the log filtered only by query_id.

The query_id already embeds $CLICKHOUSE_DATABASE, so the extra predicate
cannot select a different row; it was verified to be a live predicate and
not decoration by pointing it at a database that does not exist, which
turns the assertion into NOT SPLIT: 0.

Co-Authored-By: Claude Fable 5 <[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.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 0/0 (nothing coverable) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d7bae74

CI is fully finished on this head: 174 check-runs, all completed, 1 red. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Block structure mismatch in after optimization liftUpUnion stream (STID: 0993-23fd) AST-fuzzer trunk bug: a UNION ALL of aggregate-state columns with the same state representation but different functions, wrapped in a Tuple, makes the per-branch headers compare unequal fixing PR #111191 (external, open)

The aborting query is SELECT countMerge(*) FROM (SELECT medianState(...) AS a UNION ALL SELECT countState() UNION ALL ...), which is the mechanism #111191 fixes (it relaxes the block-structure check for aggregate-state columns nested in containers and ships 04623_union_aggregate_state_in_tuple_header). Nothing in this diff touches set operations or block-structure checks.

Session id: cron:our-pr-ci-monitor:20260730-030000

@m-selmi

m-selmi commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

@groeneai
Replace the .sh test with a simple .sql test again.
Use simplified queries, the following 2 queries already reproduce the issue:

SELECT count(), sum(coalesce(r.a, 0)), sum(coalesce(r.b, 0))
FROM (SELECT number % 2 AS k FROM numbers(1000)) AS l
LEFT JOIN (SELECT toNullable(number) AS a, number AS b FROM numbers(2)) AS r
  ON (l.k = r.a) AND (l.k > r.b)
SETTINGS join_algorithm = 'hash', max_joined_block_size_rows = 256;

Received exception from server (version 26.8.1):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Null map of size 1000 at offset 0 does not match ColumnNullable of size 256: While executing JoiningTransform. (LOGICAL_ERROR)
SELECT count(), sum(coalesce(r.a, 0)), sum(coalesce(r.b, 0))
FROM (SELECT number % 2 AS k FROM numbers(1000)) AS l
LEFT JOIN (SELECT number AS a, number AS b FROM numbers(2)) AS r
  ON (l.k = r.a) AND (l.k > r.b)
SETTINGS join_algorithm = 'hash', max_joined_block_size_rows = 256;

Received exception from server (version 26.8.1):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Invalid number of rows in Chunk UInt64(size = 256), UInt8(size = 256), UInt64(size = 256), UInt64(size = 1000) column UInt64 at position 3: expected 256, got 1000: While executing JoiningTransform. (LOGICAL_ERROR)

Also simplify the comment in the code to and make it obvious truncation happens because of max_joined_rows.

…onal-filter-rightany-null-map-3452-37cd

# Conflicts:
#	src/Interpreters/HashJoin/HashJoinMethodsImpl.h
@clickhouse-gh clickhouse-gh Bot removed the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 31, 2026
# the need_replication path that always resized `filter`, so neither query below would reproduce.
# The query cache is off because the same query runs more than once here, and serving it from the
# cache skips the join, which the assertions at the end would read as the join having changed.
SETTINGS="SETTINGS enable_analyzer = 1, query_plan_join_swap_table = false, use_query_cache = 0, join_algorithm = 'hash', max_joined_block_size_rows = 1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This split oracle still depends on an unpinned probe chunk shape. The JoinProbeTableRowCount == 3 check below only holds if numbers(2) reaches JoiningTransform as a single 2-row block; if a caller runs the shell test with max_block_size = 1 (or any future suite-level override below 2), the join stays correct but this query reports 2 and the test fails with NOT SPLIT.

Please pin max_block_size = 2 here (or opt the script out with no-random-settings) so the split assertion is guaranteed by the test itself rather than by current runner defaults.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still block-shape dependent in the current .sql test.

JoinProbeTableRowCount is incremented once per incoming probe chunk in JoiningTransform::readExecute (src/Processors/Transforms/JoiningTransform.cpp:245), and joinRightColumnsWithAdditionalFilter only produces a follow-up next_block after one chunk contributes more than max_joined_block_size_rows candidates (src/Interpreters/HashJoin/HashJoinMethodsImpl.h:945-983).

At tests/queries/0_stateless/04612_left_join_additional_filter_right_any_scatter.sql:45, the reproducer uses unique right keys, so each left row contributes at most one candidate. If a suite-level max_block_size <= 256 reaches numbers(1000), the join sees probe chunks of at most 256 rows, never emits a next_block, and JoinProbeTableRowCount stays exactly 1000. The result rows and the RightAny log check on lines 60-71 still stay green, so the test stops covering the truncated-prefix path that triggered the original bug.

Please pin max_block_size > 256 here, or opt the test out of random max_block_size, so line 45 remains a real split oracle.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured this rather than reason about it, and I disagree: line 45 holds its value across the whole max_block_size range, and the state that would move it is both unreachable and self-announcing.

The probe input is re-batched before the counter. EXPLAIN PIPELINE puts a SimpleSquashingTransform between the source and JoiningTransform, built at src/Processors/QueryPlan/JoinStepLogical.cpp:1072-1073 from min_joined_block_size_rows / min_joined_block_size_bytes (defaults 65409 / 524288), not from max_block_size. The source does honour max_block_size (blockSize() is 1 at max_block_size=1 versus 1000 at the default), but the blocks are coalesced again before JoiningTransform.cpp:245 increments the counter. Measured JoinBuildTableRowCount / JoinProbeTableRowCount at max_block_size = 1, 64, 128, 200, 255, 256, 257, 300, 512, 1000, 1001, 4096, 8000, 8192, 65409, 100000: 2 / 2464 in every arm, so split and promoted both read 1 throughout.

A suite-level value at or below 256 is not reachable. tests/clickhouse-test:1438 is "max_block_size": lambda: random.randint(8000, 100000); I extracted that generator and drove it 2,000,000 times, giving min=8000, max=100000, zero draws at or below 256. tests/integration/helpers/random_settings.py:7 has the same 8000 floor, and this is a 0_stateless test. min_joined_block_size_rows is set by no randomizer, no --client-option path and no file under tests/config/.

The value you predict is a failure, not a silent pass. probe_rows only drops to 1000 when min_joined_block_size_rows is lowered and max_block_size is small: min_joined_block_size_rows=1 with max_block_size=256 gives 2 / 1000 and split=0, likewise with max_block_size=1, while min_joined_block_size_rows=1 on its own stays at 2464. So 1000 > 1000 is false and the row fails loudly. That matches the comment above it, which already documents 1000 as the unsplit value.

I also checked the one channel that can reach min_joined_block_size_rows, since its entry sits in the 25.7 block of SettingsChangesHistory.cpp:605 and ci/jobs/scripts/stress/stress.py:240 randomizes compatibility at p=0.2. It reverts the setting to 0, and 0 means unlimited per the setting's own description, so the squash still happens: compatibility 25.6, 24.1 and 20.1 give 0 while 25.7, 25.8 and 26.6 give 65409. The full test still matches its reference under compatibility=25.6 combined with max_block_size=256 and with max_block_size=1, under compatibility=24.1 with max_block_size=200, and under compatibility=26.6 with max_block_size=256.

Given that, a pin would not change any outcome I can produce, so I am leaving the test as it is.

groeneai added 2 commits July 31, 2026 18:28
Per review feedback, replace the shell test with a plain .sql test built on
the two simplified queries from the review, plus a third case where the ON
condition holds so the assertions are not all-default.

The `enable_analyzer = 1` and `query_plan_join_swap_table = false` pins are
required: the old analyzer rejects the non-equi ON condition with
INVALID_JOIN_ON_EXPRESSION, and swapping the tables makes this a RIGHT join,
which is not promoted to RightAny and never reaches the truncated prefix, so
without the pin the queries stop covering the fixed path on stress runs that
inject the swap.

Each of the three queries reproduces on a build without the
`filter.resize(left_block_rows)` call: query 1 and 3 raise "Null map of size
1000 at offset 0 does not match ColumnNullable of size 256" and query 2 the
sibling "Invalid number of rows in Chunk ... expected 256, got 1000".
Review of the SQL conversion found two ways the test could stop covering the
fixed path without the reference changing.

Stress runs inject join_use_nulls, which decides whether the right key becomes
Nullable and therefore which of the two errors the queries raise, so each query
now pins the value it needs. The aggregates are identical under both values, so
the reference alone could not detect the flip.

The aggregates are also identical whether or not the join is promoted to
RightAny and whether or not the block is split, so the test now reads
JoinBuildTableRowCount and JoinProbeTableRowCount for the first query from
system.query_log. The right table is the build side with 2 rows only while the
join is not swapped, and 1000 left rows are probed more than 1000 times only
while the block is split. A swapped join reads 1000 build rows and 3 probes,
and an unsplit one probes exactly 1000, so either loss fails the assertion.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 08a47c9, all three points.

  1. The test is a plain .sql again, built on your two queries. I added a third with number - 1 AS b so the ON condition holds for some rows, since your two join nothing and I did not want the reference to be all-default. Both of yours reproduce exactly as you reported on a build without the resize: query 1 gives Null map of size 1000 at offset 0 does not match ColumnNullable of size 256, query 2 the sibling Invalid number of rows in Chunk ... expected 256, got 1000.

  2. The code comment needs no change: the source fix is no longer part of this PR. Fix Invalid number of rows in Chunk in JoiningTransform with additional join filter #106928 merged the equivalent resize into the same function on 2026-07-30, and after merging master HashJoinMethodsImpl.h here is byte-identical to master, so this PR is now test-only and I set the category to CI Fix or Improvement. The comment that landed with Fix Invalid number of rows in Chunk in JoiningTransform with additional join filter #106928 already says truncation happens at max_joined_block_rows.

  3. Two settings are pinned deliberately, both load-bearing:

    • query_plan_join_swap_table = false. Stress runs inject true, which makes this a RIGHT join, excluded from RightAny promotion by isInnerOrLeft. Measured: with the injection and no pin, your query 1 returns 1000 0 0 and does not raise even on the unfixed build.
    • join_use_nulls per query. Stress injects 1, which makes the right key Nullable(UInt64) and moves query 2 onto the null-map path, so it stops covering the Chunk sibling. The aggregates are identical either way, so the reference cannot detect it.

    enable_analyzer = 1 is there because the old analyzer rejects the non-equi ON with INVALID_JOIN_ON_EXPRESSION.

One residual worth your call. The aggregates are the same whether or not the promotion and the block split happen, so I assert both from system.query_log: the right table is the build side with 2 rows only while the join is not swapped, and 1000 left rows are probed more than 1000 times only while the block is split. That covers the split, but it does not prove the promotion itself. Promotion is data-driven in onBuildPhaseFinish, no setting gates it, all_join_was_promoted_to_right_any is exposed nowhere, and there is no ProfileEvent for it, so SQL cannot observe it. A result-based check is impossible too: seeing at most one right row per left row needs several right rows matching one left key, which is the duplicate-key case that prevents promotion in the first place. The only direct oracle is the Promoting join strictness to RightAny debug line, which is why the previous version was a .sh. So if promotion is ever removed the join becomes Left ALL, whose replication path was already resized, and this test would pass while covering nothing. I went with the .sql you asked for and accepted that gap; tell me if you would rather have the shell test back for that one assertion.

Verified both directions on one tree: removing the filter.resize(left_block_rows) call and rebuilding makes the shipped test fail with your exact signature, restoring it relinks bit-identically and the test passes. 50 runs, 0 failures, 0.22s each.

groeneai and others added 3 commits July 31, 2026 20:06
The profile-event assertion covered only the block split. HashJoin::onBuildPhaseFinish
decides the promotion to RightAny from the data alone, and it is reported by no setting,
profile event or query result, so a plain LEFT ALL join on the same unique right keys
reads the same 2 build rows and splits the same way. The test could therefore have kept
passing while no longer exercising the need_replication = false path the regression needs.

Assert the message the promotion logs instead, joined to the query through query_id, the
pattern 04029_join_convert_to_fixed_hash_table.sql already uses. Verified that inverting
the all_values_unique gate in onBuildPhaseFinish leaves every aggregate row and the split
assertion green while turning only the new row from 1 to 0.

Co-Authored-By: Claude Fable 5 <[email protected]>
A swapped RIGHT ALL join can still stop at the candidate limit. It is safe because that path
replicates, and the replication branch has always resized the filter; the earlier wording said
it never reaches the truncated prefix at all.

Co-Authored-By: Claude Fable 5 <[email protected]>
Per the repository instructions, literal names from the ClickHouse SQL language, classes and
functions, and literal excerpts from log messages go inside inline code blocks.

Co-Authored-By: Claude Fable 5 <[email protected]>
@PedroTadim

Copy link
Copy Markdown
Member

@m-selmi can this be merged?

@rschu1ze

rschu1ze commented Aug 3, 2026

Copy link
Copy Markdown
Member

@PedroTadim This PR has no approval yet. @m-selmi is out, he can check after return next week.

The issue exists already in 26.5 and 26.4. Therefore, it is by definition not a "26.6 blocker". I think we should remove it from the corresponding board.

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim This PR has no approval yet. @m-selmi is out, he can check after return next week.

The issue exists already in 26.5 and 26.4. Therefore, it is by definition not a "26.6 blocker". I think we should remove it from the corresponding board.

I just lowered the status, and thinking about removing it.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f95f794

CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 57 success, 117 skipped, 0 failures. Finish Workflow completed successfully, and no check reported a failed test.

Check / test Reason Owner / fixing PR
(none) no failing check on this commit not applicable

Verified from the paginated check-runs API rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers.

Session id: cron:our-pr-ci-monitor:20260803-163000

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 pr-ci 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.

6 participants