Skip to content

Use MinMax filter as join runtime filter for numeric types - #96779

Open
novikd wants to merge 38 commits into
masterfrom
minmax-join-runtime-filter
Open

novikd wants to merge 38 commits into
masterfrom
minmax-join-runtime-filter

Conversation

@novikd

@novikd novikd commented Feb 12, 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):

Use [min, max] range for join runtime filters to avoid unnecessary lookups in Bloom filters in case of numeric keys. Closes #96094.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@clickhouse-gh

clickhouse-gh Bot commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e047b98]

Summary: ❌

job_name test_name status info comment
Unit tests (asan_ubsan) FAIL
Unit tests (tsan) FAIL
Unit tests (msan) FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED

AI Review

Summary

This PR adds numeric min/max support to JOIN runtime filters, including planner logic that can keep a numeric range active when Bloom membership is skipped or dropped, plus the supporting settings, logging, tests, and perf scenarios. I found one serialization issue: the new per-step min/max mode is still encoded through the old plan-global boolean, so serialized plans cannot round-trip the actual mode of each BuildRuntimeFilterStep.

Missing context / blind spots
  • ⚠️ I did not run the runtime-filter unit tests or performance suite locally because this checkout does not contain an existing build artifact. Running the focused runtime-filter tests and the new perf XML scenario would close the execution gap.
Findings

⚠️ Majors

  • [src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp:120] RuntimeFilterMinMaxMode is now a per-step three-state contract (Disabled / Combined / Only), but serialization still collapses it to the legacy plan-global boolean here and deserialize reconstructs any true as Combined. A plan round-trip therefore cannot preserve what was actually planned: MinMaxOnly is lost even for a single step, and a plan with mixed runtime-filter steps can deserialize only one global min/max choice, so at least one placeholder step reports the wrong mode. Suggested fix: serialize the enum per step, or keep deserialized BuildRuntimeFilterStep mode-blind instead of reconstructing a specific mode.
Final Verdict

⚠️ Needs changes before merge because the new min/max mode is not serialized faithfully.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Feb 12, 2026

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

Cool PR, lgtm.

Comment thread src/DataTypes/DataTypesNumber.h Resolved
@novikd novikd changed the title WIP: Use MinMax filter as join runtime filter fallback for numeric types Use MinMax filter as join runtime filter for numeric types Feb 17, 2026
@novikd

novikd commented Feb 18, 2026

Copy link
Copy Markdown
Member Author

This min-max range check worsens performance tests. It can be seen in the reports.

image

Also, locally:

SELECT count(*)
FROM large AS l
INNER JOIN small AS s ON l.a = s.a
WHERE s.b < 10000000
SETTINGS join_runtime_filter_use_minmax = 0

Query id: 14056c8c-6e24-4604-8c04-0b8be11de2d3

   ┌─count()─┐
1. │ 2003984 │ -- 2.00 million
   └─────────┘

1 row in set. Elapsed: 0.146 sec. Processed 110.00 million rows, 480.00 MB (751.86 million rows/s., 3.28 GB/s.)
Peak memory usage: 147.81 MiB.

n0vik :) SELECT count(*) FROM large l INNER JOIN small s ON l.a = s.a WHERE s.b < 10000000 SETTINGS join_runtime_filter_use_minmax = 1;

SELECT count(*)
FROM large AS l
INNER JOIN small AS s ON l.a = s.a
WHERE s.b < 10000000
SETTINGS join_runtime_filter_use_minmax = 1

Query id: 44fd45fe-2a4b-4888-b75e-89753966b0f4

   ┌─count()─┐
1. │ 2003984 │ -- 2.00 million
   └─────────┘

1 row in set. Elapsed: 0.197 sec. Processed 110.00 million rows, 480.00 MB (559.71 million rows/s., 2.44 GB/s.)
Peak memory usage: 128.89 MiB.

@novikd

novikd commented Feb 18, 2026

Copy link
Copy Markdown
Member Author
image

@novikd

novikd commented Feb 18, 2026

Copy link
Copy Markdown
Member Author

After using native types instead of Field:
image
image
image

@rschu1ze

Copy link
Copy Markdown
Member

grace_hash_join.xml does

SELECT sum(n) FROM (SELECT number * 2 AS n FROM numbers_mt(10000000)) AS lhs JOIN (SELECT number * 3 AS n FROM numbers_mt(10000000)) AS rhs USING (n) SETTINGS {settings} FORMAT Null

So we join numeric columns, the build side has high cardinality (i.e. the set representation changes to bloom filter + minmax). On the probe side, the filter lets 1/3 of the tuples pass and 2/3 not. This is below join_runtime_filter_pass_ratio_threshold_for_disabling = 0.7, so we don't disable the filter dynamically. So it can at least be explained :-) We don't need to tune the thresholds in this PR, @cv4g wanted to do this globally for TPC-H anyways. I still wonder how two simple integer comparisons can increase runtimes by 33%.

DECLARE(Double, join_runtime_filter_pass_ratio_threshold_for_disabling, 0.7, "If ratio of passed rows to checked rows is greater than this threshold the runtime filter is considered as poorly performing and is disabled for the next `join_runtime_filter_blocks_to_skip_before_reenabling` blocks to reduce the overhead.", 0) \
DECLARE(UInt64, join_runtime_filter_blocks_to_skip_before_reenabling, 30, "Number of blocks that are skipped before trying to dynamically re-enable a runtime filter that previously was disabled due to poor filtering ratio.", 0) \
DECLARE(Double, join_runtime_bloom_filter_max_ratio_of_set_bits, 0.7, "If the number of set bits in a runtime bloom filter exceeds this ratio the filter is completely disabled to reduce the overhead.", 0) \
DECLARE(Bool, join_runtime_filter_use_minmax, false, "Enable using minmax runtime filters that keep just minimum and maximum values to avoid unnecessary bloom filter lookups.", 0) \

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.

"keep" --> "test"/"probe"/"check"

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.

@cv4g cv4g left a comment

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.

Well done! 👍 from my side. @rschu1ze?

/// when the number of unique values exceeds the limit.
/// It is used for numeric columns only.
/// The minmax range allows to quickly filter out values that are outside of the observed min and max values,
/// which can be beneficial for avoiding unnecessary bloom filter lookups.

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.

With the min max filter being the third runtime filter implementation we could consider to break the inheritance hierarchy into a composition and variant in the mid- to long-term.
This way we can keep them independent by modelling the transitions and parallel lifetimes explicitly outside the class definition:

class ExactContainsRuntimeFilter : public RuntimeFilterBase<false>;
class ExactNotContainsRuntimeFilter : public RuntimeFilterBase<true>;
class BloomFilterRuntimeFilter : public IRuntimeFilter;
class MinMaxRuntimeFilter : public IRuntimeFilter;

class ApproximateNumericContainsRuntimeFilters : public IRuntimeFilter{
  BloomFilterRuntimeFilter bloomFilter;
  MinMaxRuntimeFilter minMax;
};

using NumericContainsRuntimeFilter = std::variant<
  ExactContainsRuntimeFilter, 
  ApproximateNumericContainsRuntimeFilters, 
  MinMaxRuntimeFilter>;

ApproximateNumericContainsRuntimeFilters toApproximate(const ExactContainsRuntimeFilter&);
MinMaxRuntimeFilter removeBloomFilter(const ApproximateNumericContainsRuntimeFilters&);

/// It is used for numeric columns only.
/// The minmax range allows to quickly filter out values that are outside of the observed min and max values,
/// which can be beneficial for avoiding unnecessary bloom filter lookups.
template <typename T>

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.

Should we constrain the template parameter T to numeric types or explicitly to the four instantiations that we got in RuntimeFilterLookup.cpp:

template class ApproximateNumericRuntimeFilter<UInt64>;
template class ApproximateNumericRuntimeFilter<Int64>;
template class ApproximateNumericRuntimeFilter<Float32>;
template class ApproximateNumericRuntimeFilter<Float64>;

Even though it does not make a difference now, it'll signal to readers already here that this runtime filter implementation is for these four numerics only at the moment.

In RuntimeFilterLookup.cpp:111 too we got a function template getColumnValue() which is not constrained and defaults to the Float64 code path for any non-numeric T. Would this raise a runtime error?

template <typename T>
T getColumnValue(const IColumn & column, size_t row);

@snelheidai

Copy link
Copy Markdown

@rschu1ze asked how two simple integer comparisons can increase runtimes by 33%. Measured answer: on a
numeric-key join the runtime filter probe is already the dominant per-row cost, and with
enable_join_runtime_filters_index_analysis off (still the default) the filter removes no I/O at all.
So anything added in front of it is pure loss — and a selective filter can still be a net loss.

Screen on adapted TPC-H SF10 (dbgen data, tests/benchmarks/tpc-h schema and queries, single node,
4 vCPU, warm, one binary with only enable_join_runtime_filters flipped, minimum of 2 kept
repetitions — a screen, not a paired result). Positive = the filter costs time:

query filter on filter off delta
query_04 868 ms 596 ms +45.6%
query_21 3181 ms 2225 ms +43.0%
query_22 218 ms 172 ms +26.7%
query_16 250 ms 208 ms +20.2%
query_03 1401 ms 1195 ms +17.2%
query_08 1645 ms 1486 ms +10.7%
query_17 1738 ms 2366 ms -26.5%
query_19 1735 ms 2219 ms -21.8%
query_02 433 ms 493 ms -12.2%

read_rows is identical between the two arms for all 23 queries. The filter prunes nothing at storage
level; what it removes are rows the immediately following hash-join probe removes anyway. The bloom
probe costs two CityHash64 calls plus up to three scattered loads, while the join probe costs one
hardware-CRC32 hash. It still earns its cost on query_17, query_19 and query_02, so switching it off
is not the answer either.

This bears on the gating in this PR. join_runtime_bloom_filter_max_ratio_of_set_bits and the new
join_runtime_bloom_filter_max_estimated_ratio_of_set_bits drop membership filtering when the bloom
filter is saturated; join_runtime_filter_pass_ratio_threshold_for_disabling drops it when too many
rows pass. Your grace_hash_join.xml case is neither: it passes 1/3 of rows and the bloom filter is
not saturated, so it survives every check and still costs 33%. Selectivity is not usefulness —
rejecting a row only pays if something downstream gets cheaper, and when read_rows is unchanged and
the join probe hashes more cheaply than the filter, rejecting 2/3 of rows still loses.

Removing the hashing instead of reducing it

Since the cost is the hashing itself, an exact representation removes it. I gave the adaptive filter a
second representation: when the exact value set overflows and the key is a native integer whose
observed span fits a byte budget — the larger of the bytes the bloom filter would have used and the
bytes the keys themselves would occupy, capped at 32 MiB — the values go into one bit per value of the
covered range. Probing is one shifted load: no hashing, no false positives. The range is widened by
whole 64-bit words as later blocks arrive, so bitset_min stays word-aligned and no bit moves inside
its word. Anything not exactly representable (range outgrows the budget, or an unsigned value beyond
Int64) falls back to the bloom filter with the keys recovered from the bits, so no key is lost.
Merging filters from parallel build streams replays the source keys through the normal insert path.

Paired A/B against master 10bec7b88102, two binaries differing by this one commit, block-interleaved
whole-server arms plus a second anchor arm as an A/A null, repetition 0 discarded, Student-t 95% CI on
the mean paired log ratio, n=11 (TPC-H) and n=7 (TPC-DS):

query anchor candidate change 95% CI
tpch/query_22 222.7 ms 110.5 ms -50.2% [-53.4, -46.7]
tpcds/query_92 139.0 ms 88.9 ms -36.1% [-38.6, -33.6]
tpcds/query_93 1057.9 ms 798.4 ms -24.5% [-25.0, -24.1]
tpch/query_16 258.5 ms 202.0 ms -21.8% [-23.2, -20.5]
tpcds/query_39 1817.1 ms 1423.7 ms -21.7% [-24.0, -19.2]
tpch/query_08 1645.3 ms 1303.2 ms -20.8% [-21.9, -19.7]
tpcds/query_69 927.6 ms 737.1 ms -20.4% [-25.4, -15.1]
tpcds/query_32 169.6 ms 136.4 ms -19.5% [-21.3, -17.7]
tpch/query_09 2493.2 ms 2036.5 ms -18.3% [-19.8, -16.8]
tpcds/query_35 1073.7 ms 890.7 ms -17.1% [-17.9, -16.2]
tpcds/query_50 995.3 ms 836.0 ms -16.0% [-16.8, -15.2]

The A/A null arm shows no effect on any query in either suite (worst 2.5%). A single-pass screen over
all 98 runnable TPC-DS queries flagged eight apparent regressions and paired re-measurement removed
all eight — the largest were query_63 at +30.8% on the screen versus +0.5% [-1.2, +2.2] paired, and
query_97 at +17.9% versus -0.1%. The profile confirms the mechanism: on the anchor, query_22 spends
49.6% of its samples in findHashPairs, computeHashPair and the two CityHash64 calls; with the
patch those frames are gone.

Correctness: all 99 TPC-DS and 23 TPC-H queries give identical sorted answer digests on the two
binaries, with identical failure counts per arm. 24 predeclared cases are byte-identical across
anchor, candidate, candidate with enable_join_runtime_filters=0 and candidate at max_threads=1 —
covering the bitset path, the out-of-budget bloom fallback, ascending and descending range widening, a
mid-stream range explosion forcing the bitset-to-bloom fallback, a dense narrow range, negative
Int64, UInt64 above INT64_MAX, UInt8/Int16/Date/String/Nullable/LowCardinality/
Decimal keys, single-value and empty build sides, semi and anti joins, LEFT JOIN, cross-type keys
and two joins in one query. Peak query memory on query_09 is flat (617 versus 615 MiB warm, 705 versus
701 MiB cold), and three concurrent clients take 42970 ms of summed server time on the anchor versus
35543 ms with the patch.

Limitations

  • The prototype was measured against 10bec7b88102, which is one day older than Refactor runtime filter hierarchy #109620. It patches
    ApproximateRuntimeFilter, which no longer exists on master, so the diff below is a measured
    prototype rather than an applyable patch — the representation needs porting onto
    AdaptiveSetRuntimeFilter/ApproximateSetRuntimeFilter before it means anything for this branch.
  • query_04 and query_21 — the two queries the filter costs the most — are unchanged. Their key is
    l_orderkey: ~15M distinct values over a ~60M span needs a 7.5 MB bitset and the budget rejects it,
    so they keep the bloom filter. Raising the budget for large-span integer keys is a separate change I
    have not measured.
  • Bloom filter hash pairs hash the data twice; hashing once is bit-identical and ~11% faster on TPC-H query_21 #119562 and Cheaper hashing and a cache-line-blocked bloom filter for join runtime filters #119869 attack the same per-row term. Those gains and this one are alternatives, not
    additive.
  • One 4-vCPU node at SF10, warm: no distributed or parallel-replica measurements, and cross-node
    merging is implemented but untested at scale. A cold run after dropping the page cache is flat
    (6477 versus 6471 ms, n=1), so the gain is CPU-bound and disappears when the query is I/O-bound.

Prototype diff against 10bec7b88102 (pre-#109620), touching only
src/Processors/QueryPlan/RuntimeFilterLookup.{h,cpp}:

rtbitset.patch
diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
index 580de0812e8..0dcdc9e1a0a 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
@@ -19,6 +19,10 @@
 #include <Common/logger_useful.h>
 #include <Common/ProfileEvents.h>
 #include <algorithm>
+#include <type_traits>
+#include <limits>
+#include <bit>
+#include <Columns/ColumnVector.h>
 #include <cmath>
 #include <optional>
 #include <vector>
@@ -287,6 +291,114 @@ UInt64 growBloomFilterBytes(UInt64 distinct_keys, UInt64 hash_functions, UInt64
     const double clamped_bloom_filter_bytes = std::clamp(ideal_bloom_filter_bytes, 0.0, static_cast<double>(MAX_STATS_SIZED_BLOOM_FILTER_BYTES));
     return std::max(static_cast<UInt64>(clamped_bloom_filter_bytes), default_bloom_filter_bytes);
 }
+
+constexpr UInt64 BITSET_WORD_BITS = 64;
+
+/// Native integer keys are the ones that map one to one onto a dense bit index. Nullable and
+/// LowCardinality types are not native integers here, so they keep the exact-Set path as before.
+bool isDenseBitsetKeyType(const DataTypePtr & type)
+{
+    const WhichDataType which(type);
+    return which.isNativeInt() || which.isNativeUInt();
+}
+
+/// Align down to a word boundary. Two's complement masking also floors negative values.
+Int64 alignDownToWord(Int64 value)
+{
+    return static_cast<Int64>(static_cast<UInt64>(value) & ~(BITSET_WORD_BITS - 1));
+}
+
+/// Calls `op` with the raw data array of a native integer column. Returns false for anything else
+/// (const, sparse, or a non-vector column), so callers can use a generic fallback.
+template <typename Op>
+bool dispatchNativeIntColumn(const IColumn & column, Op && op)
+{
+#define CHPERF_DISPATCH_NATIVE_INT(TYPE) \
+    if (const auto * typed = typeid_cast<const ColumnVector<TYPE> *>(&column)) \
+    { \
+        op(typed->getData()); \
+        return true; \
+    }
+    CHPERF_DISPATCH_NATIVE_INT(UInt8)
+    CHPERF_DISPATCH_NATIVE_INT(UInt16)
+    CHPERF_DISPATCH_NATIVE_INT(UInt32)
+    CHPERF_DISPATCH_NATIVE_INT(UInt64)
+    CHPERF_DISPATCH_NATIVE_INT(Int8)
+    CHPERF_DISPATCH_NATIVE_INT(Int16)
+    CHPERF_DISPATCH_NATIVE_INT(Int32)
+    CHPERF_DISPATCH_NATIVE_INT(Int64)
+#undef CHPERF_DISPATCH_NATIVE_INT
+    return false;
+}
+
+template <typename Op>
+bool dispatchNativeIntMutableColumn(IColumn & column, Op && op)
+{
+#define CHPERF_DISPATCH_NATIVE_INT_MUT(TYPE) \
+    if (auto * typed = typeid_cast<ColumnVector<TYPE> *>(&column)) \
+    { \
+        op(typed->getData()); \
+        return true; \
+    }
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt8)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt16)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt32)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt64)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int8)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int16)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int32)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int64)
+#undef CHPERF_DISPATCH_NATIVE_INT_MUT
+    return false;
+}
+
+/// Envelope of a native integer column in Int64 space. Returns false when the column is not a
+/// native integer vector, or when an unsigned value does not fit Int64 - the bit index is computed
+/// with modular arithmetic, but the *range* bookkeeping needs an ordered signed interval.
+bool nativeIntColumnEnvelope(const IColumn & column, Int64 & out_min, Int64 & out_max)
+{
+    bool ok = false;
+    bool representable = true;
+    bool first = true;
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    ok = dispatchNativeIntColumn(column, [&](const auto & data)
+    {
+        using T = std::decay_t<decltype(data[0])>;
+        for (const auto value : data)
+        {
+            const Int64 as_int = static_cast<Int64>(value);
+            if constexpr (std::is_unsigned_v<T>)
+            {
+                if (as_int < 0)
+                {
+                    representable = false;
+                    return;
+                }
+            }
+            if (first)
+            {
+                min_value = as_int;
+                max_value = as_int;
+                first = false;
+            }
+            else
+            {
+                min_value = std::min(min_value, as_int);
+                max_value = std::max(max_value, as_int);
+            }
+        }
+    });
+    if (!ok || !representable || first)
+        return false;
+    /// Keep the interval away from the Int64 edges so widening it cannot wrap.
+    static constexpr Int64 SAFE_BOUND = std::numeric_limits<Int64>::max() / 4;
+    if (min_value < -SAFE_BOUND || max_value > SAFE_BOUND)
+        return false;
+    out_min = min_value;
+    out_max = max_value;
+    return true;
+}
 }
 
 void ExactContainsRuntimeFilter::merge(const IRuntimeFilter * source)
@@ -359,7 +471,13 @@ void ApproximateRuntimeFilter::insert(ColumnPtr values)
     if (inserts_are_finished)
         throw Exception(ErrorCodes::LOGICAL_ERROR, "Trying to insert into runtime filter after it was marked as finished");
 
-    if (bloom_filter)
+    if (bitset_active)
+    {
+        /// Bitset mode dropped the values; track the envelope here.
+        updateRange(*values);
+        insertIntoBitset(values);
+    }
+    else if (bloom_filter)
     {
         /// Bloom mode dropped the values; track the envelope here.
         updateRange(*values);
@@ -372,13 +490,22 @@ void ApproximateRuntimeFilter::insert(ColumnPtr values)
 
         Base::insert(std::move(values));
 
-        if (isFull())
+        if (isFull() && !tryStartBitset())
             switchToBloomFilter();
     }
 }
 
 void ApproximateRuntimeFilter::finishInsertImpl()
 {
+    if (bitset_active)
+    {
+        /// Nothing to check: the bitset has no false positives, so the only reason to give up on it
+        /// is poor real selectivity, which the shared pass-ratio heuristic already measures on the
+        /// probe side. Bit density would be the wrong signal - a dense set over a narrow range can
+        /// still reject almost every probe row.
+        return;
+    }
+
     if (bloom_filter)
     {
         checkBloomFilterWorthiness();
@@ -400,9 +527,17 @@ void ApproximateRuntimeFilter::merge(const IRuntimeFilter * source)
 
     if (source_typed->bloom_filter)
     {
+        if (bitset_active)
+            switchFromBitsetToBloomFilter();
         switchToBloomFilter();
         mergeBloomFilters(*bloom_filter, *source_typed->bloom_filter);
     }
+    else if (source_typed->bitset_active)
+    {
+        /// A bitset holds its keys exactly, so they can be replayed through the normal insert path,
+        /// which keeps this filter in whatever representation it is already using.
+        insert(source_typed->bitsetValuesColumn());
+    }
     else
     {
         insert(source_typed->getValuesColumn());
@@ -467,6 +602,49 @@ ColumnPtr ApproximateRuntimeFilter::findImpl(const ColumnWithTypeAndName & value
 {
     chassert(inserts_are_finished);
 
+    if (bitset_active)
+    {
+        const size_t rows = values.column->size();
+        auto dst = ColumnVector<UInt8>::create();
+        auto & dst_data = dst->getData();
+        dst_data.resize(rows);
+
+        ColumnPtr probe = values.column->convertToFullColumnIfConst();
+        probe = probe->convertToFullColumnIfSparse();
+
+        const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+        const UInt64 * const words = bitset.data();
+        const UInt64 bits = bitset_bits;
+        size_t found_count = 0;
+
+        /// A value maps into [0, bits) exactly when it lies in the covered range, so an index that
+        /// falls outside it is a definite miss: the bitset is exact over the whole range.
+        const bool dispatched = dispatchNativeIntColumn(*probe, [&](const auto & data)
+        {
+            for (size_t row = 0; row < rows; ++row)
+            {
+                const UInt64 index = static_cast<UInt64>(static_cast<Int64>(data[row])) - min_as_words;
+                const UInt8 result = index < bits ? ((words[index / BITSET_WORD_BITS] >> (index % BITSET_WORD_BITS)) & 1u) : 0u;
+                dst_data[row] = result;
+                found_count += result;
+            }
+        });
+
+        if (!dispatched)
+        {
+            for (size_t row = 0; row < rows; ++row)
+            {
+                const UInt64 index = static_cast<UInt64>(probe->getInt(row)) - min_as_words;
+                const UInt8 result = index < bits ? ((words[index / BITSET_WORD_BITS] >> (index % BITSET_WORD_BITS)) & 1u) : 0u;
+                dst_data[row] = result;
+                found_count += result;
+            }
+        }
+
+        updateStats(rows, found_count);
+        return dst;
+    }
+
     if (bloom_filter)
     {
         auto dst = ColumnVector<UInt8>::create();
@@ -498,21 +676,189 @@ void ApproximateRuntimeFilter::insertIntoBloomFilter(ColumnPtr values)
         });
 }
 
+UInt64 ApproximateRuntimeFilter::bloomFilterBytes() const
+{
+    if (distinct_keys_hint)
+        return growBloomFilterBytes(*distinct_keys_hint, bloom_filter_hash_functions, getBytesLimit(), max_ratio_of_set_bits_in_bloom_filter);
+    return getBytesLimit();
+}
+
 void ApproximateRuntimeFilter::switchToBloomFilter()
 {
     if (bloom_filter)
         return;
 
-    UInt64 bloom_filter_bytes = getBytesLimit();
-    if (distinct_keys_hint)
-        bloom_filter_bytes = growBloomFilterBytes(*distinct_keys_hint, bloom_filter_hash_functions, getBytesLimit(), max_ratio_of_set_bits_in_bloom_filter);
-
-    bloom_filter = std::make_unique<BloomFilter>(bloom_filter_bytes, bloom_filter_hash_functions, BLOOM_FILTER_SEED);
+    bloom_filter = std::make_unique<BloomFilter>(bloomFilterBytes(), bloom_filter_hash_functions, BLOOM_FILTER_SEED);
     insertIntoBloomFilter(getValuesColumn());
 
     releaseExactValues();
 }
 
+UInt64 ApproximateRuntimeFilter::bitsetMaxBytes() const
+{
+    /// Two independent budgets, whichever is larger: the bloom filter this replaces, and the space
+    /// the build-side keys themselves would occupy. The second matters because the bloom filter is
+    /// capped at 4 MiB and simply degrades its false positive rate beyond that, while a bitset has
+    /// none - but a bitset that costs more than storing every key exactly is not worth its memory.
+    static constexpr UInt64 BITSET_HARD_CAP_BYTES = 32 * 1024 * 1024;
+    static constexpr UInt64 MAX_TRUSTED_DISTINCT_KEYS_HINT = 1000000000;
+    UInt64 budget = bloomFilterBytes();
+    if (distinct_keys_hint && *distinct_keys_hint <= MAX_TRUSTED_DISTINCT_KEYS_HINT)
+        budget = std::max(budget, *distinct_keys_hint * filter_column_target_type->getSizeOfValueInMemory());
+    return std::min(budget, BITSET_HARD_CAP_BYTES);
+}
+
+bool ApproximateRuntimeFilter::tryStartBitset()
+{
+    if (!isDenseBitsetKeyType(filter_column_target_type))
+        return false;
+
+    const ColumnPtr values = getValuesColumn();
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    if (!nativeIntColumnEnvelope(*values, min_value, max_value))
+        return false;
+
+    const UInt64 max_words = bitsetMaxBytes() / sizeof(UInt64);
+    if (max_words == 0)
+        return false;
+
+    const Int64 aligned_min = alignDownToWord(min_value);
+    const UInt64 span_bits = static_cast<UInt64>(max_value) - static_cast<UInt64>(aligned_min) + 1;
+    const UInt64 words = (span_bits + BITSET_WORD_BITS - 1) / BITSET_WORD_BITS;
+    if (words == 0 || words > max_words)
+        return false;
+
+    bitset.assign(words, 0);
+    bitset_min = aligned_min;
+    bitset_bits = words * BITSET_WORD_BITS;
+    bitset_max_words = max_words;
+    bitset_active = true;
+    setBitsetBits(*values);
+
+    releaseExactValues();
+    return true;
+}
+
+/// Widen the covered range to include [lo, hi]. `bitset_min` stays word aligned, so widening
+/// downwards only prepends whole words and no bit has to move inside its word.
+bool ApproximateRuntimeFilter::extendBitsetRange(Int64 lo, Int64 hi)
+{
+    const bool below = lo < bitset_min;
+    const Int64 current_top = bitset_min + static_cast<Int64>(bitset_bits);
+    const bool above = hi >= current_top;
+    if (!below && !above)
+        return true;
+
+    const Int64 target_min = below ? alignDownToWord(lo) : bitset_min;
+    const Int64 target_top = above ? hi + 1 : current_top;
+    const UInt64 needed_bits = static_cast<UInt64>(target_top) - static_cast<UInt64>(target_min);
+    UInt64 needed_words = (needed_bits + BITSET_WORD_BITS - 1) / BITSET_WORD_BITS;
+    if (needed_words > bitset_max_words)
+        return false;
+
+    /// Grow geometrically upwards so a key column arriving in sorted order does not reallocate per block.
+    const UInt64 word_offset = (static_cast<UInt64>(bitset_min) - static_cast<UInt64>(target_min)) / BITSET_WORD_BITS;
+    needed_words = std::max(needed_words, std::min(bitset_max_words, static_cast<UInt64>(bitset.size()) * 2));
+    needed_words = std::max(needed_words, word_offset + static_cast<UInt64>(bitset.size()));
+    if (needed_words > bitset_max_words)
+        return false;
+
+    std::vector<UInt64> widened(needed_words, 0);
+    std::copy(bitset.begin(), bitset.end(), widened.begin() + word_offset);
+    bitset.swap(widened);
+    bitset_min = target_min;
+    bitset_bits = needed_words * BITSET_WORD_BITS;
+    return true;
+}
+
+void ApproximateRuntimeFilter::setBitsetBits(const IColumn & column)
+{
+    UInt64 * const words = bitset.data();
+    const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+    const bool dispatched = dispatchNativeIntColumn(column, [&](const auto & data)
+    {
+        for (const auto value : data)
+        {
+            const UInt64 index = static_cast<UInt64>(static_cast<Int64>(value)) - min_as_words;
+            chassert(index < bitset_bits);
+            words[index / BITSET_WORD_BITS] |= 1ULL << (index % BITSET_WORD_BITS);
+        }
+    });
+    if (!dispatched)
+    {
+        const size_t rows = column.size();
+        for (size_t row = 0; row < rows; ++row)
+        {
+            const UInt64 index = static_cast<UInt64>(column.getInt(row)) - min_as_words;
+            chassert(index < bitset_bits);
+            words[index / BITSET_WORD_BITS] |= 1ULL << (index % BITSET_WORD_BITS);
+        }
+    }
+}
+
+void ApproximateRuntimeFilter::insertIntoBitset(const ColumnPtr & values)
+{
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    ColumnPtr block = values->convertToFullColumnIfConst();
+    block = block->convertToFullColumnIfSparse();
+    if (block->empty())
+        return;
+
+    /// Anything the bitset cannot represent exactly - an unsupported column, a value outside the
+    /// safe range, or a range that no longer fits the byte budget - falls back to the bloom filter
+    /// with the keys recovered from the bits, so no key is ever lost.
+    if (!nativeIntColumnEnvelope(*block, min_value, max_value) || !extendBitsetRange(min_value, max_value))
+    {
+        switchFromBitsetToBloomFilter();
+        insertIntoBloomFilter(block);
+        return;
+    }
+
+    setBitsetBits(*block);
+}
+
+ColumnPtr ApproximateRuntimeFilter::bitsetValuesColumn() const
+{
+    MutableColumnPtr column = filter_column_target_type->createColumn();
+    const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+    const bool dispatched = dispatchNativeIntMutableColumn(*column, [&](auto & data)
+    {
+        using Container = std::decay_t<decltype(data)>;
+        using T = typename Container::value_type;
+        for (size_t word_index = 0; word_index < bitset.size(); ++word_index)
+        {
+            UInt64 word = bitset[word_index];
+            while (word)
+            {
+                const UInt64 bit = static_cast<UInt64>(std::countr_zero(word));
+                word &= word - 1;
+                const UInt64 value = min_as_words + word_index * BITSET_WORD_BITS + bit;
+                data.push_back(static_cast<T>(value));
+            }
+        }
+    });
+    if (!dispatched)
+        throw Exception(ErrorCodes::LOGICAL_ERROR, "Runtime filter bitset holds a non native integer key type");
+    return column;
+}
+
+void ApproximateRuntimeFilter::switchFromBitsetToBloomFilter()
+{
+    chassert(bitset_active);
+    const ColumnPtr recovered = bitsetValuesColumn();
+
+    bitset_active = false;
+    bitset.clear();
+    bitset.shrink_to_fit();
+    bitset_bits = 0;
+
+    bloom_filter = std::make_unique<BloomFilter>(bloomFilterBytes(), bloom_filter_hash_functions, BLOOM_FILTER_SEED);
+    if (!recovered->empty())
+        insertIntoBloomFilter(recovered);
+}
+
 void ApproximateRuntimeFilter::checkBloomFilterWorthiness()
 {
     const auto & raw_filter_words = bloom_filter->getFilter();
diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.h b/src/Processors/QueryPlan/RuntimeFilterLookup.h
index b22f5d1b4ff..b7500f1242d 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.h
+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.h
@@ -14,6 +14,7 @@
 #include <functional>
 #include <memory>
 #include <optional>
+#include <vector>
 
 namespace DB
 {
@@ -307,12 +308,36 @@ private:
     /// Disables bloom filter if it is likely to have bad selectivity
     void checkBloomFilterWorthiness();
 
+    /// Bytes the bloom filter would occupy.
+    UInt64 bloomFilterBytes() const;
+    /// Memory budget the dense bitset must stay within.
+    UInt64 bitsetMaxBytes() const;
+
+    /// Dense exact representation for native integer keys: one bit per value of the covered range.
+    /// Probing is a single shifted load with no hashing and no false positives, so it replaces the
+    /// bloom filter whenever the observed key span fits the same byte budget.
+    bool tryStartBitset();
+    void insertIntoBitset(const ColumnPtr & values);
+    bool extendBitsetRange(Int64 lo, Int64 hi);
+    void setBitsetBits(const IColumn & column);
+    /// Exact keys held by the bitset, used when merging with a filter in another representation.
+    ColumnPtr bitsetValuesColumn() const;
+    void switchFromBitsetToBloomFilter();
+
     const UInt64 bloom_filter_hash_functions;
     const Float64 max_ratio_of_set_bits_in_bloom_filter = 0.7;
     /// Measured distinct build-side keys from prior statistics, used to choose the bloom filter size.
     const std::optional<UInt64> distinct_keys_hint;
 
     BloomFilterPtr bloom_filter;
+
+    /// One bit per value of [bitset_min, bitset_min + bitset_bits). `bitset_min` is kept aligned to
+    /// a 64-bit word so the covered range can be widened by whole words, without shifting bits.
+    std::vector<UInt64> bitset;
+    Int64 bitset_min = 0;
+    UInt64 bitset_bits = 0;
+    UInt64 bitset_max_words = 0;
+    bool bitset_active = false;
 };
 
 /// Runtime filter that delegates probe to a function captured at publication time.

@snelheidai

Copy link
Copy Markdown

Correction to my earlier comment: the limitation I listed — query_04 and query_21 unchanged because l_orderkey needs a 7.5 MB bitset the budget rejects — is gone. Those two queries are now the largest wins in the suite, and they are the same two where the filter costs the most today.

The blocker was not the representation but a memory policy choice, and one number in that bullet was wrong:

  • The build side is sparse, not large: ~540K keys for query_04, not the ~15M I quoted. Its filter builds from ORDERS restricted to the three-month window, and those keys are spread over the whole 60M l_orderkey range (stride ~111), so one bit per value needs 7.5 MB while the keys themselves need 4.3 MB. What refused the bitset was my rule that it must not cost more than storing the keys exactly. Break-even is span ≤ 64 × keys for a 64-bit key, and real surrogate keys sit well past it.
  • For sizing, the bloom budget on a warm server is already 2.29 MB (query_04) and 5.79 MB (query_21), not the 512 KiB default, so an allowance expressed as a multiple of it starts from a realistic base.

Giving the exact bitset its own allowance — 16 × join_runtime_bloom_filter_bytes, raised further if the keys would need more, still capped at 32 MiB — and stopping speculative range growth from spending the whole budget (doubling landed on an 8 MiB window anchored above the eventual minimum key, so one later lower key forced the bloom fallback) gives, against the same untouched anchor 10bec7b88102 with the same paired block-interleaved method and node as before, n=11:

query anchor candidate change 95% CI
query_04 874 ms 494 ms -43.5% [-43.8, -43.2]
query_21 3300 ms 1909 ms -42.2% [-43.6, -40.7]
query_03 1434 ms 1134 ms -21.0% [-23.7, -18.2]

query_03 crosses into this table with the growth fix. The earlier table's wins are preserved, so I am not restating them. The A/A null arm is flat on all 11, worst -2.0% with the CI spanning zero.

The part that bears on this PR's design: because the bitset is exact inside its range, it also halves the rows the filter passes downstream — query_04 4,494,276 → 2,294,856 and query_21 6,895,425 → 3,458,628 — so the join probe receives less work, not merely cheaper filtering. A [min,max] pre-check cannot do that; it only skips lookups for values outside the range.

Costs and caveats:

  • Warm peak memory rises where the bitset now engages: query_04 62 → 102 MiB (+65%), query_03 142 → 170, query_09 587 → 629, query_21 572 → 610 MiB. That is about 7 MB per wide-span filter per build stream, bounded by the allowance and therefore scaled by join_runtime_bloom_filter_bytes. It is the tradeoff for this result.
  • Still a measured prototype rather than an applyable patch, for the reason in the earlier comment: it patches ApproximateRuntimeFilter, which Refactor runtime filter hierarchy #109620 deleted, and needs porting onto ExactSetRuntimeFilter/ApproximateSetRuntimeFilter/AdaptiveSetRuntimeFilter.
  • Answers unchanged: TPC-DS 99/99 and TPC-H 23/23 identical sorted digests with identical failure counts, and 29 predeclared runtime-filter cases byte-identical across anchor / candidate / candidate with enable_join_runtime_filters=0 / candidate at max_threads=1, with read_rows identical in every arm. TPC-DS shows no regression (n=7, worst query_63 +0.67%). On query_21, three concurrent clients give -44.4% and a cold run with the page cache dropped gives 6086 → 4399 ms (n=1, indicative); the flat cold number in the earlier comment was query_09.
  • Bloom filter hash pairs hash the data twice; hashing once is bit-identical and ~11% faster on TPC-H query_21 #119562 and Cheaper hashing and a cache-line-blocked bloom filter for join runtime filters #119869 still attack the same per-row term; those gains and this one are alternatives, not additive.

@snelheidai

Copy link
Copy Markdown

The prototype caveat in my last comment is retired: the mechanism now applies to current master as one commit, and the gains reproduce there. @cv4g — it is already expressed for the post-#109620 shape you said you would rebase onto.

Anchor is untouched master d7262251a2f, candidate is that plus one commit: 465 insertions in src/Processors/QueryPlan/RuntimeFilterLookup.{h,cpp}.

How it sits in the new hierarchy:

  • DenseBitsetRuntimeFilter becomes a fourth alternative in AdaptiveSetRuntimeFilter::Filter, entered from a new switchFromExactFilter() that tries the bitset before the bloom filter, and therefore before the predicted-saturation build skip (b02e268). A bloom filter that would be dropped for saturation is exactly where an in-budget exact bitset is worth most.
  • switchToApproximateFilter() also accepts a bitset source and rebuilds the bloom from keys recovered out of the bits. mergeFrom replays a bitset source's exact keys through the normal insert path, so bitset-vs-bitset and bitset-vs-bloom merges need no special case.
  • The allowance trusts distinct_keys_hint only when distinct_keys_hint_matches_filter_key says it counts this complete filter key; otherwise only observed key rows raise it.

Measured on master, same method and node as the earlier tables (paired block-interleaved whole-server arms, rep 0 discarded, Student-t 95% CI on the mean paired log ratio, adapted TPC-H/TPC-DS SF10 on one exclusive 4-core host, not an audited TPC result):

query master + bitset change 95% CI
h/query_22 217 ms 111 ms -49.0% [-50.4, -47.5]
h/query_04 888 ms 511 ms -42.4% [-44.9, -39.8]
h/query_21 3297 ms 1905 ms -42.2% [-43.0, -41.5]

Also h/query_08 -23.8%, query_03 -21.7%, query_16 -21.3%, query_09 -17.2%, query_02 -14.4%; ds/query_92 -38.3%, query_39 -21.0%, query_32 -20.5%, query_69 -19.2%, query_35 -18.8%, query_50 -13.7% (n=11 TPC-H, n=7 TPC-DS). The A/A null arm is flat on all 11, there is no regression anywhere, and read_rows is identical in all 26 timed queries.

Answers: TPC-H 23/23 and TPC-DS 98/99 identical sorted digests. The one difference, ds/query_65, is master's own tie-boundary nondeterminism — the unmodified anchor alternates between the same two digests, and with the LIMIT removed both arms return 181,274 rows with the identical order-insensitive digest.

Costs, on master:

  • Warm peak memory rises where the bitset engages, h/query_04 62 → 101 MiB: about 7 MB per wide-span filter per build stream, scaling with join_runtime_bloom_filter_bytes.
  • Distributed and parallel-replica filter merging is untested.
  • ds/query_93 was -24% on the older anchor and is flat on master, so master already captures that case another way.
Patch — 465 insertions, applies to d7262251a2f
Represent an integer-keyed JOIN runtime filter as a dense exact bitset

A runtime filter built from a native integer key falls back to a bloom filter as soon as the
exact set overflows, so every probe row is hashed twice and the filter passes false positives
into the join. When the observed key range fits a byte budget, one bit per value of that range
is both exact and cheaper to probe: no hashing, a single shifted load, and no false positives,
so the join probe also receives fewer rows.

The bitset is a fourth representation of AdaptiveSetRuntimeFilter and is tried before the bloom
filter, including before the predicted-saturation build skip - a bloom filter that would be
dropped for saturation is exactly where an in-budget exact bitset is worth most. It gets its own
allowance (16 x join_runtime_bloom_filter_bytes, raised when the keys themselves need more,
capped at 32 MiB) because a surrogate key is typically sparse: requiring the bitset to be no
bigger than the keys rejects it for the large probe sides where it pays off. Speculative range
growth stops at half the allowance, so a window cannot spend the whole budget above the eventual
minimum key and force a fallback. Anything that no longer fits - an unsupported column, an
out-of-range value, a range past the budget - recovers every key from the bits into the bloom
filter, so no key is ever lost.
---
 .../QueryPlan/RuntimeFilterLookup.cpp         | 416 +++++++++++++++++-
 .../QueryPlan/RuntimeFilterLookup.h           |  59 ++-
 2 files changed, 465 insertions(+), 10 deletions(-)

diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
index 97f17872c04..8b8ec39e044 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
@@ -9,6 +9,7 @@
 #include <vector>
 #include <Columns/ColumnConst.h>
 #include <Columns/ColumnSet.h>
+#include <Columns/ColumnVector.h>
 #include <Columns/ColumnsCommon.h>
 #include <Columns/IColumn.h>
 #include <DataTypes/DataTypeLowCardinality.h>
@@ -278,6 +279,113 @@ UInt64 growBloomFilterBytes(UInt64 distinct_keys, UInt64 hash_functions, UInt64
     const double clamped_bloom_filter_bytes = std::clamp(ideal_bloom_filter_bytes, 0.0, static_cast<double>(MAX_STATS_SIZED_BLOOM_FILTER_BYTES));
     return std::max(static_cast<UInt64>(clamped_bloom_filter_bytes), default_bloom_filter_bytes);
 }
+
+constexpr UInt64 BITSET_WORD_BITS = 64;
+
+/// Native integer keys are the ones that map one to one onto a dense bit index. Nullable and
+/// LowCardinality types are not native integers here, so they keep the exact/bloom path as before.
+bool isDenseBitsetKeyType(const DataTypePtr & type)
+{
+    const WhichDataType which(type);
+    return which.isNativeInt() || which.isNativeUInt();
+}
+
+/// Align down to a word boundary. Two's complement masking also floors negative values.
+Int64 alignDownToWord(Int64 value)
+{
+    return static_cast<Int64>(static_cast<UInt64>(value) & ~(BITSET_WORD_BITS - 1));
+}
+
+/// Calls `op` with the raw data array of a native integer column. Returns false for anything else
+/// (const, sparse, or a non-vector column), so callers can use a generic fallback.
+template <typename Op>
+bool dispatchNativeIntColumn(const IColumn & column, Op && op)
+{
+#define CHPERF_DISPATCH_NATIVE_INT(TYPE) \
+    if (const auto * typed = typeid_cast<const ColumnVector<TYPE> *>(&column)) \
+    { \
+        op(typed->getData()); \
+        return true; \
+    }
+    CHPERF_DISPATCH_NATIVE_INT(UInt8)
+    CHPERF_DISPATCH_NATIVE_INT(UInt16)
+    CHPERF_DISPATCH_NATIVE_INT(UInt32)
+    CHPERF_DISPATCH_NATIVE_INT(UInt64)
+    CHPERF_DISPATCH_NATIVE_INT(Int8)
+    CHPERF_DISPATCH_NATIVE_INT(Int16)
+    CHPERF_DISPATCH_NATIVE_INT(Int32)
+    CHPERF_DISPATCH_NATIVE_INT(Int64)
+#undef CHPERF_DISPATCH_NATIVE_INT
+    return false;
+}
+
+template <typename Op>
+bool dispatchNativeIntMutableColumn(IColumn & column, Op && op)
+{
+#define CHPERF_DISPATCH_NATIVE_INT_MUT(TYPE) \
+    if (auto * typed = typeid_cast<ColumnVector<TYPE> *>(&column)) \
+    { \
+        op(typed->getData()); \
+        return true; \
+    }
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt8)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt16)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt32)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(UInt64)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int8)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int16)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int32)
+    CHPERF_DISPATCH_NATIVE_INT_MUT(Int64)
+#undef CHPERF_DISPATCH_NATIVE_INT_MUT
+    return false;
+}
+
+/// Envelope of a native integer column in Int64 space. Returns false when the column is not a
+/// native integer vector, or when an unsigned value does not fit Int64 - the bit index is computed
+/// with modular arithmetic, but the *range* bookkeeping needs an ordered signed interval.
+bool nativeIntColumnEnvelope(const IColumn & column, Int64 & out_min, Int64 & out_max)
+{
+    bool representable = true;
+    bool first = true;
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    const bool dispatched = dispatchNativeIntColumn(column, [&](const auto & data)
+    {
+        using T = std::decay_t<decltype(data[0])>;
+        for (const auto value : data)
+        {
+            const Int64 as_int = static_cast<Int64>(value);
+            if constexpr (std::is_unsigned_v<T>)
+            {
+                if (as_int < 0)
+                {
+                    representable = false;
+                    return;
+                }
+            }
+            if (first)
+            {
+                min_value = as_int;
+                max_value = as_int;
+                first = false;
+            }
+            else
+            {
+                min_value = std::min(min_value, as_int);
+                max_value = std::max(max_value, as_int);
+            }
+        }
+    });
+    if (!dispatched || !representable || first)
+        return false;
+    /// Keep the interval away from the Int64 edges so widening it cannot wrap.
+    static constexpr Int64 SAFE_BOUND = std::numeric_limits<Int64>::max() / 4;
+    if (min_value < -SAFE_BOUND || max_value > SAFE_BOUND)
+        return false;
+    out_min = min_value;
+    out_max = max_value;
+    return true;
+}
 }
 
 static size_t countPassedStats(ColumnPtr values);
@@ -510,6 +618,207 @@ bool ApproximateSetRuntimeFilter::isWorthUsing(Float64 max_ratio_of_set_bits_in_
     return static_cast<double>(set_bits) <= max_ratio_of_set_bits_in_bloom_filter * static_cast<double>(total_bits);
 }
 
+bool DenseBitsetRuntimeFilter::isDataTypeSupported(const DataTypePtr & data_type)
+{
+    return isDenseBitsetKeyType(data_type);
+}
+
+DenseBitsetRuntimeFilter::DenseBitsetRuntimeFilter(const DataTypePtr & filter_column_target_type_)
+    : filter_column_target_type(filter_column_target_type_)
+{
+}
+
+bool DenseBitsetRuntimeFilter::tryInitialize(const ColumnPtr & values, UInt64 max_bytes)
+{
+    ColumnPtr block = values->convertToFullColumnIfConst();
+    block = block->convertToFullColumnIfSparse();
+
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    if (block->empty() || !nativeIntColumnEnvelope(*block, min_value, max_value))
+        return false;
+
+    const UInt64 max_words = max_bytes / sizeof(UInt64);
+    if (max_words == 0)
+        return false;
+
+    const Int64 aligned_min = alignDownToWord(min_value);
+    const UInt64 span_bits = static_cast<UInt64>(max_value) - static_cast<UInt64>(aligned_min) + 1;
+    const UInt64 words = (span_bits + BITSET_WORD_BITS - 1) / BITSET_WORD_BITS;
+    if (words == 0 || words > max_words)
+        return false;
+
+    bitset.assign(words, 0);
+    bitset_min = aligned_min;
+    bitset_bits = words * BITSET_WORD_BITS;
+    bitset_max_words = max_words;
+    inserted_key_rows = block->size();
+    setBits(*block);
+
+    LOG_TRACE(
+        getLogger("RuntimeFilter"),
+        "Representing {} key(s) as a dense bitset over [{}, {}), {} byte(s), budget {} byte(s)",
+        inserted_key_rows,
+        bitset_min,
+        bitset_min + static_cast<Int64>(bitset_bits),
+        getBytes(),
+        max_bytes);
+    return true;
+}
+
+bool DenseBitsetRuntimeFilter::insert(const ColumnPtr & values, UInt64 max_bytes)
+{
+    ColumnPtr block = values->convertToFullColumnIfConst();
+    block = block->convertToFullColumnIfSparse();
+    if (block->empty())
+        return true;
+
+    /// The budget grows with the keys observed so far, so re-read it before widening the range.
+    bitset_max_words = std::max(bitset_max_words, max_bytes / sizeof(UInt64));
+
+    Int64 min_value = 0;
+    Int64 max_value = 0;
+    if (!nativeIntColumnEnvelope(*block, min_value, max_value) || !extendRange(min_value, max_value))
+        return false;
+
+    inserted_key_rows += block->size();
+    setBits(*block);
+    return true;
+}
+
+/// Widen the covered range to include [lo, hi]. `bitset_min` stays word aligned, so widening
+/// downwards only prepends whole words and no bit has to move inside its word.
+bool DenseBitsetRuntimeFilter::extendRange(Int64 lo, Int64 hi)
+{
+    const bool below = lo < bitset_min;
+    const Int64 current_top = bitset_min + static_cast<Int64>(bitset_bits);
+    const bool above = hi >= current_top;
+    if (!below && !above)
+        return true;
+
+    const Int64 target_min = below ? alignDownToWord(lo) : bitset_min;
+    const Int64 target_top = above ? hi + 1 : current_top;
+    const UInt64 needed_bits = static_cast<UInt64>(target_top) - static_cast<UInt64>(target_min);
+    UInt64 needed_words = (needed_bits + BITSET_WORD_BITS - 1) / BITSET_WORD_BITS;
+    if (needed_words > bitset_max_words)
+        return false;
+
+    /// Grow geometrically upwards so a key column arriving in sorted order does not reallocate per
+    /// block - but never SPECULATIVELY past half the budget. A window that has already spent the
+    /// whole budget cannot be widened in the other direction, so one key below the range the first
+    /// block happened to start at would force the bloom fallback even when the real key envelope
+    /// fits: a 60M-value key range needs 7.5 MB, but doubling from 4.7 MB lands on an 8 MiB window
+    /// anchored above the eventual minimum. Growth to cover keys that have actually arrived still
+    /// uses the full budget.
+    const UInt64 word_offset = (static_cast<UInt64>(bitset_min) - static_cast<UInt64>(target_min)) / BITSET_WORD_BITS;
+    const UInt64 speculative_words = bitset_max_words / 2;
+    if (needed_words <= speculative_words)
+        needed_words = std::max(needed_words, std::min(speculative_words, static_cast<UInt64>(bitset.size()) * 2));
+    needed_words = std::max(needed_words, word_offset + static_cast<UInt64>(bitset.size()));
+    if (needed_words > bitset_max_words)
+        return false;
+
+    std::vector<UInt64> widened(needed_words, 0);
+    std::copy(bitset.begin(), bitset.end(), widened.begin() + word_offset);
+    bitset.swap(widened);
+    bitset_min = target_min;
+    bitset_bits = needed_words * BITSET_WORD_BITS;
+    return true;
+}
+
+void DenseBitsetRuntimeFilter::setBits(const IColumn & column)
+{
+    UInt64 * const words = bitset.data();
+    const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+    const bool dispatched = dispatchNativeIntColumn(column, [&](const auto & data)
+    {
+        for (const auto value : data)
+        {
+            const UInt64 index = static_cast<UInt64>(static_cast<Int64>(value)) - min_as_words;
+            chassert(index < bitset_bits);
+            words[index / BITSET_WORD_BITS] |= 1ULL << (index % BITSET_WORD_BITS);
+        }
+    });
+    if (!dispatched)
+    {
+        const size_t rows = column.size();
+        for (size_t row = 0; row < rows; ++row)
+        {
+            const UInt64 index = static_cast<UInt64>(column.getInt(row)) - min_as_words;
+            chassert(index < bitset_bits);
+            words[index / BITSET_WORD_BITS] |= 1ULL << (index % BITSET_WORD_BITS);
+        }
+    }
+}
+
+ColumnPtr DenseBitsetRuntimeFilter::find(const ColumnWithTypeAndName & values, std::optional<size_t> & rows_passed) const
+{
+    const size_t rows = values.column->size();
+    auto dst = ColumnVector<UInt8>::create();
+    auto & dst_data = dst->getData();
+    dst_data.resize(rows);
+
+    ColumnPtr probe = values.column->convertToFullColumnIfConst();
+    probe = probe->convertToFullColumnIfSparse();
+
+    const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+    const UInt64 * const words = bitset.data();
+    const UInt64 bits = bitset_bits;
+    size_t found_count = 0;
+
+    /// A value maps into [0, bits) exactly when it lies in the covered range, so an index that
+    /// falls outside it is a definite miss: the bitset is exact over the whole range.
+    const bool dispatched = dispatchNativeIntColumn(*probe, [&](const auto & data)
+    {
+        for (size_t row = 0; row < rows; ++row)
+        {
+            const UInt64 index = static_cast<UInt64>(static_cast<Int64>(data[row])) - min_as_words;
+            const UInt8 result = index < bits ? ((words[index / BITSET_WORD_BITS] >> (index % BITSET_WORD_BITS)) & 1u) : 0u;
+            dst_data[row] = result;
+            found_count += result;
+        }
+    });
+
+    if (!dispatched)
+    {
+        for (size_t row = 0; row < rows; ++row)
+        {
+            const UInt64 index = static_cast<UInt64>(probe->getInt(row)) - min_as_words;
+            const UInt8 result = index < bits ? ((words[index / BITSET_WORD_BITS] >> (index % BITSET_WORD_BITS)) & 1u) : 0u;
+            dst_data[row] = result;
+            found_count += result;
+        }
+    }
+
+    rows_passed = found_count;
+    return dst;
+}
+
+ColumnPtr DenseBitsetRuntimeFilter::getValuesColumn() const
+{
+    MutableColumnPtr column = filter_column_target_type->createColumn();
+    const UInt64 min_as_words = static_cast<UInt64>(bitset_min);
+    const bool dispatched = dispatchNativeIntMutableColumn(*column, [&](auto & data)
+    {
+        using Container = std::decay_t<decltype(data)>;
+        using T = typename Container::value_type;
+        for (size_t word_index = 0; word_index < bitset.size(); ++word_index)
+        {
+            UInt64 word = bitset[word_index];
+            while (word)
+            {
+                const UInt64 bit = static_cast<UInt64>(std::countr_zero(word));
+                word &= word - 1;
+                const UInt64 value = min_as_words + word_index * BITSET_WORD_BITS + bit;
+                data.push_back(static_cast<T>(value));
+            }
+        }
+    });
+    if (!dispatched)
+        throw Exception(ErrorCodes::LOGICAL_ERROR, "Runtime filter bitset holds a non native integer key type");
+    return column;
+}
+
 bool AdaptiveSetRuntimeFilter::isDataTypeSupported(const DataTypePtr & data_type)
 {
     return ApproximateSetRuntimeFilter::isDataTypeSupported(data_type);
@@ -528,6 +837,7 @@ AdaptiveSetRuntimeFilter::AdaptiveSetRuntimeFilter(
     , max_ratio_of_set_bits_in_bloom_filter(max_ratio_of_set_bits_in_bloom_filter_)
     , distinct_keys_hint(distinct_keys_hint_)
     , distinct_keys_hint_matches_filter_key(distinct_keys_hint_matches_filter_key_)
+    , bytes_limit(bytes_limit_)
     , filter(std::in_place_type<ExactFilter>, filter_column_target_type_, bytes_limit_, exact_values_limit_)
 {
 }
@@ -548,6 +858,18 @@ void AdaptiveSetRuntimeFilter::insert(ColumnPtr values, Filter & filter_)
         return;
     }
 
+    if (auto * bitset_filter = std::get_if<DenseBitsetRuntimeFilter>(&filter_))
+    {
+        if (bitset_filter->insert(values, denseBitsetMaxBytes(bitset_filter->getInsertedKeyRows() + values->size())))
+            return;
+
+        /// The key range no longer fits the allowance: every key recorded so far is recovered from
+        /// the bits into a bloom filter, and this block is inserted there too, so no key is lost.
+        if (auto * approximate_filter = switchToApproximateFilter(filter_))
+            approximate_filter->insert(std::move(values));
+        return;
+    }
+
     auto * exact_filter = std::get_if<ExactFilter>(&filter_);
     if (!exact_filter || exact_filter->isFull())
         throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected state of AdaptiveSetRuntimeFilter");
@@ -555,7 +877,7 @@ void AdaptiveSetRuntimeFilter::insert(ColumnPtr values, Filter & filter_)
     exact_filter->insert(std::move(values));
 
     if (exact_filter->isFull())
-        switchToApproximateFilter(filter_);
+        switchFromExactFilter(filter_);
 }
 
 void AdaptiveSetRuntimeFilter::finishInsert(RuntimeFilterEvaluationState & evaluation_state)
@@ -563,6 +885,11 @@ void AdaptiveSetRuntimeFilter::finishInsert(RuntimeFilterEvaluationState & evalu
     std::visit(
         Overloaded{
             [](ExactFilter & exact_filter) { exact_filter.finishInsert(); },
+            [](DenseBitsetRuntimeFilter &)
+            {
+                /// A bitset has no false positives, so there is no fill rate to check: poor real
+                /// selectivity is still caught by the shared probe-side pass-ratio heuristic.
+            },
             [&](ApproximateSetRuntimeFilter & approximate_filter)
             { checkApproximateFilterWorthiness(evaluation_state, approximate_filter); },
             [&](KeySetDropped &) { evaluation_state.markKeySetDropped(); },
@@ -590,6 +917,7 @@ ColumnPtr AdaptiveSetRuntimeFilter::find(const ColumnWithTypeAndName & values, s
     return std::visit(
         Overloaded{
             [&](const ExactFilter & exact_filter) -> ColumnPtr { return exact_filter.find(values, rows_passed); },
+            [&](const DenseBitsetRuntimeFilter & bitset_filter) -> ColumnPtr { return bitset_filter.find(values, rows_passed); },
             [&](const ApproximateSetRuntimeFilter & approximate_filter) -> ColumnPtr
             { return approximate_filter.find(values, rows_passed); },
             [&](const KeySetDropped &) -> ColumnPtr
@@ -613,6 +941,12 @@ void AdaptiveSetRuntimeFilter::mergeFrom(const AdaptiveSetRuntimeFilter & source
     std::visit(
         Overloaded{
             [&](const ExactFilter & source_exact_filter) { insert(source_exact_filter.getValuesColumn(), filter); },
+            [&](const DenseBitsetRuntimeFilter & source_bitset_filter)
+            {
+                /// The bits hold the keys exactly, so they can be replayed through the normal insert
+                /// path, which keeps this filter in whatever representation it is already using.
+                insert(source_bitset_filter.getValuesColumn(), filter);
+            },
             [&](const ApproximateSetRuntimeFilter & source_approximate_filter)
             {
                 if (auto * destination_approximate_filter = switchToApproximateFilter(filter))
@@ -635,16 +969,20 @@ ApproximateSetRuntimeFilter * AdaptiveSetRuntimeFilter::switchToApproximateFilte
     if (std::holds_alternative<KeySetDropped>(filter_))
         return nullptr;
 
-    auto * exact_filter = std::get_if<ExactFilter>(&filter_);
-    if (!exact_filter)
+    ColumnPtr values;
+    if (auto * exact_filter = std::get_if<ExactFilter>(&filter_))
+        values = exact_filter->getValuesColumn();
+    else if (auto * bitset_filter = std::get_if<DenseBitsetRuntimeFilter>(&filter_))
+        values = bitset_filter->getValuesColumn();
+    else
         throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected state of AdaptiveSetRuntimeFilter");
-    auto values = exact_filter->getValuesColumn();
-    UInt64 bytes_limit = exact_filter->getBytesLimit();
+
+    UInt64 bloom_filter_bytes = bytes_limit;
 
     if (distinct_keys_hint)
     {
-        bytes_limit
-            = growBloomFilterBytes(*distinct_keys_hint, bloom_filter_hash_functions, bytes_limit, max_ratio_of_set_bits_in_bloom_filter);
+        bloom_filter_bytes = growBloomFilterBytes(
+            *distinct_keys_hint, bloom_filter_hash_functions, bloom_filter_bytes, max_ratio_of_set_bits_in_bloom_filter);
 
         /// The filter size is capped, so a build side with more distinct keys would produce a Bloom filter
         /// that `checkApproximateFilterWorthiness` discards. Predict that fill rate before constructing it.
@@ -654,7 +992,7 @@ ApproximateSetRuntimeFilter * AdaptiveSetRuntimeFilter::switchToApproximateFilte
                 = static_cast<double>(*distinct_keys_hint) / HashJoinEntry::MAX_OVERESTIMATION_FACTOR;
             const double predicted_fill_rate = -std::expm1(
                 -static_cast<double>(bloom_filter_hash_functions) * least_distinct_keys
-                / (static_cast<double>(bytes_limit) * 8.0));
+                / (static_cast<double>(bloom_filter_bytes) * 8.0));
             if (predicted_fill_rate > max_ratio_of_set_bits_in_bloom_filter)
             {
                 ProfileEvents::increment(ProfileEvents::RuntimeFilterBloomFilterBuildsSkipped);
@@ -664,11 +1002,71 @@ ApproximateSetRuntimeFilter * AdaptiveSetRuntimeFilter::switchToApproximateFilte
         }
     }
 
-    auto & approximate_filter = filter_.emplace<ApproximateSetRuntimeFilter>(bytes_limit, bloom_filter_hash_functions);
+    auto & approximate_filter = filter_.emplace<ApproximateSetRuntimeFilter>(bloom_filter_bytes, bloom_filter_hash_functions);
     approximate_filter.insert(values);
     return &approximate_filter;
 }
 
+void AdaptiveSetRuntimeFilter::switchFromExactFilter(Filter & filter_)
+{
+    /// The dense bitset is tried first: it is exact like the set it replaces, its probe is cheaper
+    /// than a bloom filter's, and it is most valuable exactly where the bloom filter would be
+    /// predicted saturated and dropped below.
+    if (trySwitchToDenseBitsetFilter(filter_))
+        return;
+
+    switchToApproximateFilter(filter_);
+}
+
+bool AdaptiveSetRuntimeFilter::trySwitchToDenseBitsetFilter(Filter & filter_)
+{
+    if (!DenseBitsetRuntimeFilter::isDataTypeSupported(filter_column_target_type))
+        return false;
+
+    auto * exact_filter = std::get_if<ExactFilter>(&filter_);
+    if (!exact_filter)
+        return false;
+
+    const ColumnPtr values = exact_filter->getValuesColumn();
+    DenseBitsetRuntimeFilter bitset_filter(filter_column_target_type);
+    if (!bitset_filter.tryInitialize(values, denseBitsetMaxBytes(values->size())))
+        return false;
+
+    filter_.emplace<DenseBitsetRuntimeFilter>(std::move(bitset_filter));
+    return true;
+}
+
+UInt64 AdaptiveSetRuntimeFilter::denseBitsetMaxBytes(UInt64 observed_key_rows) const
+{
+    /// The exact bitset gets a larger memory allowance than the bloom filter it replaces, because
+    /// what it buys is paid per PROBE row: no hashing at all, one shifted load, and no false
+    /// positives. A surrogate key is usually sparse - TPC-H l_orderkey has ~15M values over a 60M
+    /// range - so requiring the bitset to be no bigger than the keys themselves (break-even is
+    /// span <= 64 x keys for a 64-bit key) would reject exactly the large probe sides where the
+    /// saving is worth most. The allowance is a fixed multiple of the user's filter memory setting,
+    /// so lowering join_runtime_bloom_filter_bytes still lowers it.
+    ///
+    /// It is raised further when the keys themselves would occupy more than that, because then the
+    /// bitset is the cheaper exact representation anyway, and it is always capped: a range that
+    /// needs more than BITSET_HARD_CAP_BYTES keeps the bloom filter.
+    static constexpr UInt64 BITSET_HARD_CAP_BYTES = 32 * 1024 * 1024;
+    static constexpr UInt64 MAX_TRUSTED_DISTINCT_KEYS_HINT = 1000000000;
+    static constexpr UInt64 EXACT_BITSET_BYTES_PER_BLOOM_BYTE = 16;
+
+    /// The observed key rows are an upper bound on the distinct keys this filter has to represent
+    /// and are always available. The statistics hint only raises that count, and only when it
+    /// counts distinct values of this complete filter key: an upper bound taken over a wider key
+    /// would inflate the allowance of a filter that does not need it.
+    UInt64 keys = observed_key_rows;
+    if (distinct_keys_hint && distinct_keys_hint_matches_filter_key && *distinct_keys_hint <= MAX_TRUSTED_DISTINCT_KEYS_HINT)
+        keys = std::max(keys, *distinct_keys_hint);
+
+    UInt64 budget = std::min(bytes_limit, BITSET_HARD_CAP_BYTES) * EXACT_BITSET_BYTES_PER_BLOOM_BYTE;
+    if (keys != 0)
+        budget = std::max(budget, keys * filter_column_target_type->getSizeOfValueInMemory());
+    return std::min(budget, BITSET_HARD_CAP_BYTES);
+}
+
 void AdaptiveSetRuntimeFilter::checkApproximateFilterWorthiness(
     RuntimeFilterEvaluationState & evaluation_state, const ApproximateSetRuntimeFilter & approximate_filter) const
 {
diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.h b/src/Processors/QueryPlan/RuntimeFilterLookup.h
index 5f4e54e0ce9..0dd8867438c 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.h
+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.h
@@ -190,6 +190,55 @@ private:
     BloomFilter bloom_filter;
 };
 
+/// Exact runtime filter that represents native integer keys as one bit per value of the covered
+/// range. A probe is a single shifted load: no hashing, and no false positives, so the filter also
+/// passes fewer rows downstream than a bloom filter holding the same keys. Used instead of the
+/// bloom filter whenever the observed key range fits the bitset's byte budget.
+class DenseBitsetRuntimeFilter
+{
+public:
+    static constexpr bool is_prebuilt = false;
+
+    static bool isDataTypeSupported(const DataTypePtr & data_type);
+
+    explicit DenseBitsetRuntimeFilter(const DataTypePtr & filter_column_target_type_);
+
+    /// Covers the values of `values` with a bitset of at most `max_bytes` bytes. Returns false when
+    /// the key range does not fit, leaving this object unusable, so the caller keeps the bloom filter.
+    bool tryInitialize(const ColumnPtr & values, UInt64 max_bytes);
+
+    /// Returns false when the keys can no longer be represented within `max_bytes`. The caller then
+    /// recovers every key with `getValuesColumn()`, falls back to a bloom filter, and inserts
+    /// `values` there as well: the block that did not fit is not recorded by this call.
+    bool insert(const ColumnPtr & values, UInt64 max_bytes);
+
+    /// `rows_passed` is always set: the probe counts the matches while filling the mask.
+    ColumnPtr find(const ColumnWithTypeAndName & values, std::optional<size_t> & rows_passed) const;
+
+    /// The exact keys held by the bits, used when merging with a filter in another representation.
+    ColumnPtr getValuesColumn() const;
+
+    DataTypePtr getTargetType() const { return filter_column_target_type; }
+    UInt64 getInsertedKeyRows() const { return inserted_key_rows; }
+    UInt64 getBytes() const { return bitset.size() * sizeof(UInt64); }
+
+private:
+    bool extendRange(Int64 lo, Int64 hi);
+    void setBits(const IColumn & column);
+
+    DataTypePtr filter_column_target_type;
+
+    /// One bit per value of [bitset_min, bitset_min + bitset_bits). `bitset_min` is kept aligned to
+    /// a 64-bit word so the covered range can be widened by whole words, without shifting bits.
+    std::vector<UInt64> bitset;
+    Int64 bitset_min = 0;
+    UInt64 bitset_bits = 0;
+    UInt64 bitset_max_words = 0;
+    /// Key rows recorded so far. The memory allowance is derived from it, so the budget grows only
+    /// when the observed data justifies it.
+    UInt64 inserted_key_rows = 0;
+};
+
 /// Starts with an exact set and switches to an approximate set once the exact set becomes too large.
 class AdaptiveSetRuntimeFilter
 {
@@ -220,11 +269,17 @@ private:
     struct KeySetDropped
     {
     };
-    using Filter = std::variant<ExactFilter, ApproximateSetRuntimeFilter, KeySetDropped>;
+    using Filter = std::variant<ExactFilter, DenseBitsetRuntimeFilter, ApproximateSetRuntimeFilter, KeySetDropped>;
 
     void insert(ColumnPtr values, Filter & filter);
     void dropKeySet(Filter & filter);
     ApproximateSetRuntimeFilter * switchToApproximateFilter(Filter & filter);
+    /// Leaves the exact set for the cheapest representation that can hold its keys: the exact dense
+    /// bitset when the key range fits its allowance, the bloom filter otherwise.
+    void switchFromExactFilter(Filter & filter);
+    bool trySwitchToDenseBitsetFilter(Filter & filter);
+    /// Memory allowance of the dense bitset, given the key rows observed so far.
+    UInt64 denseBitsetMaxBytes(UInt64 observed_key_rows) const;
 
     /// Disables approximate filter if it is likely to have bad selectivity.
     void checkApproximateFilterWorthiness(
@@ -237,6 +292,8 @@ private:
     const std::optional<UInt64> distinct_keys_hint;
     /// Whether the hint counts distinct values of this complete filter key, rather than only providing an upper bound.
     const bool distinct_keys_hint_matches_filter_key;
+    /// Byte budget of one filter, as configured by `join_runtime_bloom_filter_bytes`.
+    const UInt64 bytes_limit;
 
     Filter filter;
 };
-- 
2.43.0

@cv4g

cv4g commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

This PR should merge after #120232 which moves certain code parts into place as a preparatory step

@cv4g

cv4g commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

@snelheidai Thank you, that is a very interesting idea. Please open a PR based on current master and tag me on it. I am happy to review the change set and look forward to the CI Benchmark Suite results. Please try to avoid defining the CHPERF_DISPATCH_NATIVE_INT macro and check if you can go with another template meta programming alternative.

…-filter

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)
- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp`
- `src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp`
- `src/Processors/QueryPlan/RuntimeFilterBuildOptions.h`
- `src/Processors/QueryPlan/RuntimeFilterLookup.cpp`
- `src/Processors/QueryPlan/RuntimeFilterTypes.h`
- `src/Processors/Transforms/BuildRuntimeFilterTransform.cpp`
- `src/Processors/benchmarks/benchmark_runtime_filter.cpp`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
settings[QueryPlanSerializationSetting::join_runtime_filter_pass_ratio_threshold_for_disabling] = pass_ratio_threshold_for_disabling;
settings[QueryPlanSerializationSetting::join_runtime_filter_blocks_to_skip_before_reenabling] = blocks_to_skip_before_reenabling;
settings[QueryPlanSerializationSetting::join_runtime_bloom_filter_max_ratio_of_set_bits] = build_options.max_ratio_of_set_bits;
settings[QueryPlanSerializationSetting::join_runtime_filter_use_minmax]

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.

RuntimeFilterMinMaxMode is now a per-step three-state contract, but serialization still collapses it to the legacy plan-global boolean here and deserialize turns any true back into Combined. That means the round-trip can no longer preserve what was actually planned: a MinMaxOnly step comes back as combined, and a plan with mixed runtime-filter steps (for example one numeric key and one String key) can only deserialize one global minmax choice, so at least one placeholder step reports the wrong mode.

Please serialize the enum per step, or keep deserialized BuildRuntimeFilterStep explicitly mode-blind instead of reconstructing a specific minmax mode.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Evaluate MIN/MAX join runtime filters

6 participants