Repository navigation
JOIN runtime filters index analysis : prune the left side by several key ranges instead of one [min, max] - #117322
shankar-iyer wants to merge 11 commits into
Conversation
Cuts the range tracking from 449 to 323 lines with no behaviour change. - Drop `seedRangeCoverFromValues`. It sorted up to ~75k keys through `getPermutation` and materialized them as a `std::vector<Field>`, and only ran for key types the histogram cannot bucket (`DateTime64`, `LowCardinality`). Those already fall back to the per-block extremes, which is what `master` does for them, so the path cost a multi-megabyte allocation to serve a case that degrades gracefully without it. - Drop `coverIsWorthSplitting`. It was a second, redundant rule: `dropUselessSplits` already fuses neighbours whose gap is under 1% of the span, and when no gap qualifies that loop leaves a single interval, which is the plain `[min, max]` envelope the removed rule produced. - Replace `insertInterval` with `normalize`. Maintaining a sorted, disjoint invariant on every insertion put the burden on each caller; they now append and normalize, which also shortened `updateRange`, `mergeRange` and `effectiveRangeCover`. - Derive key signedness inside the typed dispatch instead of re-deriving it from the `DataTypePtr`, dropping `isColumnedAsSignedKey`. - Fold `startRangeHistogram` into its only caller. The three remaining helpers share one primitive, `excludedBetween`, so the "keys are integral, neighbours one apart exclude nothing" reasoning lives in one place instead of being repeated. Also corrects the `max_key_range_intervals` comment. It implied `MAX_BITS_FOR_PARTIAL_DISJUNCTION_RESULT` (32) was the binding constraint on the budget, but the runtime filter reader is created with `use_for_disjunctions=false` (`ReadFromMergeTree.cpp`), so that bound does not apply on this path. Co-Authored-By: Claude Opus 5 <[email protected]>
Covers the shape the key-range cover exists for: a build side that falls into two clusters far apart in the key domain, which a single `[min, max]` envelope cannot describe. The data mirrors keys minted in insertion order (auto-increment, IDENTITY, Snowflake), so `rf_orders.id` ascends with `order_date` and restricting the parent to two disjoint periods restricts the child to two disjoint key ranges. On the Stack Overflow dataset the same correlation measures 0.9995. Three queries. The first has two 10-day windows at opposite ends of the table with index analysis on, and emits `[0, 99999] OR [19900000, 19999999]`. The second is the same query with index analysis off, which is both what `master` does on the first query (its envelope `[0, 19999999]` spans the whole key domain and prunes nothing) and a noise baseline: if it moves too, the first result is environmental. The third uses one contiguous 20-day window, where the intervals correctly collapse to `[0, 199999]`, guarding against the first query improving for reasons unrelated to the clustering. Locally: 100 marks / 817k rows / 20 MiB for the first query against 7354 marks / 60.2M rows / 1.79 GiB for the second, with identical results. Co-Authored-By: Claude Opus 5 <[email protected]>
The bucket window started exactly at the smallest key seen, so a build side arriving in descending key order undercut the base on every key, and each of those rescales remapped the whole bitmap. Measured over 4M keys: 11387 ns/key against 2.41 ns/key for ascending input, with one rescale per key and ~3016 remap iterations each. A descending build side is ordinary - MergeTree sorting keys may be `DESC`, as `04628_join_runtime_filter_reverse_key` already exercises. Take a window twice the span that has to fit and start it a quarter of the way in. Every rescale then grows the span by at least half, which bounds their number by the width of the key domain rather than by the number of keys. Over the same 4M keys, descending input drops to 2.41 ns/key with 17 rescales in total. `buckets` goes from 4096 to 8192, i.e. 1 KiB of bits per filter instance, so that the coarser window keeps the same effective resolution over the occupied span. The margin buckets are always empty, and `appendIntervals` clamps the outer edges to the exact extremes, so nothing about the emitted ranges gets looser. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [c5aa705] Summary: ✅
AI ReviewSummaryThe PR replaces the single JOIN runtime-filter envelope with up to eight key ranges, improving pruning for clustered build keys after the exact-values limit is exceeded. Reviewed head Consumer tracing covered Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings; both existing bot-authored threads remain correctly resolved. Normal CI gates still apply. |
|
I will merge this PR and then default enable |
Addresses the AI review on ClickHouse#117322. The bucket grid can extend past the end of the UInt64 coordinate space, and both places that computed a bucket's high edge wrapped there: - `appendIntervals` derived the run's high edge from one past the last set bucket, so a wrap made it small and `std::min` with the exact maximum then picked the wrapped value. That emits an inverted `Range`, which `KeyCondition` reads as empty, prunes every granule and drops matching rows. - `rescale` computed the old bucket's high edge the same way, so a wrap remapped the bucket to the wrong place or dropped it, losing its keys from the cover. Both edges are now saturating, and `appendIntervals` derives the run's high edge from the last set bucket rather than from one past it, since `base + (bucket << shift)` can itself overflow for a run that reaches the top bucket. Reproduced with build keys in two clusters just under `UINT64_MAX`, which emitted `[18446744073709547615, 14]`. Whether it triggers depends on where the grid falls relative to the last key, so it reproduces for some cluster widths and not others, and from SQL also on the iteration order of the exact-values set. `05023_join_runtime_filters_index_analysis_multi_range` gains cases at the top of both the UInt64 and Int64 domains, asserting the result is unchanged with index analysis on. Also uses `IColumn::empty` instead of `size() == 0` in `updateRange`, for clang-tidy `readability-container-size-empty`. Co-Authored-By: Claude Opus 5 <[email protected]>
|
📊 Cloud Performance Report
Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR changes only how JOIN runtime filters record build-side keys: a bucket histogram and up to 8 OR'd key ranges replace the single [min, max] envelope. The other changes are tests. All six flagged improvements are single-table ClickBench GROUP BY queries that never build a JOIN runtime filter. Q16, Q18, Q31, Q33 and Q34 (-8.3% to -16.5%) are therefore downgraded to not sure. Q32 (-46.3%) is locked as an improvement by the large-delta rule, but the diff cannot explain it and it should be rerun before anyone credits the PR. No tpch_adapted_1_official query moved, and those join-heavy queries are the only place this change could plausibly show up. clickbench🟢 1 improved · Flagged queries (6 of 43)
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. tpch_adapted_1_official🟢 No significant changes Debug info
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+125.59 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units157 translation units recompiled, 1843 s compile time in total, 157 of them have a recent master baseline. |
This PR and even the original #109085 does not help TPC-H because there is no correlation between the Is this PR a premature optimization ? I have presented a couple of example queries in the PR description to illustrate the shape of queries that will benefit. In general, when the build side runs into millions / billions of keys, it looked instinctively in my first work itself to implement some sort of bucket'ization.
Yes, my first implementation was straightforward theory implementation - Claude said that is efficient, but suggested this alternate bitmap version to go as low CPU as possible for per-row filter update costs. @groeneai What method do you recommend to split an incoming stream into ranges? The stream could be random / ascending / descending. |
|
@rschu1ze Sorry, I edited your comment itself with my responses ☝️ ! |
|
Groeneai didn't reply but my Claude returned the same algorithm for online histogram construction. Okay then, let's try. I would love to see an evaluation how effective this is on TPC-H, TPC-DS and JOB. |
|
On splitting the incoming stream into ranges: the greedy you wrote is the right method, and the ordering question has an exact answer. For a fixed value set the covered span is the total span minus the gaps you split at, so the tightest cover of N intervals is exactly "split at the N-1 widest gaps", and fusing the smallest gap removes that gap and changes no other. On a monotone stream, ascending or descending, gaps are only ever added, so the splits you hold are always the N-1 widest seen so far and the cover is optimal at every prefix. On an unordered stream it is a heuristic: a fuse is irreversible, and a value arriving later inside a gap you kept can shrink that gap below one you already fused. Simulating So the shape worth keeping is the one you have: record each key with something that is not an irreversible fuse, which is what |
|
CC: @cv4g |
@rschu1ze This PR is not immediately impacting the queries in TPC-H & TPC-DS. Let me use run the JOB benchmark |
# Conflicts: # src/Processors/QueryPlan/RuntimeFilterLookup.cpp # src/Processors/QueryPlan/RuntimeFilterLookup.h
…nalysis_ranges Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nalysis_ranges Resolve conflicts with the JOIN runtime filter transport added on master. `AdaptiveSetRuntimeFilter` now tracks the multi-interval key cover via `getKeyRanges`, computed by the new non-memoized `RuntimeFilterIndexAnalysis::computeRanges` because the transported partial state may still change. The serialized state keeps master's wire format and carries the envelope of the cover as [min, max]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`KeyRangeHistogram::add` dispatched on `ColumnVector` only, so a build key read from a part with sparse serialization (`ColumnSparse`) fell back to the `[min, max]` envelope and the multi-range cover pruned nothing. Unwrap the column with `convertToFullIfWrapped` first. The new case in `05023` covers it; the test failed in CI under `ratio_of_defaults_for_sparse_serialization = 0.0`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117322&sha=9dcc954b2f5460f202bb7c1be94650961abc7e77&name_0=PR PR: ClickHouse#117322 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@davenger Refreshed to latest master and CI is green. |
There was a problem hiding this comment.
@shankar-iyer I have some small suggestion and a couple of bigger concerns: test for range tracking logic and the exclusive lock. Please see the comments. Other than that the PR looks good
| static constexpr size_t words = buckets / 64; | ||
| /// Flipping the sign bit maps a signed key to a UInt64 of the same ordering. | ||
| static constexpr UInt64 sign_bias = UInt64(1) << 63; | ||
|
|
||
| UInt64 bits[words] = {}; | ||
| UInt64 base = 0; /// coordinate where bucket 0 starts | ||
| unsigned shift = 0; /// bucket width is 1 << shift | ||
| UInt64 min_coordinate = 0; | ||
| UInt64 max_coordinate = 0; | ||
| bool is_signed = false; | ||
| bool initialized = false; | ||
|
|
||
| bool isSet(size_t bucket) const { return (bits[bucket >> 6] >> (bucket & 63)) & 1; } | ||
| size_t lastBucket() const { return std::min<size_t>((max_coordinate - base) >> shift, buckets - 1); } | ||
| Field toField(UInt64 coordinate) const | ||
| { | ||
| return is_signed ? Field(static_cast<Int64>(coordinate ^ sign_bias)) : Field(coordinate); | ||
| } | ||
|
|
||
| /// Widen the buckets, and move the base down, until `coordinate` fits; then remap what we have. | ||
| void rescale(UInt64 coordinate) | ||
| { | ||
| const UInt64 low = std::min(coordinate, min_coordinate); | ||
| const UInt64 high = std::max(coordinate, max_coordinate); | ||
|
|
||
| /// Window twice the span, starting a quarter in, or descending input rescales on every key. | ||
| unsigned new_shift = shift; | ||
| while (new_shift < 63 && ((high - low) >> new_shift) >= buckets / 2) |
There was a problem hiding this comment.
A suggestion: something like
using WordType = UInt64;
static constexpr size_t word_bits = sizeof(WordType) * 8;
WordType bits[words] = {};
and using WordType instead of explicit 64-s and 63-s could make the code bit cleaner
| const auto range = key_range.getRange(); | ||
| writeBinary(UInt8(!key_range.isEnabled() ? 0 : (range ? 2 : 1)), out); | ||
| if (range) | ||
| /// Only the envelope of the cover is sent; the receiver prunes by [min, max] for this partial. |
There was a problem hiding this comment.
Sending multiple ranges in distributed case might be a follow-up
| ASSERT_TRUE(range); | ||
| EXPECT_EQ(range->left.safeGet<UInt64>(), 1); | ||
| EXPECT_EQ(range->right.safeGet<UInt64>(), 5); | ||
| ASSERT_FALSE(range.empty()); |
There was a problem hiding this comment.
The range tracking logic has almost no test coverage. The tests in this file check only the lowest and the highest bound, so they also pass if the filter always returns one range. If somebody changes this code later and makes a mistake, CI might not catch it.
I'd add targeted unit tests that check how the ranges are created, extended and merged. For example:
- two groups of keys far apart give two ranges;
- keys next to an existing range extend it, and keys far from it start a new range;
- more than 8 groups of keys give 8 ranges, and the widest gaps stay;
- groups with small gaps between them merge into one range;
- the merge of two filters gives ranges that cover the keys of both.
| std::vector<Range> RuntimeFilter::getRecordedKeyRanges() const | ||
| { | ||
| SharedLockGuard lock(mutex); | ||
| if (!data.build_state.isFinished()) | ||
| return {}; | ||
| return data.index_analysis.getRange(); | ||
| /// Called once per part, and the cover cannot change after the build finished, so memoize it. | ||
| { | ||
| SharedLockGuard lock(mutex); | ||
| if (!data.build_state.isFinished()) | ||
| return {}; | ||
| if (auto cached = data.index_analysis.getCachedRanges()) | ||
| return std::move(*cached); | ||
| } | ||
|
|
||
| std::lock_guard lock(mutex); | ||
| return data.index_analysis.getRanges(); |
There was a problem hiding this comment.
I suggest computing the final ranges once in RuntimeFilter::finishInsert, so that this getter is a plain read under the shared lock, as it was before this PR.
Now the getter takes the exclusive lock to fill a mutable cache. When the key type has no range support (for example a String key with more values than join_runtime_filter_exact_values_limit), getRanges returns before it fills the cache. Then each call, one for each part, takes the exclusive lock, and find on the probe threads must wait.
|
What was the verdict from performance tests TPC-* and JOB again? |
When a JOIN runtime filter's build side exceeds
join_runtime_filter_exact_values_limit, the filter does not enumerate its keys, so the left side is pruned by the key range it recorded instead. That range is a single[min, max]envelope, which spans not just the keys but every gap between them. On a build side that falls into two or more clusters , the envelope covers almost the whole table and prunes nearly nothing.The keyword above is clusters. That would be dataset schema dependent and also on primary key/surrogate key INSERTion order etc.
Example from a simple TPC-H schema query that will improve with this PR if
orderkeyandorderdatewere correlated in the data -From a real StackOverflow dataset -
Changelog category
Changelog entry
enable_join_runtime_filters_index_analysisnow prunes by several key ranges instead of one big[min, max]rangeWorkflow [PR]
Sync PR [sync-upstream/pr/117322]