Skip to content

Switch the JOIN runtime filter from its exact set at the first key past the limit - #133383

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:adaptive-runtime-filter-switch-at-first-new-key
Nov 22, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:adaptive-runtime-filter-switch-at-first-new-key

Conversation

@groeneai

@groeneai groeneai commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #133269
Related: #129092

Changelog category (leave one):

  • Performance Improvement

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

The JOIN runtime filter stops filling its exact set at the first new key past join_runtime_filter_exact_values_limit, instead of inserting the whole block before it switches to a Bloom filter or a dense bitset. This lowers the memory and time of building the filter when a build-side block has many distinct keys.

Description

AdaptiveSetRuntimeFilter::insert put the whole block into the exact set and checked the limit only afterwards, so the hash table and the set elements grew to the block's distinct-key count, although the replacement's size does not depend on it (#133269 review).

Change: an overload of Set::insertFromColumns takes a key cap, checked in the bulk insert loop only after a new key. It stops after the row whose key makes the set hold more than the cap, so the exact set holds at most limit + 1 keys (the existing "full" threshold), and reports the rows it took. The replacement (dense bitset or Bloom filter, chosen as before) takes the exact keys plus the rest of the block. An exact-set-only positive filter (e.g. Nullable keys) stops too, as it drops a full set; NOT IN keeps every key of the block, as before. Duplicates run the same code; IN sets pass no cap and pay one compare per new key.

If building the replacement throws (memory limit), the exact set keeps the rows up to and including the first key past the limit, and the exception fails the query; the next insert retries the switch, as in #133269.

Peak memory of one insert (default geometry, distinct UInt64 keys), master -> PR: 65,409 rows 3,088 -> 1,552 KiB; 1M rows 41,936 -> 9,312 KiB. The rest is mostly the existing block-sized reserve in Set::appendSetElements, shared with IN sets.

Release A/B, PR / master: one block of 1M distinct build keys, filter build 0.23, query 0.86; duplicate-heavy builds (number % 10000 and % 9000, 20M rows) within noise; IN subqueries 1.00-1.03.

Validation: gtests for duplicates at the limit then new keys, the reported row count, replacements starting at that row, NOT IN, and a refused Bloom filter allocation (red on master); the #133269 retry test is unchanged.


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

Version info

  • Merged into: 26.12.1.217-master (included in 26.12 and later)

groeneai and others added 3 commits November 21, 2026 04:26
…y past the limit

`AdaptiveSetRuntimeFilter::insert` inserted the whole block into the exact set and only
then checked `exact_values_limit`, so a block with many distinct keys grew the exact set's
hash table and set elements to the block's distinct-key count before the switch to the dense
bitset or Bloom filter, whose size does not depend on that count.

`Set::insertFromColumns` gets an optional `max_keys`: once the set holds that many keys, rows
with keys it already has are still taken and the first row with a new key stops the insert.
The capped loop is a separate out-of-line function chosen once per block, only when the block
can reach the cap, so `IN` sets run the unchanged bulk loop. The adaptive filter inserts with
`max_keys = exact_values_limit` and switches when the insert stopped (or the set is full by
bytes); the replacement is filled locally from the exact keys and the whole block, then moved
in, so a refused allocation leaves the exact set with the rows before the first new key past
the limit. ClickHouse#133269's retry of a full exact set folds into the same condition.

Tests: duplicates at the limit then new keys, on success (dense bitset) and with a refused
Bloom allocation; ClickHouse#133269's retry test no longer expects the refused key in the filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t loop

The out-of-line capped loop was taken for practically every block of a
runtime filter build (the default limit is 10000 keys, blocks are 65409
rows), and its per-row bookkeeping made duplicate-heavy filter builds
1.29-1.35x slower. It is removed.

Set::insertFromBlockImplCase now checks the cap only right after a key was
newly inserted and stops after the row whose key makes the set hold more
than the cap. Rows whose key is already in the set run the same code as
before, and IN sets, which pass no cap, pay one compare per new key. The
exact set holds at most exact_values_limit + 1 keys, which is the existing
"full" threshold, so the retry after a refused switch from ClickHouse#133269 and its
test stay as they are; the replacement takes the exact keys plus the whole
block. If its allocation is refused, the exact set holds the rows up to
and including the first key past the limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comment on where the key cap is checked in Set::insertFromBlockImplCase; fold the retry comment in AdaptiveSetRuntimeFilter::insert back to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding), plus one point from my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ AdaptiveFilterSwitchesAtTheFirstNewKeyPastTheLimit passes on master, so it does not pin the early stop DISAGREE The stop is pinned by AdaptiveFilterKeepsTheRowsUpToTheFirstNewKeyWhenItsSwitchThrows (mask {1, 1, 1, 0}), which fails on master at row 3 and when the stop is removed. On success the stop changes only memory; the first test covers that side.
2 💡 No tests/performance change DISAGREE The gain is the peak memory of one insert, which the performance comparison does not report, and the build time of blocks with many distinct keys. join_runtime_filter.xml already runs the adaptive filter's insert path.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261121-060701

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The gtest AdaptiveFilterKeepsTheRowsUpToTheFirstNewKeyWhenItsSwitchThrows fails on master (key 8 passes the filter because the whole block entered the exact set) and passes here. A peak-memory probe of one insert is deterministic: 1M distinct UInt64 keys need 41,936 KiB on master, 9,312 KiB here.
b Root cause explained? AdaptiveSetRuntimeFilter::insert inserted the whole block into the exact set and checked join_runtime_filter_exact_values_limit only afterwards, so the hash table and set elements grew to the block's distinct-key count, while the replacement's size does not depend on it.
c Fix matches root cause? Yes. The bulk insert loop stops after the key that makes the set exceed the cap, checked only after a new key, and the replacement takes the exact keys plus the whole block.
d Test intent preserved / new tests added? Two new gtests: duplicates at the limit then new keys (dense bitset), and a refused Bloom filter allocation (the set keeps the rows up to the first new key). The #133269 retry test is unchanged. Mutations of the stop, of each replacement's block insert, and of the boundary (> to >=) each turn a test red.
e Both directions demonstrated? Yes: the refused-allocation gtest and the peak probe, on master and on this branch.
f Fix is general across code paths? Only the adaptive filter passes a cap; plain exact-set filters and IN sets pass none. Both replacements (dense bitset, Bloom filter) take the block; the retry after a refused switch passes none. The runtime filter's set never spills, so the spill path, which ignores the cap, is not reached.
g Fix generalizes across inputs (params/datatypes/wrappers)? The check is in the one loop template every Set method instantiates, with and without a null map; NULL keys are skipped before it as before. Nullable and LowCardinality are stripped before the loop. Boundary: a set at exactly the limit does not switch, the next new key does. Tested with UInt16 (dense bitset) and UInt64 (Bloom filter).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default changes; the exact set holds at most limit + 1 keys, the existing "full" threshold, so serialized filters see no new state.
i Invariants and contracts preserved? Set elements match the hash table (the filter is zeroed after the stop row); the key range still takes the whole block; #133269's fill-then-nothrow-move is kept for both replacements. A refused allocation leaves the set holding the rows up to and including the first key past the limit, and the next insert retries the switch.

Session id: cron:clickhouse-impl-slot-4:20261121-052100

@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf61d33]

Summary: ✅


AI Review

Summary

The PR bounds positive JOIN runtime filters' exact sets at the first key beyond join_runtime_filter_exact_values_limit, then fills the replacement from the retained keys and the unconsumed block suffix. Reviewed head cf61d330510c15d20de2f743aab8b187c5dedd6c, including all prior discussion and the latest revisions. No actionable findings.

Missing context / blind spots
  • ⚠️ C++ tests and benchmarks were not rerun locally because this checkout has no configured build or test binary. Validation relies on the supplied regression tests and before/after measurements, plus current-head fast-test CI: 79 runtime-filter tests passed, 11 skipped, none failed.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cf61d3305 with master 3232ee3c9 (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.

Compile time of recompiled translation units

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

Job report

@stresshouse

stresshouse Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

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

This PR changes how IN-sets and join runtime filters take keys. They now stop at the first new key past the limit, and the replacement dense bitset or Bloom filter takes the rest of the block. The only flagged query, clickbench Q30 (+17.5%, 160 ms to 188 ms), was held back as inconclusive because it falls within master's own variance. That decision is consistent with the data: 188 ms sits inside master's recent 152-205 ms range, the baseline was near the low end of that range, and this query's history is noisy. Q30 is a plain GROUP BY with no IN or join, so it does not run the changed code, and the result shows no performance effect from this PR.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 160 188 +17.5% <0.0001 aggregation: Q30 is a plain filtered two-key GROUP BY with no IN-set or join, so it never runs the changed Set or runtime-filter insert code. Its 188 ms sits inside master's recent 152-205 ms range.

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: e401f927-2dce-4c63-891e-d1260aa858df
  • MIRAI run: 61544a54-32bb-4d5d-b296-8bc3c7a711e1
  • PR check IDs:
    • clickbench_885988_1795393368
    • clickbench_886096_1795393374
    • tpch_adapted_1_official_886227_1795393442
    • tpch_adapted_1_official_886357_1795393456

@snelheidai

Copy link
Copy Markdown

@cv4g

Repeated iteration: it is redundant, not needed for correctness. The replacement first inserts the exact set's keys, which include every key of the rows the set took, and Bloom filter and bitset inserts only set bits, so those rows add nothing the second time. Only the rows after the stopping row need the block insert.

A row count would save one Bloom or bitset insert per row of that prefix, once per filter: at most 10,001 rows (join_runtime_filter_exact_values_limit + 1) when the keys are distinct, and up to the whole block when the block repeats keys or the set fills on its byte limit.

Callers: no. Set::insertFromColumns is also called by Set::insertFromBlock (IN subqueries in CreatingSetsTransform, and StorageSet), by CreatingSetsOnTheFlyTransform and InverseDictionaryLookupPass, and through the holder overload by FutureSetFromTuple (literal IN tuples). None passes a cap. CreatingSetsTransform and CreatingSetsOnTheFlyTransform stop filling their set on false, so a plain size_t return would lose that signal.

…t did not take

`Set::insertFromColumns` gains an overload that reports how many rows it took
before it stopped at `max_keys` (the row with the key that filled the set
included); `ExactSetRuntimeFilter::insertUntilFull` returns that count. The
dense bitset or Bloom filter that replaces the full exact set is filled from
the exact keys plus the rows of the block after that count, so the rows the
exact set already took are no longer hashed a second time.

The other `insertFromColumns` callers (`CreatingSetsTransform` through
`insertFromBlock`, `CreateSetAndFilterOnTheFlyTransform`,
`InverseDictionaryLookupPass`, `PreparedSets`) keep the overload that returns
the IN-set limit result and does not cap keys.

The failure contract is unchanged: the replacement is filled before it
replaces the exact set, so a refused allocation leaves the set holding the
rows it took. Tests: the dense bitset test now has a new key right after the
key that fills the set (an off-by-one in the offset reddens it), a new test
covers the same boundary for the Bloom filter, and another pins the count that
`insertUntilFull` returns, which membership alone cannot show.

Review: ClickHouse#133383 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Set.h Resolved
Comment thread src/Interpreters/Set.cpp Resolved
…rity

ExactSetRuntimeFilter::insert now returns the rows it took and passes the cap to
Set::insertFromColumns itself, so insertUntilFull and insertKeys(max_keys) are gone.
A positive set stops after the key that makes it full: a full positive set is released
in finishInsert, so the rest of the block was never used (this now also bounds the
non-adaptive ExactContains filter, e.g. Nullable keys). NOT IN (ExactNotContains)
filters by every key of a full set, so it stays uncapped, as before
(05817: "partial exact set, 1000 unique keys" at exact_values_limit = 100).

The std::fill in Set::insertFromBlockImplCase zeroes the filter of the rows after the
stop: SetKeyColumns::filter is created uninitialized and appendSetElements filters the
whole block with it. The count test now checks the set elements; without the fill it
holds 4 values instead of 3.

A new test inserts into a dense bitset and a Bloom filter from a nonzero first_row
and checks that the rows before it are absent (starting at row 0 reddens it).

Removed the two API comments the review asked to drop.

Review: ClickHouse#133383 (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
…of the fuzzer log

The La Casa Del Dolor job fails the run as `dolor.py exception` when
`Traceback (most recent call last):` appears in the last 20000 characters
of fuzzer.log (dolor.py's stdout and stderr), whatever dolor.py's exit
code. Four handlers in tests/casa_del_dolor/catalogs ignore an error on
purpose but called traceback.print_exc() before self.logger.exception(e),
so every ignored error also went to stderr as a traceback.

Since ClickHouse#131994 enabled RabbitMQ, Kafka and NATS in the job, the two
streamingtest.py handlers run in CI, and the fuzzed exchange redeclare
with a random type routinely gets 406 PRECONDITION_FAILED from the broker.
That made La Casa Del Dolor (amd_debug) red on PR ClickHouse#133383 although
dolor.py and the server both exited 0: the last ignored traceback started
14.8 KB before the end of fuzzer.log.

logger.exception already writes the message and the traceback to
dolor.log (dolor.py routes the root logger to --log-path only), so
print_exc() was a duplicate. Remove it at all four sites (streamingtest.py
create_table/update_table, tablecheck.py check_table, datagenerator.py
update_table; the last two are Spark-only and not run in CI yet) together
with the then unused `import traceback`. The safety net is unchanged and
still reports an exception nobody caught.

Validated locally by calling the four real handlers with the error
injected and the job's check applied to their output: on master all four
trip it, with the change stderr stays empty and dolor.log keeps the
traceback. No test for the test infrastructure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov 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.

Looks alright.

@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 22, 2026
Merged via the queue into ClickHouse:master with commit 19f5e0a Nov 22, 2026
195 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants