Skip to content

Do not split a bucketed distributed read into primary-key layers for a join - #129420

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/join-by-pk-ranges-skip-bucketed-read
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/join-by-pk-ranges-skip-bucketed-read

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Experimental Feature

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

With make_distributed_plan and enable_cascades_optimizer, a join over a bucketed distributed read of a MergeTree table no longer returns its rows multiplied by the number of reader tasks when query_plan_join_shard_by_pk_ranges shards the join by primary-key ranges.

Description

Found by the AST fuzzer TLP oracle: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112805&sha=8c15f2c48f9d60fd977139bdc49ed302255dceb6&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 (the exists / not exists / isNull arms of a correlated EXISTS summed to 4x the table count). No related open issue found.

On a distributed-plan worker, a bucketed ReadFromMergeTree (getDistributedReadBucketCount() > 0) reads only its bucket's marks, which initializePipeline pins into parts_with_ranges. The worker runs the regular optimizations on its fragment, and optimizeJoinByShards split all local parts into layers for a non-spilling HashJoin on a primary-key prefix; readByLayers reads those layers, not parts_with_ranges, so every task read the whole table. With 4 tasks, SELECT count() FROM t_orders WHERE EXISTS (SELECT 1 FROM t_lineitem WHERE l_orderkey = o_orderkey) returned 80 instead of 20 (needs max_bytes_before_external_join = 0 and max_bytes_ratio_before_external_join = 0; with the default ratio the join is a SpillingHashJoin, which is never sharded).

findReadingStep now refuses such a read, like the other worker-side passes that rebuild a read from its analysis (optimizeLazyFinal #112493, projections #108256, trivial count from a text index). The join then runs unsharded inside the task.

Validation: the new test 05510_distributed_plan_join_by_pk_ranges_bucketed_read fails on master (80, 3920, 80, 80 vs 20, 980, 20, 20) in 20/20 randomized runs and passes 50/50 with the fix; the 202 stateless tests that use make_distributed_plan give the same results before and after, apart from the new test.


Workflow [PR]
Sync PR [sync-upstream/pr/129420]

…a join

On a distributed-plan worker, a `ReadFromMergeTree` of a bucketed distributed read
(`getDistributedReadBucketCount() > 0`) reads only the marks of its bucket. They arrive as a
task parameter and are pinned into `parts_with_ranges` in `initializePipeline`.

The worker runs the regular plan optimizations on its fragment, including
`optimizeJoinByShards` (`query_plan_join_shard_by_pk_ranges`, on by default). For a non-spilling
`HashJoin` whose join key is a primary-key prefix of both sides it split ALL local parts into
layers (`split_parts`), and `readByLayers` reads those layers instead of `parts_with_ranges`.
So every reader task read the whole table and the result was multiplied by the number of tasks:
with 4 tasks, `SELECT count() FROM t WHERE EXISTS (SELECT 1 FROM s WHERE s.k = t.k)` returned
80 instead of 20. Found by the AST fuzzer TLP oracle (exists / not exists / isNull arms summed
to 4x the table count).

Refuse such a read in `findReadingStep`, as the other worker-side passes that rebuild a read from
its analysis already do (`optimizeLazyFinal`, projections, trivial count from text index). The
join then runs unsharded inside the task, as it does with the default spill settings, where the
join is a `SpillingHashJoin` and is never sharded.

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

groeneai commented Nov 5, 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; 1 finding) plus my own review (1 nit).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test does not pin join_algorithm; a stress worker without a hash-family algorithm keeps the join local and the EXPLAIN check fails DISAGREE Stress jobs do not report per-test result mismatches, and the jobs that do (stateless, flaky check) never vary join_algorithm (tests/clickhouse-test has no randomizer for it). The default and every hash-family value reproduce on master.
2 💡 Trigger settings are pinned with SET rather than a Random settings limits clamp DISAGREE They define the scenario, not a flakiness clamp; same form as 04040_cascades_semi_join_broadcast_correctness.

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

Session id: cron:clickhouse-review-slot-9:20261105-011400

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test (and the CI oracle query replayed with the CI table shapes) fails on every run on master: 20/20 randomized runs give 80 / 3920 / 80 / 80 instead of 20 / 980 / 20 / 20; the CI replay gives 160 vs 40 and a metamorphic sum of 5000 vs 1250, as in the CI report.
b Root cause explained? On a distributed-plan worker, a bucketed ReadFromMergeTree reads only its bucket's marks, pinned into parts_with_ranges in initializePipeline. The worker's optimizeJoinByShards split all local parts into primary-key layers (split_parts) for a non-spilling HashJoin, and readByLayers reads the layers, so each of the 4 tasks read the whole table (server log: every ::stage_0_N task logs reading by layers and reads all parts).
c Fix matches root cause? Yes. findReadingStep refuses a read with getDistributedReadBucketCount() > 0, so the layers are never built from parts the task does not own. Same predicate as optimizeLazyFinal (#112493), projections (#108256) and the text-index trivial count. With the fix each task logs default reading and reads exactly one part.
d Test intent preserved / new tests added? New SQL test 05510_distributed_plan_join_by_pk_ranges_bucketed_read: semi, anti, explicit LEFT SEMI and INNER join arms, each compared with the local plan, plus an EXPLAIN check that the plan is still a broadcast join over a ParallelRead (so the arms cannot pass by losing the distributed plan).
e Both directions demonstrated? Yes, on Build-ID-verified binaries: master 217cb430 fails 20/20, fix a5e1cd72 passes 50/50 with randomized settings.
f Fix is general across code paths? The guard is in the shared source finder of the pass, so it covers both join sides and both sharded algorithms (HashJoin, FullSortingMergeJoin). The other worker-side passes were audited: the ones that replace or re-split a read are already guarded (lazy FINAL, projections, text-index trivial count); the rest only set flags on the read, whose bucket pin still applies.
g Fix generalizes across inputs (params/datatypes/wrappers)? The refusal depends only on the read being bucketed, not on key types or join kind. Measured with UInt64 keys and the CI shape (Nullable(IPv4) payload, duplicated keys across parts); max_threads 1/2/8 and join_algorithm hash / parallel_hash / direct,hash / default all reproduce on master and pass with the fix.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or serialization change. Bucketed worker fragments only lose the intra-task layered join, which they also do not get with the default spill settings.
i Invariants and contracts preserved? A bucketed read reads exactly its bucket's marks on every path; the read's port layout stays one port per stream, as for any read that findReadingStep refuses (FINAL, parallel replicas, partition ports). Non-distributed plans are unchanged (distributed_read_bucket_count is 0 there).

Session id: cron:clickhouse-impl-slot-40:20261105-000203

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [781ccbf]

Summary: ✅


AI Review

Summary

PR #129420, reviewed at 781ccbf5dd67e61b82bcf5e65703312fc536dcc7, prevents optimizeJoinByShards from replacing a bucketed ReadFromMergeTree read with layers covering all local parts, which multiplied distributed join results by the reader-task count. The shared source guard covers both join inputs and both supported sharding algorithms. The new stateless regression compares distributed and local semi, anti, and inner joins and checks that the plan remains distributed. No actionable findings.

Missing context / blind spots
  • ⚠️ Targeted and flaky-check CI jobs are still pending. No local ClickHouse binary or build was available to repeat the test independently; runtime evidence currently comes from the author's documented before/after runs. Completed CI results for 05510_distributed_plan_join_by_pk_ranges_bucketed_read would provide independent confirmation.
Final Verdict

Status: ✅ Approve. No code changes requested; normal CI completion remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 5, 2026
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @KochetovNicolai, could you review this and add the can be tested label so CI runs? On a distributed-plan worker, optimizeJoinByShards split all local parts into primary-key layers for a bucketed ReadFromMergeTree, and readByLayers bypassed the bucket marks pinned in initializePipeline, so every task read the whole table; findReadingStep now refuses bucketed reads, like optimizeLazyFinal and projections.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 781ccbf5d with master 6a59c7376 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 16 s compile time in total, 7 of them have a recent master baseline.

Job report

@shankar-iyer shankar-iyer self-assigned this Nov 5, 2026
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

This also fixes 04502_distributed_plan_one_bucket_exchange, which fails on code with #128519 (1, 2): 27445000 instead of 13722500. With the default join_algorithm, the join order optimizer can now plan full_sorting_merge, Cascades still broadcasts that join over a bucketed read, and the worker splits the read into primary-key layers as described above.

No random join order is needed: two tables ORDER BY k with 4M and 3M rows, joined on k with only make_distributed_plan = 1, enable_cascades_optimizer = 1 and 2 workers, return twice the local sum with the binary of the #128519 merge commit, and the local sum with the amd_binary of this PR.

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

This also fixes 05019_cascades_replicated_total_rows, which fails in PR runs (1, 2): the self-join count() returns 800000 or 400000 instead of 200000. It needs a non-zero query_plan_optimize_join_order_randomize, which the test runner randomizes, and a small randomized index_granularity. With the seed, the join order optimizer plans full_sorting_merge for the broadcast join over the bucketed read (with seed 0 the join is a SpillingHashJoin, which is not sharded), so the default max_bytes_ratio_before_external_join does not prevent it.

With index_granularity = 260, 4 workers and seed 752933, master 7a516a1aba46 returns 800000, and each of the 4 tasks logs reading by layers and reads all 4 granules. The amd_binary of this PR returns 200000 for seeds 0, 1, 2, 752933 and 964843, with 2 or 4 workers.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #130887 (merged 2026-11-12), which adds the same check in findReadingStep, so this PR can be closed.

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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants