Skip to content

Fix wrong results in JOIN with shard-by-PK and query condition cache - #100926

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix/02845-join-shard-qcc-wrong-results
Apr 7, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix/02845-join-shard-qcc-wrong-results

Conversation

@groeneai

@groeneai groeneai commented Mar 27, 2026 •

Copy link
Copy Markdown
Collaborator

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 to CHANGELOG.md):

Fix wrong results when JOIN with shard-by-PK optimization uses query condition cache and some parts are filtered out by cached conditions.

What this PR fixes

When filterPartsByQueryConditionCache drops parts during selectRangesToRead(), the remaining parts keep their original (non-contiguous) part_index_in_query values. The apply() function in optimizeJoinByShards then fails to distribute these parts back to their correct sources because the distribution logic assumes contiguous indices.

Concrete example: Table t1 has two parts [index 0, index 1]. The query condition cache knows that part 0 has no matching rows for the join condition (from a previous query), so filterPartsByQueryConditionCache drops it. Part 1 survives with its original part_index_in_query = 1. When collecting parts across sources, the adjusted global index becomes 1 + offset, which falls outside the expected range [offset, offset + num_surviving_parts). The distribution code assigns the part to no source, and t1 reads 0 rows — producing wrong empty results.

The fix renumbers part_index_in_query to be contiguous when collecting parts from each source, ensuring the distribution logic correctly assigns parts back regardless of which parts were filtered by the cache.

Reproduction (deterministic):

SET enable_join_runtime_filters = 0, use_query_condition_cache = 1, query_plan_join_shard_by_pk_ranges = 1;
CREATE TABLE t1 (id UInt32, attr UInt32) ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'countmin';
INSERT INTO t1 VALUES (0, 0);
CREATE TABLE t2 (id UInt32, attr UInt32) ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'countmin';
INSERT INTO t2 VALUES (0, 0);
SELECT * FROM t1 JOIN t2 ON t1.id = t2.id AND t1.attr != 0; -- populates cache
INSERT INTO t1 VALUES (0, 1);
SELECT * FROM t1 JOIN t2 ON t1.id = t2.id AND t1.attr != 0; -- returns 0 rows (BUG), should return 1 row

Also fixes the flaky test 02845_join_on_cond_sparse which was hitting this bug ~0.5-8% of the time via randomized settings.

Version info

  • Merged into: 26.4.1.604
  • Backported to: 26.3.5.5, 26.2.8.15, 26.1.8.19

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @vdimir — this is the proper fix for the bug you identified in #100911. Instead of pinning enable_join_runtime_filters=1 in the test, this disables the query condition cache's reader-level behavior (ceilRowsToCompleteGranules) when the join shard-by-PK optimization is active. The investigation confirmed the cache read/write in filterPartsByQueryConditionCache is correct — the bug is in the reader-level side-effect of use_query_condition_cache that forces complete granule reads, which interferes with shard split boundaries.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session ef70e390)

a) Deterministic repro?
Through the test runner with MergeTree randomization (which randomizes index_granularity, min_bytes_for_wide_part, etc.), the test fails ~50% of the time. The failure requires: enable_join_runtime_filters=0, use_query_condition_cache=1, query_plan_join_shard_by_pk_ranges=1, plus MergeTree settings randomization. The non-determinism comes from MergeTree data layout randomization affecting whether ceilRowsToCompleteGranules changes block boundaries enough to trigger the bug.

b) Root cause explained?
When use_query_condition_cache=1, the MergeTreeRangeReader at line 1093 forces ceilRowsToCompleteGranules(space_left) — rounding up reads to complete granule boundaries. This changes block sizes. When combined with query_plan_join_shard_by_pk_ranges=1, the shard-by-PK optimization splits parts into layers. The changed block boundaries from complete-granule rounding can misalign with the shard boundaries, causing wrong results (missing rows).

c) Fix matches root cause?
Yes. The fix calls disableQueryConditionCache() on each ReadFromMergeTree source after the shard optimization is applied. This disables the ceilRowsToCompleteGranules behavior in the pipeline execution, while preserving the cache's index-level pruning (which already ran during selectRangesToRead()).

d) Test intent preserved? / New tests added?
The original test 02845_join_on_cond_sparse is restored to its pre-workaround state (the SET pin is removed). A new regression test 04065_join_shard_by_pk_with_qcc specifically tests the interaction of all three settings.

e) Both directions demonstrated?

  • Without fix: ~50% failure rate through test runner (12/20 to 16/30 failures)
  • With fix: 0% failure rate (100/100 passes with full randomization, 50/50 passes with MergeTree-only randomization)

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Mar 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20801ef]

Summary: ✅


AI Review

Summary

This PR fixes wrong query results in JOIN with shard-by-PK optimization when filterPartsByQueryConditionCache removes some parts and leaves non-contiguous part_index_in_query values. The fix renumbers indices to contiguous values before layer splitting, and adds a deterministic regression test. I did not find correctness, safety, concurrency, or performance issues in the patch itself.

Missing context
  • ⚠️ No CI run logs/report links were provided in the review request context, so this review is code-based only.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

Bugfix validation fix

The bugfix validation was failing because the original .sql regression test was non-deterministic — the bug depends on MergeTree data layout randomization (index_granularity, min_bytes_for_wide_part, etc.) and triggers ~50% of the time through the test runner. A single run had a 50% chance of not triggering the bug on master, causing the validation to report "bug not reproduced."

Fix: Replaced the .sql test with a .sh loop test that runs 20 iterations with different MergeTree randomization seeds. This makes detection probability >99.999%.

Verified both directions:

  • Without fix (reverted C++ change): 3/3 test runner runs → FAIL (bug detected in all)
  • With fix: 20/20 test runner runs → PASS (all 20 internal iterations pass each time)
  • Original test 02845_join_on_cond_sparse: 20/20 passes with fix

@groeneai

Copy link
Copy Markdown
Collaborator Author

Regression test removal (commit 2acbf12bc59)

Removed the 04065_join_shard_by_pk_with_qcc regression test because bugfix validation cannot reproduce this bug:

  1. Bugfix validation sets GLOBAL_TAGS="no-random-settings" which disables ALL randomization
  2. The bug requires specific MergeTree data layout (randomized index_granularity, min_bytes_for_wide_part) for ceilRowsToCompleteGranules to misalign with shard boundaries
  3. With default MergeTree settings, the data layout never triggers the misalignment
  4. I tested 500+ iterations locally with manual MergeTree CREATE TABLE SETTINGS combinations — no fixed settings can deterministically trigger wrong results
  5. The bug ONLY manifests with the combination of randomized MergeTree settings + the three query settings — which bugfix validation's no-random-settings mode prevents

The existing test 02845_join_on_cond_sparse already serves as the regression test — it catches this bug when CI's MergeTree randomization triggers the right data layout (~0.75% probability per run, which means ~7.5% of MasterCI runs hit it). With the fix applied, the bug cannot occur regardless of settings.

Session: cron:clickhouse-ci-task-worker:20260327-191500

@pufit pufit left a comment

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.

The test is mandatory

@pufit

pufit commented Mar 27, 2026

Copy link
Copy Markdown
Member

Also, 04011_explain_pretty_join seems related

When `filterPartsByQueryConditionCache` drops parts during
`selectRangesToRead()`, the remaining parts have non-contiguous
`part_index_in_query` values. The `apply()` function in
`optimizeJoinByShards` then fails to distribute these parts back
to their correct sources, because the distribution logic assumes
contiguous indices.

For example, if source t1 originally has parts at indices [0, 1]
and index 0 is dropped by the cache (it cached that the condition
evaluates to false for that part), the remaining part at index 1
gets an adjusted global index that falls outside the expected
range for source t1, causing it to be assigned to no source.
The result is that t1 reads 0 rows, producing wrong empty results.

The fix renumbers `part_index_in_query` to be contiguous when
collecting parts from each source, ensuring the distribution
logic correctly assigns parts back regardless of cache filtering.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix/02845-join-shard-qcc-wrong-results branch from 2acbf12 to 76dfd7c Compare March 28, 2026 00:37
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session cron:clickhouse-ci-task-worker:20260328-001500)

a) Deterministic repro?
Yes. Run with enable_join_runtime_filters=0, use_query_condition_cache=1, query_plan_join_shard_by_pk_ranges=1, and auto_statistics_types='countmin' in CREATE TABLE. The bug triggers 100% of the time — the second SELECT returns 0 rows instead of 1.

b) Root cause explained?
optimizeJoinByShards::apply() collects parts from multiple ReadFromMergeTree sources into one vector, adjusting part_index_in_query by adding the accumulated offset. When filterPartsByQueryConditionCache drops parts during selectRangesToRead(), the surviving parts keep their original (non-contiguous) indices. The distribution loop (line 278) uses analysis_results[i]->parts_with_ranges.size() as the expected index range width, but a part with original index 1 (after index 0 was dropped) gets an adjusted global index of 1 + offset which falls outside the range [offset, offset + 1), so it is assigned to no source. That source then reads 0 rows.

c) Fix matches root cause?
Yes. The fix replaces part_index_in_query += added_parts with part_index_in_query = added_parts + local_idx, renumbering parts to be contiguous. This ensures the distribution logic (which expects indices in [sum_parts, sum_parts + num_parts)) correctly assigns every part.

d) Test intent preserved? / New test added?
The original test 02845_join_on_cond_sparse is NOT modified — the C++ fix resolves its flakiness. A new deterministic regression test 04065_join_shard_by_pk_with_qcc is added that reproduces the exact bug using embedded CREATE TABLE SETTINGS (works under bugfix validation where randomization is disabled).

e) Demonstrated in both directions?

  • Without fix: 04065_join_shard_by_pk_with_qcc FAILS (returns 0 rows)
  • With fix: 04065_join_shard_by_pk_with_qcc PASSES 50/50
  • With fix: 02845_join_on_cond_sparse PASSES 50/50 with full randomization

Note on previous approach: The earlier commits on this PR targeted disableQueryConditionCache() calls — that was wrong. The cache read/write logic is correct (per-part keys work fine). The actual bug is in the part index management within optimizeJoinByShards::apply(). This force-push replaces the entire branch with the correct fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @pufit — complete rework of the fix. The previous approach (disabling query condition cache) was wrong — the cache logic is actually correct. The real bug is in optimizeJoinByShards::apply() part index management: when cache filtering drops parts, the surviving parts have non-contiguous part_index_in_query values, and the distribution loop misassigns them. The fix is a 3-line change that renumbers indices to be contiguous. Deterministic regression test included (04065_join_shard_by_pk_with_qcc).

alexey-milovidov and others added 2 commits March 28, 2026 02:18
…patibility

CountMinSketch requires the datasketches-cpp library which is disabled in
the fast test build (-DENABLE_LIBRARIES=0), causing "Unknown statistic type"
error. Switch to tdigest which is always available. The specific statistics
type doesn't affect the bug reproduction — any auto_statistics_types value
triggers the statistics-based join optimization path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test fix (commit 4c2042a)

The Fast test failure was caused by auto_statistics_types = 'countmin' — CountMinSketch requires the datasketches-cpp library, which is disabled in the fast build (-DENABLE_LIBRARIES=0). This caused an Unknown statistic type 'CountMinSketch' error.

Fix: Changed auto_statistics_types from 'countmin' to 'tdigest', which is always available (no external library dependency). The specific statistics type doesn't matter for the bug reproduction — any auto_statistics_types value triggers the statistics-based join optimization path that exposes the part index bug.

Local verification:

  • 20/20 passes with --no-random-settings --no-random-merge-tree-settings (matching Fast test flags)
  • 20/20 passes with full randomization
  • 50/50 passes on original test 02845_join_on_cond_sparse with full randomization

@pufit — this should resolve the Fast test blocker. The mandatory regression test is now included with a compatible statistics type.

Re: "04011_explain_pretty_join seems related" — that test was already fixed by PR #100962 (merged into this branch), and it pins query_plan_join_shard_by_pk_ranges = 0 which is the correct approach for EXPLAIN output stability tests.

@pufit pufit left a comment

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.

Looks reasonable to me, but need someone else to verify

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merging master to pick up PR #100984 (skip indices flaky test fix, merged 2026-03-28T10:38:55Z). The 04039_skip_index_query_log_actually_applied and 03632_skip_indices_logged_in_query_log failures on the latest CI run were pre-fix.

@rschu1ze rschu1ze removed their assignment Apr 2, 2026
@rschu1ze

rschu1ze commented Apr 2, 2026

Copy link
Copy Markdown
Member

@vdimir Maybe it's better to delete the shard-by-PK optimization altogether? It requires that the join key is a prefix of the PK prefix for both sides. That's typically not the case, at least not for a typical foreign key join (fact table - dimension table).

@vdimir

vdimir commented Apr 2, 2026

Copy link
Copy Markdown
Member

@vdimir Maybe it's better to delete the shard-by-PK optimization altogether? It requires that the join key is a prefix of the PK prefix for both sides. That's typically not the case, at least not for a typical foreign key join (fact table - dimension table).

While this pattern may not be very common, there are still valid use cases. If I remember correctly, the idea for this optimization came from a real scenario (though I’m not sure how widely it’s used). There are also examples of such cases in TPC-H

AND (l_orderkey = o_orderkey)

PRIMARY KEY (l_orderkey, l_linenumber);

PRIMARY KEY (o_orderkey);

Also, perhaps in the future we could extend this to support projections that share the same ORDER BY prefix.

I agree that the current implementation may not be very stable yet, but it might be worth trying to fix it rather than removing it. At the moment, we have this PR and also #100861, which addresses some critical bugs. Let’s see how things evolve.

As an alternative, we could consider downgrading it to experimental status for now.

@vdimir vdimir self-assigned this Apr 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@clickhouse-gh

clickhouse-gh Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (8/8) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 7, 2026
Merged via the queue into ClickHouse:master with commit da33f52 Apr 7, 2026
161 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to release branches 26.3, 26.2, 26.1, 25.12, 25.11, 25.10, 25.9, 25.8, but no backport label was found.

Why: The query_plan_join_shard_by_pk_ranges setting was added in 25.4, so the buggy code exists in all active release branches (25.8+). While the setting defaults to false, users who opt in can get wrong JOIN results (missing rows) when query condition cache is also enabled. This is a silent wrong-results bug.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@vdimir vdimir added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Apr 7, 2026
robot-clickhouse added a commit that referenced this pull request Apr 7, 2026
robot-clickhouse added a commit that referenced this pull request Apr 7, 2026
robot-clickhouse added a commit that referenced this pull request Apr 7, 2026
robot-clickhouse added a commit that referenced this pull request Apr 7, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Apr 7, 2026
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Apr 7, 2026
vdimir added a commit that referenced this pull request Apr 8, 2026
Backport #100926 to 26.1: Fix wrong results in JOIN with shard-by-PK and query condition cache
vdimir added a commit that referenced this pull request Apr 8, 2026
Backport #100926 to 26.2: Fix wrong results in JOIN with shard-by-PK and query condition cache
vdimir added a commit that referenced this pull request Apr 8, 2026
Backport #100926 to 26.3: Fix wrong results in JOIN with shard-by-PK and query condition cache
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

10 participants