Skip to content

Apply primary key pruning before read-time skip indexes on parallel replicas followers - #126145

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/pr-follower-skip-index-pk-narrowing
Oct 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/pr-follower-skip-index-pk-narrowing

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124628

Changelog category (leave one):

  • Performance Improvement

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

With parallel replicas and use_skip_indexes_on_data_read (the default), follower replicas now evaluate skip indexes only over the primary key ranges of each part instead of the whole part, so they read about as much skip index data as the initiator. Closes #124628.

Description

With parallel_replicas_index_analysis_only_on_coordinator (the default), a follower skips its own index analysis and keeps every mark of every part, because the coordinator assigns its ranges. The read-time skip-index input was built from those ranges, so the first task touching a part made MergeTreeSkipIndexReader::read evaluate the skip indexes over the whole part, without primary key pruning.

The follower branch of selectRangesToRead now keeps the key condition it did not apply, and the skip-index reader narrows each part's input with markRangesFromPKRange before reading the indexes. This is the PK step the initiator and a single-node read already do, so the granules it drops cannot contain a matching row; a follower with parallel_replicas_index_analysis_only_on_coordinator = 0 does the same at plan time, while this runs lazily, only for the parts the follower touches. What followers announce and read, and the coordinator, are unchanged. It covers query-based and plan-based parallel replicas, all read pools and the JOIN runtime-filter-only reader.

On the issue's reproduction (200 parts, bloom filter on mapValues, 3 local replicas), ReadCompressedBytes per follower goes from 40.8 / 39.1 MiB to 3.8 / 4.2 MiB (plan-based: 41.3 / 38.0 to 3.6 / 3.1 MiB), with identical results. The price is the PK step on followers, which also loads a part's primary index if no query has loaded it yet: 1.2-2 ms per follower there, 0.3 ms when the primary key does not prune.

Not addressed: evaluating the index only over the assigned ranges (the issue's second option), releasing the per-part result when part_remaining_marks never reaches zero (not follower-specific), and the plan-based initiator's extra reads.

The new test checks that no follower selects more marks than a single-node read; it fails 10/10 without the fix.


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

Version info

  • Merged into: 26.11.1.180-master (included in 26.11 and later)

groeneai and others added 2 commits October 15, 2026 21:21
…replicas followers

With parallel replicas, a follower skips its own index analysis
(`parallel_replicas_index_analysis_only_on_coordinator`) and keeps every mark of every part, because the
coordinator assigns its ranges. With `use_skip_indexes_on_data_read` the read-time skip-index input is
built from those ranges, so the first task that touches a part made `MergeTreeSkipIndexReader::read`
evaluate the skip indexes over the whole part, without primary-key pruning. With stealing, each follower
read close to the whole table's skip index (issue: ~40 MiB per follower vs 0.45 MiB with the setting off).

The follower branch of `selectRangesToRead` now records the key condition it did not apply
(`AnalysisResult::key_condition_not_applied`), `initializePipeline` hands it to the skip-index reader, and
`read()` narrows each part's input with `markRangesFromPKRange` before reading the skip indexes. This is
the same PK step the initiator and any single-node read already do, so granules it drops cannot hold a
matching row; they are marked not selected and skipped like any other read-time-skipped granule, exactly
as on a follower with `parallel_replicas_index_analysis_only_on_coordinator = 0`. What the follower
announces and reads is unchanged, so the coordinator is untouched. Covers query-based and plan-based
parallel replicas, every read pool and the JOIN runtime-filter-only reader.

Closes ClickHouse#124628

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y step

The plan-time primary key step (`filterPartsByPrimaryKeyAndSkipIndexes`) passes the
primary-key-to-partition-minmax mapping to `markRangesFromPKRange` when
`use_partition_minmax_for_primary_key_pruning` is on (the default), so a primary key column that is
also a partition key input is bounded by the part's partition minmax where the index leaves it
unbounded. The read-time step added for parallel replicas followers passed no mapping, so a
follower's narrowing could be looser than the initiator's. `buildPrimaryKeyToMinMaxSlotMapping` is now
a public static of `MergeTreeDataSelectExecutor`, and `initializePipeline` builds the mapping under the
same setting and hands it to the skip-index reader together with the key condition.

The test table is now `PARTITION BY p ORDER BY (k, p)` and the filter ORs in `p = 100`, which no part
holds: a granule whose `k` differs between its boundary keys leaves `p` unbounded, so only the
partition bound rules that branch out. Without the bound a follower keeps 92 of each part's 100 marks
(the minmax index drops 8), with it 3, as the single-node read. Base, a reader that is never given
the key condition, and one given it without the mapping all fail 10/10 randomized runs.
`use_lightweight_primary_key_index_analysis` is clamped to 1: with 0 the plan-time step itself does
not apply the partition bound to such a granule, the single-node baseline becomes 920 marks and the
oracle cannot tell the arms apart (measured: 4 of 10 unclamped runs drew 0 and all 4 passed on the
mapping-less reader).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 4 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The read-time PK step passed no partition-minmax mapping, unlike the plan-time step AGREE, fixed in 64753b8 the mapping is passed; the test fails 10/10 without it
2 ⚠️ The follower oracle can pass when followers get no tasks DISAGREE without the fix the test fails 10/10 (and 19/19 earlier); a participation assertion would make the pass condition timing-dependent
3 ⚠️ The oracle checks the selected marks, not the skip-index input DISAGREE the test fails 10/10 without the fix and without either half of it; no counter exposes the read-time skip-index input (only a timer), so the I/O effect is the one measured in the description (40.8 to 3.8 MiB per follower)
4 💡 The may_skip_granules_besides_top_k_primary_key comment does not list the primary key noted, not blocking comment only, the flag is set correctly
5 💡 The read-time PK step does not bump FilteringMarksWithPrimaryKeyProcessedMarks noted, not blocking observability only

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-49:20261015-222400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's repro on one server with 3 local replicas: followers read 40.8 / 39.1 MiB (query-based) and 41.3 / 38.0 MiB (plan-based) every run. The new test fails 10/10 on master, without the key condition, and without the partition-minmax mapping.
b Root cause explained? A follower skips index analysis and keeps whole parts (the coordinator assigns ranges); the read-time SkipIndexReadInput was built from those ranges, so MergeTreeSkipIndexReader::read evaluated the skip indexes over every granule of each part the follower touched, with no primary key pruning.
c Fix matches root cause? Yes. The follower keeps the key condition it did not apply, and the reader runs markRangesFromPKRange (with the partition-minmax mapping) on each part's input before the skip indexes, the same step the initiator does.
d Test intent preserved / new tests added? New test 05401_parallel_replicas_follower_skip_index_primary_key: no follower's SelectedMarks may exceed the single-node read's (query-based and plan-based), plus result checks. Untagged; use_lightweight_primary_key_index_analysis clamped to 1 (with 0 the single-node baseline ignores the partition bound for this filter).
e Both directions demonstrated? Without the fix 10/10 FAIL (92 marks per part on followers vs 30 in total single-node); with it 50/50 randomized, parallel replicas and Replicated database lanes 10/10 each. Issue scale: 40 MiB to 4 MiB per follower.
f Fix is general across code paths? Applied to whichever skip-index reader is built (skip indexes or JOIN runtime filters only); every read pool and the refiner go through getOrBuildIndexReadResult; query-based and plan-based followers both measured.
g Fix generalizes across inputs (params/datatypes/wrappers)? Key types are handled by KeyCondition as at plan time; no primary key or use_primary_key = 0 leaves the input unchanged; a query whose primary key does not prune was measured unchanged (PK step 0.3 ms).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, format or protocol change; the coordinator and what followers announce are unchanged.
i Invariants and contracts preserved? granules_selected stays a superset of the matching granules (KeyCondition soundness, as on the initiator); the per-part result promise, cancellation and exception paths are unchanged.

Session id: cron:clickhouse-impl-slot-4:20261015-215800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @devcrafter, could you review this? Parallel replicas followers skip index analysis and keep whole parts, so the read-time skip-index reader evaluated the indexes over every granule of each part they touched; it now narrows each part's input by the primary key first, the same step the initiator does.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eef2049]

Summary: ✅


AI Review

Summary

The PR applies primary-key pruning, including partition-minmax bounds, before parallel-replica followers evaluate read-time skip indexes. The regression covers query-based and plan-based replicas, and the PR supplies before/after I/O measurements. No actionable findings were identified for head eef20494a3b7a634e9774d7ec406833dada4ecfc.

Missing context / blind spots
  • ⚠️ No local build or tests were run because no ClickHouse binary is available. The targeted CI reports did not expose completed test results for this head; execution evidence relies on the reproduction and repeated-test measurements recorded in the PR. Completed targeted CI would close this gap.
Final Verdict

Status: ✅ Approve. No required code changes identified.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
The flaky check failed 23 of 81 runs with the `query_based` line missing. In the tsan job's
`query_log`, both followers of every failing run ended `ExceptionBeforeStart` with code 735
(`QUERY_WAS_CANCELLED_BY_CLIENT`), and the server log shows why: the coordinator had assigned
all marks to the initiator's local replica before the followers announced, and cancelled them as
unused ("All ranges for reading has been assigned to replicas. Cancelling execution for unused
replicas. Used replicas: 0"). The `GROUP BY mode` over finished followers then had no row.

Both parallel queries now run with `parallel_replicas_prefer_local_replica = 0`. Without a local
plan every replica, the initiator's own server included, is a remote follower that skips its own
index analysis, so the data is always read by followers and each mode has a finished follower.
`sleepEachRow` only gave followers time to start before the local replica drained the work, so it
is gone. The oracle and the reference are unchanged.

Validation, with the `parallel_replicas_delay_announcement` failpoint standing in for the CI
timing (every announcement delayed by 3 s): the previous test failed 4/4 with both lines
missing. The new one passes 8/8 there, 353/353 randomized concurrent runs, 40/40 with the server
limited to one CPU, 3/3 each with `use_indexes_refiner_in_read_pools` 0 and 1, and 10/10 in each
parallel replicas lane emulation. In the 253 runs counted from `query_log`, every one had a
finished follower in both modes, with at most 30 selected marks, as many as the single-node
read. A master binary without the fix fails 17/17 (4/4 under the failpoint) and a reader without
the partition minmax mapping 10/10, with followers at 460 to 828 marks.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Amazing, thank you!

@alexey-milovidov alexey-milovidov self-assigned this Oct 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit 1daec15 Oct 19, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
nickitat added a commit that referenced this pull request Oct 20, 2026
The revert of #126145 is now a separate PR, #126955, which this
one is stacked on. This branch already removed the same code, so its tree is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Oct 22, 2026
…rallel replicas followers"

This reverts ClickHouse#126145 (merge commit 1daec15): source
changes and the test `05401_parallel_replicas_follower_skip_index_primary_key`. The declaration of
`key_condition_not_applied` in `ReadFromMergeTree.h` was removed by hand, because `pk_condition_useful`
was added next to it afterwards.

A follower will take the ranges analyzed on the initiator from the coordinator instead of repeating
the primary key analysis: ClickHouse#126954

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
… on the initiator

With `parallel_replicas_index_analysis_only_on_coordinator`, a parallel replicas follower skips its own
index analysis and keeps every mark of every part. With `use_skip_indexes_on_data_read`, that whole-part
input made `MergeTreeSkipIndexReader::read` evaluate the skip indexes over whole parts. ClickHouse#126145 narrowed
the input by running the primary key analysis again on each follower.

The coordinator already holds the analyzed ranges: the snapshot announcement of the initiator registers
them, and `InitialAllRangesAnnouncementResponse` carries them back for in-order reads. A `Default` mode
follower that skipped analysis and has a read-time skip-index reader now asks for that response with a
new `wants_analyzed_ranges` field of `InitialAllRangesAnnouncement` (parallel replicas protocol 9), and
evaluates the skip indexes over those ranges. In-order followers use the response they already receive.
This replaces the primary key step of ClickHouse#126145, so followers do not repeat the analysis, and their input
matches the initiator's exactly, partition minmax pruning included.

Other `Default` mode reads still neither send nor wait for the response, and the coordinator no longer
copies the registered parts into a response that is not sent. With an initiator older than protocol 9
the follower does not ask and evaluates whole parts, as before ClickHouse#126145.

The test now runs with the initiator's local replica, the default: without a local plan no replica
analyzes, so the coordinator has no analyzed ranges to hand out.

Issue reproduction (200 parts, bloom filter, 3 local replicas, caches dropped before each query),
`ReadCompressedBytes` per follower: no fix 16-105 MiB (1073 selected marks), ClickHouse#126145 0.25-3.3 MiB,
this change 0.17-1.9 MiB (20 selected marks in both).

Related: ClickHouse#124628
Related: ClickHouse#126145

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Oct 23, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 125569 116724 Revert "Verify the server certificate hostname on outbound TLS connections"
Changelog-revert: 125763 120058 Revert "Filter `PartsSplitter` layers on the key columns the sorting expression computed"
Changelog-revert: 125827 125763 Revert "Revert "Filter `PartsSplitter` layers on the key columns the sorting expression computed""
Changelog-revert: 126138 125569 Revert "Revert "Verify the server certificate hostname on outbound TLS connections""
Changelog-revert: 126955 126145 Revert "Apply primary key pruning before read-time skip indexes on parallel replicas followers"
Changelog-revert: 127378 126987 Revert "Take the format settings of object storage tables from the server, not the creating session"
Changelog-deleted-entry: 126145 [Performance Improvement] [section] * With parallel replicas and `use_skip_indexes_on_data_read` (the default), follower replicas now evaluate skip indexes only over the primary key ranges of each part instead of the whole part, so they read about as much skip index data as the initiator. Closes [#124628](#124628). [#126145](#126145) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 126987 [Backward Incompatible Change] [raw] * Tables with the `S3`, `AzureBlobStorage`, `HDFS` and data lake engines take format settings (e.g. `format_csv_delimiter`) from the server's settings and the table's `SETTINGS` clause, as `File` and `URL` do, and no longer from the session that creates them. Before, the session's values applied only until the table was loaded again, e.g. on server restart. To keep a format setting, state it in the table's `SETTINGS` clause. [#126987](#126987) ([Vadim Lopatin](https://github.com/buggins)).
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 4, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parallel replicas followers evaluate read-time skip indexes over whole parts (use_skip_indexes_on_data_read)

6 participants