Skip to content

Do not repeat the coordinator's index analysis on distributed plan replicas - #131216

Open
shankar-iyer wants to merge 16 commits into
ClickHouse:masterfrom
shankar-iyer:distributed-plan-worker-analysis-own-bucket
Open

shankar-iyer wants to merge 16 commits into
ClickHouse:masterfrom
shankar-iyer:distributed-plan-worker-analysis-own-bucket

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Under make_distributed_plan, every replica task ran the full index analysis (partition pruning, primary key, skip indexes, query condition cache) over all parts of its local snapshot, and then replaced the result with the marks the coordinator had selected. The coordinator had already done the same analysis, so the work was repeated once per task, over the whole table each time.

A replica task now reads its bucket parameter before the index analysis and pins its parts to the received marks (pinPartsToReceivedMarks), keeping the snapshot order and the offsets of the parts in the query. selectRangesToRead then keeps those ranges without repeating the primary key, skip index and query condition cache analysis. A FINAL read is pinned to the union of the ranges of its lanes. The replica still runs the analysis, over its own marks only, when it can prune more than the coordinator: with use_index_for_in_with_subqueries = 0 the coordinator does not use an IN subquery set, while the replica receives the set as values (see 05021_distributed_plan_read_locally_pruned_part). A read with sampling is not pinned, because an absolute sample size is turned into a ratio of the rows of the parts the analysis is given.

make_distributed_plan no longer turns off use_skip_indexes_on_data_read. With it, the coordinator analyzes only the primary key, and each replica applies the skip indexes while reading its own marks, so the skip indexes of a part are read only by the replica that reads it. The buckets stay contiguous slices of marks, which keeps part affinity on the replicas; a selective skip index can leave the work unevenly split between them.

Measured with distributed_plan_execute_locally = 1 and 3 buckets over a 100-mark table: the replica tasks analyze 0 primary key marks (300 before), and their selected marks add up to those of the same query on a single node.

Known limitations, left for follow-ups

  • max_partitions_to_read is checked per replica against its bucket, as on master. With pinned reads, the max_concurrent_queries admission compares the marks of a bucket, not of the whole read, with min_marks_to_honor_max_concurrent_queries. The admission is local to each server, so fixing it needs a decision for the whole read shipped to the replicas and one slot per query on each reading server.
  • Pinned reads skip the replica's own query condition cache lookup and, as on master, do not write to the cache.
  • The bucket is read when the pipeline is built. A replica-side plan optimization that analyzes the read earlier sees the whole snapshot; useVectorSearch and optimizeJoinByShards have no guard for bucketed reads.

Changelog category (leave one):

  • Performance Improvement

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

With make_distributed_plan, replicas no longer repeat the coordinator's index analysis of the whole table for every task; each task analyzes only the marks it reads, or none. use_skip_indexes_on_data_read is no longer turned off by make_distributed_plan, so the skip indexes are applied by the replicas while they read their own marks.

🤖 Generated with Claude Code


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

shankar-iyer and others added 4 commits November 13, 2026 06:34
…plicas

Under `make_distributed_plan`, every replica task ran the full index analysis
(partition pruning, primary key, skip indexes, query condition cache) over all
parts of its local snapshot, and then replaced the result with the marks the
coordinator had selected. The coordinator had already done the same analysis,
so the work was repeated once per task.

A replica task now reads its bucket parameter before the index analysis
(`readDistributedReadTaskBuckets`, the parsing code moved unchanged). For a
non-FINAL read, `pinPartsToReceivedMarks` restricts `prepared_parts` to the
received marks, keeping the snapshot order and the offsets of the parts in
the query. `selectRangesToRead` then keeps the received ranges without the
primary key, skip index and query condition cache analysis
(`index_analysis_already_done`). A FINAL read keeps all local parts, because
each lane's marks are resolved against them, and skips the analysis as well.

The replica still runs the analysis, over its received marks only, when it can
prune more than the coordinator: with `use_index_for_in_with_subqueries = 0`
the coordinator does not use an `IN` subquery set, while the replica receives
the set as values and can (see `05021_distributed_plan_read_locally_pruned_part`).

`make_distributed_plan` no longer turns off `use_skip_indexes_on_data_read`:
with it, the coordinator analyzes only the primary key, and each replica
applies the skip indexes while reading its own marks, so the skip indexes of a
part are read only by the replica that reads the part.

Tests:
- New `05617_distributed_plan_worker_analyzes_only_its_marks`: replica tasks
  analyze no primary key marks (300 before, with 3 tasks over 100 marks), for
  plain and FINAL reads, and analyze only their own marks in the `IN` set case.
- `04656_distributed_plan_workers_disable_jit_and_skip_index_read`: expect
  `use_skip_indexes_on_data_read` to stay enabled on the replica tasks.
- `05021_distributed_plan_read_locally_pruned_part`: pin
  `use_skip_indexes_on_data_read = 0`, so that the skip-index route still
  tests the pruning by the index analysis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Found by a local review of the previous commit:

- A FINAL read on a replica skipped the index analysis without being pinned,
  so its analysis result kept every local part with its whole range. The
  partition and row limits then counted parts the coordinator had excluded:
  with `max_partitions_to_read = 1`, a FINAL query whose primary key selects
  one partition threw `TOO_MANY_PARTITIONS`. FINAL reads are now pinned to the
  union of the ranges of their lanes. The lanes can name one part several times
  and the primary-key-range layers can share a boundary granule, so the ranges
  are sorted by their beginning (`MarkRange::operator<` rejects intersecting
  ranges) and merged.

- `getSampling` turns an absolute sample size into a ratio of the rows of the
  parts it is given. On a pinned read these are only the rows of the task's
  bucket, so `SAMPLE 10000` read without sampling on the replicas
  (`_sample_factor = 1`), and `SAMPLE 10000 OFFSET 0.2` threw. A read with
  sampling is not pinned and runs the index analysis as before.

The row limits that a pinned replica read checks now count the task's share
instead of the whole selection. The coordinator checks them on the whole
selection in its own analysis.

Tests: `05617_distributed_plan_worker_analyzes_only_its_marks` covers an
absolute `SAMPLE` (with `OFFSET` and `_sample_factor`) and a FINAL read under
`max_partitions_to_read = 1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`max_partitions_to_read` and the `max_concurrent_queries` admission of a read
of at least `min_marks_to_honor_max_concurrent_queries` marks are checked only
by `ReadFromMergeTree::AnalysisResult::checkLimits`, which runs when the
pipeline of the read is built. Under `make_distributed_plan` that happens on
the replicas, and each replica reads only its bucket of the read:

- Each replica counted only the partitions of its bucket, so a query reading
  three partitions in three buckets passed `max_partitions_to_read = 1`. This
  was already the case before pinning replica reads to their buckets, because
  the analysis result was narrowed to the bucket before `checkLimits`.
- With the reads pinned to their buckets, each replica compared the marks of
  its bucket with `min_marks_to_honor_max_concurrent_queries`, so a query
  whose buckets are each below the threshold was never admitted, and ran
  while another query held the only slot. Before pinning, each replica took a
  slot of its own under its own task query id, so a distributed query competed
  with itself and failed with `max_concurrent_queries = 1` even when it ran
  alone.

`QueryPlan::convertToDistributed` now checks the limits once per bucketed
read, against the coordinator's analysis of the whole read
(`ReadFromMergeTree::checkLimitsOfDistributedRead`), and keeps the
`max_concurrent_queries` slot in the resources of the plan, which the
pipeline of the query holds until the query finishes. The replicas no longer
call `checkLimits` for a bucketed read. The row limits are not affected: the
index analysis checks them, on the coordinator.

The partition limit and the admission bypass were reported by a local review
of this branch; the self-blocking admission was found while reproducing them.

Tests: new `05618_distributed_plan_limits_of_whole_read`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This reverts commit ca01d72.

The `max_concurrent_queries` admission is local to each server, so a slot
held on the coordinator does not protect the replicas that read on other
servers: a distributed read ran on a worker while another query held the
worker's only slot. The limits of a whole read across replicas need a
separate design (an admission decision for the whole read, shipped to the
replicas, and one slot per query on each reading server), so they are left
as on master here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Nov 13, 2026
…rker-analysis-own-bucket

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f6f8aa]

Summary: ✅


AI Review

Summary

make_distributed_plan now restricts worker index analysis to assigned marks, skips redundant analysis where possible, and permits read-time skip indexes. Reviewed head 8f6f8aa199379634e2f3be5d71372fec16a00b98; the checkout has the identical tree. The earlier concurrency-admission and specific descriptor-bounds defects are fixed, but a previously discussed, explicitly deferred descriptor-safety defect remains.

Findings

❌ Blockers

  • src/Processors/QueryPlan/ReadFromMergeTree.cpp:5957 Repeated part entries still cause a null-pointer dereference. [dismissed by author -- https://github.com/Do not repeat the coordinator's index analysis on distributed plan replicas #131216#discussion_r4574998741] A non-FINAL descriptor with one lane and two entries naming the same existing part, each with a valid range such as [0, 1), passes validation. pinPartsToReceivedMarks coalesces the analysis ranges but leaves both entries in the bucket. The resolution loop then moves the same map value twice, appending a second RangesInDataPart with a null data_part; partition bookkeeping dereferences it at line 6058. The normal coordinator does not produce this descriptor, but malformed interserver bytes must produce an exception instead of undefined behavior. This is pre-existing and explicitly deferred by the author; it remains real because the current consumer still assumes uniqueness without checking it. Reject duplicate part names within a non-FINAL bucket before consuming entries, or link a tracking issue for the deferred defect. No duplicate inline comment or thread reopening is warranted.
Tests
  • ⚠️ The added SQL tests exercise valid descriptors, but the new rejection paths have no focused malformed-payload coverage. Add a small boundary test for invalid lane counts, border arity beyond the primary key, and empty/reversed/out-of-bounds ranges; include repeated part names when fixing the remaining defect. The null-pointer finding above is based on a concrete source trace; no local binary was available to execute it.
Final Verdict

Status: ❌ Block

Reject repeated part entries with an exception, or link a tracking issue for that explicitly deferred pre-existing defect. Add focused regression coverage for the descriptor validation introduced here.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 13, 2026
- Remove a duplicate include of `Columns/ColumnSet.h` from
  `ReadFromMergeTree.cpp`: the merge with master brought one in already
  (`readability-duplicate-include`).
- `05617_distributed_plan_worker_analyzes_only_its_marks`: pin
  `max_rows_to_group_by = 0`, which the test runner randomizes and which
  `make_distributed_plan` rejects, together with
  `automatic_parallel_replicas_mode = 0`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131216&sha=7dcabd0cb0ea92e6f024e1ba353ac902362dd2b8&name_0=PR
PR: ClickHouse#131216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f6f8aa19 with master 50bbe27ba (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

47 object files changed (+53.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.71 MiB 2.77 MiB +54.76 KiB (+1.97%)

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

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

Job report

shankar-iyer and others added 5 commits November 13, 2026 11:33
`AnalysisResult::checkLimits` admits a read to `max_concurrent_queries` when
it selects at least `min_marks_to_honor_max_concurrent_queries` marks. A
replica read pinned to its bucket selects only the marks of the bucket, so a
read whose buckets are each below the threshold took no slot, and ran while
another query held the table's only slot. Until the replicas get the
admission decision of the whole read, a read from a table with both settings
is not pinned and keeps the analysis of the whole snapshot, as before.

`05231_distributed_plan_task_query_log_attribution`: a replica task now
reports as selected only the parts it was assigned, where it reported every
part its own analysis of the whole table selected. Check that instead of a
fixed number of parts per task, which depends on how the buckets fall on the
parts.

Tests: new `05628_distributed_plan_concurrent_queries_admission`.

Review comment: ClickHouse#131216
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131216&sha=a983bd95ae72bde4bd84806c1e882295376f7f89&name_0=PR

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The read-volume check of `05021_distributed_plan_read_locally_pruned_part`
counts whole parts: of three parts, the worker reads only the one that can
match. With a randomized `index_granularity` a part has several granules, and
the worker, which now keeps the granule pruning of its own analysis instead of
reading the coordinator's ranges, reads one granule of that part (439 rows
with a granularity of 425, below the lower bound of 500). Make each part a
single granule.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131216&sha=212ce529285a4d5d14bf7e012dc48b7ebbb007a8&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
PR: ClickHouse#131216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n a failed holder

In the parallel replicas job, the slot holder of
`05628_distributed_plan_concurrent_queries_admission` read with parallel
replicas. A replica's query took a `max_concurrent_queries` slot of its own,
was rejected with `TOO_MANY_SIMULTANEOUS_QUERIES` because the table allows one
query, and the holder failed at once. The test then waited for the holder to
read until it timed out. Run the holder and the checked queries without
parallel replicas, and stop waiting when the holder has exited.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131216&sha=3beb72f6ed436abfd285bd691dbc79551c56cf6b&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#131216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). I also added a small commit that switches the new code to the -WithMemoryTracking types where it meets the APIs changed there, so that it compiles. This update was made automatically.

shankar-iyer and others added 3 commits November 18, 2026 10:33
The bucket parameter of a distributed read was used as received: its border
arity indexed the primary key types without a bound, a read without FINAL
took the first of possibly no lanes, and its mark ranges were installed
without checking them against the local parts. `readDistributedReadTaskBuckets`
now checks, once, that the task has at least one lane, exactly one without
FINAL, that the layer borders have no more columns than the primary key, and
that every range of a local part is non-empty and within the part's marks. A
descriptor that fails any of these is rejected with `INCORRECT_DATA`.

Review comment: ClickHouse#131216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`AnalysisResult::checkLimits` counts the partitions of the analysis result
against `max_partitions_to_read`. A FINAL replica kept the whole selection
there, so the limit held for the whole read. Pinned to its lanes, a task
counted only the partitions of its own lanes: three partitions in three
buckets passed `max_partitions_to_read = 1`. A FINAL read with the limit set
is not pinned, and the replica analyzes the whole snapshot as before.

Found by a local review of the branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rker-analysis-own-bucket

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 19, 2026
shankar-iyer and others added 2 commits November 20, 2026 04:05
…rker-analysis-own-bucket

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
The style check requires the `-WithMemoryTracking` containers in
`src/Processors/QueryPlan` since ClickHouse#129617.

PR: ClickHouse#131216

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@shankar-iyer

Copy link
Copy Markdown
Member Author

Fixed the new style check failures.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants