Repository navigation
Narrow main-table mark ranges using projection index bitmap - #103117
EmeraldShift wants to merge 10 commits into
Conversation
|
Workflow [PR], commit [c4b1fcf] Summary: ❌
AI ReviewSummaryThis PR moves projection-index pruning into the Missing context / blind spots
Findings❌ Blockers
Final VerdictChanges requested. |
a2942f5 to
aa0ad06
Compare
6e6948e to
308ca7e
Compare
|
AST fuzzer - STID: 3262-4259, seems unrelated @nihalzp Does that ^^ sound right? Would you be able to lend a review? |
LLVM Coverage Report
Changed lines: 80.99% (196/242) | lost baseline coverage: 4 line(s) · Uncovered code |
|
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. |
308ca7e to
7de7eb2
Compare
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]>
Reinitialize the moved-from `cut_ranges` from a fresh variable instead of calling `clear` on it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110291&sha=de381925c8bd51eef6d60b4e39eb6f68755184e1&name_0=PR PR: ClickHouse#110291 Co-Authored-By: Claude Fable 5 <[email protected]>
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
7de7eb2 to
c4b1fcf
Compare
| } | ||
| else | ||
|
|
||
| if (refinement_part_idx != part_idx) |
There was a problem hiding this comment.
❌ 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:
- first response for part
preturns a high segment like[256, 384)that the projection bitmap filters out completely, so the session advances its cursor past that region; - the next response for the same part returns a lower segment like
[0, 128); - reusing the same forward cursor means
seekAtLeastcannot 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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Changelog category (leave one):
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 fromMergeTreeIndexReadResultPoolinsidegetTask(), converts it toMarkRanges, and intersects with the batch beforecreateTask()runs. Empty batches are dropped and the pool fetches the next one.MergeTreeReadPoolInOrderloops until a non-empty batch or the part drains --nullptrstill means "no more work for this part" per the existing contract.The bitmap ->
MarkRangesconversion is cached once per part onMergeTreeIndexReadResultviastd::call_once, so concurrent tasks for the same part share it.Tests:
03775_projection_index_narrow_marksand03776_projection_index_point_readassert 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