Skip to content

Cherry pick #125687 to 26.10: Pair reads by table for automatic parallel replicas over nested aggregations - #132388

Merged
nickitat merged 26 commits into
backport/26.10/125687from
cherrypick/26.10/125687
Nov 17, 2026
Merged

nickitat merged 26 commits into
backport/26.10/125687from
cherrypick/26.10/125687

Conversation

@robot-ch-test-poll4

Copy link
Copy Markdown
Contributor

Original pull-request #125687

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

nickitat and others added 25 commits October 14, 2026 15:03
`transplantAnalysisToAllReads` paired the reads of the two plans by the name the
analyzer gave each table expression, on the premise that both plans are built from
the same query so the names agree. They do not. The replicas plan's local plan is
built from the tree `buildQueryTreeForShard` returns, which re-runs
`createUniqueAliasesIfNecessary` - renumbering `__tableN` from 1 - over a tree
`inlineAliasColumns` and `rewriteJoinToGlobalJoin` have already rewritten. Where that
rewrite changes the traversal order the numbers land on different tables than the
initiator gave them, no read pairs up, and the whole optimization is declined even
when the cost model wanted it.

Three tables with the big one written last is enough. On a three-table join the
single-node plan named the reads `mid=__table2, small=__table3, big=__table4` and the
replicas plan named the same reads `mid=__table2, big=__table3, small=__table4`, while
`EXPLAIN QUERY TREE` shows the two query trees agree - the divergence is entirely the
shard-side renumbering. At TPC-H sf=100 this is what declines `q09`, whose cost model
had favoured parallel replicas and which plain parallel replicas runs 15% faster.

Pair by the table read instead: a table read once by each plan leaves only one
possible pairing and needs no name. The analyzer's name is kept for the one case that
still needs it, several reads of one table, where a mismatch declines as before.

The messages now carry the name and the per-table read counts. The old one said
"no counterpart of the same name" both for a read the other plan named differently and
for a read with no name at all, and printed neither.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017LMx8PkGBrowNrHvRMw4xi
Randomization turns it off, and without statistics the cost model does not favour
replicas for this data at all: the optimization is never applied, both shapes report
no replicas used, and the test fails having measured nothing. It failed once in 20
randomized runs; 30 in 30 pass with the setting pinned.

Found with `clickhouse-test --diagnose-random-settings`, which confirms the failure
comes from randomization and then minimizes it to the single setting.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017LMx8PkGBrowNrHvRMw4xi
…egation

Results are hashed by wrapping the query in
`SELECT sum(cityHash64(tuple(*))) FROM (...)`. Two such shapes were never
given parallel replicas even when the cost model wanted them: a `GROUP BY`
subquery (its reads did not pair up for the transplant of index analysis)
and a subquery with a redundant `ORDER BY` (the replicas kept sorting, and
the two plans did not match). Each shape is run until it can act on the
statistics, and every result is compared with the single-node one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in `05261`

The redundant `ORDER BY` shape of `05395_autopr_nested_query_shapes` needs
#125685, so it is commented out
with a reference to it.

`05261_autopr_transplant_analysis_table_order` reads two of its three tables
whole on every replica, about half of what the query reads, and the
duplicated-read limit merged into master since then declined it. Raise the
limit in the test: what it covers is the pairing of reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cache key of an expression is written by `ActionsDAG::serialize` with
`for_cache_key`, which leaves out the names the plan build chose and the
values of constants with no fixed size. `ColumnSet` is one of those, and the
set was told apart only by its `__set_<hash>` name, so `v IN (1, 2, 3)` and
`v IN (5, 6, 7)` computed in an expression got one key, and automatic parallel
replicas decided one query from the statistics collected for the other. Write
the set: `serializeConstant` writes only its hash, as `Node::updateHash` keeps
it for the same reason. A filter was not affected, because its predicate is
keyed through `getOutputIdentity`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Both tests only asserted that replicas were used at least once, so a run
that intermittently stayed single-node - the regression they are for -
still passed, and `05261` also left such a run out of its marks
comparison. Require both expected runs and replica use on each of them,
and compare the marks of every run with the single-node ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es-stacked

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
Master moved the automatic parallel replicas messages from the
`optimizeTree` logger to `AutoParallelReplicas`, so the `text_log`
search for `No stats found for hash` matched nothing and every run
reported statistics as found. Count `AutoParallelReplicasNoStatistics`
in `query_log` instead, which does not depend on the logger name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Nothing relies on the order: the maps by table are keyed by pointer, so
their order is arbitrary anyway, and the map by name is only looked up.
The ordered maps were left over from the pairing by `ReadIdentity`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es-stacked

# Conflicts:
#	src/Interpreters/ActionsDAG.cpp
#125685 is merged, so the
redundant `ORDER BY` shape of `05395_autopr_nested_query_shapes` is back.

`05261_autopr_transplant_analysis_table_order` compared only the selected
marks, which a read handed another read's analysis can leave unchanged:
the filter selects as many marks of `t_order_mid` as of `t_order_big`.
Print the result of every run too, so such a read shows as wrong rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`transplantAnalysisToAllReads` told several reads of one table apart by
the analyzer's `__tableN` name. The replicas plan's tree is rebuilt by
`buildQueryTreeForShard`, which renumbers those names over a join tree
`CrossToInnerJoinPass` may have reordered, so two reads can swap names
while each name still finds exactly one counterpart. For
`FROM d, t AS a, t AS b WHERE d.id = b.id AND a.id = b.k AND b.id < 20000`
each read of `t` was handed the other's mark ranges: 14576 rows instead
of 20000 with `AutoParallelReplicasApplied = 1`, or a
`THERE_IS_NO_COLUMN` exception when the two reads need different columns.

Identify a table occurrence by the `SELECT` it was written in (its whole
AST hash, without its own `SETTINGS`, which the replicas build may drop)
and the path to it under that `SELECT`'s `FROM`. Both builds derive it
from their own copy of the query's AST, which analyzer passes and the
shard rebuild do not touch. A read is identified only through a table
node of its own plan's tree, found by its `original_ast`, which clones
keep, and only when exactly one table in each tree has that identity:
a CTE or a view expanded twice, a read analyzed outside the tree (a view
that is not inlined, a table function), or a missing AST declines.

Reported in #125687 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…5628`

Two subqueries written alike give their reads of `t_occ_t` one identity,
although the join pushes different conditions into them, so the pairing
has to decline. Check that it does so once the cost model has favoured
replicas, by `AutoParallelReplicasCostModelEvaluated` followed by
`AutoParallelReplicasPlansNotComparable` with nothing applied, and that
the results stay equal to the single-node ones. A reused CTE does not
serve: its plans never match, so it is skipped before the cost model.
`optimize_move_to_prewhere` is pinned for the same reason: without it
this shape is skipped early too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`TableOccurrences` is keyed by the `ASTPtr` itself, which keeps it alive, so the
separate vector of kept ASTs goes. Each scope `SELECT` is hashed once rather than
once per table in it. `decideAtBoundary` takes the `PlanWithParallelReplicas`
instead of its plan and the two occurrence collections, the transplant takes each
counterpart from its map instead of copying them into a vector, and the occurrence
members are default-initialized, so the skip helper goes too.

`05628` keeps the three cases that test different things - reordered aliases,
`WHERE` against `PREWHERE` scopes, and scopes written alike - with one warmup and
one checked run each; the reference holds the correct results, so the single-node
baselines and the three-read chain go.

Related: #125687 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
…es-stacked

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
…nto autopr-nested-queries-stacked

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
Without a `SELECT` to identify the tables of a scope by, walking its join tree
recorded nothing; its subqueries are reached as its children anyway. Also say
why the path to a table is part of its identity: the tables of one scope share
the scope's hash.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`collectTableOccurrences` drops an identity that more than one table of the
tree has, so being found there already means being unique there, and
`certainOccurrence` only has to check that the other tree has the identity too,
instead of looking up and comparing counts in both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The single-node reads are grouped by table up front, and the finder takes the
table occurrences of both trees as arguments; the builder of the plan with
parallel replicas binds them with `std::bind_front`, instead of calling a
lambda that returned the finder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An identity that more than one table of a tree has is already dropped from its
`TableOccurrences`, so a read matched against a read of the other plan is unique
in both trees: the set of identities and the lookup in the other tree add
nothing. A paired single-node read is erased from the map, so a second claim
fails the ordinary lookup and `claimed` goes too. The transplant takes the
analysis with `getOrCreateAnalyzedResult`, and its comment is cut down to the
invariants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fix and its test `05396_autopr_cache_key_set_identity` are now in
#132104, which fixes it on master
independently of this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pair reads by table for automatic parallel replicas over nested aggregations
@robot-ch-test-poll4 robot-ch-test-poll4 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 17, 2026
Resolve conflicts against 26.10, which lacks `isInsertedDataOfTableFunction`
and `SelectQueryOptions::positionalArgumentsAlreadyResolved`: keep the 26.10
code around them and apply only the changes of the original PR.

Original PR: #125687
Cherry-pick PR: #132388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat merged commit d2e393e into backport/26.10/125687 Nov 17, 2026
1 check passed
@nickitat
nickitat deleted the cherrypick/26.10/125687 branch November 17, 2026 18:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants