Skip to content

Narrow main-table mark ranges using projection index bitmap - #103117

Open
EmeraldShift wants to merge 10 commits into
ClickHouse:masterfrom
EmeraldShift:proj-index-narrow-marks
Open

EmeraldShift wants to merge 10 commits into
ClickHouse:masterfrom
EmeraldShift:proj-index-narrow-marks

Conversation

@EmeraldShift

@EmeraldShift EmeraldShift commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Improved the performance of filtering large tables with projection indexes.

What this PR does

The deferred read path distributes all main-table mark ranges to reader threads and uses canSkipMark() per granule to drop non-matching ones. For narrow filters on large tables (#99114) that's O(marks) of mark-index reads, buffer allocations, and bitmap lookups per query, even when the answer is a handful of granules.

This PR narrows main-table mark ranges using the projection index bitmap, gated behind projection_index_narrow_marks (default false). When on, the read pool looks up the already-cached projection bitmap from MergeTreeIndexReadResultPool inside getTask(), converts it to MarkRanges, and intersects with the batch before createTask() runs. Empty batches are dropped and the pool fetches the next one. MergeTreeReadPoolInOrder loops until a non-empty batch or the part drains -- nullptr still means "no more work for this part" per the existing contract.

The bitmap -> MarkRanges conversion is cached once per part on MergeTreeIndexReadResult via std::call_once, so concurrent tasks for the same part share it.

Tests: 03775_projection_index_narrow_marks and 03776_projection_index_point_read assert identical results with preread on and off, including a missing-key case across multiple parts.

Performance (release, 10M rows / 20 parts / index_granularity=8, max_threads=1): steady-state per-query wall time drops from 63 ms to 8.5 ms. Parent-reader ProfileEvents (FileOpen, ReadCompressedBytes, CompressedReadBufferBytes, MarkCacheMisses) drop about 6x. On the production workload in #99114 the original report saw 4.15 s -> 0.18 s.

Closes #99114

cc @amosbird

@EmeraldShift

Copy link
Copy Markdown
Contributor Author

Hi @nihalzp can you please enable testing for this PR and/or review (+ @amosbird)?

@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Apr 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4b1fcf]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR moves projection-index pruning into the MergeTree read pools and wires it through the plain, prefetched, in-order, and parallel-replica paths. The current head fixes the earlier iterator and prefetched-pool gaps, but the default parallel-replica pool now reuses a forward refinement session across coordinator assignments even though those assignments can arrive out of mark order, which can drop real rows.

Missing context / blind spots
  • ⚠️ CI coverage on this head is incomplete: the only populated Praktika report is Build (arm_tidy), which failed before any runtime signal for the new 04516, 04538, or 04539 paths was available.
Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeReadPoolParallelReplicas.cpp:265] MergeTreeReadPoolParallelReplicas::getTask caches one forward refinement session across loop iterations for the same part. In default parallel-replicas mode that is not a safe invariant: DefaultCoordinator::tryToStealFromQueue walks queues from rbegin(), and sortResponseRanges only orders ranges within a single response, so two successive responses for the same part can go from a higher segment to a lower one. If the higher segment refines to empty first, the reused cursor cannot move backwards and the lower segment is incorrectly refined to empty as well. Recreate the session per coordinator assignment, or guard reuse with a monotonic-range check.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 20, 2026
@EmeraldShift
EmeraldShift force-pushed the proj-index-narrow-marks branch 2 times, most recently from a2942f5 to aa0ad06 Compare April 20, 2026 14:57
@EmeraldShift
EmeraldShift force-pushed the proj-index-narrow-marks branch from 6e6948e to 308ca7e Compare April 20, 2026 18:42
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

AST fuzzer - STID: 3262-4259, seems unrelated

@nihalzp Does that ^^ sound right? Would you be able to lend a review?

@clickhouse-gh

clickhouse-gh Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 80.99% (196/242) | lost baseline coverage: 4 line(s) · Uncovered code

Full report · Diff report

@nihalzp

nihalzp commented Apr 21, 2026

Copy link
Copy Markdown
Member

The improvement is in critical components and I am not a big expert on these topics. It will be better to be reviewed by someone with experience.

@EmeraldShift
EmeraldShift force-pushed the proj-index-narrow-marks branch from 308ca7e to 7de7eb2 Compare April 22, 2026 23:22
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

Hi @nihalzp @amosbird would either of you be able to recommend a reviewer for this feature? It's quite important for our observability use case to make projection-indexed lookups not sit for 5-20s looping in canSkipMark.

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]>
KochetovNicolai and others added 7 commits July 14, 2026 11:29
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: ClickHouse#110291

Co-Authored-By: Claude Fable 5 <[email protected]>
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
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
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)
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
@EmeraldShift
EmeraldShift force-pushed the proj-index-narrow-marks branch from 7de7eb2 to c4b1fcf Compare July 14, 2026 23:33
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 14, 2026
@KochetovNicolai KochetovNicolai removed the manual approve Manual approve required to run CI label Jul 15, 2026
}
else

if (refinement_part_idx != part_idx)

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.

❌ The new refinement cache is unsafe in the default parallel-replicas pool because coordinator assignments for one part are not globally monotonic.

MergeTreeReadPoolParallelReplicas::getTask now keeps one forward session alive across loop iterations for the same part_idx, but DefaultCoordinator can hand the same part back in descending segment order once stealing is involved: tryToStealFromQueue walks queues from rbegin() and sortResponseRanges only sorts ranges inside one response, not across successive responses. A concrete trace is:

  1. first response for part p returns a high segment like [256, 384) that the projection bitmap filters out completely, so the session advances its cursor past that region;
  2. the next response for the same part returns a lower segment like [0, 128);
  3. reusing the same forward cursor means seekAtLeast cannot move backwards, so the lower segment is treated as empty too and matching rows are lost.

Please recreate the refinement session for each coordinator assignment in MergeTreeReadPoolParallelReplicas, or only reuse it when the next cut is known to start at or after the previous cut.

@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds an opt-in setting use_projection_index_in_read_pools (default off) plus a refactor of MergeTree read-pool task cutting; with the setting off, the projection-index range refiner is never constructed and query execution is byte-for-byte the prior path. The two flagged ClickBench improvements (Q4 -18.7%, Q15 -18.1%) sit inside master's current variance band and show flat CPU, so they are run-to-run variance rather than a real effect — the deterministic suppression to no_change is correct. No query exercises the new code path at default settings, so no directional verdict is warranted.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ff94b898-bb9b-41be-a61b-40ab053dfa11
  • MIRAI run: 524c4b0a-6019-40ed-ab4c-93d8baa3b681
  • PR check IDs:
    • clickbench_648493_1784141103
    • clickbench_648506_1784141103
    • clickbench_648512_1784141103
    • tpch_adapted_1_official_648518_1784141103
    • tpch_adapted_1_official_648524_1784141103
    • tpch_adapted_1_official_648532_1784141103

@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

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

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Narrow marks before reading with Projection Index

5 participants