Skip to content

JOIN runtime filters index analysis : prune the left side by several key ranges instead of one [min, max] - #117322

Open
shankar-iyer wants to merge 11 commits into
ClickHouse:masterfrom
shankar-iyer:join_filter_index_analysis_ranges
Open

shankar-iyer wants to merge 11 commits into
ClickHouse:masterfrom
shankar-iyer:join_filter_index_analysis_ranges

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

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 orderkey and orderdate were correlated in the data -

  SELECT sum(l_quantity * l_extended) price
  FROM lineitem, orders
  WHERE l_orderkey = o_orderkey
  AND (o_orderdate between '1-1-1990' and '31-1-1990'
          OR 
       o_orderdate between '1-1-1991' and '31-1-1991')

From a real StackOverflow dataset -

posts.Id is an IDENTITY column, so it ascends with CreationDate. The query asks for votes on posts from 
two months of 2 different years:

  SELECT count(), sum(v.BountyAmount)
  FROM votes AS v
  INNER JOIN posts AS p ON v.PostId = p.Id
  WHERE (p.CreationDate >= '2011-01-01' AND p.CreationDate < '2011-02-01')
     OR (p.CreationDate >= '2020-01-01' AND p.CreationDate < '2020-02-01')

The build side is 587,821 ids in two clusters, 4.57 M–5.37 M and 59.5 M–60.1 M, with 97.4% of the span 
between them empty.

  Predicate pushed to the left side:

  master       pruning by range [4572748, 60094986]
  this branch  pruning by 8 range(s) [4572748, 5369545] OR [6396034, 6412417]
                                  OR [7784138, 7786478] OR [9459842, 9476225]
                                  OR [11460298, 11462638] OR [12039882, 12114049]
                                  OR [12791498, 12840349] OR [59539103, 60094986]

 Before / after

  ┌────────────────────────────────┬────────┬─────────────┬────────────┬────────┬────────┐
  │                                │ marks  │  rows read  │ bytes read │  best  │ median │
  ├────────────────────────────────┼────────┼─────────────┼────────────┼────────┼────────┤
  │ master, index analysis off     │ 29,249 │ 239,606,603 │ 919.37 MiB │ 171 ms │ 178 ms │
  ├────────────────────────────────┼────────┼─────────────┼────────────┼────────┼────────┤
  │ master, index analysis on      │ 20,980 │ 171,868,160 │ 660.13 MiB │ 132 ms │ 134 ms │
  ├────────────────────────────────┼────────┼─────────────┼────────────┼────────┼────────┤
  │ this branch, index analysis on │ 886    │ 7,258,112   │ 30.12 MiB  │ 28 ms  │ 29 ms  │
  └────────────────────────────────┴────────┴─────────────┴────────────┴────────┴────────┘

Changelog category

  • Performance Improvement

Changelog entry

  • enable_join_runtime_filters_index_analysis now prunes by several key ranges instead of one big [min, max] range

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

shankar-iyer and others added 5 commits August 24, 2026 09:07
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5aa705]

Summary: ✅


AI Review

Summary

The 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 c5aa7050d2832d53523bd2e3f9163b5ddb93a9d6, the complete diff, and all prior discussion. No actionable blockers or majors remain; the previously reported bucket-edge overflow and recursive locking issues are fixed. The description supplies before/after measurements, and focused SQL tests cover pruning, shuffled and sparse input, nullable keys, reverse sorting, and upper-domain boundaries.

Consumer tracing covered HashJoin publication, which copies the range vector; same-task publication, which preserves the cover; transport, which retains the existing envelope wire representation; and MergeTreeSkipIndexReader, RuntimeFilterReadRangesRefiner, Parquet, and Iceberg pruning, which consume the resulting disjunction through existing condition builders.

Missing context / blind spots
  • ⚠️ Full build and runtime-test checks for this head were still pending when reviewed. No local ClickHouse binary/build was available. A throwaway arithmetic model passed 1,508 deterministic streams, including domain boundaries, ascending/descending/shuffled input, and four-stream merging; it does not validate C++ execution, column handling, SQL, transport, or locking. The pending CI checks provide that execution evidence.
Final Verdict

Status: ✅ Approve. No new inline findings; both existing bot-authored threads remain correctly resolved. Normal CI gates still apply.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 31, 2026
@shankar-iyer

Copy link
Copy Markdown
Member Author

I will merge this PR and then default enable enable_join_runtime_filters_index_analysis in 26.9

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 40 analysed

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 · ⚠️ 5 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1376 739 -46.3% <0.0001 aggregation: The delta is large enough that this verdict is locked and cannot be downgraded. Q32 is a single-table GROUP BY with no JOIN, so the runtime-filter change cannot explain -46.3%. Rerun before crediting the PR.
⚠️ 16 not_sure 628 565 -10.0% <0.0001 aggregation: This is a single-table GROUP BY on hits with no JOIN, so it never builds a JOIN runtime filter. The PR's only code change is in that filter path, so it cannot explain this -10.0% shift.
⚠️ 18 not_sure 1101 919 -16.5% <0.0001 aggregation: This is a single-table GROUP BY with no JOIN, so the runtime-filter range code this PR changes never runs. The -16.5% shift cannot come from the diff.
⚠️ 31 not_sure 309 268 -13.3% <0.0001 aggregation: This is a filtered GROUP BY on one table and never goes through the JOIN runtime filter path. The -13.3% shift is not attributable to this diff.
⚠️ 33 not_sure 1256 1152 -8.3% <0.0001 aggregation: This is a heavy GROUP BY on URL with no JOIN, so the runtime filter code this PR changes never runs. The -8.3% shift is not from this diff.
⚠️ 34 not_sure 1259 1146 -8.9% <0.0001 aggregation: This is a heavy GROUP BY on URL with no JOIN, so the runtime filter code this PR changes never runs. The -8.9% shift is not from this diff.

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
  • StressHouse run: d747e5e1-66aa-4a98-b60e-f6e344e8686c
  • MIRAI run: 9e4f1821-4a5d-4315-88fd-fc779455d644
  • PR check IDs:
    • clickbench_1896911_1790397301
    • clickbench_1896917_1790397301
    • clickbench_1896923_1790397301
    • tpch_adapted_1_official_1896934_1790397301
    • tpch_adapted_1_official_1896946_1790397301
    • tpch_adapted_1_official_1896982_1790397301

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c5aa7050d with master aab48fe2f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

11 object files changed (+125.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/RuntimeFilterLookup.cpp.o 704.15 KiB 824.94 KiB +120.79 KiB (+17.15%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.70 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 13.1 s +9.3 s (+249%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.3 s +5.2 s (+245%)
Compile time of recompiled translation units

157 translation units recompiled, 1843 s compile time in total, 157 of them have a recent master baseline.

Job report

@rschu1ze

rschu1ze commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

One could argue that this optimization targets a rare case - very large build sides (larger than the exact values limit) and clustered data distribution. Before merging this ... can we check the impact on all TPC-H and TPC-DS queries?

This PR and even the original #109085 does not help TPC-H because there is no correlation between the orderdate and orderkey columns in the default datagen and essentially the entire range of keys on the LHS are required for all queries. PR #109085 did greatly benefit TPC-DS. But this PR does not help TPC-DS immediately because most TPC-DS join queries boil down to needing a single cluster of keys on the LHS.

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.

The current implementation is quite complex. I wonder if there is a simpler way to carve out ranges.
The input is a stream of values (= values that constitute the build side). We like to cluster them into N ranges such that all points are covered by at least one range. Ranges may overlap, even if that is not desired. What is the simplest way to build the ranges online? There must already be some simple algorithm for that.

Yes, my first implementation was straightforward theory implementation -

 keep ≤ N disjoint intervals, sorted by left bound
  for each incoming value v:
      if v falls inside an existing interval  -> done
      otherwise insert [v, v] in sorted position
      if there are now N+1 intervals -> merge the adjacent pair with the smallest gap

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.

@shankar-iyer

Copy link
Copy Markdown
Member Author

@rschu1ze Sorry, I edited your comment itself with my responses ☝️ !

@rschu1ze

rschu1ze commented Sep 2, 2026

Copy link
Copy Markdown
Member

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.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

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 coalesceToBudget at budget 8 over 100k random value streams, ascending and descending are optimal in all of them, while unordered is looser than a single end-of-stream reduce in 54%, mean +3.7%, worst 1.40x.

So the shape worth keeping is the one you have: record each key with something that is not an irreversible fuse, which is what KeyRangeHistogram does (the loss becomes bucket width rather than arrival order), and run the gap-greedy once over the complete cover. The one place that is still given up is updateRange, which coalesces to max_key_range_intervals on every block: over 200k random block sequences 5.1% end up strictly looser than the same blocks reduced once, worst 1.50x. Letting range_cover grow to a small multiple of the budget while accumulating, and coalescing to 8 only in effectiveRangeCover which already does it, gets that back at no cost.

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
@rschu1ze

Copy link
Copy Markdown
Member

CC: @cv4g

@shankar-iyer

Copy link
Copy Markdown
Member Author

Okay then, let's try. I would love to see an evaluation how effective this is on TPC-H, TPC-DS and JOB.

@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]>
@davenger davenger self-assigned this Nov 11, 2026
shankar-iyer and others added 2 commits November 13, 2026 10:08
…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]>
@shankar-iyer

Copy link
Copy Markdown
Member Author

@davenger Refreshed to latest master and CI is green.

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

@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

Comment on lines +428 to +455
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)

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.

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.

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.

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());

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.

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.

Comment on lines +1363 to +1375
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();

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.

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.

@rschu1ze

Copy link
Copy Markdown
Member

What was the verdict from performance tests TPC-* and JOB again?

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

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants