Skip to content

Fix duplicate filter push-down in plan-based parallel replicas - #117731

Merged
nickitat merged 15 commits into
masterfrom
pr-plan-based-duplicate-disjunction-pushdown
Oct 7, 2026
Merged

nickitat merged 15 commits into
masterfrom
pr-plan-based-duplicate-disjunction-pushdown

Conversation

@nickitat

@nickitat nickitat commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

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

Fixed duplicate filter push-down in plan-based parallel replicas.


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

Version info

  • Merged into: 26.10.1.1704-master (included in 26.10 and later)

`tryPushDownFilter` marks a join with `disjunctions_optimization_applied` once it has pushed the
partial predicates of an `OR` across it, so the push does not repeat. Join reordering builds a fresh
`JoinStepLogical` for every join it re-shapes and did not carry that mark over, so the guard read
false again afterwards.

A plan optimized once never notices. The plan-based parallel-replicas path optimizes the plan a second
time, and there the push ran again: on TPC-H `o07` the second round left a `Filter` above a `nation`
read whose `PREWHERE` already applied the same `n_name = 'FRANCE' OR n_name = 'GERMANY'` - the same
rows filtered twice, once per row, for nothing. Single-node and the tree-based parallel-replicas path
produced no such step, so the plans also stopped hashing equal, which is what made
`considerEnablingParallelReplicas` unable to match them.

Carry the mark onto the rebuilt steps. On `o07` at sf=1 all three builds now agree - no leftover
`Filter`, the same two `PREWHERE` predicates on the two `nation` reads - and results are unchanged
across single-node, tree-based and plan-based.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [41df9c9]

Summary: ✅


AI Review

Summary

This PR correctly carries disjunctions_optimization_applied through join reordering, JoinStepLogical cloning/serialization, physical join construction, and the cascades aggregation-pushdown rebuild. I do not see a remaining source-level bug in those paths, but the new worker-side regression test still does not guarantee that any remote replica executes the shipped fragment, so the serialization half of the fix can still go completely unexercised.

Findings
  • ⚠️ Majors
    • [tests/queries/0_stateless/05056_pr_plan_based_disjunction_pushdown_guard_over_wire.sh:41] [dismissed by author -- https://github.com/Fix duplicate filter push-down in plan-based parallel replicas #117731#discussion_r3918006165] The test explicitly documents that the number of secondary queries “can be zero”, then accepts on_replicas = 0 anyway. In that zero-secondary case the query never serializes/deserializes a JoinStepLogical on a worker, so the new JoinStepLogical::serialize / deserialize code is not exercised and the worker-side half of the bug can regress unnoticed. Suggested fix: force at least one remote replica to receive work and assert it (for example by creating enough ranges, setting parallel_replicas_mark_segment_size = 1, and requiring ProfileEvents['ParallelReplicasUsedCount'] > 1), then keep on_replicas = 0 as the actual regression check.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: strengthen tests/queries/0_stateless/05056_pr_plan_based_disjunction_pushdown_guard_over_wire.sh so it proves at least one secondary replica ran before asserting that replicas produced zero Pushed down partial filter messages.

LLVM Coverage Report

Measured on commit 41df9c9.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 71/72 (98.61%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@zlareb1

This comment was marked as spam.

`buildQueryGraph` reads the mark off the join it is called on, but a flattenable child join is built
into its own `QueryGraphBuilder` and merged in by `uniteGraphs`, which copied every field except that
one. A graph whose only marked join sat in the merged sub-graph therefore reordered as unmarked, and
the rebuilt steps read false again - the same leak this branch fixes, one level down.

The path is reachable: a probe in `uniteGraphs` fires twice over `clickhouse-test join` on master's
own tests, both on the `LEFT JOIN ... INNER JOIN ... ON` shape of `02372_analyzer_join.gen.sql`. I
could not turn either into an observable plan difference - `tryPushDownFilter` sets the mark whenever
it reaches the disjunction block, whether or not a partial predicate was extracted, and in every
shape where one was extracted the mark also sat at the graph root, where it is already carried. So
this goes in without a test of its own; the 1071 tests of `clickhouse-test join` fail identically
with and without it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
nickitat and others added 2 commits September 2, 2026 19:04
`JoinStepLogical::serialize` wrote a hardcoded `flags = 0` and `deserialize` read the byte and threw it
away, so `disjunctions_optimization_applied` did not survive serialization. The plan-based
parallel-replicas path ships an already-optimized plan and the replica optimizes it again before building
the pipeline, so every remote fragment arrived unmarked and pushed the partial predicates a second time.

Measured on a three-replica cluster with the query of `05055`: each remote fragment carried, above each
of the two reads, a `Filter` with exactly the predicate that read already applies through `PREWHERE` -
four redundant steps, every row filtered twice on every replica. `Pushed down partial filter` is logged
six times for the query, of which only two come from the initiator's own planning.

Encode the mark in bit 0 of the flags byte that is already on the wire. An old reader ignores a bit it
does not know and a new reader sees `flags = 0` from an old writer, so both directions keep behaving as
they do today and the plan format needs no version bump.

The test counts the push-down messages logged under the secondary queries alone, so it does not depend
on how many replicas the query used: four without this change, zero with it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
The style check wants `current_database = currentDatabase()` on every query that reads
`system.query_log`. Putting it on the subselect as written silences the check and the test with it: the
secondary queries of the plan-based path are logged with `current_database` = `default` rather than the
database of the query they belong to, so the condition drops exactly the rows the assertion is about -
the test then passed against a build without the serialization fix.

Pin the condition to the initiator row, where it holds, and admit the secondaries explicitly. The test
also reports the initiator's own push count now, so renaming the log message fails the test instead of
quietly reporting no pushes anywhere. Verified both ways again: `2 4` without the serialization fix,
`2 0` with it, 12 of 12 runs with settings randomization.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 41df9c9fb with master c881ee63b (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

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

Job report

nickitat and others added 4 commits September 3, 2026 11:47
… the old analyzer

Both tests could pass without covering anything. `05055` compared the plans of the two
`parallel_replicas_plan_based` modes but never checked either query built a parallel-replicas read, so a
fall back to a local plan compared two plans that prove nothing. `05056` accepted zero replica-side
push-downs without establishing that a fragment was ever shipped.

`05055` now also counts the read step each mode is expected to build - `ReadFromRemoteParallelReplicas`
for the tree-based mode, `ReadFromParallelReplicas` for the plan-based one - and `05056` reports whether
any secondary query ran at all. Checked by re-running with `enable_parallel_replicas = 0`: both new
columns read zero there, so a fallback now fails the test instead of passing it.

That is also what the old-analyzer run was hitting: `05056` reported `0 0` there, no push-down anywhere,
because `JoinStepLogical` and the plan-based path are new-analyzer only. Tag both `no-old-analyzer`
rather than teach them to expect a plan the old analyzer never builds.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117731&sha=latest&name_0=PR&name_1=Stateless+tests+%28amd_llvm_coverage%2C+old+analyzer%2C+s3+storage%2C+DBReplicated%2C+parallel%2C+1%2F3%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117731&sha=latest&name_0=PR&name_1=Stateless+tests+%28amd_llvm_coverage%2C+old+analyzer%2C+s3+storage%2C+DBReplicated%2C+parallel%2C+2%2F3%29
#117731

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
The analyzer has been the default since 24.3, and the style check rejects "new analyzer". Say what the
tag is actually about instead: the old analyzer has neither the plan-based parallel-replicas path nor
`JoinStepLogical`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
The flaky check reported `0 2 0`: the initiator had planned and pushed as expected, but no secondary
query was visible. Reproduced locally in 1 run out of 40 - the secondary rows reach `query_log` slightly
after the initiator's own row, so the single `SYSTEM FLUSH LOGS` sometimes misses them, and a second
flush then shows all of them.

That is worth guarding rather than tolerating, because the missing rows are what the replica-side count
is derived from: without them `on_replicas` reads zero for the wrong reason and the test would have
passed vacuously. It only failed because `shipped_to_replicas` was there to notice, which is the column
added for exactly this.

Flush and re-check until a secondary query shows up. A query that really did not ship a fragment
exhausts the wait and still fails, so the assertion keeps its teeth either way. 60 of 60 runs pass with
settings randomization.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117731&sha=4122a7fa1cb48e3dae028006be121c663b018b98&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
#117731

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
The comment said four occurrences instead of two while the test asserted three, and neither number was
right. Measured against the build before the first commit of this branch: three is the `OR` left on the
join plus the partial predicate pushed to each of the two reads, and the regression turns that into five
by leaving a redundant `Filter` above each read.

Establishing that also showed the test was not testing anything. It asserts a plan shape, and
`clickhouse-test` randomizes both inputs the join order optimizer needs for that shape to be reached:
`query_plan_optimize_join_order_randomize` to a non-zero value in 95% of runs, which replaces the real
statistics with invented ones and picks a different order, and `query_plan_optimize_join_order_limit` to
0 in 5%, which turns reordering off entirely. With neither pinned, 20 out of 20 runs against a build
without the fix passed. With both pinned, 23 of 25 fail, and 25 of 25 pass with the fix.

The remaining two runs are not a hole in the assertion - a redundant `Filter` carries the disjunction and
would be counted - but plans where the duplicate never arises, so this query cannot do better.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
nickitat and others added 2 commits September 3, 2026 15:55
The wait broke on the first secondary query to show up, which does not mean the others have been flushed.
A replica whose rows are still missing contributes no push-down messages to count, so it cannot make the
assertion fail - the same way a pass could be vacuous before, only per replica instead of wholesale.

Take the expected number from the cluster - one secondary per replica, bar the one the initiator runs in
process - and wait for all of them. `>=` rather than `=` so a retried connection logging an extra row
does not turn into a failure. A replica that never reports still leaves `shipped_to_replicas` zero.

Verified again both ways with the counting unchanged otherwise: `1 2 0` with the serialization fix over
15 runs with settings randomization, `1 2 4` without it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
`constructPhysicalStep` built `JoinStep` and `FilledJoinStep` with the guard left at its default `false`,
so converting a logical join dropped it. That is the last carrier boundary that lost it: `optimizeTree`
converts joins to physical and then, if any join runtime filter was added, runs `tryPushDownFilter` over
the tree again, and by then it is the physical step the guard would be read off. Thread the flag through
`buildPhysicalJoinImpl` to both overloads.

The read is inert today, and this changes no plan. Instrumenting `tryPushDownFilter` shows the second
pass does reach a residual disjunction over the converted join - twice on a single-node query with
`enable_join_runtime_filters = 1` - but with `disj_enabled=false`, because `constructPhysicalStep` never
passes `use_join_disjunctions_push_down` to the `JoinStep` constructor, where it defaults to false, and
the old analyzer's construction in `InterpreterSelectQuery` does not pass it either. Nothing sets it on a
physical step, so the push-down only ever runs on `JoinStepLogical`. The probe fires zero times across
the 1071 tests of `clickhouse-test join`, which also fail identically with and without this commit.

So this goes in without a test: one enabling `enable_join_runtime_filters` would pass either way. The
field decides the question if `use_join_disjunctions_push_down` ever reaches a physical step, and a
default `false` would decide it wrong.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
@nickitat
nickitat marked this pull request as ready for review September 3, 2026 17:02
@nickitat
nickitat requested a review from devcrafter September 3, 2026 17:03
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@devcrafter devcrafter self-assigned this Sep 7, 2026
nickitat and others added 2 commits September 7, 2026 12:59
…cate-disjunction-pushdown

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp
The TSan flaky check reported `0 2 0`: the wait for one secondary query per replica never reached two,
after running its full hundred rounds over four minutes. The expectation was simply wrong. Measured
locally over repeated runs of the same query, the number of secondary rows is 0, 2 or 4 - a replica logs
one row or two, and with tables this small `ParallelReplicasUsedCount` is 1, so the coordinator gives the
single granule to one replica and the others do no reading at all. Deriving the count from the number of
replicas in the cluster cannot work.

Take the proof that the query really went through the parallel-replicas path from the initiator's own
row instead - `ProfileEvents['ParallelReplicasQueryCount']`, 1 whenever it did and 0 when it did not,
with no dependence on when a replica gets around to logging. The wait stays, now settling on the number
of secondary queries rather than expecting one: replicas still must not be counted while their rows are
in flight, which was the point of waiting at all.

The replica-side count therefore proves absence only where those rows do surface; where they never do,
it degrades to no evidence rather than to a false pass, and the initiator half still holds. Verified
both ways: `1 2 0` over 20 runs with settings randomization, `1 2 4` without the serialization fix.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117731&sha=c9cba1372e75f84c840d9c81da5c2dc7959ec053&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
#117731

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
@nickitat

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

…cate-disjunction-pushdown

# Conflicts:
#	src/Processors/QueryPlan/JoinStepLogical.cpp

Co-authored-by: nickitat <[email protected]>

Copilot AI commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

🕵 Resolved in fa427ddf3: merged master into this branch and fixed the conflict in src/Processors/QueryPlan/JoinStepLogical.cpp by preserving both the disjunction optimization flag restoration and join decision flags deserialization.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ nickitat
❌ Copilot
You have signed the CLA already but the status is still pending? Let us recheck it.

@devcrafter

Copy link
Copy Markdown
Member

In general, we should have a way to provide remote node set of optimizations to apply or to exclude, especialy for optimizations which are non reentrant. This pr stop applying one particular optimization, which is acceptable for now but fills somewhat invasive since we need to change internals of logical step

@devcrafter

devcrafter commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

rebuildJoinWithNewInput (src/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationPushdown.cpp:370) is a second site that rebuilds a JoinStepLogical without carrying the guard, so the duplicate push-down can still happen through it. Cascades runs under make_distributed_plan, whose fragments are re-optimized on the replicas, and the rebuilt step has optimized = true, so filterPushDown.cpp:1063-1069 sees a logical join with a cleared guard and pushes the partial predicates again.

     new_join_step->setOptimized();
+    new_join_step->setDisjunctionsOptimizationApplied(join_step.isDisjunctionsOptimizationApplied());
     new_join_step->setStepDescription(join_step);

Not urgent — enable_cascades_optimizer is off by default. JoinCommutativity is fine, it goes through cloneStepAs -> clone.

@devcrafter devcrafter 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.

with comments

In general, applying optimizations twice (once on initiator, second time on remote) shouldn't lead to less optimal or more bloatet plan. But it's another thing to address. The current pin-point fix, addressing matching of plan steps for autopr, which is acceptable but in general not the way to go

nickitat and others added 2 commits October 6, 2026 17:52
…n pushdown

`rebuildJoinWithNewInput` is the only `JoinStepLogical` built outside `optimizeJoin`, and it left the
guard at its default. Unlike the physical steps, this one is a logical join, where the push-down is
enabled from the join's own settings, so a cleared guard here really would let the partial predicates be
pushed a second time when the fragment is optimized on a replica. `JoinCommutativity` is fine: it goes
through `cloneStepAs` and `clone` already copies the field.

It does not change a plan today either, and for a structural reason rather than a disabled setting. The
guard is set only when a `Filter` is still above the join once the main push-down is done -
`tryPushDownFilter` reaches the disjunction block only with a filter in hand - and
`collectJoinsUnderAggregation` matches an `Aggregating` over a join through at most one identity
`ExpressionStep`, never through a `Filter`. So the join this rule rebuilds is never a marked one. A probe
on the call site confirms it: 42 firings across `clickhouse-test cascades` and the tests above, every one
of them with the guard false. Shown directly too - 04926's pushable query stops pushing down as soon as
an `OR` across both sides is added, because the residual `Filter` lands between the aggregation and the
join, while an `OR` confined to the pushed side pushes through and leaves no filter to mark the join
with.

`clickhouse-test cascades` fails identically with and without this commit (27 pass, the same 11 fail on
missing cluster and worker configuration my local server does not have).

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KVh4Bk2WsveqGUeQLw8jJo
@nickitat
nickitat enabled auto-merge October 6, 2026 20:53
@nickitat
nickitat added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 7d4c81b Oct 7, 2026
150 checks passed
@nickitat
nickitat deleted the pr-plan-based-duplicate-disjunction-pushdown branch October 7, 2026 00:45
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
Conflicts resolved additively:

- `JoinStepLogical.cpp`: master (ClickHouse#117731) now encodes the disjunction push-down
  mark in bit 0 of the `flags` byte, the bit this branch used for the reorder
  boundary. Keep master's bit and move the boundary to bit 1; it stays gated on
  `Join` step version 1. The gtest arm that pinned the whole byte to `1` now
  checks that each mark round-trips without setting the other (it reddens if
  both use bit 0).
- `ProtocolDefines.h`: keep master's new constants next to ours. 26.10 is not
  released, so 20 is still the current release's plan version and the `Join`
  step version 1 keeps `since_plan_version = 20` with no global bump.
- `StorageView.cpp`: includes from both sides.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

6 participants