Repository navigation
Pair reads by table for automatic parallel replicas over nested aggregations - #125687
Conversation
|
Workflow [PR], commit [b72fdb8] Summary: ✅
AI ReviewSummaryThe 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 PR MetadataThe Findings💡 Nits
Final VerdictStatus: ✅ Approve. The description cleanup is non-blocking. |
`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]>
7f22e16 to
3bd6602
Compare
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes78 object files changed (+105.92 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units217 translation units recompiled, 2324 s compile time in total, 217 of them have a recent master baseline. |
`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
|
🕵 Merged |
…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
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]>
groeneai
left a comment
There was a problem hiding this comment.
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 306222600for the aliases shape andTHERE_IS_NO_COLUMNfor 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,
INover the same table,UNION ALL,GROUP BYone 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 withb.id < 20000pushed into one side (14576 rows instead of 20000), andTHERE_IS_NO_COLUMNfor 6 others (the 05628 subqueries shape, two identical subqueries, subqueries that differ only in inner aliases or inSETTINGS, 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:
- 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 < 20000logsThe 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 bis applied. The CTE reference is a clone whose original AST is set to the referencing identifier (QueryAnalyzer.cpp:5164), sogetScopeSelectfinds noSELECTfor it and the table inside gets no identity. - 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.
|
|
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]>
Cherry pick #125687 to 26.10: Pair reads by table for automatic parallel replicas over nested aggregations
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]>
… replicas over nested aggregations
Backport #125687 to 26.10: Pair reads by table for automatic parallel replicas over nested aggregations
Changelog category (leave one):
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__tableNnames, 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 BYsubquery, such asSELECT 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::serializewithfor_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))andsum(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, asNode::updateHashalready does. A filter was not affected: its predicate is keyed throughgetOutputIdentity. The new test05396_autopr_cache_key_set_identityfails without this change.Workflow [PR]
Sync PR [sync-upstream/pr/125687]
Version info
26.11.1.2579-master(included in26.11and later)26.10.6.11