Repository navigation
Extend sharing of prepared sets with automatic parallel replicas probe plan - #114231
Conversation
To decide whether parallel replicas pay off, `considerEnablingParallelReplicas` builds a second, throwaway plan for the same query. Optimizing that plan runs index analysis over its reads, and a `col IN (subquery)` condition makes the analysis build the set on the spot (`KeyCondition::tryPrepareSetIndexForIn`), so every `IN` subquery of the query was executed a second time just to plan a candidate that is usually discarded. `moveSetsFromLocalPlanToReplicasPlan` already transplants the single-node plan's sets into the probe plan, but it runs inside the apply branch, long after the probe plan has optimized itself and paid for its own copies. Collect the sets the single-node plan has already filled and hand them to the builder, which adopts them before optimizing: `FutureSetFromSubquery::build` and `buildOrderedSetInplace` both return early once the set is created. Sets do not live only in a plan's own nodes, so `forEachSubquerySet` follows two extra edges: a set's source is a plan of its own (where a nested `IN` keeps its set), and the parallel-replicas local branch hangs off `ReadFromLocalParallelReplicaStep` rather than being a child node. Missing either skips exactly the sets that get rebuilt. Measured on TPC-H SF1 (adapted queries), `automatic_parallel_replicas_mode=1` against the same queries with parallel replicas off. `read_rows` under AutoPR returned to the single-node value on every query that does not run parallel replicas - it was inflated up to 2.00x before. The overhead of enabling AutoPR dropped from +36ms to +2ms on Q18, +22ms to +5ms on Q20 and +11ms to +7ms on Q10. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
`ConditionSelectivityEstimator` answers "how selective is `col IN (subquery)`?" by copying every element of the set into a `Field`, turning each into a `Range` and sorting them. For a large set that dominates query planning, and every consumer of the same set derives an identical result - notably the two plan builds that automatic parallel replicas performs for one query. Build that view once, lazily, on the `Set` itself and share it afterwards. The set is the identity of its contents and cannot change once created, so the cached value needs no invalidation and dies with the set. Combined with sharing the sets between both plan builds, the probe plan now reuses the ranges instead of re-deriving them. The ranges are pulled at the point of use rather than when the atom is parsed. The checks in between can still reject the atom - `Q21` filters on `bitXor(l_orderkey, 42) IN (...)`, whose left side is an expression rather than a column, so the estimator bails out - and deriving ranges for an atom that is then discarded is exactly the work this is meant to avoid. Deferring also drops the `Field` materialization the rejected path used to pay for. Measured on TPC-H SF1 (adapted queries), the overhead of enabling AutoPR dropped from +336ms to +70ms on Q5, +130ms to +45ms on Q3, +130ms to +51ms on Q7 and +50ms to +20ms on Q12. `Q21` also got faster with parallel replicas off, 100ms -> 70ms, from no longer materializing a set it rejects. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
|
Workflow [PR], commit [5d822c8] Summary: ✅
AI ReviewSummaryThis PR shares already-built prepared sets with the automatic parallel replicas probe plan and caches single-column set ranges for selectivity estimation, so planning avoids re-running the same Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 5d822c8.
Changed lines: Changed C/C++ lines covered: 134/145 (92.41%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes155 object files changed (-45.98 KiB total), 0 added.
716 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 units614 translation units recompiled, 5244 s compile time in total, 614 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: 1 improved query(s). K_source=6 K_base=30 flagged=1/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 1 improved Flagged queries (1 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
1f0d4cc to
1545d93
Compare
…lements `BuiltSetsByHash` now uses `UnorderedMapWithMemoryTracking`, which needs a hash for `FutureSet::Hash` (`CityHash_v1_0_2::uint128`, no `std::hash`). `PreparedSets::Hashing` already did this but was declared after `BuiltSetsByHash`, so hoist it to namespace scope as `FutureSetHashing` and alias `PreparedSets::Hashing` to it. The container is only `emplace`d into, `find`-ed and tested for emptiness, so dropping the ordering is safe. Also restrict the shared pool to sets that have explicit elements. `FutureSetFromSubquery::buildOrderedSetInplace` returns the set as soon as `get` succeeds, so a probe plan that adopted a set built without elements could no longer build them from its own source, degrading index and selectivity analysis (`ConditionSelectivityEstimator` checks `hasExplicitSetElements` before using `getPlainRanges`). This costs nothing in practice: over the 44 TPC-H queries, 19 reuse sets and all 33 reuses already carry explicit elements, so the collected and reused counts are identical with and without the check. Sets are collected while the plan is being optimized, and the only sets created that early are the ones `buildOrderedSetInplace` built, which always have elements. Co-Authored-By: Claude Opus 5 <[email protected]>
Reverts the `hasExplicitSetElements` restriction from the previous commit, keeping only the comment that explains the trade-off. Withholding such a set does not avoid work, it adds work. The probe plan then builds its own set from `source`, so the subquery source is scanned three times instead of once (`SelectedRows` 10501215 vs 7501215 on `SELECT count() FROM lineitem WHERE l_orderkey IN (SELECT o_orderkey FROM orders WHERE o_totalprice > 100)` with `use_index_for_in_with_subqueries_max_values=10`, which is what makes the single-node plan build the set without elements). What is lost by sharing is confined to the probe: `buildOrderedSetInplace` returns the set as-is, so `ConditionSelectivityEstimator` falls back to a default estimate for that `IN`. The accepted plan is unaffected, because `moveSetsFromLocalPlanToReplicasPlan` transplants the built set into it at commit time. Paying repeated subquery execution to sharpen the estimates of a plan that is often discarded is the wrong side of that trade. The restriction was also inert on TPC-H: all 33 set reuses across the 44 queries already carry explicit elements, so it only ever fired in the shape described above. All 44 queries match single-node results. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@copilot resolve the merge conflicts in this pull request |
Co-authored-by: nickitat <[email protected]>
Resolved the merge conflict in |
|
|
`Interpreters/Set.h` was included twice in `CreatingSetsStep.cpp`, which fails the tidy build with `readability-duplicate-include`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114231&sha=ecb4155316d9442d3515651bf43a1b99ed810548&name_0=PR&name_1=Build+(arm_tidy) #114231 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
`moveSetsFromLocalPlanToReplicasPlan` walked both plans with `traverseQueryPlan`, which follows only `node->children`. A `DelayedCreatingSetsStep` can also sit inside a plan a step owns through `getChildPlans` (`ReadFromMerge`, `JoinStepLogicalLookup`), inside a set's own source plan when an `IN` is nested, or - on the parallel-replicas side - inside the local branch held by `ReadFromLocalParallelReplicaStep`, which is not a child node at all. Sets in those places were never adopted from the single-replica plan, so their subqueries ran a second time at execution. The probe plan now reuses such sets while planning, which made the gap visible: the probe skips the subquery but the accepted plan re-runs it anyway. Reuse `forEachSubquerySet` for both directions so the collect walk, the reuse walk and the transplant walk all cover the same plan surface. It is exported from `CreatingSetsStep.h` for that. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
The previous commit made `forEachSubquerySet` follow the plans a step owns
through `getChildPlans`, so that a set under `ReadFromMerge` or
`JoinStepLogicalLookup` would be shared with the automatic parallel replicas
probe plan instead of being rebuilt. Measured on the shape it targets, it does
the opposite.
`SELECT key, pad FROM big WHERE key IN (SELECT key FROM <merge table>)`, where
the merge table's child is a view holding an `IN` of its own, reads (rows
selected by the whole query, `automatic_parallel_replicas_mode = 1`, three runs
each, right side of the nested `IN` is 500 rows):
without the descent 6000500 (== the same query with automatic parallel replicas off)
with the descent 6001000
`ReadFromMerge::getChildPlans` calls `filterTablesAndCreateChildrenPlans`, so
asking for the child plans builds them rather than handing them out, and that
costs one more execution of the nested subquery than the sharing saves.
Such a step also disqualifies the plan from automatic parallel replicas
altogether, since `supportsDataflowStatisticsCollection` is false for it and the
eligibility check in `considerEnablingParallelReplicas` bails out - verified in
the server log as `Unsupported steps: ReadFromMerge_6`. So the only sets the
walk still misses are those below a set's own source plan.
The transplant in `moveSetsFromLocalPlanToReplicasPlan` keeps using
`forEachSubquerySet`: following a set's own source plan and the local branch
under `ReadFromLocalParallelReplicaStep` has no such cost.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
A review asked for the reachability gap to be closed the other way round: make the plan simplicity check in `considerEnablingParallelReplicas` see through a set's source plan, so that an unsupported step hidden there (a `Merge` read, a lookup join) keeps automatic parallel replicas off the query instead of letting it run with a set it cannot share. Implemented and measured, that check never fires. By the time the optimization runs, every `FutureSetFromSubquery` in the plan has been through `build`, which moves the source plan out, so `getQueryPlan` is already null and there is nothing left to look at. Logged the walk on `SELECT ... WHERE key IN (SELECT ... FROM <merge table>)` and on the same query against a plain table, each with `use_index_for_in_with_subqueries` 0 and 1: the step is still `DelayedCreatingSets`, it still holds its set, and the set's source plan is gone in all four. That also settles the gap itself. A nested set is built only by executing the outer set's source plan, and every path that does so consumes it - a source holding a nested `DelayedCreatingSetsStep` is deliberately non-clonable, so `buildOrderedSetInplace` takes its destructive fallback (see the comment in `PreparedSets.cpp`). The nested set is therefore unreachable from the plan by any traversal, whether or not it follows `getChildPlans`; sharing it would need the consumed source plan kept alive, which is a different change. Comment `collectBuiltSets` with what the walk can actually reach, so the next reader does not have to rerun the experiment. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
`considerEnablingParallelReplicas` checked the plan with `traverseQueryPlan`, which follows only `node->children`. A set's source is a plan of its own, so an unsupported step there stayed invisible and the outer query could still be picked for automatic parallel replicas while holding sets that neither `collectBuiltSets` nor `moveSetsFromLocalPlanToReplicasPlan` can reach - their subqueries then run twice. Move the check into `collectStepsUnsupportedForStatistics`, which recurses into `FutureSetFromSubquery::getQueryPlan` on the way. It does not call `getChildPlans`: a step that owns nested plans is unsupported in its own right, so it is already reported, and `ReadFromMerge::getChildPlans` would build those plans rather than hand them out. The recursion does not fire under today's set lifetimes - by this point `build` has moved every source plan out and `getQueryPlan` returns null, checked with the `IN` over a `Merge` table and over a plain table with `use_index_for_in_with_subqueries` 0 and 1. The comment says so. It is here so that a set arriving with its source still attached is checked rather than silently trusted. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
`getSetElements` starts with `checkIsCreated`, `getPlainRanges` did not, so it read `set_elements` on trust. The one caller, `ConditionSelectivityEstimator::extractAtomFromTree`, reaches `getSetElements` first and is therefore safe, but the miss is worse here than a plain unchecked read: the ranges are cached under `callOnce`, so a caller that skipped the guard would not get one wrong answer, it would pin an empty range set for every later caller of that set. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
… shares them There was no test that the automatic parallel replicas probe plan actually adopts the sets the single-node plan has filled, only the absence of a second execution in a profile. Add `SetsBuiltFromSubquery`, incremented where `CreatingSetsTransform` finishes filling a set, which is the one place a set is filled by running its subquery - the speculative build during index analysis goes through the same transform, and a set served from the prepared sets cache is not counted. The test asserts the count is 1 for a query with a single `IN`. The join in it is load-bearing: measured with the sharing disabled, the probe plan rebuilds the set only when it reaches it through a join (2 without sharing, 1 with), while a plain `SELECT ... WHERE key IN (...)` reports 1 either way and would pass with the optimization removed. Two shapes are worth recording as not covered by the sharing, both still 2 with it enabled: a query with two distinct `IN` sets (2 is simply the right answer there) and one run with `parallel_replicas_min_number_of_rows_per_replica`, where the probe rebuilds the set regardless. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
`collectStepsUnsupportedForStatistics` applied one predicate everywhere, so a leaf inside a set's source plan - `ReadFromSystemNumbersStep` for `WHERE non_key IN (SELECT number FROM numbers(1000))`, a `ReadFromPreparedSource` for a dictionary or system table - counted as a blocker and would take automatic parallel replicas off the query. Those plans are never instrumented, so the statistics predicate has nothing to say about them. What matters inside a set source plan is only whether a step holds plans of its own, since a set below one of those is reachable by neither `collectBuiltSets` nor `moveSetsFromLocalPlanToReplicasPlan` - both stop at `getChildPlans`, which for a `Merge` read builds the child plans instead of handing them out. Report that and nothing else. `ownsChildPlans` answers it without the build. It is a separate predicate rather than `!getChildPlans().empty()` for exactly that reason, and every step that overrides `getChildPlans` overrides it too. No query changes behaviour today: the recursion still does not fire, because the source plan has already been moved out of the set by this point. Confirmed on the query above - it reports `The applied formula` both before and after. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
…idate Pins the shape the previous commit is about: `WHERE non_key IN (SELECT number FROM numbers(1000))` must stay a candidate for automatic parallel replicas, rather than being disqualified by the `ReadFromSystemNumbers` inside the set's source plan. The assertion is `ProfileEvents['RuntimeDataflowStatisticsInputBytes'] > 0`, which is non-zero only for a query the simplicity check let through and the optimization then instrumented. The test does not fail on the code before that commit. Built a binary with the narrowing reverted and ran it: still passes, because the recursion into set source plans never fires - `addPlansForSets` runs after `considerEnablingParallelReplicas` in `optimizeTree`, and a set already built by then never gets a `DelayedCreatingSetsStep` at all, so the walk finds no source plan to inspect either way. It is a guard for the day that changes, plus a plain regression test that this query shape stays a candidate at all. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
Reverts "Let the plan simplicity check see into the `IN` set source plans" and "Report only child-plan owners from inside a set source plan". Neither changes the behaviour of any query, so they are not worth carrying. The walk was added so that an unsupported step hidden inside a set's source plan would keep automatic parallel replicas off a query whose sets it cannot share. It never finds one: at the point the check runs, the set no longer holds its source plan. Logged the walk across both values of `use_index_for_in_with_subqueries`, with the `IN` on an indexed and on a plain column, over a plain table and over a `Merge` table, and with statistics off - the source is absent in every one, so the recursion returns immediately. That also removes the reason for the second commit, which existed only to stop the widened check from rejecting a leaf such as `ReadFromSystemNumbers` in a set source plan, and for `ownsChildPlans`, which existed only to answer that check without paying for `ReadFromMerge::getChildPlans`. The test added alongside them stays, retargeted at what it can actually pin: that `WHERE non_key IN (SELECT number FROM numbers(1000))` remains a candidate for automatic parallel replicas. It is the regression guard against widening the check this way again, and it records the measurement that no fix is needed here. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FQgeojS99TPYBt4jyakpPF
`UnionStep` does not collect dataflow statistics either, so a check that walked the set source plan would reject a union in the `IN` just as it would reject the `numbers` leaf. Measured on a binary carrying such a check: the union shapes - `UNION ALL` over two `numbers` and `UNION DISTINCT` over a table - reach `The applied formula` all the same, because the set has no source plan left by then. Pin both arms. The filter is an exact list rather than `LIKE '..._%'`: `_` is a wildcard, so the pattern also matched the test runner's own `.sql-default` log comment. Co-Authored-By: Claude Opus 5 <[email protected]>
`moveSetsFromLocalPlanToReplicasPlan` walks the chosen parallel-replicas plan and
throws if a set it reaches has no counterpart in the single-node plan. Since the
walk followed each set's own source plan, a nested `IN` made it throw on a query
that was perfectly executable: the outer set on the single-node side had been
filled in place during index analysis, which consumes the source plan, so its
nested set was never collected - while the chosen plan still carries both.
SELECT sum(key) FROM t
WHERE non_key IN (SELECT x FROM s WHERE y IN (SELECT z FROM r))
aborts the server with `Cannot find a matching set in the map of sets from
single-replica plan` on the second run, once statistics exist and replicas are
actually picked. `abort_on_logical_error` is on for tests, so in CI it is a crash
rather than an exception.
Let the visitor of `forEachSubquerySet` say whether to descend into a set's own
source plan, and stop there once the set has been adopted. Nothing is lost by
stopping: an adopted set is built, so `makePlansForSets` skips its source plan
and the sets nested in it are never created. `reuseBuiltSets` stops for the same
reason, and both collect walks still descend.
The test fails on the code before this commit with `server died 32`.
Co-Authored-By: Claude Opus 5 <[email protected]>
The comment justified skipping `getChildPlans` only with the cost of `ReadFromMerge::getChildPlans`, which reads as if a cheap carrier would be worth descending into. It would not be, and the reason is not the same for all three steps that own child plans. `LazyReadReplacingFinalStep` is the second materializing one - `getChildPlans` builds its `explain_plan` on the first call. `JoinStepLogicalLookup` is the cheap one, and it cannot hold a set: `PlannerJoinTree` builds that step only for a right side whose `useful_sets` is empty, and a set on that side is exactly what makes it non-empty. So there is no cheap carrier that can hide a set from this walk. Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Extend sharing of prepared sets with automatic parallel replicas probe plan to avoid duplicate execution.
Workflow [PR]
Sync PR [sync-upstream/pr/114231]