Skip to content

Find the node to instrument through wrappers and equal inputs - #118657

Merged
nickitat merged 32 commits into
masterfrom
autopr-wrappers-min
Sep 26, 2026
Merged

nickitat merged 32 commits into
masterfrom
autopr-wrappers-min

Conversation

@nickitat

@nickitat nickitat commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Related: #118265


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

Version info

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

nickitat and others added 7 commits August 27, 2026 19:27
Three things kept the automatic-parallel-replicas decision from finding the
single-node counterpart of the top of its probe plan.

The wrappers between the `Union` and that node were peeled by two single-shot
checks - one for `Expression`/`Filter`, one for `CreatingSets` - so any stack
deeper than that left the top node on a wrapper. TPC-H `a02` builds
`Expression -> Limit -> Sorting`, and the search stopped at the `Limit`. Peel in
a loop instead, and include `Limit` and `Sorting`: like the `Filter` already
handled here, they change how much of the result survives or the order it
arrives in, never what the node below computes, so the bytes the replicas would
ship are the same either way.

The guard that rejects plans containing steps which cannot collect dataflow
statistics allowed `CreatingSetsStep` and `DelayedCreatingSetsStep` but not the
singular `CreatingSetStep`, though it is the same family in the same position
below the instrumented node. TPC-H `a02` at sf=100 is refused for exactly that.

Finally, a subtree hash cannot express every correspondence: an `Aggregating` on
the replicas side emits partial states for the initiator to merge while the
single-node plan aggregates to final values, so the two never hash equal even
though they are the same aggregation over the same rows. Their inputs do agree
once the cache key ignores branch-local naming, so when nothing hashes equal,
match a node of the same kind over an identically-hashing input - and only when
it is the single such candidate, so a wrong node is never instrumented.

With the cache-key change, the decision reaches the cost model on 32 of 44 TPC-H
queries instead of 27, adding `a05`, `a07`, `a10`, `o08`, `o09` and `o13`. Two of
them are queries where plain parallel replicas wins outright (`a10` -23%), so the
probe was being built and discarded without ever costing them. Results are
identical to single-node on all 44.

Co-Authored-By: Claude Opus 5 <[email protected]>
…strument

They are not pass-through steps: the replicas ship what comes out of them, so
matching a node below one would instrument a node carrying more rows than the
replicas would actually send, and the estimate would overstate their output.
Both already report `supportsDataflowStatisticsCollection`, so they can be
matched on their own terms and need no special treatment here.

The loop itself stays: it is what lets a stack of genuine wrappers be peeled,
where the two single-shot checks it replaced left the search stranded on the
second of `Expression -> CreatingSets -> Expression`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Uncommitted work carried over from the autopr-match-through-wrappers worktree, so
the starting point here is exactly the tree that was measured against #118265.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
It was justified by an `Aggregating` on the replicas side emitting partial states
where the single-node plan aggregates to final values, "so the two steps
serialize differently and never hash equal". That has not been true since
`Fold skip_final_flag into for_cache_key` (e5ea557, 2026-06-16), which stops
`AggregatingStep::serialize` from writing the `final` flag into a cache key -
two months before this fallback was written. The three `COUNT(*)` queries of
`03634_autopr_input_bytes_estimation_compact` match by exact hash under
`parallel_replicas_plan_based = 1`, and none of that test's eight queries ever
reaches the fallback.

What it compared was also weaker than a correspondence: the step's display name
and its children's hashes, and nothing about the step itself. An `Aggregating`
with a different `GROUP BY` over the same input is "the same kind over the same
input", and so is a `Limit 10` next to a `Limit 1000`. Requiring a unique
candidate does not make the one candidate the right node.

Where exact matching does fail on some other shapes, the cache key is what needs
fixing - a non-rename `Expression` serializes its DAG, branch-local names and
all - not a heuristic that ignores what the step does.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JXyGf21FeMvi7WmkstbFzN
`optimizePrewhere` replaces a fully-moved `Filter` with an `ExpressionStep` ("Have
to keep this expression to change column names to column identifiers"), and it
runs after expression merging has already gone by. So the plan is left with two
neighbouring `Expression` steps, which no plan built any other way carries - the
parallel-replicas local branch, for one, calls `tryMergeExpressions` again right
after optimizing itself.

That difference is not cosmetic. `calculateHashTableCacheKeys` hashes a node's
child through it even when the step's own contribution is zero, so one extra step
renumbers every node above it, and `findCorrespondingNodeInSingleNodePlan` can no
longer find the top of the replicas plan in the single-node plan. Automatic
parallel replicas then collects no statistics and never enables itself for those
shapes. Under `parallel_replicas_plan_based = 1` this is what kept
`03634_autopr_input_bytes_estimation_compact` (its `ORDER BY ... LIMIT` query),
`04341_autopr_mode1_apply_join` (`INNER` and `RIGHT`) and
`04100_autopr_input_bytes_estimation_aggregation_in_order` from matching; all
three pass now, and the `autopr` suite goes from 18 to 21 passing without
regressing anything in either implementation.

The updated references are plan shape only - two `Expression` steps becoming one,
and the indentation that follows. No query result changes.

Related: #118265

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

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b41496b]

Summary: ✅


AI Review

Summary

This PR tightens automatic parallel replicas boundary matching by distinguishing true pass-through ExpressionSteps from computed projections, walking wrapper chains more consistently, and declining set-building roots that cannot be safely replaced. The current head also adds focused coverage for window, projection, reorder, wrapper-chain, and set-root shapes. I did not find an unresolved correctness, safety, or compatibility issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit b41496b.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 95/105 (90.48%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 7, 2026
nickitat and others added 4 commits September 8, 2026 11:57
The previous commit re-ran `tryMergeExpressions` over the whole plan after the
PREWHERE pass. That repairs the double-`Expression` the pass leaves behind, but it
also collapses neighbours everywhere else - pairs the earlier merging round had left
alone for its own reasons - and it showed up as 79 further plan references CI had to
be told about, on top of the 30 the commit already carried.

Merge only above what the pass actually rewrote instead. `optimizePrewhere` turns a
fully-moved `Filter` into an `ExpressionStep` in place, so record those nodes as they
are visited and, on the way back up, merge a node with its single child only when that
child is one of them. Children are left before their parent, so the record is complete
by the time it is read. The merge cannot cascade: it does not change the parent's step
kind, and the parent and its own parent were already merged in the earlier round.

That brings the reference churn from 109 files to 75, and the 34 files it drops are
exactly the ones with no PREWHERE in them - `Left Pre Join Actions` over `Change column
names to column identifiers`, and the like. The 75 that remain are the plan shape the
fix is for: two `Expression` steps becoming one where a filter moved into PREWHERE, and
the indentation below it. No query result changes.

Note that this makes the affected `EXPLAIN` output depend on `optimize_move_to_prewhere`
and `query_plan_optimize_prewhere`, which the functional-test runner randomizes; on
master both settings produced the same step count for these plans. Seven of the tests
flaked once each across ten randomized runs of the set. Merging over the whole plan has
the same property, so this is a cost of repairing the leftover at all, not of scoping it.

CI report for the previous commit:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=latest&name_0=PR
Related: #118657
Related: #118265

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
Both the whole-plan version and the scoped one fixed the double-`Expression` by
changing the plan, which costs 75-109 plan reference files and makes the affected
`EXPLAIN` output depend on `optimize_move_to_prewhere` / `query_plan_optimize_prewhere`
- settings the functional-test runner randomizes, and which produced the same step
count on master. Seven tests flaked once each across ten randomized runs.

The node that has to disappear is only ever hashed, so remove it from the key instead
of from the plan. Done in the next commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
`calculateHashFromStep` already returns 0 for a row-preserving step whose output
keeps its input's byte layout - a rename is exactly that. But returning 0 only skips
the step's own contribution, not the step: the node still gets a frame, still does
`frame.hash.update(cache_keys[child])`, and still calls `get64()`, so its key is
`SipHash(key(child))` rather than `key(child)`. Such a step is free of content but
not free of position, and every key above it shifts when it is present.

That is what `optimizePrewhere` runs into. A filter fully moved into PREWHERE leaves
an `Expression` in the `Filter`'s place, and expression merging has already run by
then, so the plan is left with two neighbouring `Expression` steps that no plan built
any other way carries - the parallel-replicas local branch, for one, merges
expressions again right after optimizing itself. One extra step renumbers everything
above it and `findCorrespondingNodeInSingleNodePlan` can no longer find the top of
the replicas plan in the single-node plan.

Adopt the child's key instead of re-hashing it. The step becomes genuinely invisible:
a plan that carries one and a plan that does not agree on every key above it, and no
plan has to change shape for them to agree.

Because a chain of such steps - and the step below it - now answer to the same hash,
`findCorrespondingNodeInSingleNodePlan` has to choose within the chain rather than
take whatever the unordered map yields first. It walks the plan bottom-up and takes
the lowest node, since the numbers a chain shares are the ones its bottom produces:
instrumenting a rename over an `Aggregating` would measure the finalized values
instead of the partial states replicas ship, which
`04100_autopr_input_bytes_estimation_aggregation_in_order` sees as an output estimate
~3x too small. A chain bottoming out in the reading step is the exception - that step
records only input bytes - so there the lowest wrapper above it is taken, mirroring
`findTopNodeOfReplicasPlan` stopping above the read on the other side.

Under `parallel_replicas_plan_based = 1` the `autopr` suite goes from 18 to 21 passing:
`03634_autopr_input_bytes_estimation_compact`, `04341_autopr_mode1_apply_join` and
`04100_autopr_input_bytes_estimation_aggregation_in_order` now match. With
`parallel_replicas_plan_based = 0` it is unchanged at 23. No plan changes, so no query
plan references move.

CI report that prompted this:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=latest&name_0=PR
Related: #118657
Related: #118265

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
`04502_autopr_input_bytes_estimation_window_function` asserted that a window function
over a bare table scan collects no statistics at all. Its reasoning was that the
matched boundary is the reading step, which records only input bytes, so proceeding
would feed `output_bytes = 0` into the cost model - "shipping all pre-window rows to
the initiator is free".

That premise no longer holds. `findTopNodeOfReplicasPlan` stops one step above the
read rather than peeling all the way down to it, and the wrapper it stops on does
record output bytes: for this query input is 1945308 and output 1950927, the
pre-window rows the replicas would ship, not zero. The cost model then reaches the
same conclusion the blanket skip did, but on measurements - `1945308 / 1 ? (1945308 / 1
+ 1950927 / 3)`, so local reading wins and parallel replicas are not applied - and
unlike the skip it can still engage on shapes where shipping is genuinely cheaper.

So assert what now happens rather than inverting the old flag to `0` and leaving a
column named `read_boundary_skipped` behind: statistics are collected, and the recorded
output is a real measurement bounded by the input, since a pass-through wrapper ships
what it read. Ran 12 times with settings randomization; the bound holds.

The `autopr` suite goes to 24 passing with `parallel_replicas_plan_based = 0` and 22
with it set, in both cases this test and nothing else changing.

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

`isPassThroughWrapper` accepted every `ExpressionStep`, on the grounds that looking
through one is "safe most of the time". It is not. The first-stage planner deliberately
places real computation below the `Union` for queries that finish on the initiator:
`Before WINDOW` for a window function, `Projection` and `Before ORDER BY` otherwise
(`Planner.cpp`, and `PlannerExpressionAnalysis.cpp` where `before_window_actions`
materializes the window arguments, partition keys and order keys). Those columns are
part of what the replicas send, so peeling such a step lands below the real boundary and
undercounts the output.

The bare-window shape normally hides this, which is why it went unnoticed: expression
merging folds `Before WINDOW` into the rename above the read, and the read guard in the
loop then stops on the merged step. Take the merging away and the two stay separate -
with `query_plan_merge_expressions = 0` the loop peels through `Before WINDOW` and stops
on the rename, and the instrumented header comes out as `key UInt64, value UInt64` where
the replicas actually ship `value UInt64, modulo(key, 10) UInt8, key UInt64`. The
partition key drops out of the estimate.

So peel an `ExpressionStep` only when it is byte-transparent - it preserves the number of
rows and its output byte layout equals its input's, which is what a rename is and what a
materializing expression is not. That test already existed inside
`calculateHashTableCacheKeys`, deciding which steps contribute nothing to a cache key;
it is now `isByteTransparentTransform`, shared by both. The two must agree: a step
invisible to the key but visible to the boundary search (or the reverse) would be
instrumented in one plan and matched in the other.

`DelayedCreatingSetsStep` and `CreatingSetsStep` pass their rows through by construction
and are unchanged. The type restriction stays, so `Limit` and `Sorting` are still not
looked through.

`04502_autopr_input_bytes_estimation_window_function` covers it now, with the merging
pinned off and a wide `String` partition key so the two boundaries are far apart:
stopping on `Before WINDOW` records ~3.1x the input bytes, stopping on the rename ~1.0x.
Verified the check fails on the old behaviour. The `autopr` suite is unchanged at 24
passing with `parallel_replicas_plan_based = 0` and 22 with it set, and the 119
plan-reference tests all pass.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
nickitat and others added 2 commits September 8, 2026 20:21
`isByteTransparentTransform` compares output column types position by position, which
was fine while it only chose which steps contribute nothing to a cache key - the
worst case there is a slightly-off estimate. The previous commit gave it a second job,
deciding which steps the replica-boundary search may look through, and the same
approximation is not good enough for that: a wrong choice there instruments a node
below the boundary and hands Auto-PR an output figure that is not what the replicas
send.

The first-stage `Projection` is the arbitrary DAG built from the query's projection
list (`Planner.cpp`, `PlannerExpressionAnalysis::analyzeProjection`), so it can keep the
column count, the positions and the type names while changing how wide the values are.
`SELECT repeat(a, 20) AS a, b` over two `String` columns is such a step, and with the
expressions left unmerged it was peeled: the estimate came out at 1.56x the bytes read
where instrumenting the projection gives 4.09x, so the query was costed on well under
half of what it ships.

Settle it on the DAG instead: an expression is transparent when every output traces back
to an `INPUT` through `ALIAS` links alone. A `FUNCTION` or a constant `COLUMN` means the
step puts something in the column that was not read. The header comparison stays as the
first, cheap condition, and the other transforming steps - which have no expression to
inspect - are decided by it as before.

One consequence worth naming: `SELECT repeat(a, 20) AS a, b FROM t` under default
settings now collects no statistics at all rather than an estimate. Its projection is
folded into the reading step in the single-replica plan and kept as its own step in the
parallel-replicas plan, so with the two no longer transparent their keys stop matching.
That is the fail-closed direction and the direction this branch has taken before (see
`Drop the same-kind-over-same-input fallback`): no decision beats a decision made on
the wrong bytes.

`05136_autopr_projection_is_not_peeled` covers it. It compares the recorded output of
the widening query against that of the same query with a rename-only projection, so the
compression codec and block sizing move both alike and drop out - instrumenting the
projection records about eight times the baseline, peeling it records the same as the
baseline. Verified against a build without the DAG check, on a freshly started server:
4.22M vs 4.26M there, 34.6M vs 4.27M here. 15 randomized runs pass.

The `autopr` suite is unchanged apart from the new test, at 25 passing with
`parallel_replicas_plan_based = 0` and 23 with it set, and the 119 plan-reference tests
all pass.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
The check added in `Peel only byte-transparent expressions when locating the replica
boundary` compared one query's recorded output against its own input. Those are not
alike: the input is a compressed read, the output a serialized estimate, and the codec
moves them apart - the same trap `04100_autopr_input_bytes_estimation_aggregation_in_order`
avoids by pinning `default_compression_codec` and refusing randomized settings. It
passed here and failed in CI: `Stateless tests (amd_tsan, parallel)` already reproduced
it 13 times out of 13 at the commit that introduced it, and `Fast test` followed one
commit later.

Rewriting it to compare the unmerged run against a merged one - the form that made
`05136_autopr_projection_is_not_peeled` robust - does not work either: with the wide
partition key both runs record the same figure whether or not the expression is peeled,
so the check stops discriminating. Built without the peel restriction to confirm that,
and it passes there, which makes it worthless as a regression test.

`05136_autopr_projection_is_not_peeled` covers the same mechanism - an `ExpressionStep`
that materializes a column must not be looked through - and it does discriminate: on a
freshly started server it records 4.22M against a 4.26M baseline without the fix and
34.6M against 4.27M with it. So drop this one rather than keep a check that fails where
it cannot be reproduced and passes where the bug is present. 04502 returns to the shape
that was green in CI.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
Two questions were being answered by one predicate, and it was too loose for the harder
of them.

A step contributes nothing to a cache key when it changes neither the row count nor the
byte layout. Being wrong there costs a slightly-off estimate, so the header comparison is
good enough, and that is what it goes back to.

Whether a step can be *skipped over* - looked through when locating the boundary the
replicas ship from, and collapsed onto its child when keying it - is stricter, and now has
its own predicate. An `ExpressionStep` qualifies only when its outputs are a permutation of
its inputs: each traces back to an `INPUT` through `ALIAS` links alone, and no two land on
the same one. Requiring only the first half let `SELECT a AS x, a AS y` over `(a, b)` pass,
which keeps two `String` columns in the header while what leaves the step is `a + a`, not
`a + b`. (Column pruning usually drops `b` from the read and the arity check then rejects
the step anyway, so I could not construct a query where this bites today - the guard is
there because the rule should be right, not because a shape was found.)

The narrower predicate also keeps a full `SortingStep` out of it. Sorting preserves rows and
layout, so it contributes nothing to a key - but the previous commit let anything that
contributes nothing adopt its child's key, and `findCorrespondingNodeInSingleNodePlan` picks
the lowest node of a shared key, so a `Sorting` at the top of the replicas plan could be
matched to the step below it. That undoes `Do not look through `Limit` and `Sorting` when
picking the node to instrument`. Adoption is now restricted to pass-through expressions,
which is all the PREWHERE leftover ever needed.

Putting the key contribution back to the header rule also restores what the previous commit
cost: `SELECT repeat(a, 20) AS a, b FROM t` under default settings collects statistics again
(input 2725026, output 1115715) instead of failing to match. The projection is still not
peeled - that is the strict predicate's job, and `05136_autopr_projection_is_not_peeled`
still passes.

Verified on freshly started servers: the `autopr` suite at 25 passing with
`parallel_replicas_plan_based = 0` and 23 with it set, the 119 plan-reference tests green,
and 12 randomized runs of both autopr tests green.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
nickitat and others added 2 commits September 9, 2026 13:58
`sameByteLayout` and `isByteTransparentTransform` moved into the file's anonymous
namespace when they stopped being shared, and `static` is redundant there.
`readability-static-definition-in-anonymous-namespace` fails the `Build (arm_tidy)` job
on it.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=adcb292d321c723b2913f14279b7f746dea04eca&name_0=PR&name_1=Build%20%28arm_tidy%29
Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
`findTopNodeOfReplicasPlan` peels the wrappers between the `Union` and the node the two
plans have in common, and its comment is about a chain that mixes kinds - the very case
`Expression -> CreatingSets -> Expression` that used to leave the search stranded. Every
test so far only ever fed it expressions.

The chain is real. Instrumenting the loop to log what it walks shows that any
`IN (subquery)` produces `Expression`, `DelayedCreatingSets`, `Expression` before the
search stops, with the set step in the middle - in the projection, in the `WHERE`, with
two sets, and with `correlated_subqueries_use_in_memory_buffer = 0` alike. Without a set
the same query walks three expressions and no set step at all.

So this pins the shape that has one. Stopping early there is not a near miss:
`DelayedCreatingSets` does not support dataflow statistics collection, so a search
stranded on it matches nothing in the single-replica plan and the query records nothing.
The check is zero against non-zero for exactly that reason - and because the recorded
figures are a compressed read on one side and a serialized estimate on the other, which
the codec moves apart, so any ratio between them holds on one build and not another.

Verified it discriminates: with the set steps taken back out of `isPassThroughWrapper`
the search strands on `DelayedCreatingSets` and the check reads `0`.

The test does not pass under `parallel_replicas_plan_based = 1`, where this shape
collects no statistics at all - one more of the nine that implementation already fails.
That setting is not randomized by the test runner, and the `distributed plan` CI lane
sets `serialize_query_plan = 1` instead, under which the test passes.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b41496b73 with master a32c4c20b (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

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

Job report

`03800_autopr_reuse_index_analysis` fails on every stateless job: its `GLOBAL IN` query
reports 4 rounds where the reference says 3. It never fails on master, and it was
`SKIPPED` on the earlier commits of this branch because only `Fast test` had run, so
this is the first time CI executed it here.

A `GLOBAL IN` runs its subquery as a plan of its own, so Auto-PR is asked about it a
second time. Letting `CreatingSetStep` through the "simple enough" gate - which is what
makes Auto-PR consider `IN`-subquery plans at all - now carries that second ask far
enough to build a probe plan, and the probe's index analysis is not reused. It then
fails to find a matching node, so the round is spent for nothing. The decision log shows
the difference plainly: where the merge-base stops at `Unsupported steps: CreatingSet_62`,
this branch goes on to a second `Top node of replicas plan: Aggregating`.

Reproduced away from `test.hits` on a synthetic stand-in - the same `GLOBAL IN` shape
under `automatic_parallel_replicas_mode = 1` - measured on freshly started servers with
freshly loaded data:

    merge-base                                              3
    this branch                                             4
    this branch + `autopr-transplant-index-analysis`        4
    this branch + `autopr-probe-does-not-materialize-subqueries`  2

So the round goes away with `Do not materialize subqueries while costing a plan that may
be thrown away`, and that branch takes the query to 2 - below what it was before this
one. Transplanting the index analysis does not touch it.

Take the 4 for now with a comment naming the fix, rather than narrowing the gate: the
gate is what `IN`-subquery support rests on, and narrowing it would take
`05137_autopr_set_step_in_wrapper_chain` with it.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=latest&name_0=PR
Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
nickitat and others added 3 commits September 11, 2026 18:10
`findCorrespondingNodeInSingleNodePlan` said "take the lowest node of the chain" in a comment and
got there by relying on `traverseQueryPlan`'s leave-callback being post-order, so that the first
match with children happened to be the lowest on its path. That dependency was written down
nowhere, and `matched_leaf` existed only so a reading step forming a whole chain on its own still
reached the caller's fail-close.

Say it in the code instead: find any member of the chain, then walk down while the single child
carries the same key. That is the bottom by construction rather than by traversal order, and the
leaf case stops being special - a read with nothing above it is simply the bottom, so the
fail-close stays reachable and `matched_leaf` goes away.

`isPassThroughExpression` moves from `Optimizations.h` to `Utils.h`. It has to be shared, since
the two users must agree on it or a step is instrumented in one plan and matched in the other, but
`Optimizations.h` lists plan-optimisation entry points while `Utils.h` is where shared helpers
live. The definition stays next to the two private predicates it composes, so
`isByteTransparentTransform` remains un-exported - keeping those two notions apart is the point of
`adcb292d`.

Also: the forwarded-input set is now `UnorderedSetWithMemoryTracking`; a note on
`expressionPermutesInputs` records that a forwarded column is an `INPUT` whether or not it is
constant (`ActionsDAG::addInput` never sets `node.column`), so a `COLUMN` output is always a
constant the step materialized itself and rejecting it is right; and three comment blocks that
explained more than they earned are gone.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
@thevar1able thevar1able self-assigned this Sep 23, 2026
nickitat and others added 3 commits September 23, 2026 17:35
Letting `CreatingSetStep` through the "simple enough" gate made Auto-PR consider plans it had
been skipping, and a set-building plan is one of them. `FutureSetFromSubquery::build` finishes
with `plan->addStep(CreatingSetStep)`, so such a plan is rooted in the step that fills the set,
and that root is what gives it the empty header `addPlansForSets` hands to `CreatingSetsStep`.
`makePlansForSets` optimizes each of those plans, so `considerEnablingParallelReplicas` runs with
that `CreatingSetStep` as the root.

Switching to the candidate replaces the root, and the candidate is built without a set-building
step of its own, so the plan would come back carrying the subquery's columns and
`CreatingSetsStep` would reject it: `Creating set input must have empty header`. Today the match
fails before it gets that far, which is the only reason this has not fired - and making the match
succeed more often is exactly what the rest of this branch does.

So refuse at the root. Only the root matters: a `CreatingSetStep` further down belongs to a set
the plan consumes rather than builds, and the steps above it are replaced without disturbing it -
`05137_autopr_set_step_in_wrapper_chain`, whose query reads through a set, still collects its
statistics.

This also retires the temporary bump in `03800_autopr_reuse_index_analysis`. A `GLOBAL IN` runs
its subquery as a plan of its own, and that plan is set-building, so the second ask now stops at
the root instead of building a probe whose index analysis is not reused. `query_6` is back to 3
without waiting for `autopr-probe-does-not-materialize-subqueries`, so the reference and the note
pointing at it are reverted.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
The refusal itself is not directly observable - the exception it prevents is currently out of
reach, because a set plan that would be switched only exists once the query around it has already
switched, and such a plan carries `Union` / `ReadFromRemote` steps that the statistics-support gate
rejects first. What is observable is the work the refusal saves. AutoPR prices a switch by building
a probe plan, and building one runs index analysis, so considering a set-building plan costs a
round whatever the verdict.

`GLOBAL IN` runs its subquery as a plan of its own, so the count is easy to pin: three rounds with
the refusal in place, four without. Verified both ways on one binary, with the refusal made
switchable at run time for the comparison, and through `clickhouse-test`: 10/10 with and without
settings randomization, and the test fails with `4` when the refusal is removed.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
`isPassthroughActions` already exists in the same header, and it cannot be reused here: it asks for
`getOutputs() == getInputs()`, and a rename makes the output an `ALIAS` node standing for the input
rather than the input itself. Every analyzer query is bracketed by exactly such steps - `Change column
names to column identifiers` going in, `Project names` coming out - so the identity test recognises no
wrapper at all. Substituting it loses the statistics on 13 of the `autopr` tests, among them
`04035_autopr_no_parallel_replicas_for_small_reads` (`stats_collected` 1 -> 0) and
`05137_autopr_set_step_in_wrapper_chain`; only the join shape of issue 118265, whose extra step really
is an identity, survives. It is also stricter in a second way that does not serve us: `trivial` walks
every node, so a `FUNCTION` unreachable from the outputs disqualifies the step.

So keep the predicate and name it for what it allows, in the spelling the neighbour uses:
`isPassthroughExpressionWithRenames`, over `outputsAreRenamedInputs`, with `isPassthroughWrapper`
following suit. The comment now says why the two are not one function, so the next reader does not have
to rediscover it.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
@nickitat
nickitat enabled auto-merge September 25, 2026 21:22
Every regression added here ran with `parallel_replicas_plan_based` at its default 0, so they only
watched the query-based walk - and the mismatches this PR is about are the plan-based ones, where the
boundary is a `ReadFromParallelReplicasStep` and the wrappers above it are laid out differently. Each
scenario now runs in both implementations.

The plan-based rows are not decoration. On the merge-base binary both rows of
`04502_autopr_input_bytes_estimation_window_function` report `0`, so the plan-based half of that shape
would have caught the boundary landing on the read just as the query-based half does.

`05218` needed a second measure to stay meaningful. Under plan-based the refusal costs no round at all -
that implementation matches this shape, so it prices the switch from the statistics instead of
re-analysing - and the round count alone cannot see it. `ParallelReplicasQueryCount`, the number of
queries AutoPR weighed up, can: the refusal takes it from 2 to 1 there, and from 4 to 2 under
query-based. Removing the guard moves both rows again.

Worth recording for whoever reads the logs: this `GLOBAL IN` shape is one the query-based walk gives up
on (`Cannot find step with matching hash in single-node plan`) while plan-based matches it, so
plan-based is the implementation that reaches the set-building plan in the first place.

Verified with settings randomization and without, 10 runs each, all four tests.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
nickitat and others added 2 commits September 25, 2026 23:43
… position

`sameByteLayout` compares the two headers column by column, so an expression that only reorders its
columns passed for a wrapper when the types happened to line up and failed when they did not.
`SELECT b, a` over `(a UInt64, b String)` is the second case, and the planner really does emit that
reorder as a step of its own - a `Project names`, a `Projection`, or the merged expression above a JOIN.

Decide it from the mapping the DAG already gives instead: each output traced to a distinct `INPUT`
through `ALIAS` links, as many outputs as inputs. That makes the mapping a bijection, and since an
`ALIAS` carries its child's type, following each output to its input compares like with like - the
column set and the bytes are the same however they are ordered. No header comparison is left in the
predicate.

This costs statistics today, not just in theory. For
`SELECT r.b, l.a FROM left AS l JOIN right AS r ON l.a = r.a` the reorder sits above the JOIN, the
boundary stops on it, its key matches nothing in the single-node plan, and the query records nothing at
all: `RuntimeDataflowStatisticsInputBytes` and `...OutputBytes` both 0, now both non-zero.
`05243_autopr_reordering_wrapper_is_looked_through` covers that shape and the simpler reorder over a
read, in both implementations, and its JOIN row fails on the commit before this one.

The `Union` branch that reads from the other replicas is the same question from the other side, and it
should never have been asked there: that branch is never instrumented, only recognised, so walk down to
it through anything with a single child, as `readingFromParallelReplicas` in `optimizeReadInOrder`
already does. A wrapper we could not see through used to be mistaken for a second branch to instrument,
which skips the whole query. Master peeled one `Expression`/`Filter` there unconditionally and this is
what restores that tolerance. It is untested: the shape does occur - a materialized CTE puts an
`Expression` above `ReadFromRemoteParallelReplicas` - but AutoPR does not consider those plans at all,
so there is nothing to assert on yet.

Also drop `index_analysis_rounds` from `05218`. How many rounds a consideration costs depends on what
index analysis can reuse, which moves with the environment - the plan-based figure is 2 here and 3 in
CI, which is what the flaky check caught:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=295acb7b1cb2013b9799d9907cba26521cf07c07&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29
`ParallelReplicasQueryCount` is the figure that answers the question the test asks, and it is the one
that moves in both implementations when the refusal is removed.

Related: #118657

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

`ParallelReplicasQueryCount` looked like the right figure and is not: it is raised when the reading
coordinator is destroyed, which need not happen while the query is still the accounted one. In Fast test
both rows came back `0` although AutoPR runs there quite normally - `04341_autopr_mode1_apply_join`
applies parallel replicas in the same job:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=ee68279bc7d6a95272f41fc83959bfb6e49594c7&name_0=PR&name_1=Fast%20test

Both figures tried so far measure what the refusal happens to save rather than the refusal, and both move
with the environment - the rounds of index analysis with what index analysis can reuse, the query count
with where a destructor runs. So assert the refusal: the optimization logs it, `system.text_log` keeps it,
and a `GLOBAL IN` brings a set-building plan in front of AutoPR in both implementations. With the guard
removed the line is absent and both rows read `0`, which is the whole point of the test.

Also switch both this test and `05243` from `LIKE` to `startsWith`. `_` is a single-character wildcard in
`LIKE`, so `'05243_wrapper_over_%'` was one character away from matching the harness's own log comment.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
`outputsAreRenamedInputs` needs both halves to mean anything: as many outputs as inputs, and no two
outputs forwarding the same input. Only the first half is reachable from SQL. For a duplicating step to
have matching arity it must also drop an input, and the analyzer prunes a column the step above it does
not use, so every duplication the planner emits differs in arity and is refused on the count alone.

Measured rather than assumed. With `SELECT a AS x, a AS y FROM t WHERE b != ''` the recorded output bytes
come out around 1.5x the `SELECT a AS x, b AS y` baseline, which looks like the wanted signal but is just
the query shipping two wide columns instead of one wide and one narrow: removing the uniqueness check
leaves those figures where they were (3.39M vs 3.67M against a 2.2M baseline, fresh server each time, both
implementations). The step's input header carries one column there, so the arity check answers first.
Pinning `query_plan_remove_unused_columns = 0` does not change that - the pruning is the analyzer's, not
that optimization's. A SQL test built on this pair would stay green with the check gone, which is the
false comfort worth avoiding.

So assert the predicate directly, since `isPassthroughExpressionWithRenames` is shared through `Utils.h`
anyway. Six DAGs over `(a UInt64, b String)`: a rename and a reorder of unlike types are looked through, a
duplicate alias, a dropped input, a computed output and a materialized constant are not. Deleting the
uniqueness check fails exactly one of them and leaves the other five green, which is what a regression
there would look like.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
…e gate still refuses them

`DelayedMaterializingCTEsStep` is as transparent as `DelayedCreatingSetsStep` - the main stream is its
only child - so `isPassthroughWrapper` now names both CTE steps alongside both set steps. Whoever opens
the gate to them will not find the boundary search stranded on one.

The gate itself stays shut, and the reason is measured rather than assumed. Relaxing it does get a query
with `enable_materialized_cte = 1` past the refusal: with two references to a materialized CTE, both
behind `IN` subqueries, the placeholder is the only step the gate objects to
(`Unsupported steps: DelayedMaterializingCTEs_24`), and with it allowed through the boundary is found.
Matching then fails anyway - `Cannot find step with matching hash in single-node plan` for the query-based
implementation, `contains no read from the other replicas` for the plan-based one - so nothing is
collected either way. Letting a transparent step adopt its child's key, which is what makes the two plans
agree elsewhere in this file, does not change that either: the wrapper is demonstrably not what blocks
these queries. Since AutoPR pays for a probe plan, index analysis included, the moment it takes a query
seriously, opening the gate now would cost every materialized-CTE query a round and parallelize none of
them - the same argument the set-building refusal in this file rests on.

So no regression test with it: there is no outcome to assert beyond the refusal that is already there.
The comment records what was tried, so the next attempt starts from the matching rather than from here.

Related: #118657

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bLFeSCQeaKGvcA5ZHYGK7
@nickitat
nickitat disabled auto-merge September 26, 2026 17:23
@nickitat
nickitat enabled auto-merge September 26, 2026 17:23
@nickitat
nickitat added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit 62a371c Sep 26, 2026
339 of 341 checks passed
@nickitat
nickitat deleted the autopr-wrappers-min branch September 26, 2026 21:41
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 18, 2026
`automatic_parallel_replicas_mode` = 1 is the only mode that runs the cost model
and replaces the plan with the parallel-replicas one. The settings randomizer in
`clickhouse-test` picks only 0 or 2, and mode 2 collects statistics without ever
switching, so today the plan-rewriting half of the optimization is covered only
by the handful of tests written for it.

Reading the server log of `Stateless tests (amd_debug, parallel)` on a recent run
shows the shape of the gap: of 5971 probe plans built, 26 reached the cost model
and 18 switched - and all 18 came from AutoPR's own tests. Not one of the ~14000
other tests ever exercised the switch.

Add `Stateless tests (amd_debug, AutoParallelReplicas, parallel)` and its
sequential counterpart, which install a profile pinning mode 1. The profile also
sets `automatic_parallel_replicas_min_bytes_per_replica` to 0: stateless test
tables read far less than the 1 MiB per replica the setting defaults to, so
keeping the default would make the cheap pre-check reject every plan before the
probe is built and the jobs would pass without exercising anything.

`clickhouse-test` gains `--autopr`, which stops the randomizer from sending a
per-query `automatic_parallel_replicas_mode` that would override the profile the
job just installed.

The jobs reuse `parallel_replicas_blacklist.txt`, but tolerate-only: a listed
test may fail without failing the job, and - unlike the forced parallel-replicas
job - a listed test that passes is not turned into `NOT_FAILED`. AutoPR switches
a query only when its statistics say it pays off, so most blacklisted tests
legitimately keep passing, and the usual inversion would report all of them as
needing removal from the list.

Log analyzed:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118657&sha=latest&name_0=PR&name_1=Stateless+tests+(amd_debug%2C+parallel)
Related: ClickHouse#118657

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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-not-for-changelog This PR should not be mentioned in the changelog 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