Skip to content

Lazy range refinement in read pools - #110291

Merged
CurtizJ merged 18 commits into
masterfrom
lazy-range-refinement-in-read-pools
Jul 28, 2026
Merged

CurtizJ merged 18 commits into
masterfrom
lazy-range-refinement-in-read-pools

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Added a new setting use_projection_index_in_read_pools (disabled by default). When enabled, mark ranges that are fully filtered out by a projection index are dropped inside MergeTree read pools before read tasks are created for them, instead of being skipped granule by granule during reading. This avoids creating read tasks and setting up readers for data that will not be read, and keeps read task sizes measured in surviving marks.

Claude

This PR introduces a deferred range-refinement contract for MergeTree read pools and adds its first consumer, the projection index (see optimize_use_projection_filtering).

Motivation. The ranges a read pool is created with are an upper bound: some information usable for pruning becomes available only at execution time. Today the projection index bitmap is applied only during reading
(MergeTreeReaderIndex): fully filtered granules are skipped and the remaining rows are filtered inside the reading chain, but the read task covering a pruned granule still exists, occupies a scheduling slot, and pays the reader setup
cost. The same limitation will apply to runtime filters collected from a JOIN build side, which is the longer-term motivation: this contract is the first step towards applying runtime filters to the primary key inside pools, and later
towards gating reads per PK-range epoch for collocated JOINs (the refinement point is where a pool will stop and wait for the next epoch to be sealed).

What is done:

  • IMergeTreeReadRangesRefiner: refines (shrinks) mark ranges cut from a part right before they become a read task. May block on first use per part, therefore pools call it outside of their scheduling mutex. Refinement is an
    optimization: it is always sound to skip it, since rows outside the refined ranges are filtered later during reading anyway.
  • MergeTreeReadPool and MergeTreeReadPoolInOrder apply the refiner at task-cut time: cut under the mutex, refine outside of it, take the next cut if everything was dropped. Marks dropped by the refiner do not count towards the task
    size: MergeTreeReadPool::getTask keeps cutting more marks from the same part until the task reaches its intended size in surviving marks, so heavy pruning does not produce many tiny tasks. Prefetched and parallel-replicas pools keep the
    existing read-time-only filtering for now.
  • ProjectionIndexReadRangesRefiner applies the granule-level part of the projection index bitmap (the same predicate as the projection branch of MergeTreeReaderIndex::canSkipMark) at task-cut time, reusing the per-part cached bitmap
    from MergeTreeIndexReadResultPool. Row-level filtering of the surviving granules still happens in MergeTreeReaderIndex. Marks dropped by the refiner are subtracted from MergeTreeIndexBuildContext::part_remaining_marks, so the cached
    per-part index result is still released after the last task of the part.
  • New ProfileEvents ReadPoolRangeRefinerDroppedMarks and ReadPoolRangeRefinerDroppedCuts; the setting is randomized in functional tests.

Note: the added perftest includes new settings, so it's not comparable to the old build. On a new build, the enabled setting gives ~x2 the speedup vs. the disabled setting.
https://s3.amazonaws.com/clickhouse-test-reports/PRs/110291/c363937fe020c42d4d14519ff14174c7b2810c7c/performance_comparison_arm_release_master_head_3_6/report.html

Version info

  • Merged into: 26.8.1.263 (included in 26.8 and later)

KochetovNicolai and others added 3 commits July 13, 2026 16:20
Introduce a deferred range-refinement contract for MergeTree read pools:
the ranges a pool was created with are an upper bound, and a refiner
(`IMergeTreeReadRangesRefiner`) may shrink every cut right before it
becomes a read task. Pools cut ranges under their scheduling mutex as
before, call the refiner outside of the mutex (it may block, e.g. to
build a projection index bitmap on the first use for a part), and take
the next cut if everything was dropped, so fully pruned ranges never
become read tasks.

The first refiner is `ProjectionIndexReadRangesRefiner`: it applies the
granule-level part of the projection index bitmap (the same predicate as
the projection branch of `MergeTreeReaderIndex::canSkipMark`) at
task-cut time. Row-level filtering of the surviving granules still
happens in `MergeTreeReaderIndex`. Marks dropped by the refiner are
subtracted from `MergeTreeIndexBuildContext::part_remaining_marks` so
the per-part cached index result is still released after the last task.

The refiner is applied by `MergeTreeReadPool` (including the stealing
path) and `MergeTreeReadPoolInOrder`; prefetched and parallel-replicas
pools keep the existing read-time-only filtering.

Controlled by the new setting `use_projection_index_in_read_pools`
(default off, randomized in functional tests). New ProfileEvents
`ReadPoolRangeRefinerDroppedMarks` and `ReadPoolRangeRefinerDroppedCuts`.

Co-Authored-By: Claude Fable 5 <[email protected]>
Marks dropped by the ranges refiner no longer count towards the read
task size. `MergeTreeReadPool::getTask` now accumulates: after refining
a cut (outside of the mutex, since the first refinement per part may
block), if the surviving marks are below the task size target, it cuts
more marks from the same part and refines them too, until the target is
reached, the part is exhausted, or another part gets on top of the
queue. Without this, heavy pruning produced many tiny read tasks with
per-task reader setup overhead.

The cutting logic is split into `cutRangesToRead` (queue selection and
task size computation), `cutMoreRangesToRead` (continuation from the
same part) and the shared `cutFromThreadTask`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [94a6bfd]

Summary: ✅


AI Review

Summary

This PR adds a lazy range-refinement hook to MergeTree read pools and uses it to apply projection-index pruning before read tasks are created, with follow-up fixes for the parallel-replicas metrics and warmup cases raised in earlier review threads. I did not find a remaining correctness, concurrency, or resource-lifetime bug in the current head. The only remaining issue is a changelog overstatement: the code now explicitly documents that MergeTreePrefetchedReadPool still decides task sizing and prefetch admission on unrefined ranges, so the current PR text promises slightly more than the implementation guarantees there. Residual risk is mostly performance characterization: the comparable CI performance run still exercised the default-off path, so the enabled-path speedup is supported mainly by the added benchmark plus the local numbers in the PR description.

PR Metadata
  • Changelog category: Improvement is correct.
  • Changelog entry: required and mostly clear, but the sentence saying the change "keeps read task sizes measured in surviving marks" is not accurate for MergeTreePrefetchedReadPool after the documented limitation added in src/Core/Settings.cpp.
  • Suggested replacement:
Added a new setting `use_projection_index_in_read_pools` (disabled by default). When enabled, mark ranges that are fully filtered out by a projection index are dropped inside `MergeTree` read pools before a `MergeTreeReadTask` is created for them, instead of being skipped granule by granule during reading. This avoids creating readers for data that will not be read; in the prefetched read pool, dropped ranges are still removed before prefetch, but task sizing and prefetch admission remain based on the unrefined ranges.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 13, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

Hi, this looks closely related to #103117. I like the refiner abstraction here, especially filling tasks based on surviving marks. My version can leave small tasks after heavy pruning.

One difference I noticed is that the projection refiner here still checks every candidate mark with rangeAllZero. In #103117 I walk the bitmap once, skip to the next granule after finding a matching row, and merge adjacent surviving granules into MarkRanges cached per part. Each cut then only intersects with those ranges. For sparse lookups, the work scales with the surviving granules rather than all the marks considered by the read pool.

On my benchmark this brought point lookups from about 63 ms to 8.5 ms. Maybe that approach could fit into this refiner while keeping the survivor-based task sizing from this PR.

One smaller thing I ran into: the setting has no effect when a prefetched pool is selected. The test disables prefetching, but I don’t think the setting description mentions that.

Happy to help port the range conversion or run the #99114 benchmark against this branch.

@KochetovNicolai

Copy link
Copy Markdown
Member Author

@EmeraldShift thank you for your ideas. I did not check your PR yet, but I will try to merge the ideas from both PRs.
My plan is to use refiner for runtime filters as well (which also intersects with #109085) , and then also support collocated joins (and runtime filters for collocated joins). But the simple step was to try on projections first.

KochetovNicolai and others added 2 commits July 14, 2026 13:47
With a refiner set, refinement becomes the first stage of the prefetch
job: `PrefetchedReaders` gets a constructor that runs "refine the task
ranges, recompute patch ranges, create readers, prefetch" as a single
job in the prefetch thread pool, so that ranges dropped by the refiner
are never prefetched and a fully pruned task produces no readers at all
(it is marked with `pruned_by_refiner` and skipped by `getTask`).

`getTask` is restructured to pop the thread task under the mutex and
resolve it outside: waiting for the prefetch job, refining a task that
was not admitted to prefetching, and creating readers no longer happen
under the pool mutex. `stealTask` returns the raw thread task for the
same reason.

Also fix the test: `ORDER BY ALL` triggered reading in order, so the
queries meant to exercise `MergeTreeReadPool` and
`MergeTreePrefetchedReadPool` were actually served by the in-order
pool. Pin `optimize_read_in_order = 0` there and add a dedicated
prefetched-pool query (verified against the `MergeTreePrefetchedReadPool`
logs that the pool is engaged).

Co-Authored-By: Claude Fable 5 <[email protected]>
The loop condition reads `all_mark_ranges` on the next iteration after
the whole-remaining-ranges branch moved it out. Reinitialize it
explicitly after the move.

Checked the same clang-tidy checks locally on all read pool files,
including `MergeTreePrefetchedReadPool` which has not been through the
CI clang-tidy build yet.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110291&sha=3ea4389310ca672307f14ffe1081cdbbb572880f&name_0=PR
PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
`MergeTreeReadPoolParallelReplicas` and
`MergeTreeReadPoolParallelReplicasInOrder` now apply the ranges refiner
to the ranges assigned by the coordinator, right before creating a read
task. The locked part of `getTask` is extracted into `cutRangesToRead`
(requesting an assignment from the coordinator as before), refinement
runs outside of the mutex, and a fully pruned cut loops to the next one.

Dropping refined ranges locally is sound: refinement only removes marks
whose rows would be filtered out during reading anyway, and the ranges
are already owned by this replica.

In `MergeTreeReadPoolParallelReplicas` the marks dropped by the refiner
do not count towards the task size: `cutMoreRangesToRead` keeps cutting
while the coordinator assignment continues with the same part (without
extra coordinator requests), mirroring `MergeTreeReadPool`.

The test gets a parallel replicas query over the localhost cluster;
verified that the pool is engaged (`ParallelReplicasReadMarks` = 256)
and 255 of 256 marks are dropped by the refiner.

Co-Authored-By: Claude Fable 5 <[email protected]>
EmeraldShift added a commit to EmeraldShift/ClickHouse that referenced this pull request Jul 14, 2026
PR ClickHouse#110291 moves projection filtering into the read pool, but its refiner
still calls `rangeAllZero` once for every mark in each cut. With very small
index granularity, task creation remains proportional to the number of
candidate marks even when only a few granules survive.

Give each task a direction-aware refinement session. The session resolves
the shared bitmap once, keeps its cursor while the pool collects more cuts,
and merges bitmap offsets with the input `MarkRanges`. After emitting a
granule, advance the bitmap iterator once and seek only if the next value
remains inside that granule. Keep the current input range until the bitmap
hit crosses its end, then lower-bound the next possible range. Reverse reads
use the same rule with predecessor seeks.

This keeps the surviving-mark task sizing from ClickHouse#110291 while avoiding work
proportional to all candidate marks. On a one-million-row part with
`index_granularity=1`, point lookups improved from 13.5 ms with the per-mark
refiner to 8.5 ms. A random 1% range improved from 91 ms to 83 ms.

PR: ClickHouse#110291
EmeraldShift added a commit to EmeraldShift/ClickHouse that referenced this pull request Jul 14, 2026
Cover the session paths that are not exercised by ClickHouse#110291's original test:
adaptive granularity, several separated primary-key ranges, multiple default-
pool readers, and reverse read-in-order. Matching rows at the first and last
marks exercise the cursor boundary cases.

PR: ClickHouse#110291
EmeraldShift added a commit to EmeraldShift/ClickHouse that referenced this pull request Jul 14, 2026
The prefetched-pool update in PR ClickHouse#110291 still calls the original stateless
refiner API. Give each prefetched task its own session before refining,
creating readers, and starting prefetches.

Also install and apply the refiner in both parallel-replica pools. Keep
coordinator requests and assignment cutting under their existing mutexes,
but release the mutex before creating a session, building the projection
bitmap, or creating readers. Fully pruned coordinator cuts are skipped and
the same session is reused while a `getTask` call advances through cuts of
the same part.

This addresses the current AI review finding that
`use_projection_index_in_read_pools` is silently ignored when parallel
replicas are selected.

PR: ClickHouse#110291
Review: ClickHouse#110291 (comment)
EmeraldShift added a commit to EmeraldShift/ClickHouse that referenced this pull request Jul 14, 2026
Exercise the default and both in-order coordinator paths on a non-replicated
`MergeTree` using the `parallel_replicas` test cluster. The queries cover a
sparse projection result in normal, ascending-LIMIT, and descending-LIMIT
reads.

PR: ClickHouse#110291
Two causes, both from settings randomization in the test harness:

1. The `ReadPoolRangeRefinerDroppedCuts > 0` assertion depended on the
   task sizing regime: whenever the whole part is consumed as a single
   cut (in-order fallback after stream collapse, remote-disk task
   sizing, layered reads), no cut is dropped as a whole even though all
   the same marks are dropped. The regime is environment-dependent, so
   the assertion is removed; `ReadPoolRangeRefinerDroppedMarks` does not
   depend on how the marks are split into cuts and stays.

2. The parallel replicas query relied on projection support under
   parallel replicas, which is gated on `parallel_replicas_local_plan`
   and on `optimize_aggregation_in_order` being disabled (the gate
   applies even to queries without aggregation). Both are randomized;
   pin them in the query.

Reproduced locally by replaying the randomized settings from the failed
CI runs; after the fix the test passes with both failing settings sets
and 6/6 harness runs with fresh randomization.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110291&sha=efe707855197e7de2678f022a80947ff365bd4eb&name_0=PR
PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
KochetovNicolai and others added 3 commits July 15, 2026 13:05
Add two focused queries with `enable_parallel_replicas = 1` and
`optimize_read_in_order = 1`: `ORDER BY id LIMIT` for the `WithOrder`
coordination mode and `ORDER BY id DESC LIMIT` for `ReverseOrder`
(verified via coordination-mode log messages that both engage
`MergeTreeReadPoolParallelReplicasInOrder`). The forward query asserts
dropped marks > 0 (the LIMIT terminates reading early); the reverse one
has to pass almost the whole part before the matching mark, so it
asserts > 200.

The first parallel replicas query marker is renamed to
`refiner_query_parallel_replicas_default` so that its `LIKE` pattern
does not match the new markers.

Verified against both settings sets captured from the flaky CI runs and
6/6 harness runs with fresh randomization.

PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
In `MergeTreeReadPoolParallelReplicasInOrder` the warmup growth of
`per_part_marks_in_range` happened at cut time, before it is known
whether the cut survives refinement. A fully pruned prefix would double
the warmup size on every dropped cut, so the first surviving task could
become much larger than the small-limit warmup intends, and with
scattered matches such a task reads granules the LIMIT never needed.

`cutRangesToRead` now reports the warmup size as it was before the cut,
and `getTask` restores it when the whole cut is dropped by the refiner:
a dropped cut reads nothing, so it must not advance the warmup. Restoring
the saved value is exact for all growth paths of `get_from_buffer`.

Verified with a part where the only matching granule is at mark 100 and
a second matching granule is at mark 106: `ORDER BY id LIMIT 5` under
parallel replicas reads 16 rows (one granule); without the fix the
warmup inflated to a 64-mark window covering both granules.

PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
The event's contract is "how many marks were read by the given
replica", but the increments happened on the pre-refinement cut, so
marks dropped by the ranges refiner (which never reach a reader) were
counted as read, making sparse parallel-replicas reads look more
expensive than they are.

Increment the event with the surviving ranges right before the read
task is created, in both `MergeTreeReadPoolParallelReplicas` and
`MergeTreeReadPoolParallelReplicasInOrder`. Without a refiner the
counted value is unchanged.

Verified on the refiner test's parallel replicas query: it now reports
1 read mark with 255 marks dropped by the refiner (previously 256).

PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
KochetovNicolai and others added 2 commits July 15, 2026 14:58
A single needle cluster in a 90M-row table with a projection index:
almost every read task is fully dropped by the ranges refiner, so with
`use_projection_index_in_read_pools = 1` the pruned ranges never become
read tasks. With small read tasks (which make the per-task costs
visible) the query is ~2.4x faster with the plain read pool and ~2.2x
with the prefetched pool (53 ms -> 22 ms and 60 ms -> 27 ms locally);
the prefetched pool additionally avoids submitting prefetches for
ranges that would be dropped.

The queries with the setting enabled fail on the reference server that
does not know the setting yet and are reported as partial by the
performance comparison framework; the disabled variants compare
normally and guard the refiner-off path.

Co-Authored-By: Claude Fable 5 <[email protected]>
…lback

The parallel replicas assertions only checked `ReadPoolRangeRefinerDroppedMarks`,
which would stay unchanged if `ParallelReplicasReadMarks` moved back to
pre-refinement accounting or if fully pruned prefix cuts re-inflated the
in-order warmup task size.

The data now has two `rare` clusters: mark 100 (rows 1600-1610) and
mark 106 (rows 1700-1710), separated by a 100-mark common prefix.

- The default parallel replicas query asserts
  `sum(ParallelReplicasReadMarks) < 10`: only the 2 surviving marks are
  counted as read; pre-refinement accounting would report 256.
- The forward in-order LIMIT query asserts
  `sum(ParallelReplicasReadMarks) <= 1`: with the warmup rollback the
  100 dropped prefix cuts stay 1 mark wide and the first surviving task
  covers only mark 100; an inflated task would also pick up the second
  cluster in mark 106 and read 2 marks. The query is pinned to
  `max_threads = 1` so the task sequence is deterministic (no reading
  ahead of the LIMIT). The soft-limit warmup branch engages
  deterministically for this query shape (`query_task_size_limit` is the
  query LIMIT, always below `max_block_size`).
- The reverse query threshold is adjusted to > 100: the suffix after the
  last matching mark is ~150 marks now.

Verified with both settings sets captured from the earlier flaky CI runs
and 8/8 harness runs with fresh randomization; the measured values sit
exactly on the designed points (1 read mark in-order, 2 for the default
query).

PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>
@KochetovNicolai
KochetovNicolai marked this pull request as ready for review July 15, 2026 15:28
@KochetovNicolai KochetovNicolai added the pr-performance Pull request with some performance improvements label Jul 16, 2026
In `MergeTreePrefetchedReadPool` the ranges refiner never lets dropped
ranges be prefetched, but the task boundaries and the prefetch admission
(`filesystem_prefetch_max_memory_usage`, `filesystem_prefetches_limit`)
are decided at fill time from the unrefined ranges: a heavily refined
task is not topped up to the intended size in surviving marks and a
fully pruned task does not return its admission budget. Both effects
only make the pool more conservative than theoretically possible and
are still strictly better than reading without refinement (which
reserved the same budget and also performed the prefetch I/O).

Fixing them requires cutting tasks at prefetch time instead of at fill
time; that restructuring is planned together with the range-gated
reading work, where the cutter has to become range-aware anyway.
Document the limitation in the setting description and at the code site
instead of half-fixing it with fragile task bookkeeping.

PR: #110291

Co-Authored-By: Claude Fable 5 <[email protected]>

@CurtizJ CurtizJ 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.

Ok, let's add support for skip indexes in the refiner in a follow-up PR.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds a projection-index range refiner to the MergeTree read pools, gated behind the new use_projection_index_in_read_pools setting which defaults to false, plus a behavior-equivalent refactor of the read-pool getTask paths. Across tpch_adapted_1_official every flagged query moved by less than 2% (at most +14 ms on Q4, most within +/-1 ms), and all remained not_sure because only 2 source replicates were available. Since the new code path is dormant by default, none of these deltas are attributable to the PR; they read as normal run-to-run variance. No regression or improvement is supported by this run.

tpch_adapted_1_official

⚠️ 9 inconclusive

Flagged queries (9 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 0 not_sure 67 67 +0.0% 0.0006 io: Median unchanged (67 ms, +0.0%). The PR's new read-pool range refiner is gated behind use_projection_index_in_read_pools, which defaults off, so this path is unchanged.
⚠️ 2 not_sure 62 61 -1.6% <0.0001 io: -1.6% (-1 ms) is within run-to-run variance; with only 2 source replicates and a default-off setting this is not a PR effect.
⚠️ 4 not_sure 1056 1070 +1.3% 0.0313 io: +1.3% (+14 ms) on a ~1 s scan is borderline and unattributable: the new refiner is disabled by default, so the read path is unchanged here.
⚠️ 7 not_sure 557 560 +0.5% 0.1639 io: +0.4% (+2.5 ms) is noise; the changed read-pool code is dormant unless use_projection_index_in_read_pools is enabled.
⚠️ 8 not_sure 165 165 +0.0% 0.0395 io: Median unchanged (165 ms, +0.0%). Read-pool refactor is behavior-equivalent when the refiner is off, which is the default.
⚠️ 9 not_sure 107 108 +0.9% <0.0001 io: +0.9% (+1 ms) is within measurement noise despite low test spread; a 1 ms shift on a 107 ms query is not meaningful and the changed path is default-off.
⚠️ 17 not_sure 67 66 -1.5% 0.0002 io: -1.5% (-1 ms) is run-to-run variance; the new projection-index refiner is disabled by default so cannot cause this.
⚠️ 18 not_sure 74 73 -1.4% <0.0001 io: -1.4% (-1 ms) is noise on a fast query; the read-pool change is gated behind a default-off setting.
⚠️ 20 not_sure 116 116 +0.0% 0.0007 io: Median unchanged (116 ms) and the measurements are very noisy, so no signal; the changed read path is dormant by default.

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
  • StressHouse run: 579787cf-13dd-4b4a-993c-bb8a7872a705
  • MIRAI run: d977f6cb-847b-4e95-9059-294559151d32
  • PR check IDs:
    • tpch_adapted_1_official_525981_1785160372
    • tpch_adapted_1_official_526001_1785160372

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 367/392 (93.62%) · Uncovered code

Full report · Diff report

@CurtizJ
CurtizJ added this pull request to the merge queue Jul 28, 2026
Merged via the queue into master with commit 36f6cbd Jul 28, 2026
351 of 352 checks passed
@CurtizJ
CurtizJ deleted the lazy-range-refinement-in-read-pools branch July 28, 2026 10:52
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
The loop condition reads `all_mark_ranges` on the next iteration after
the whole-remaining-ranges branch moved it out. Reinitialize it
explicitly after the move.

Checked the same clang-tidy checks locally on all read pool files,
including `MergeTreePrefetchedReadPool` which has not been through the
CI clang-tidy build yet.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110291&sha=3ea4389310ca672307f14ffe1081cdbbb572880f&name_0=PR
PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
Two causes, both from settings randomization in the test harness:

1. The `ReadPoolRangeRefinerDroppedCuts > 0` assertion depended on the
   task sizing regime: whenever the whole part is consumed as a single
   cut (in-order fallback after stream collapse, remote-disk task
   sizing, layered reads), no cut is dropped as a whole even though all
   the same marks are dropped. The regime is environment-dependent, so
   the assertion is removed; `ReadPoolRangeRefinerDroppedMarks` does not
   depend on how the marks are split into cuts and stays.

2. The parallel replicas query relied on projection support under
   parallel replicas, which is gated on `parallel_replicas_local_plan`
   and on `optimize_aggregation_in_order` being disabled (the gate
   applies even to queries without aggregation). Both are randomized;
   pin them in the query.

Reproduced locally by replaying the randomized settings from the failed
CI runs; after the fix the test passes with both failing settings sets
and 6/6 harness runs with fresh randomization.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110291&sha=efe707855197e7de2678f022a80947ff365bd4eb&name_0=PR
PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
Add two focused queries with `enable_parallel_replicas = 1` and
`optimize_read_in_order = 1`: `ORDER BY id LIMIT` for the `WithOrder`
coordination mode and `ORDER BY id DESC LIMIT` for `ReverseOrder`
(verified via coordination-mode log messages that both engage
`MergeTreeReadPoolParallelReplicasInOrder`). The forward query asserts
dropped marks > 0 (the LIMIT terminates reading early); the reverse one
has to pass almost the whole part before the matching mark, so it
asserts > 200.

The first parallel replicas query marker is renamed to
`refiner_query_parallel_replicas_default` so that its `LIKE` pattern
does not match the new markers.

Verified against both settings sets captured from the flaky CI runs and
6/6 harness runs with fresh randomization.

PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
In `MergeTreeReadPoolParallelReplicasInOrder` the warmup growth of
`per_part_marks_in_range` happened at cut time, before it is known
whether the cut survives refinement. A fully pruned prefix would double
the warmup size on every dropped cut, so the first surviving task could
become much larger than the small-limit warmup intends, and with
scattered matches such a task reads granules the LIMIT never needed.

`cutRangesToRead` now reports the warmup size as it was before the cut,
and `getTask` restores it when the whole cut is dropped by the refiner:
a dropped cut reads nothing, so it must not advance the warmup. Restoring
the saved value is exact for all growth paths of `get_from_buffer`.

Verified with a part where the only matching granule is at mark 100 and
a second matching granule is at mark 106: `ORDER BY id LIMIT 5` under
parallel replicas reads 16 rows (one granule); without the fix the
warmup inflated to a 64-mark window covering both granules.

PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
The event's contract is "how many marks were read by the given
replica", but the increments happened on the pre-refinement cut, so
marks dropped by the ranges refiner (which never reach a reader) were
counted as read, making sparse parallel-replicas reads look more
expensive than they are.

Increment the event with the surviving ranges right before the read
task is created, in both `MergeTreeReadPoolParallelReplicas` and
`MergeTreeReadPoolParallelReplicasInOrder`. Without a refiner the
counted value is unchanged.

Verified on the refiner test's parallel replicas query: it now reports
1 read mark with 255 marks dropped by the refiner (previously 256).

PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…lback

The parallel replicas assertions only checked `ReadPoolRangeRefinerDroppedMarks`,
which would stay unchanged if `ParallelReplicasReadMarks` moved back to
pre-refinement accounting or if fully pruned prefix cuts re-inflated the
in-order warmup task size.

The data now has two `rare` clusters: mark 100 (rows 1600-1610) and
mark 106 (rows 1700-1710), separated by a 100-mark common prefix.

- The default parallel replicas query asserts
  `sum(ParallelReplicasReadMarks) < 10`: only the 2 surviving marks are
  counted as read; pre-refinement accounting would report 256.
- The forward in-order LIMIT query asserts
  `sum(ParallelReplicasReadMarks) <= 1`: with the warmup rollback the
  100 dropped prefix cuts stay 1 mark wide and the first surviving task
  covers only mark 100; an inflated task would also pick up the second
  cluster in mark 106 and read 2 marks. The query is pinned to
  `max_threads = 1` so the task sequence is deterministic (no reading
  ahead of the LIMIT). The soft-limit warmup branch engages
  deterministically for this query shape (`query_task_size_limit` is the
  query LIMIT, always below `max_block_size`).
- The reverse query threshold is adjusted to > 100: the suffix after the
  last matching mark is ~150 marks now.

Verified with both settings sets captured from the earlier flaky CI runs
and 8/8 harness runs with fresh randomization; the measured values sit
exactly on the designed points (1 read mark in-order, 2 for the default
query).

PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
In `MergeTreePrefetchedReadPool` the ranges refiner never lets dropped
ranges be prefetched, but the task boundaries and the prefetch admission
(`filesystem_prefetch_max_memory_usage`, `filesystem_prefetches_limit`)
are decided at fill time from the unrefined ranges: a heavily refined
task is not topped up to the intended size in surviving marks and a
fully pruned task does not return its admission budget. Both effects
only make the pool more conservative than theoretically possible and
are still strictly better than reading without refinement (which
reserved the same budget and also performed the prefetch I/O).

Fixing them requires cutting tasks at prefetch time instead of at fill
time; that restructuring is planned together with the range-gated
reading work, where the cutter has to become range-aware anyway.
Document the limitation in the setting description and at the code site
instead of half-fixing it with fragile task bookkeeping.

PR: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 3, 2026
The merge of `master` into this branch kept both the renamed history
entry `use_indexes_refiner_in_read_pools` and the old
`use_projection_index_in_read_pools` entry that master still carries
from ClickHouse#110291, while
`Settings.cpp` merged cleanly and declares only the new name.

`SettingsImpl::applyCompatibilitySetting` calls `getTier` for every
history entry newer than the requested version, and `getTier` throws
`UNKNOWN_SETTING` for a name that is not declared. A dangling entry
therefore makes every `SET compatibility = ...` fail, which broke 25
otherwise unrelated fast tests.

The old name was introduced in the same unreleased 26.8 cycle and never
shipped, so its history entry is simply dropped.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112296&sha=c3a5f3209fa04b588d5c4cfc51921e9bdeae8ad8&name_0=PR&name_1=Fast%20test
Related: ClickHouse#112296

Co-Authored-By: Claude Opus 5 <[email protected]>
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 3, 2026
`use_projection_index_in_read_pools` was renamed to
`use_indexes_refiner_in_read_pools` in this pull request. The previous
commit dropped its settings history entry, which the style check
`settings_changes_history` rejects: a removed record is
indistinguishable, from the diff alone, from a default change that was
reverted without being recorded, and the check's only exemption is a
change touching `src/Core/SettingsChangesHistory.cpp` alone - which a
rename can never be, since it edits `src/Core/Settings.cpp` too.

Declare the old name in `OBSOLETE_SETTINGS` and restore its history
entry. `applyCompatibilitySetting` skips entries whose tier is
`OBSOLETE`, so `SET compatibility` no longer throws `UNKNOWN_SETTING`,
and `03999_stateless_settings_history` ignores obsolete settings. It
also keeps configurations written against master, where the old name has
been present since
ClickHouse#110291, from failing to
load.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112296&sha=318ff84832ea55bcc8c68f33e8860a4df16d744a&name_0=PR&name_1=Style%20check
Related: ClickHouse#112296

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 8, 2026
Generalize `ProjectionIndexReadRangesRefiner` into `IndexReadRangesRefiner`:
mark ranges fully filtered out by indexes evaluated at data-read time are
dropped in MergeTree read pools before a read task is created for them.
Previously only the projection index bitmap was applied this way; now the
skip index read result (`use_skip_indexes_on_data_read`), including the
top-k threshold check and runtime filters from JOIN, is applied as well.

The granule-skipping predicate is factored into
`MergeTreeIndexReadResult::canSkipMark`, shared between the refiner and
`MergeTreeReaderIndex`, so task-cut time and read time decisions cannot
diverge. Applying the top-k threshold earlier is sound because
`TopKThresholdTracker` only tightens monotonically.

Replace the setting `use_projection_index_in_read_pools` (introduced in
the same unreleased version) with a single common setting
`use_indexes_refiner_in_read_pools` that covers both index kinds.

Follow-up to: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 29, 2026
…ment job

Since ClickHouse#110291, when a ranges refiner is set, MergeTreePrefetchedReadPool runs
refinement, the patch-range computation, MergeTreeReadTask::createReaders and
the first prefetches as one job on the prefetch pool. The Keeper component is
a thread-local, and ThreadPoolCallbackRunnerLocal carries only the thread group
across the hop, so the job runs with an empty component, while the same work
on the inline path runs under MergeTreeSource::tryGenerate.

The job checks skip-index files through IMergeTreeIndex::getDeserializedFormat
(from the refiner, from getIndexReadTaskForReadStep and from the text-index
reader). When a file is in neither checksums.txt nor skp_idx.packed, the check
reaches the disk. On a disk whose metadata storage is Keeper that is a Keeper
request, and with enforce_keeper_component_tracking it throws LOGICAL_ERROR
"Current component is empty", which aborts debug and sanitizer servers.

Capture the enqueuing thread's component and restore it as the job's first
statement, as ClickHouse#98663 does for the prewarmCaches pool jobs, so the whole job,
including its early return and any exception, runs under the component of the
read that scheduled it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

4 participants