Skip to content

Transplant the single-node index analysis onto every read, not just one - #115153

Merged
nickitat merged 33 commits into
masterfrom
autopr-transplant-index-analysis
Sep 23, 2026
Merged

nickitat merged 33 commits into
masterfrom
autopr-transplant-index-analysis

Conversation

@nickitat

@nickitat nickitat commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Improves automatic parallel replicas for multi-read queries by reusing local plan index analysis in the parallel replicas plan, reducing extra reads when parallel replicas is enabled.

Awaiting: #114231


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

Version info

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

nickitat and others added 3 commits August 17, 2026 15:08
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
The parallel replicas plan is built without index analysis because the read step
the decision is matched on is handed the single-node plan's result instead. That
covers a single-table query, but a plan with several reads left the rest
unanalyzed - and when replicas are chosen, that plan is what runs. TPC-H q03
selected 1045 marks where the single-node plan selects 614, and read three times
the rows. On a three-node staging cluster at sf=100 the same query selected 94718
marks against plain parallel replicas' 60963.

Hand the analysis over for all of them. The two plans are built from the same
query and differ only where the replicas step is substituted, so their reads pair
up in traversal order; the storage of each pair is checked and the transplant is
skipped entirely if anything does not line up. Index analysis is lazy, so a read
the single-node plan has not needed yet has nothing to hand over - analyze it
here, exactly as the matched read step already was.

This costs one analysis per read, done once on the single-node plan and shared,
rather than having the replicas plan repeat work the single-node plan does
anyway. A single-table query is unaffected: it has one read, already covered.

Two alternatives were measured and rejected. Building the replicas plan with
`query_plan_optimize_primary_key` on works, but analyzes every read a second
time, which is a regression for single-table reads - the shape that needs it
least. Deferring index analysis and PREWHERE and replaying both over the chosen
plan produces the right reads but changes the plan's shape, so
`findCorrespondingNodeInSingleNodePlan` stops matching it against the single-node
plan and replicas are declined outright.

TPC-H at sf=1 now selects identical marks with and without automatic parallel
replicas on q03 (614), q12 (619), q17 (1493) and q22 (241). At sf=100 on the
staging cluster this took q22 from +96% to +14% against single-node, q12 from
+13% to -13%, q14 from +23% to -15% and q02 to -14%.

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

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [743125b]

Summary: ✅


AI Review

Summary

This PR extends automatic parallel replicas so the chosen replicas plan can reuse single-node index analysis and filter state across multiple ReadFromMergeTree reads, and it adds focused regressions for the broadcast-read, skip-index, query-condition-cache, and self-join cases. The remaining issue is a supported-query performance regression: when the new pairing logic cannot prove a one-to-one match, it now rejects AutoPR outright even in modes where the unmatched read would still analyze itself correctly at execution time.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp:754 The new fail-closed return on transplantAnalysisToAllReads(...) == false is too strong when parallel_replicas_index_analysis_only_on_coordinator = 0. In that mode an unpaired ReadFromMergeTree still builds its own analysis on first use (ReadFromMergeTree::getAnalysisResultImpl at src/Processors/QueryPlan/ReadFromMergeTree.cpp:4346), and the planner has already populated query_info.filter_actions_dag for table filters (src/Planner/PlannerJoinTree.cpp:1665). A concrete shape is a materialized common subplan referenced twice: materializeQueryPlanReferences clones the read, but ReadFromMergeTree::clone shallow-copies query_info.table_expression (src/Processors/QueryPlan/ReadFromMergeTree.cpp:4527), so both copies keep the same __tableN alias, pairing fails, and AutoPR is disabled even though the query could still execute correctly with local analysis on that branch. Suggested fix: only reject the candidate when an unpaired read would actually skip local analysis, or strengthen the pairing identity so cloned common-subplan reads remain distinguishable.
Tests
  • ⚠️ There is no regression case for an AutoPR query that duplicates one filtered subplan under parallel_replicas_index_analysis_only_on_coordinator = 0, so the new fail-closed path is currently unpinned.

LLVM Coverage Report

Measured on commit 743125b.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 91/128 (71.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 743125b2e with master e96f004b9 (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.

Object file sizes

4 object files changed (+180.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp.o 199.18 KiB 380.06 KiB +180.89 KiB (+90.82%)

716 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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 4, 2026
@nickitat nickitat changed the title Share prepared sets with the automatic parallel replicas probe plan Transplant the single-node index analysis onto every read, not just one Sep 4, 2026
@nickitat

nickitat commented Sep 4, 2026

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

nickitat and others added 2 commits September 5, 2026 13:38
…ndex-analysis

# Conflicts:
#	src/Interpreters/InterpreterSelectQueryAnalyzer.cpp
#	src/Interpreters/PreparedSets.h
#	src/Interpreters/Set.cpp
#	src/Processors/QueryPlan/CreatingSetsStep.cpp
#	src/Processors/QueryPlan/CreatingSetsStep.h
#	src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
#	src/Processors/QueryPlan/ReadFromLocalReplica.h
#	src/Storages/Statistics/ConditionSelectivityEstimator.cpp
Review asked twice whether `collectBuiltSets` runs too early to catch the sets
that index analysis builds, since the forced `selectRangesToRead` comes after it.
It does not: `optimizePrimaryKeyConditionAndLimit` runs earlier in the same pass
(`optimizeTreeSecondPass`) and ends in `applyFilters`, where `buildIndexes` builds
the `KeyCondition` that calls `buildOrderedSetInplace` for every `IN` whose left
argument maps to key columns. `selectRangesToRead` then reuses those `indexes`,
building them only `if (!indexes)`, so it creates no set a later collection
would catch.

Measured on a cold plan (fresh server, first execution of the query):
`k IN (SELECT ...)` on the sorting key gives an adoption map of 1 set at the
reuse point, and a set on a non-key column gives 0 - matching the rule that
`KeyCondition` materializes ordered sets only for key-mapped `IN`s. Rows read
are identical with the probe plan on and off (62344 for the key-mapped shape,
2005000 for the non-key shape, the latter being 2000000 from the outer table
plus the subquery's 5000 read exactly once), so the probe re-executes nothing
in either case - it is built with `query_plan_optimize_primary_key = false` and
`build_sets = false`, so no `KeyCondition` is ever constructed for it.

Comment only, no behaviour change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
nickitat and others added 4 commits September 7, 2026 12:30
…oadcast read

Review raised that this condition is written in terms of the query ("am I a
follower, is the setting on?") rather than the read, so an uncoordinated read
shipped inside a parallel-replicas fragment - the broadcast side of a JOIN under
`serialize_query_plan` - would skip index analysis and scan every mark with no
coordinator to assign its ranges.

That does not happen: `context_` is the read's own context, and the planner
leaves parallel replicas enabled only in the context of the table expression it
actually parallelizes, so the broadcast read answers `false` here and analyzes
itself.

Verified by logging the decision on a three-replica cluster with
`serialize_query_plan = 1` across 16 query shapes (two- and three-table inner,
left and right joins, swapped build side, `IN` and `GLOBAL IN` subqueries,
`UNION ALL`, a join over a grouped subquery, and a join over a subquery):
37 decisions, no read ever took the fast path with
`is_parallel_reading_from_replicas = false`, and that flag agreed with
`canUseTaskBasedParallelReplicas` in every one (15 false, 22 true). Adding
`is_parallel_reading_from_replicas` to the condition, as suggested, would not
have changed a single outcome.

Comment only, no behaviour change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
…and a broadcast read"

This reverts commit c2ec3e3.

The comment claimed that an uncoordinated read inside a parallel-replicas fragment
answers `false` to `canUseParallelReplicasOnFollower` and so analyzes itself. That
is true only for the query-tree-based path. It is wrong for plan-based parallel
replicas (`parallel_replicas_plan_based`, experimental, off by default), where the
whole fragment is rebuilt on the follower from one shared `ctx.context`: every read
in it then answers `true`, including the broadcast side of a JOIN, which has no
coordinator to assign its ranges.

The earlier verification missed this because it set only `serialize_query_plan`,
which does not by itself route through `applyParallelReplicas` and
`buildPlanFragment`. Re-measured with `parallel_replicas_plan_based = 1`, an
uncoordinated read takes the fast path (10 of 18 fast-path decisions had
`is_parallel_reading_from_replicas = false`), and a follower then reads 31482 marks
and 137906748 rows for a query that reads 22 marks and 40960 rows with
`parallel_replicas_index_analysis_only_on_coordinator = 0`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
A follower may skip its own index analysis and return every mark only when the
coordinator assigns its ranges, which the coordinator derives from the analysis
done on the initiator. The condition guarding that only asked whether the query
is running on a follower, which is a property of the context rather than of the
read.

With the query-tree implementation of parallel replicas the two coincide: the
planner leaves parallel replicas enabled only in the context of the table
expression it parallelizes, so an uncoordinated read answers `false` there. With
plan-based parallel replicas (`parallel_replicas_plan_based`) they do not:
`buildPlanFragment` marks only the coordinated reads for parallel reading, but
the follower rebuilds every `ReadFromMergeTree` of the fragment from one shared
`ctx.context`, so the broadcast side of a `JOIN` answers `true` as well. It then
skipped primary key and skip index pruning with nobody to narrow it afterwards,
and read the whole table on every remote replica.

Test the read's own `is_parallel_reading_from_replicas` instead. Such a read has
to analyze itself in any case: an analysis produced on the initiator names the
initiator's parts, which are not the parts the replica reads, so the analysis
cannot be shipped to it either.

Measured on a three-replica cluster, `SELECT count() FROM big INNER JOIN bcast ON
big.k = bcast.id WHERE bcast.id < 5000`, summed over the follower queries. With
`parallel_replicas_plan_based = 1` the followers read 31482 marks and 137906748
rows before this change and 14652 marks and 40960 rows after it, the same 40960
rows they read with `parallel_replicas_index_analysis_only_on_coordinator = 0`;
the marks that remain are the coordinated read announcing all of its marks, which
is what the coordinator assigns ranges from. On the query-tree path the numbers
are unchanged (14652 marks and 16384 rows, against 22 and 16384 with the analysis
forced), confirming the condition is inert there. Five join shapes return
identical results on a single node, with plan-based and with query-tree parallel
replicas.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
The test joins two `MergeTree` tables, filters on the right-hand key, and checks
that the marks selected with automatic parallel replicas match the marks the
single-node plan selects. Without the transplant the second read is left
unanalyzed and selects every mark: 490 against 26 on this data.

`replicas_were_used_at_least_once` guards the comparison. The optimization
declines for many reasons, and every one of them would otherwise leave the query
single-node, where the marks trivially match and the test would pass while
testing nothing.

Three things had to be pinned to make the decision reproducible, each of which
made the test flaky in a way that had nothing to do with what it checks. The part
layout and granularity, because the cost model works off estimated bytes. One
part per table, because the plan being matched depends on how the insert was
split. And the join side: left to `auto` it is chosen from estimated table sizes,
and the plan built for parallel replicas estimates differently from the
single-node plan, being built with `query_plan_optimize_primary_key = 0` and so
without index analysis - the two then build opposite sides, their steps hash
differently, and `findCorrespondingNodeInSingleNodePlan` gives up. That last one
alone accounted for roughly a third of runs.

Verified 57 runs with settings randomization and 12 without, all passing, and 8
runs with the transplant removed, all failing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
The existing test covers the classic local-plan path only, where the guard on the
follower index-analysis fast path is inert. This one exercises the path the guard
is actually for: with `parallel_replicas_plan_based`, the fragment is rebuilt on
the follower from one shared context, so the broadcast side of a `JOIN` used to
satisfy the follower condition too, skip primary key pruning, and read the whole
table with no coordinator to narrow it.

The filter selects one granule of the broadcast table, and the probe side is kept
small, so the rows a follower reads say whether it pruned: about 58 thousand when
it does, over two million when it does not.

`parallel_replicas_prefer_local_replica = 0` is what makes this reproducible.
Otherwise the local replica claims every range before the remote ones announce
themselves and the query runs with no follower at all, which no amount of
repetition fixes reliably - it was observed in only 60 to 90 percent of runs, and
correlated within a run. With the local replica no longer preferred a follower
took part in all 30 probe runs and all 55 test runs.

Verified 45 runs with settings randomization and 10 without, all passing, and 8
runs with the guard removed, all failing on
`every_follower_pruned_the_broadcast_read` while a follower did execute.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
/// JOIN - answers `true` here as well, and skipping would leave it reading every mark with nobody to
/// narrow it. Such a read has to analyze itself in any case: an analysis made on the initiator names
/// the initiator's parts, which are not the parts this replica reads.
if (context_->canUseParallelReplicasOnFollower() && is_parallel_reading_from_replicas_

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This technically is a separate issue, but I don't want to multiply the number of PRs...

@nickitat
nickitat requested a review from devcrafter September 7, 2026 17:19
@nickitat
nickitat marked this pull request as ready for review September 7, 2026 17:19
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 3ae2e3e2-d160-4b9a-bb3a-5e320a9527ec
  • MIRAI run: e59b0e46-763c-4ab6-8888-a11b05cce064
  • PR check IDs:
    • clickbench_1397633_1790120731
    • clickbench_1397639_1790120731
    • clickbench_1397645_1790120731
    • tpch_adapted_1_official_1397656_1790120731
    • tpch_adapted_1_official_1397667_1790120731
    • tpch_adapted_1_official_1397703_1790120731

The test timed out in the flaky check under TSan at 184.75s against a 180s limit,
while the plan-based test next to it finished in 11 to 26s. The difference was
data: two tables of two million rows each carrying a 60 character `String`, about
250 MB, where the plan-based test writes plain `UInt64` columns.

The padding column was only there to give the cost model bytes to weigh, which it
does not need - `merge_tree_min_bytes_per_task_for_remote_reading` is already
lowered so that a table of any size splits into enough reading tasks for replicas
to look worthwhile. Drop it and take the tables down to 300000 rows each, roughly
10 MB in total, and narrow the filter to keep the same shape.

The signal is unchanged: the measured query selects 6 marks, exactly what the
single-node plan selects, and without the transplant the second read is left
unanalyzed and selects every mark of its table.

Verified 25 runs with settings randomization and 10 without, all passing, and 6
runs with the transplant removed, all failing.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115153&sha=0fa3303320ba9be67db7f318917274432c366ffd&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
Related: #115153

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
@devcrafter devcrafter self-assigned this Sep 14, 2026
nickitat and others added 2 commits September 15, 2026 21:51
A skip index is applied while granules are read rather than during index analysis
(`use_skip_indexes_on_data_read`, on by default). The reader that does that is
created only when the read carries the conditions built from the query, and the
plan built for automatic parallel replicas never carries them: it is built with
`query_plan_optimize_primary_key` off, so `applyFilters` never runs on its reads,
and a read that is handed an analysis result does not build them later either -
`selectRangesToRead` returns the result it was given and stops. `supportsSkipIndexesOnDataRead`
is then false and the index is not applied at all.

Transplant the conditions along with the analysis. They are what the single-node
read built for the same query over the same table, which the transplant already
requires, so nothing is recomputed - only the ranges were being handed over where
both were needed.

Measured on a three-replica cluster, `SELECT sum(key) FROM t WHERE np < 20000`
against 400000 rows with a `minmax` index on `np`: the initiator read 49 of 49
marks and 400000 rows before this change and 3 marks and 24576 rows after it, the
same as the single-node plan. Results are unchanged across 24 query shapes
(joins, `IN` subqueries, `UNION ALL`, views, `Merge` tables, projections,
aggregations), and none of them reads more than a single node afterwards.

The query condition cache hid this after the first execution: whichever run does
apply the index records the granules it discarded, and later runs prune up front
from the cache. Only the first run on a cold cache - after a restart, an
eviction, or for a new condition - paid the full read, which is why it looked
intermittent.

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

/// Every read of the candidate has to be given its analysis. One that is not would read
/// every mark, so the candidate is worse than the plan it replaces; decline rather than run it.
if (!transplantAnalysisToAllReads(*query_plan.getRootNode(), *plan_with_parallel_replicas->getRootNode()))

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.

This fail-closed return is only sound when parallel_replicas_index_analysis_only_on_coordinator = 1. With that setting off, an unpaired ReadFromMergeTree still builds its own analysis at execution (getAnalysisResultImpl -> selectRangesToRead), so a pairing miss here is not a correctness problem; it just means that read will analyze locally.

Returning here therefore regresses supported queries to single-node execution whenever the alias pairing cannot prove a match (for example, duplicate table_expression aliases after materializeQueryPlanReferences). Please gate the rejection on the coordinator-only setting, or otherwise on whether the affected read would actually skip local analysis.

nickitat added a commit that referenced this pull request Sep 18, 2026
The sequential lane fails four query-condition-cache tests. They are not artifacts
of the lane's configuration: a plan rewritten by automatic parallel replicas never
populates the query condition cache, so the next query over the same condition
misses it. `system.query_condition_cache` holds one entry after a single-node run
and none after a rewritten one. This is the same root cause as
#115153 - the rewritten plan's reads
carry ranges but not conditions - and has been handed to that PR with a repro.

They cannot go in `parallel_replicas_blacklist.txt`. Two of them,
`03229_query_condition_cache_profile_events` and
`05099_query_condition_cache_formatdatetime_settings`, PASS in
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, sequential)`,
where parallel replicas is forced on; they fail only when the optimization does
the rewrite. That list inverts its verdict, so listing them there would report
them as needing removal and turn the forced job red.

Add `tests/autopr_blacklist.txt`, read only under `--autopr` and tolerate-only:
a listed test may fail without failing the job, and a listed test that passes is
not flagged. A pass carries no information here anyway, since the optimization
only switches a query when its statistics say it pays off.

Remove the entries once #115153 lands - the file documents what it is waiting on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
nickitat and others added 2 commits September 18, 2026 12:24
The candidate plan is optimized without `optimizePrimaryKeyConditionAndLimit`, so
`applyFilters` never runs on its reads, and a read handed an analysis result never
builds anything later either - `selectRangesToRead` returns what it was given and
stops. Handing over only the ranges therefore leaves several things behind, and
each of them is consumed separately while reading. They have been turning up one
at a time, as bug reports; adopt the whole set at once instead.

  - `indexes`, without which `supportsSkipIndexesOnDataRead` is false and skip
    indexes are not applied to granules at all (this was the previous commit);
  - the filter actions, which the reader needs to have a condition to record;
  - `limit`, which bounds how much an ordered read has to produce;
  - the filters `FINAL` defers past deduplication, which must not be applied
    before it.

`setIndexes` becomes `adoptFiltersFrom` so the set lives in one place next to the
reason each member is in it, rather than being extended a member at a time from
the call site.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
The granules a filter discarded are recorded by tagging the filter step, which
`updateQueryConditionCache` does early in plan optimization and only for a read
that already carries its filter actions. The candidate plan has none then - it is
built with `query_plan_optimize_primary_key` off, and its reads are handed their
analysis only once the decision is made - so nothing was tagged and a query this
optimization rewrote wrote nothing to the query condition cache at all. Every later
query over the same predicate then read the table again.

Re-walk the pass over the candidate once its reads have their filter actions, the
way the passes that rebuild filter steps already do further up the same file.

This is the mirror of what the skip index commit describes: there the cache hid an
index that was never applied, here the rewrite stops the cache being written and
the hiding stops with it.

Measured with the reporter's repro: a rewritten query left 0 cache entries and the
next query over the same predicate missed; it now leaves 1 and that query hits.

Reported with a repro by the session building the automatic-parallel-replicas test
lane, #120438.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
…lling it again

The matched read was given the analysis when it had none of its own, with a comment
arguing that an analysis it already had would be equivalent. Neither half is true
any more: `transplantAnalysisToAllReads` pairs that read with the same single-node
read `findReadingStep` returns here, installs its analysis and filter state, and
declines the candidate when any read cannot be paired - so the read always arrives
carrying exactly the analysis this code would install, and the branch never runs.

Assert that instead. It says what now holds, and it fails where the old comment
only reasoned: if the transplant's pairing and this descent ever disagree about
which read the decision was matched on, the reads are carrying ranges selected for
another read's predicates, which is a wrong answer rather than a bad estimate.

Verified by logging both pointers: they are the same object across a single-table
read on a primary key and on a column outside it, two- and three-way joins, a
self-join, an `IN` subquery, an aggregation, `ORDER BY ... LIMIT`, and with
`parallel_replicas_min_number_of_rows_per_replica` raised, which is the setting
that prefills an analysis early. Then the assertion was made a hard check and the
`autopr`, `pr_plan_based`, `parallel_replicas_join` and `query_condition_cache`
families run: it never fired, and the pass and failure counts were unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
nickitat and others added 3 commits September 21, 2026 11:48
`adoptFiltersFrom` filled each member only when this read had nothing of its own,
while the analysis next to it is replaced outright by `setAnalyzedResult`. Anything
this read did carry would then be kept beside ranges selected by another read's
conditions - ranges and conditions from different reads, which is the one thing the
pairing above exists to prevent.

Take them over wholesale so the two always describe the same thing.

Nothing in the candidate builds these - it is optimized without
`optimizePrimaryKeyConditionAndLimit`, so `applyFilters` never runs on its reads -
and logging the adoption confirms it: over runs with
`parallel_replicas_min_number_of_rows_per_replica` at 0, 1 and 1000, the read had
no conditions on every call and the single-node read's were copied each time. So
this changes no behaviour today; it makes the pairing independent of whether
something prefills them, rather than of the observation that nothing does.

The skip index test gets a second pair of runs with that setting, since it is what
makes the planner analyze a read before its filters are attached.

Reported against #115153.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
A read step serializes its prewhere and its row-level filter and nothing else, so
a predicate that is not moved into PREWHERE does not travel that way. Add the case
to the plan-based test, where the broadcast read would arrive with nothing to prune
by if that were the only channel.

It is not: the filter is a step of the shipped fragment, and the follower optimizes
the plan it deserializes, so the read gets its conditions back from `applyFilters`.
Measured over four combinations of `optimize_move_to_prewhere` and
`use_skip_indexes_on_data_read`, including a predicate on a column outside the
broadcast table's primary key, where pruning depends on the skip index rather than
the key condition: every follower read the probe table plus one granule of the two
million row broadcast table, and every result matched the single-node plan.

The test pins the behaviour so the channel cannot quietly become the only one.

Reported against #115153.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
Both runs shared one `log_comment` and the check ran over the pool, so the run with
PREWHERE could vouch for the one without it: if only the first had followers the
test still passed and the path added in the previous commit was not covered at all.

Report per run. That alone is not enough either, which the fix itself turned up: a
follower can be started and read nothing, when the local replica takes every range
before it announces itself. Counting followers is then satisfied by a follower that
proves nothing about pruning - the run this way round scored 1 follower and 0 rows.
So the check is on rows: one follower has to have done the reading, and none may
have read the whole broadcast table.

Verified by leaving the second run to the local replica, where it reports
`a_follower_did_the_reading = 0` and the test fails. With both runs spread over the
replicas they read 58192 rows each - the probe table plus one granule of two
million - over 30 runs with and without settings randomization.

Reported against #115153.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
The run with `parallel_replicas_min_number_of_rows_per_replica` shared its
`log_comment` and its aggregated assertion with the earlier one, so the run that
did use replicas could vouch for one that quietly stayed single-node, leaving
that branch untested while the test still passed.

Verified by making the second run decline parallel replicas: only that run's row
flips, which the pooled form would have hidden.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
nickitat and others added 6 commits September 21, 2026 15:52
Reads of the two plans are paired by the table together with the name the
analyzer gave the table expression. The existing regression joins two different
tables, where the table alone already pairs them, so nothing there depends on
the name being right.

Checked by reducing the identity to the table: the self-join test fails and the
two-table one still passes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
A projection read selects the projection's parts and columns, and the plan built
for parallel replicas is built with `optimize_projection` off, so its reads are
of the base table. Pairing is by table and table expression name, both of which a
projection read inherits from the base read it replaced, so nothing in the
pairing itself keeps them apart.

What keeps them apart today is the hash of the node the decision is matched on,
taken bottom-up over its whole subtree: a projection read under it makes the hash
disagree and the optimization stops well before the transplant. Measured across
twelve shapes - normal and aggregate projections, under aggregation, under a
join, in an IN-subquery, in a join of two aggregating subqueries - the
optimization declines at the hash in every one where a projection was used, and
the guard never fires. It is there for a read outside that subtree, which the
transplant would still reach.

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

Three points from review.

The pairing was unique on the single-node side only: two reads of the candidate
could look up the same single-node read. The plans have equally many reads, so
one claimed twice means another was not claimed at all - the plans do not read
the same things - and the candidate is declined.

`adoptFiltersFrom` copied the other read's deferred `FINAL` filters. Those are
that read's own `query_info.prewhere_info` and `query_info.row_level_filter`
under another name, so the copy holds only as long as the two plans split the
`WHERE` into a `PREWHERE` the same way. Defer this read's own instead. No
`FINAL` read reaches the optimization today - `supportsDataflowStatisticsCollection`
is false for one, and every step of the plan has to support it - so this is what
it would do if one ever did, not a fix for anything observable.

Nothing in `ReadFromMergeTree` reads the inherited `limit`; the ordered read
takes its bound from `query_info.input_order_info`. The copy stays, because the
pass being stood in for does set it, but the comment no longer claims an effect
it does not have.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
The analysis carries `column_names_to_read`, and that list - not the step's own
`all_column_names` - is what the read follows, while `output_header` is built
from the step's own. Handing an analysis to another read hands it that list too,
so the two reads have to want the same columns; one analysis cannot serve two
column lists.

They agree in every reachable shape: 65 transplants across the `autopr` tests and
the join, self-join, projection and lazy-materialization sweeps, all with equal
column lists and equal output headers. The passes that change a read's columns
after analysis - lazy materialization, a rewritten `PREWHERE`, vector search -
run on the candidate as well, which is why. Lazy materialization was measured
specifically: `JoinLazyColumnsStep` in the plan, parallel replicas chosen, both
plans making the same split.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
A read contributes its name, its table and its `PREWHERE` to the hash and nothing
else - not its columns, not its filter actions - so it is the steps above a
projection read that make the hash disagree, not the read itself.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
This reverts commit 2245a74.

Branch `autopr-read-key-columns` hashes the read's output header into its
statistics key, so two reads of one table that produce different columns no
longer match at the boundary and the optimization declines before the transplant
is reached. That is the better place for it: it declines earlier, and it fixes
the statistics entry those two reads were sharing rather than only guarding the
transplant.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9RgG25RYDPTTwhGrBwwcr
@nickitat
nickitat enabled auto-merge September 22, 2026 22:47
@nickitat
nickitat added this pull request to the merge queue Sep 23, 2026
Merged via the queue into master with commit bf8170e Sep 23, 2026
519 of 522 checks passed
@nickitat
nickitat deleted the autopr-transplant-index-analysis branch September 23, 2026 13:36
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
nickitat added a commit that referenced this pull request Sep 23, 2026
…dropped

`autopr-transplant-index-analysis` landed on master in #115153, so the merge
resolved `considerEnablingParallelReplicas.cpp` by taking master's copy whole.
That is right for the transplant half - master's version supersedes this
branch's, including the distinct-table pairing - but the same file also held
this branch's own half, the two call sites that arm and then undo the probe's
deferred subquery materialization, and those went with it.

What was left does not compile: `QueryPlanOptimizationSettings` still declares
the builder as returning a `ParallelReplicasPlan` and taking a
`defer_materialization` flag, while the call site passes one argument and
dereferences the result as a plan pointer.

Restored verbatim from 05e469f: build the probe deferred, and, once replicas
have won, rebuild it with the subqueries materialized before it becomes the plan
that runs - declining if that rebuild does not come back, rather than executing
a plan whose temporary tables are empty. Nothing of the transplant work comes
back with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
nickitat added a commit that referenced this pull request Sep 27, 2026
All four entries were there because a plan rewritten by the optimization never
populated the query condition cache, so the next query over the same condition
missed it. That was the same root cause as #115153, which is now merged: the
index-analysis transplant carries `allow_query_condition_cache` onto the
parallel-replicas step, which is what gates the cache on both sides.

Checked rather than assumed, because the list is tolerate-only and a pass in it
was defined to carry no information: with the `AutoParallelReplicas` profile
active, each test's own queries were counted for `ParallelReplicasUsedCount`, so
the plan demonstrably was rewritten and the test still passed -
`03229` 1 query, `04320` 3, `05099` 19, and `03783`'s `query_1` in 3 of 6 runs.
They pass with nothing tolerating them any more.

`blacklist_tolerate_only` itself stays: it still routes
`parallel_replicas_blacklist.txt` under `--autopr`, where a pass genuinely says
nothing because the optimization only switches when its statistics say it pays
off. `--autopr` also still drops the two settings the randomizer would otherwise
use to turn the optimization off.

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-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-performance Pull request with some performance improvements 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