Skip to content

Push filters into the part of the query parallel replicas execute, and ship them to the replicas - #117373

Merged
nickitat merged 77 commits into
masterfrom
pr-local-plan-filter-pushdown
Oct 14, 2026
Merged

nickitat merged 77 commits into
masterfrom
pr-local-plan-filter-pushdown

Conversation

@nickitat

@nickitat nickitat commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Related: #95524

Under parallel replicas, a condition standing above the part of the query the replicas execute was
kept out of that part entirely unless parallel_replicas_filter_pushdown was switched on - and it is
off by default. The initiator read its share unfiltered, the replicas read theirs unfiltered and
returned every row for the initiator to filter, and a join runtime filter, which can never travel to
the replicas at all, was lost along with the rest.

That setting was added to switch off a push-down that could leave the initiator reading in a
different order than the replicas (Replica A decided to read in B mode, not in C): the initiator
ordered its read by a condition the replicas never got.

In short: when pushing a filter into the initiator's copy of the fragment, we dry-run the replicas'
splice on a copy of the query to learn which atoms it would leave out, and push every atom except
those left out that may fix a column. The splice to the replicas keeps the existing conversion, but
now reads its settings from the fragment's context, is skipped when a serialized plan is sent, and is
on by default.

So this makes both sides get the same conditions. The condition is spliced into the query the
replicas run - the way the distributed path beside it has always done it - and the initiator's copy
of the fragment takes exactly the conjuncts that splice carries, as decided by the splice's own
conversion. A conjunct it leaves out stays above the fragment, unless it cannot fix a column - a
range, or a join runtime filter, which can never travel - and then it only prunes there. Any equality
it leaves out stays above, even one on a column outside the sorting key: the check does not look at
the read's key.

parallel_replicas_filter_pushdown stays, now on by default, as the way out if this misbehaves in
production: with it off the condition stays above the read and nothing is shipped, which is what
versions before 26.10 did. Both halves are switched together - shipping the condition to the replicas
while the initiator kept it above the read would have them order their read by something the
initiator never applied there, which is the same disagreement from the other side.

The splice stays an optimization, not a substitute: the filter remains above the remote branch, so a
predicate the rewrite drops - a runtime filter, anything non-deterministic - is still applied to the
rows that come back.

It is skipped entirely when the replicas are sent a serialized plan. Such a plan carries no pushed
condition, and the query text remains their fallback for a replica too old to be sent a plan with
execution limits: one reading the condition out of that fallback text would order its read by
something the initiator kept above its own.

On 20M rows, with a predicate no index can answer (ts % 7 = 3):

replicas read replicas returned
before 11.17M rows 11.17M rows
after 10.12M rows 1.43M rows

and on a key predicate the initiator's own read goes from 7813 granules to 79, 11.44 MiB to 5.86 MiB.

Where the rewrite refuses the fragment as a whole - a join tree of more than one table, a UNION ALL
fragment, LIMIT BY, WITH FILL, a window or non-deterministic SELECT list - and where the replicas
are sent a plan, every equality stays above the initiator's copy too, whatever column it is on, and so
does the pruning or PREWHERE it would have given there. 05183 keeps one representative of each kind of refusal and records why the rest
answer the same way.

Tests: 05055 (what goes into the fragment and what stays above, conjunct by conjunct, what the
replicas are sent, and the switch), 05056 (a runtime filter reaches the fragment while its conjoined
equality reaches the replicas), 05161 (a fragment with several coordinated reads, with the splice and
without it), 05183 (the refusal list, a joining fragment among it), 05366 (a condition on a column the
fragment computes as an equality, with the replicas forced to take part). 05055 also covers which
context the splice answers to. The stateless parallel-replicas suite passes in CI.

Changelog category (leave one):

  • Performance Improvement

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

Under parallel replicas, a condition standing above the part of the query the replicas execute is now
pushed into it and shipped to the replicas, so they filter and prune by it themselves instead of
returning every row for the initiator to filter, and a join runtime filter now reaches the reads it
was built for. This is controlled by parallel_replicas_filter_pushdown, which is now enabled by
default; SET parallel_replicas_filter_pushdown = 0 restores the behaviour of versions before 26.10.


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

Version info

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

`parallel_replicas_filter_pushdown` gates two different things. On the remote half of the
read it splices the predicate into the query AST shipped to the replicas
(`ReadFromParallelRemoteReplicasStep::initializePipeline` -> `addFilters`). On the local half it
only moves a `Filter` into the plan fragment the initiator runs itself, which is an ordinary
in-process plan optimization - the fragment is then optimized like any other plan, so the
predicate becomes a `PREWHERE` and prunes the index.

Stop gating the local half. `ReadFromLocalParallelReplicaStep` exists only when
`canUseLocalPlanForParallelReplicas` accepted the query, so this is exactly "ignore the setting
in local mode"; the setting keeps governing the remote query, where the AST surgery lives.

Nothing is filtered on the initiator only: the union push-down clones the `Filter` into both
branches and pushing into a `SourceStepWithFilterBase` keeps the step, so the remote branch
still filters what the replicas send back. The replicas also need not agree on which ranges the
local plan reads - each announces its own and the coordinator reconciles them.

The push-down used to be unconditional; the setting was added in #95510 to mitigate
#95524, where a filter reaching the local plan
let `optimize_aggregation_in_order` pick a coordination mode the replicas did not use
("Replica 1 decided to read in WithOrder mode, not in ReverseOrder"). That was fixed at its root
in #98467, and the local plan now inherits the read-in-order gates from the subquery's own
settings, so the mitigation is no longer needed. `03787_pr_group_by_read_mode_error`,
`03810_pr_aggr_in_order_read_mode` and `04009_pr_aggr_in_order_coordination_mode` cover it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a19b9c2]

Summary: ✅


AI Review

Summary

This PR tightens the parallel-replicas filter-pushdown handshake substantially: the initiator now asks the same AST rewrite that the replicas use which conjuncts actually travel, and the new tests cover most of the earlier WithOrder/Default mismatch shapes. I still see one correctness hole in the shared remote rewrite path, though: shipped fragments with QUALIFY are still treated as rewriteable, so a pushed predicate can be injected into HAVING and run before the window/QUALIFY pass on remote replicas.

Findings

❌ Blockers

  • [src/Interpreters/PredicateRewriteVisitor.cpp:167] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117373#discussion_r4250567206] rewriteSubquery still accepts fragments with QUALIFY and rewrites pushed predicates into HAVING. That is not semantics-preserving: an outer predicate that filters inside a window partition (for example on the ordered column) changes the rows seen by row_number/other window functions when it runs before QUALIFY. In this PR that path is now used both to decide which conjuncts may enter the initiator's local fragment and to splice the predicate into the replicas' shipped query, and allow_push_predicate_ast_for_distributed_subqueries is on by default, so a query-based parallel-replicas view with QUALIFY can return different rows on the remote half than on the initiator-local half. Suggested fix: refuse QUALIFY in this gate (or rewrite into a post-window position with equivalent semantics) and add a regression that uses a QUALIFY row_number() OVER (...) fragment plus an outer predicate on the window order key.
Final Verdict

❌ Needs changes before merge: the remote AST splice still has a wrong-results path for QUALIFY fragments.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 31, 2026
A join runtime filter is the one predicate that reaches the initiator's local plan but can
never reach the replicas: `FunctionApplyFilter::isDeterministic` is `false`, and the DAG-to-AST
conversion behind `ReadFromParallelRemoteReplicasStep::addFilters` skips non-deterministic
functions. So the local fragment is optimized with a filter the replicas do not have, and if that
changed the announced coordination mode the read would fail with "Replica N decided to read in X
mode, not in Y".

It does not: `__applyFilter` passes its key column through unchanged and adds no fixed column
(`enrichFixedColumns` needs every argument fixed or constant, and the probe key is neither), and
read-in-order *through* a join - the only other way a plan carrying a runtime filter reaches
`requestReadingInOrder` - is already refused under parallel replicas. Pin that: aggregation in
order over the sort key picks `InOrder` with and without the filter, with every replica forced to
take part.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a19b9c2b0 with master af433c160 (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.

Object file sizes

72 object files changed (+42.23 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromRemote.cpp.o 620.11 KiB 636.92 KiB +16.81 KiB (+2.71%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +468.4 s (+5%) in total before that adjustment.

Job report

@nickitat
nickitat marked this pull request as ready for review September 1, 2026 11:21
@nickitat
nickitat requested a review from devcrafter September 1, 2026 12:00
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 42 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 199f81ff-ecf5-4431-bfd7-0c7ec618661b
  • MIRAI run: 66328045-bbc3-4fa6-8733-8a857a6f840d
  • PR check IDs:
    • clickbench_933792_1788379090
    • clickbench_933806_1788379090
    • clickbench_933813_1788379090
    • tpch_adapted_1_official_933819_1788379090
    • tpch_adapted_1_official_933848_1788379091
    • tpch_adapted_1_official_933862_1788379091

It ran over the 180s limit in the private CI. `index_granularity = 8` over 100000 rows built
12501 marks, and on shared storage every mark is a read of its own plus coordinator traffic
for the task it belongs to - locally the same query is 342ms, so the cost is entirely the mark
count, not the data.

Nothing in the test needs small granules except handing work to more than one replica, so
10000 rows at `index_granularity = 128` (79 marks) does the same job. The control query
without the runtime filter only re-ran the same read - it exercises no divergence, since
without the filter both sides plan identically - so drop it and halve what is left.

What the test still covers, checked on the smaller data: the read is `InOrder`, the runtime
filter is in the local plan, and both remote replicas issue read requests, so the coordinator
does compare their mode against the initiator's. The failpoint has to stay: without it only
0-1 of the remote replicas read anything and the check is silently skipped.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
The test only checked that the join returns 200, which it does whether or not the filter ever
reaches the local plan - so it would have passed against the very regression it guards.

Pin the plan instead. The filter's position relative to the partial `Aggregating` is what says
which side of the parallel-replicas split it landed on, and the reference now records it below:

    Aggregating
    Aggregating
    Filter column: RF1(a, a from default.b_rf_read_mode)
    ReadFromMergeTree (default.t_rf_read_mode)
    Read type: InOrder

Checked against a binary that still gates the push-down: there the filter prints between the two
`Aggregating` lines instead, so the reference no longer matches - while the result stays 200. The
`Read type` line comes along for free and makes the coordination mode an assertion rather than
something only a logical error would have caught.

`EXPLAIN` only plans, so this costs nothing: 125ms for the whole file under the settings that
timed out, and 0.22-0.32s over 20 randomized runs.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
nickitat and others added 4 commits September 2, 2026 17:39
An equality on a sort key prefix is the predicate that could make the initiator diverge: it fixes
that column, and a sort or an aggregation on the rest of the key can then read in order. Pushed
into the local fragment only - the replicas get it only with `parallel_replicas_filter_pushdown` -
that would leave the initiator announcing `WithOrder` against their `Default`.

It cannot happen, because the filter is pushed into the fragment only when it sits above it, and
so does the sort or aggregation that would use it - and `optimizeReadInOrder` refuses to descend
through the parallel replicas union at all: "avoid applying read-in-order optimization for local
replica since it will lead to different parallel replicas modes between local and remote nodes".

Both halves are in the reference, so it says what it is testing: single node picks `InOrder` for
the same two queries, parallel replicas keep `Default`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
Pushing every predicate into the local fragment was wrong. A predicate the replicas do not have
must not change what the fragment announces to the shared coordinator, and an ordinary equality
does: it fixes a sort key column, so a sort or an aggregation on the rest of the key reads in
order. A view that sorts is enough, because then read-in-order is decided inside the fragment,
where the refusal to descend through the parallel replicas union does not apply:

    CREATE TABLE t (tenant UInt64, ts UInt64) ENGINE = MergeTree ORDER BY (tenant, ts);
    CREATE VIEW v AS SELECT * FROM t ORDER BY ts;
    SELECT ts FROM v WHERE tenant = 42 LIMIT 5;   -- parallel_replicas_filter_pushdown = 0

The initiator read `InOrder` while the replicas, planned without `tenant = 42`, stayed `Default`,
and the query failed with "Got read request from replica 1 for unknown stream". On master the same
query reads `Default` and returns rows.

So keep the gate for everything except a condition made only of join runtime filters. Those cannot
fix a column - `enrichFixedColumns` needs every argument fixed or constant and a probe key is
neither - and they are the one predicate `parallel_replicas_filter_pushdown` could never mirror
anyway, since `addFilters` drops non-deterministic functions. That is the case this branch is for;
an ordinary filter still travels with the setting, which puts it in the replicas' query too.

05055 now pins the boundary from both sides instead of asserting the old behaviour, and 05057
covers the shape above: `Default` at the default, `InOrder` once the replicas get the filter too,
and `Default` with a runtime filter in the local plan.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCAGFHu72JG9die3EDo8t4
Rejecting the whole condition when any part of it is an ordinary predicate was too blunt:
`WHERE ...` above the read merges with the runtime filter into one `Filter`, and that shape is
the common one, so the runtime filter never reached the local plan in the queries that most want
it.

Split the conjunction instead. `extractConjunctionAtoms` gives the atoms, the runtime filters
among them go into the local fragment through `createActionsForConjunction`, and everything else
stays above it - so the fragment still never sees a predicate that could fix a sort key column.
The original `Filter` is left in place rather than rebuilt without the pushed atoms: its actions
may compute more than the predicate, and filtering the same rows twice costs nothing. The local
step remembers what it has taken so the pass does not push it again on the next round.

    Filter column: tenant = 42 AND RF1(tenant, tenant from mix.b)
      ReadFromMergeTree
        Read type: Default
        Runtime filters: RF1(tenant, tenant from mix.b)

A condition made only of runtime filters still moves in whole, and with
`parallel_replicas_filter_pushdown` the whole condition moves in as before.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit left the pushed runtime filters in the original `Filter` and had the local
step remember them so the pass would not take them twice. That is not how the rest of
`filterPushDown` works: `splitActionsForFilterPushDown` builds the pushed actions with
`createActionsForConjunction` and then calls `removeUnusedConjunctions` to rewrite the predicate
down to what stayed, and the step is rebuilt around it.

Do the same here. `ActionsDAG::splitActionsForFilterPushDown` gets an overload that chooses the
conjunction atoms with a callback instead of by which inputs are available; everything after that
is the existing code path, so the parent step becomes an `ExpressionStep` when nothing is left to
filter and keeps filtering by the remainder otherwise. The bookkeeping on the local step is gone -
the atoms are no longer there to be pushed again.

    Filter column: tenant = 42
      ReadFromMergeTree
        Read type: Default
        Runtime filters: RF1(tenant, tenant from mix.b)

Co-Authored-By: Claude Opus 5 <[email protected]>
@nickitat
nickitat marked this pull request as draft September 2, 2026 19:09
…ction names

`isOnlyJoinRuntimeFilters` did not check that a runtime filter was there at all - it only rejected
disallowed function names, so `WHERE flag` or a bare cast passed as "runtime-filter only" and went
into the local fragment with the setting off. The name promised an identity check and the body was
a safety check, and neither was right.

Ask the question that matters instead: can this condition decide how the fragment reads. Only a
condition that pins a column to one value can, because read-in-order treats such a column as
satisfying any position of the sort key - that is what turns `WHERE tenant = 42` into an in-order
read of `ORDER BY (tenant, ts)` while `tenant > 42`, a bare boolean or a runtime filter leave the
decision alone.

Note the direction of the check. `appendFixedColumnsFromFilterExpression` is the analysis that
finds fixed columns, but it walks `and` chains only, so an equality under any other node is
invisible to it - and `removeUnusedConjunctions` wraps a lone remaining atom in an `ALIAS` over a
`CAST`, which is exactly such a node. Missing a fixed column costs that analysis an optimization;
missing one here would cost correctness. So this looks for the equality anywhere in the condition
rather than reusing a function whose conservatism points the other way. Reusing it let
`tenant = 42` back into the local plan on the second push-down round, which is how the test caught
it.

05055 now pins all three: an equality waits for the setting, a comparison and a bare boolean do not.

Co-Authored-By: Claude Opus 5 <[email protected]>
`parallel_replicas_filter_pushdown` does two separate things: it puts the
condition into the initiator's local plan, and it puts it into the replicas'
query by rewriting that query's AST in
`ReadFromParallelRemoteReplicasStep::initializePipeline`. The first is sound only
because of the second - a condition only the initiator has can fix a sort key
column, which lets a sort or an aggregation inside the fragment read in order,
and the initiator then announces `WithOrder`, with `#split_i` stream ids, against
the replicas' `Default`.

The rewrite does not always happen. `allow_push_predicate_ast_for_distributed_subqueries`
gates it, and under `serialize_query_plan` the replicas run a serialized plan and
never look at the rewritten AST - the log shows them planning with `Key
condition: unknown` while the initiator prunes by the equality. Either way the
condition stayed on the initiator alone and the coordinator raised

    Coordination mode mismatch for stream default.t: got Default, expected WithOrder
    Got read request from replica 1 for unknown stream default.t.

which is what the two reports below hit. Both reproduce on `master`.

So the whole-condition push-down now asks
`parallel_replicas_filter_pushdown_reaches_replicas` - the setting *and* the two
settings that decide whether the rewrite reaches the replicas - and otherwise
falls back to the split that only lets through what cannot fix a column.

While here, narrow that split with what the fragment reads: a fixed column only
ever matters against a sort key, so a fragment whose reads are all `ORDER BY ()`
takes the condition either way.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117373&sha=c81051d0d3076cbe57255fcd4f9d7f09f66c719c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117373&sha=c81051d0d3076cbe57255fcd4f9d7f09f66c719c&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%20selected%20tests%29
Related: #117373
@nickitat nickitat changed the title Always push filters into the parallel-replicas local plan Push a filter into the parallel-replicas local plan when it cannot change how that plan reads Sep 3, 2026
@devcrafter devcrafter self-assigned this Sep 3, 2026
The setting text and the surrounding comments described the rule the gate is
aimed at, not the one it implements. `mayFixColumn` takes any equality anywhere
in the atom, whatever it compares; `fixedColumnMayChangeReadMode` only asks
whether the fragment reads by a sorting key at all, never whether that key has
anything to do with the fixed column. So `WHERE b = 'x'` against a table sorted
by `a` waits for `parallel_replicas_filter_pushdown` even though it could safely
go in, and reading the setting's description you would expect otherwise.

Narrowing the test to the columns a sorting key is built from would mean
following the condition's inputs down through the fragment's own projections and
renames, which this pass - standing above a fragment it does not look inside -
cannot do. So describe the coarse rule instead of the ideal one, in the setting,
at the gate, and in the tests, and pin it: 05055 now also shows an equality off
the sorting key staying out.

What the relaxation is actually for is unchanged: a join runtime filter carries
no equality, so it goes in either way, and it is the one condition the setting
could never ship to the replicas.
…er the setting is on

`parallel_replicas_filter_pushdown_reaches_replicas` treated the settings as
proof that the replicas end up with the condition. They are not. `addFilters`
splices the predicate into the shipped query by attributing it to the single
table that query reads, and gives up when the join tree has more than one table
expression - which is exactly what parallel replicas ship when the join is
inside the fragment rather than above it:

    SELECT ts FROM (
        SELECT t.ts AS ts, t.tenant AS tenant
        FROM t AS t JOIN b AS bb ON t.tenant = bb.tenant
        ORDER BY t.ts
    ) WHERE tenant = 42 LIMIT 5

The initiator's fragment read this with `Key condition: (column 0 in [42, 42])`
while both replicas read it with `Key condition: unknown`. Nothing failed here
only because in-order did not fire through this join shape; the invariant the
gate rests on was gone all the same.

So split the shape half of `addFilters` out as `canAddFiltersToShippedQuery` -
it depends on the query, not on the predicate, so plan optimization can ask it
before there is a predicate - and record the answer on the local-plan step. The
plan-based path answers no outright: it ships a plan fragment, and the rewrite
that carries a predicate to the replicas never runs on it.

The residual is narrower and predicate-shaped: `tryBuildAdditionalFilterAST` can
still fail to express a particular predicate against the shipped projection.

Reported by clickhouse-gh[bot]:
#117373 (comment)
`shippedQueryCanCarryFilter` answered only what the query's join tree decides.
`addFilters` has two more ways to decline, and one of them is not about the join
tree at all: `PredicateRewriteVisitor::rewriteSubquery` refuses a subquery whose
`SELECT` list carries a window function, an `untuple` or a stateful function, and
it refuses for every predicate at once. A shipped query like

    SELECT tenant, ts, count() OVER (PARTITION BY tenant) AS c FROM t ORDER BY ts

read with `Key condition: (column 0 in [42, 42])` on the initiator and `Key
condition: unknown` on both replicas, with the setting on and the shape check
satisfied.

Every early return in `rewriteSubquery` depends on the subquery alone, never on
the predicate, so it can be asked ahead of time: split it out as
`canRewriteSubquery` and let `canAddFiltersToShippedQuery` ask it too. What is
left - whether *this* predicate can be expressed against what the shipped query
selects - is answered by building it, so `canAddFiltersToShippedQuery` now takes
the condition and runs the same `tryBuildAdditionalFilterAST` the real splice
runs. `tryPushDownFilter` puts the condition it is holding to it.

A predicate needing an `IN` set's temporary table is answered no rather than
registering one during the question. That is the safe direction and costs
nothing: an `IN` fixes no column, so it reaches the local plan by the other route
regardless.

The reported `untuple` case cannot arise on this path - the analyzer expands
`untuple` into `tupleElement` before the query is shipped - but window functions
survive, and they reach the same barrier.

Reported by clickhouse-gh[bot]:
#117373 (comment)
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 4, 2026
The overload added here had copied the sibling's skeleton - find the predicate,
give up on a constant one, build the actions, rebuild the DAG around what stayed
- and differed only in how it partitions the conjunction: by what each atom is,
rather than by which inputs are available. Two copies of that tail can drift.

Take it out as `findPredicateToSplit` and `splitConjunction` and route both
overloads through them, so each is left with only its own partitioning.

Trim the comments around the parallel-replicas gate while here; the block above
the push-down had grown to seventeen lines for one boolean.

Co-Authored-By: Claude Opus 5 <[email protected]>
nickitat and others added 4 commits September 27, 2026 13:11
Whether a condition pushed into the fragment the initiator runs locally also
reaches the replicas was answered for the fragment alone - the shape of the
query and the settings, via `canSpliceFiltersIntoRemoteQuery`. The rewrite that
performs the splice drops a conjunct it cannot write back as an AST, and a
lambda is one of those. A sorting key may be a higher-order expression, so that
conjunct can be the one that would fix a key column: the initiator would order
its read by something the replicas never receive, announcing `InOrder` against
their `Default`.

Ask the rewrite about the condition as well, through
`remoteRewriteDropsCondition`, which shares the test with the builder's own drop
path. It is asked conjunct by conjunct, the way the splice drops them: a plain
equality standing next to a lambda does travel, and withholding the ordering
there would leave the replicas the ones reading in order - diverging the other
way round.

Read-in-order does not match a higher-order key expression today, so the first
half of test 05259 guards the invariant rather than reproducing a failure; the
second half - `tenant = 5 AND arrayExists(x -> x = 1, arr)` still reading
`InOrder` - is what the per-conjunct question keeps.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
The walk over an `and` chain was a third traversal of the same condition next to
`mayFixColumn` and `remoteRewriteDropsCondition`. `mayFixColumn` already visits
every equality in the condition, so ask it there: with
`only_those_the_splice_drops` it counts only an equality whose own subtree the
splice cannot carry. Same answers, one walk less, and per equality rather than
per top-level conjunct.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
…r-pushdown

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
#	tests/queries/0_stateless/03733_pr_view_filter_pushdown.sh
Three things the merge needs:

`tryPushDownFilter` names its `ExtraSettings` parameter again - this branch had
dropped the name along with the only field it read, and master now reads
`filter_push_down_below_limit_by` from it. `filterPushDown.cpp` keeps its
`logger_useful.h` include as well, rather than relying on `Context.h` to pull it
in for the `LOG_DEBUG` calls already there.

`hasNonRewritableFunction` now also refuses a non-deterministic `SELECT` list
(master commit f1f9e98), because the pushed copy of a condition would call the
function a second time. So the replicas are no longer sent the condition for a
fragment whose select list calls `rand()`, and this branch correctly withholds
the ordering: that case of test 05183 reads `Default` now, and its wording says
why rather than treating non-determinism as the counter-example to
statefulness.

Tests that arm a fail point must be tagged `no-parallel` and `no-fasttest`
(master's new `failpoint_tests_are_isolated` check), which 05056 and 05161 do.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
nickitat and others added 2 commits October 12, 2026 16:33
What was asked of a pushed condition was whether the splice into the replicas'
query drops an equality. The answer covers the whole read, so a condition that is
only partly dropped lost the ordering it could have taken from the conjunct that
does travel: for `tenant = 5 AND arrayCount(x -> x = 1, arr) = 1` over a fragment
ordered by `ts` with key `(tenant, ts)`, the initiator read `Default` while the
replicas, whose query carries `HAVING and(equals(tenant, 5), 1)`, announced
`WithOrder` - the disagreement this is meant to remove, mirrored.

Ask instead whether an equality reaches them, and leave the read as it is when one
does. Conditions are pushed in one at a time and the first of them may not answer
for the rest, so an equality that reaches them also lifts a restriction taken for
a condition pushed earlier - the shape where the lambda-bearing conjunct sits in a
subquery read `Default` for that reason alone.

Both now read in order, against the replicas' `WithOrder`, while a condition that
leaves them nothing - `arrayCount(x -> x = 1, arr) = 1` on its own - still reads
`Default` on both sides.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
The test surface was wider than the invariant needs. `05183` pinned ten shapes
of the rewrite's refusal list; it now keeps one representative per family - a
subquery clause (`LIMIT BY`), a function property (a non-deterministic `SELECT`
list), and a shape the rewrite does take (`untuple`) - and the header names the
rest with the reason they answer the same way. A `LIMIT`, an `OFFSET`, a
`LIMIT AFTER .. UNTIL`, a `WITH` list, a named subquery, a window or stateful
`SELECT` list and `FINAL` leave nothing to withhold in the first place.

`05255` and `05259` asked the same question of the same fragment and ran the same
query-log check twice, so they are one test now, the lower number. Its own first
case went too: `tenant = 5 AND ts < 100000` ships whole, so the conjunct-by-conjunct
rule is pinned by the lambda cases, and the plain positive - a condition both sides
have ordering the read - is already `05055`.

Tests shrink by 195 lines; `filterPushDown.cpp` and the PR body name `05255` alone.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
nickitat and others added 5 commits October 12, 2026 17:47
The fixed-column restriction recorded the input columns under each fixed
expression rather than the expressions themselves. A fragment that fixes
`tenant % 2` allowed `tenant`, so with the splice off

    CREATE VIEW v AS SELECT tenant, ts FROM t WHERE tenant % 2 = 1 ORDER BY ts;
    SELECT tenant, ts FROM v WHERE tenant = 5 ORDER BY ts
    SETTINGS allow_push_predicate_ast_for_distributed_subqueries = 0;

read `InOrder` on the initiator against the replicas' `Default` and failed with
`Got read request from replica 1 for unknown stream`.

Rather than mend the snapshot, drop it. The initiator's copy of the fragment now
takes the conjuncts the splice carries to the replicas, as decided by the
splice's own conversion run on a copy of the condition, plus those that cannot
fix a column - a range, a join runtime filter. A conjunct the replicas would miss
and that could fix one stays above the fragment, so both sides order their reads
by the same conditions. Leaving a whole condition above would not do: the splice
still carries its other conjuncts, and `tenant = 5 AND rand() % 2 = 0` would then
have the replicas read in order and the initiator not. So the condition is split,
by a new `ActionsDAG::splitActionsForFilterPushDown` overload that takes the
conjuncts to push.

Gone: the snapshot on `SelectQueryInfo`, the restriction threaded through
`buildSortingDAG`, the walks that took and lifted it, and the lambda predictor
in `ReadFromRemote`. The cost is the local pruning an equality used to give
where the splice does not reach - a fragment the rewrite refuses as a whole, a
plan-based or serialized fragment, the splice switched off.

Tests: `05055`, `05255` and `05256` shared one fixture and are one test now,
with the case above added; the joining fragment of `05182` is one more refusal
in `05183`. `03787`, `04009`, `05045` and `03733` are back to pinning
`parallel_replicas_filter_pushdown` as master does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
`conjunctsLeftOutOfRemoteQuery` now runs `addFilters` - the splice - on a copy of
the query, rather than a separate statement of when it would run. `addFilters`
says whether it spliced and reports the conjuncts its conversion dropped; with
that, `canSpliceFiltersIntoRemoteQuery`, the `RewriteTarget` refactor and the
`subqueryAcceptsPushedPredicate` extraction go, and `PredicateRewriteVisitor` is
back to master. `ReadFromRemote.cpp` changes 87 lines instead of 234.

A filter left above the local fragment kept the next filter from reaching it,
while the remote step gathers the whole chain above it. With
`query_plan_merge_filters = 0`,

    SELECT tenant, ts FROM (SELECT tenant, ts, arr FROM v WHERE arrayCount(x -> x = 1, arr) = 1)
    WHERE tenant = 5 ORDER BY ts

read `Default` on the initiator while the replicas got `HAVING tenant = 5` and
announced `WithOrder`. Found by settings randomization of 05055. The push-down now
merges such a filter into the one below it, so the gate splits them together.

`05162` folds into `05055`: the same fixture, three more cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
`mayFixColumn` only looked for an equality in the DAG at the fragment's boundary,
where a column the fragment computes is an `INPUT`. With

    CREATE VIEW v AS SELECT tenant, ts, tenant = 5 AS is_five FROM t ORDER BY ts;
    SELECT tenant, ts FROM v WHERE is_five ORDER BY ts
    SETTINGS allow_push_predicate_ast_for_distributed_subqueries = 0;

`is_five` went into the initiator's copy of the fragment as order-neutral, the
composed DAG there exposed `tenant = 5`, and the read went `InOrder` while the
replicas, which never got the condition, stayed `Default`: `Got read request from
replica 1 for unknown stream`. The same with `serialize_query_plan = 1` and with any
fragment the splice refuses.

Read-in-order looks for an `equals` through aliases and `and` only, so an input
reached that way is what may turn into one; anything else wrapping an input stays
order-neutral. Test 05366 forces the replicas to take part with
`parallel_replicas_wait_for_unused_replicas` and
`slowdown_parallel_replicas_local_plan_read`; without this change it fails with that
`LOGICAL_ERROR`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
- 05055's check that the replicas are sent nothing with the push-down off is 03733's
  "filter pushdown can be disabled by setting".
- Its "no splice" (`tenant % 2 = 1` fragment) and "shipped as a plan" cases are the
  rule 05366 pins with the replicas forced to take part; the `tenant % 2` shape
  moves there.
- Its "same equality written inside the fragment" is a fragment's own filter
  ordering its read, master behaviour that 05161's first branch shows as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
nickitat and others added 2 commits October 12, 2026 20:43
…pty ranges

- `tryPushDownFilter`: the comment over the `parallel_replicas_filter_pushdown`
  check goes; the setting's own description says it.
- `conjunctsLeftOutOfRemoteQuery`: a conjunct the conversion dropped is always one
  of the condition's atoms - it is a child of an `and` in the chain from the root,
  which `extractConjunctionAtoms` descends - so a miss is a `LOGICAL_ERROR` rather
  than a silent skip.
- `ImplInterface::initializedWithEmptyRanges` is pure virtual: both coordinators
  answer it, and the `false` default is what had the in-order one report an empty
  stream as still holding ranges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
…n it is on

`mayFixColumn` does not look at the sorting key of the read inside the fragment, so an equality on an
unrelated column stays above too when the splice does not carry it. Narrow the comments to that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
@nickitat
nickitat marked this pull request as ready for review October 13, 2026 11:33
c-end pushed a commit to c-end/ClickHouse that referenced this pull request Oct 13, 2026
The rewrite writes the pushed predicate into the subquery's `HAVING`, which is
evaluated before the window functions `QUALIFY` filters by. So the predicate
changed which rows were numbered:

    SELECT count(), sum(ts) FROM (
        SELECT tenant, ts FROM remote('127.0.0.2', db, t)
        QUALIFY row_number() OVER (PARTITION BY tenant ORDER BY ts) <= 5
    ) WHERE ts % 20 = 0

answered 5, 200 instead of 3, 60, the shard having been sent
`HAVING ts % 20 = 0 QUALIFY ...`. This is the distributed path as it is on master;
parallel replicas only get there by the same rewrite, and the initiator's copy of
the fragment follows it.

Review: ClickHouse#117373 (comment)

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

clickhouse-gh Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

if (!condition)
return 0;

const auto missed = parallel_replicas_local_plan->conjunctsTheReplicasMiss(*condition);

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.

conjunctsTheReplicasMiss runs the whole splice here — buildFilterActionsDAG, query_ast->clone(), tryBuildAdditionalFilterAST, rewriteSubquery — but missed is only ever read as the left operand of the && below. When no atom can fix a column (WHERE ts < 190000, say) the result is discarded and every atom is pushed anyway.

Asking the cheap question first avoids it:

auto atoms = ActionsDAG::extractConjunctionAtoms(condition);
if (std::ranges::none_of(atoms, mayFixColumn))
    to_push = atoms;
else
{
    const auto missed = parallel_replicas_local_plan->conjunctsTheReplicasMiss(*condition);
    /* existing loop */
}

Behaviour-identical: with no column-fixing atom the && is false for all of them, so to_push already ends up holding every atom and some_stay_above stays false.

Measured ~0.5 ms/plan (4.0 vs 3.5 ms over 40 EXPLAIN runs; 12.0 vs 11.0 ms on a 40-column fragment). Minor and non-blocking — only the all-ranges case benefits, since any equality legitimately still pays for the dry run.

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.

@nickitat It's a bit nitpicking. so, up2u

@nickitat
nickitat added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit 92d73f5 Oct 14, 2026
349 of 351 checks passed
@nickitat
nickitat deleted the pr-local-plan-filter-pushdown branch October 14, 2026 09:34
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 14, 2026
The only conflict is in `tryPushDownFilter`, where master added a branch
that merges a filter into the one above `ReadFromLocalParallelReplicaStep`
(ClickHouse#117373) at the same spot this branch adds the `IntersectOrExceptStep`
case. The two are independent, so both are kept; master's branch stays
directly above the `ReadFromLocalParallelReplicaStep` case it refers to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-performance Pull request with some performance improvements 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.

3 participants