Skip to content

Pair reads by table for automatic parallel replicas over nested aggregations - #125687

Merged
nickitat merged 24 commits into
masterfrom
autopr-nested-queries-stacked
Nov 17, 2026
Merged

nickitat merged 24 commits into
masterfrom
autopr-nested-queries-stacked

Conversation

@nickitat

@nickitat nickitat commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Improved logic of matching read steps between single-node and parallel replicas plans. This fixes a potential wrong query result in case of an incorrect matching and also makes the automatic parallel replicas optimization applicable to more queries.


Related: #116781
Related: #125685

Stacked on #116781: the base branch is autopr-build-independent-cache-keys, and only the commits on top of it belong to this PR. Before 116781, the plan hash of a nested query includes the analyzer's __tableN names, so the plans never match and this fix has nothing to act on.

Automatic parallel replicas never applied to an outer aggregation over a GROUP BY subquery, such as SELECT sum(cityHash64(tuple(*))) FROM (SELECT ... GROUP BY ...), which is how query results are hashed. The plans matched and the cost model chose replicas, but the optimization was declined: Read of ... in the replicas plan has no counterpart of the same name in the single-node plan. The single-node plan names the table __table2, because the subquery itself is __table1, while the replicas plan is built from the subquery alone and names it __table1. Reads were paired by that name to hand the index analysis over, so they never paired. They are now paired by table, and the name is used only to tell several reads of one table apart.

It also fixes a key collision that 116781 introduced. An expression's cache key is written by ActionsDAG::serialize with for_cache_key, which leaves out derived names and the values of constants with no fixed size. A set is one of those constants, and its __set_<hash> name was the only thing in the key that told two sets apart. Since 116781 drops that name, sum(v IN (1, 2, 3)) and sum(v IN (5, 6, 7)) got one key, and one query was decided from the statistics collected for the other. The set's hash is now written into the key, as Node::updateHash already does. A filter was not affected: its predicate is keyed through getOutputIdentity. The new test 05396_autopr_cache_key_set_identity fails without this change.


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

Version info

  • Merged into: 26.11.1.2579-master (included in 26.11 and later)
  • Backported to: 26.10.6.11

@nickitat
nickitat added this pull request to stack #125688 October 13, 2026 21:10
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b72fdb8]

Summary: ✅


AI Review

Summary

The PR pairs reads by storage and uses AST scope/path identities to distinguish repeated occurrences, preventing exchanged index analyses and enabling automatic parallel replicas for nested aggregations. Reviewed head b72fdb8712c48a866daea73192a6c0c310c68953. Both earlier findings are addressed; no remaining blocker or major finding. The three regression tests passed all 150 executions in the ASan/UBSan flaky check.

PR Metadata

The Bug Fix category is appropriate, and its required changelog entry describes the affected behavior adequately. The explanatory body needs the scope correction below.

Findings

💡 Nits

Final Verdict

Status: ✅ Approve. The description cleanup is non-blocking.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Oct 13, 2026
Base automatically changed from autopr-build-independent-cache-keys to master October 14, 2026 13:03
nickitat and others added 5 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]>
nickitat and others added 7 commits October 20, 2026 19:57
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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b72fdb871 with master 9005321e3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e4cde4748; 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

78 object files changed (+105.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Utils.cpp.o 673.20 KiB 716.30 KiB +43.10 KiB (+6.40%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp.o 550.03 KiB 582.28 KiB +32.25 KiB (+5.86%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterSelectQueryAnalyzer.cpp.o 303.00 KiB 329.37 KiB +26.37 KiB (+8.70%)

711 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

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

Job report

nickitat and others added 4 commits November 13, 2026 15:33
`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
@nickitat

Copy link
Copy Markdown
Member Author

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

…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
@nickitat nickitat added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Nov 16, 2026
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]>
@nickitat
nickitat marked this pull request as ready for review November 16, 2026 19:45

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review approves this commit, see the AI Review comment.

@devcrafter
devcrafter requested a review from groeneai November 16, 2026 20:22
@devcrafter devcrafter self-assigned this Nov 16, 2026

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I built b72fdb8 (debug) and ran it on a local three-replica cluster (test_cluster_one_shard_three_replicas_localhost on 127.0.0.1-3, the settings block of 05628), with a master build (fdc4389) as the control.

  • The three tests pass on the PR head and fail on master: 05628 returns 14576 106222600 106222600 251982600 306222600 for the aliases shape and THERE_IS_NO_COLUMN for the subqueries shape, and 05261 / 05395 show no replicas use.
  • 36 query shapes with repeated or nested reads (self joins, 3 and 4 reads of one table, look-alike subqueries, CTEs, views, IN over the same table, UNION ALL, GROUP BY one and two levels under an outer aggregation), each run single-node, as a warmup and twice decided in mode 1. On the PR head every result equals the single-node one, with no exceptions. On master 8 do not: wrong rows for the reordered self join and for a CTE used twice with b.id < 20000 pushed into one side (14576 rows instead of 20000), and THERE_IS_NO_COLUMN for 6 others (the 05628 subqueries shape, two identical subqueries, subqueries that differ only in inner aliases or in SETTINGS, 4 reads of one table, (SELECT ...) AS a, a AS b).
  • Now applied, declined on master: the 6 outer-aggregation shapes and FROM d, t AS a, (SELECT id, k, v FROM t) AS b. Now declined, applied on master: a CTE referenced twice and two look-alike subqueries at different depths. Master was right on those only because both reads selected the same ranges.

Two notes, neither blocking:

  1. A CTE referenced once next to a direct read of its table still declines after the cost model (master does too). WITH bb AS (SELECT id, k, v FROM t) SELECT ... FROM d, t AS a, bb AS b WHERE d.id = b.id AND a.id = b.k AND b.id < 20000 logs The single-node plan reads t 2 times and cannot tell this read apart from the others with certainty, while the same query with (SELECT id, k, v FROM t) AS b is applied. The CTE reference is a clone whose original AST is set to the referencing identifier (QueryAnalyzer.cpp:5164), so getScopeSelect finds no SELECT for it and the table inside gets no identity.
  2. The description still covers the set identity in the cache key and 05396, which moved to #132104, and says the PR is stacked on #116781 while the base is master now.

@nickitat

Copy link
Copy Markdown
Member Author

[Build Toolchain (PGO, BOLT) (aarch64)](https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125687&sha=b72fdb8712c48a866daea73192a6c0c310c68953&name_0=PR&name_1=Build%20Toolchain%20%28PGO%2C%20BOLT%29%20%28aarch64%29) times out but it shouldn't have built at all: #130064 (comment)

@nickitat
nickitat added this pull request to the merge queue Nov 17, 2026
Merged via the queue into master with commit 2296f65 Nov 17, 2026
796 of 945 checks passed
@nickitat
nickitat deleted the autopr-nested-queries-stacked branch November 17, 2026 14:49
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
PedroTadim pushed a commit to raimannma/ClickHouse that referenced this pull request Nov 17, 2026
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
`isConstantValueInCacheKey` leaves out the value of a set. 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`.

Split out of ClickHouse#125687.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nickitat added a commit that referenced this pull request Nov 17, 2026
Cherry pick #125687 to 26.10: Pair reads by table for automatic parallel replicas over nested aggregations
nickitat added a commit that referenced this pull request 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]>
robot-clickhouse added a commit that referenced this pull request Nov 17, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 17, 2026
Backport #125687 to 26.10: Pair reads by table for automatic parallel replicas over nested aggregations
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants