Skip to content

Keep the JOIN runtime filter usable when its switch to a Bloom filter hits the memory limit - #133269

Merged
cv4g merged 3 commits into
ClickHouse:masterfrom
groeneai:adaptive-runtime-filter-keep-exact-set-on-throw
Nov 21, 2026
Merged

cv4g merged 3 commits into
ClickHouse:masterfrom
groeneai:adaptive-runtime-filter-keep-exact-set-on-throw

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129092
Related: #129186

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

When the memory limit refuses the Bloom filter that AdaptiveSetRuntimeFilter switches to once its exact set overflows, the next block of the same build stream throws LOGICAL_ERROR "Unexpected state of AdaptiveSetRuntimeFilter", which aborts debug and sanitizer builds. Release builds return MEMORY_LIMIT_EXCEEDED either way, so there is no user-visible change. BuzzHouse randomizes all three ingredients (join_runtime_bloom_filter_bytes, join_runtime_filter_exact_values_limit, max_memory_usage).

Root cause: switchToApproximateFilter emplaced the Bloom filter into the variant, so std::variant::emplace destroyed the exact set before the constructor allocated the buffer; the refusal left the variant valueless. BuildRuntimeFilterTransform is an ISimpleTransform, which passes the exception downstream and keeps feeding blocks into the same filter. The mergeFrom path (a Bloom filter source) uses the same function.

Change: build and fill the Bloom filter in a local, then move it in (nothrow, as switchToDenseBitset already does), so a refused allocation keeps the exact set. A full exact set on the next insert now retries the switch; the full set still holds every key. No exception is caught. The exact set is now freed only after the Bloom filter is filled, so the switch briefly holds both; the exact set is capped by the exact-set limits (for a local filter, about the Bloom filter's size).

#129186 had this fix; the scope cut in af3c523 dropped it along with the dense-bitset memory handling.

Validation: two gtests (insert path, merge path) abort on master and pass with the fix; each half of the change alone leaves the insert test red. A SQL repro with max_threads = 32, max_block_size = 64, max_memory_usage = 80000000 and a 16 MiB Bloom filter aborted a master debug build 14/200 times and the fixed build 0/200.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits November 20, 2026 13:32
… hits the memory limit

`AdaptiveSetRuntimeFilter::switchToApproximateFilter` emplaced the Bloom
filter into the variant directly. `std::variant::emplace` destroys the exact
set first and then runs the constructor, which allocates the Bloom filter's
buffer through the memory tracker. When the memory limit refuses it, the
variant is left valueless. `BuildRuntimeFilterTransform` is an
`ISimpleTransform`, which passes the exception downstream and keeps pulling
blocks into the same filter, so the next block threw LOGICAL_ERROR
"Unexpected state of AdaptiveSetRuntimeFilter" and aborted debug and
sanitizer builds. The merge path (`mergeFrom` with a Bloom filter source)
went through the same function.

Build and fill the Bloom filter in a local and only then move it into the
variant, as `switchToDenseBitset` already does; the move is nothrow
(static_assert), so a refused allocation now leaves the exact set in place.
A full exact set on the next insert then means the previous switch threw;
it still holds every key (`ExactSetRuntimeFilter::insert` inserts the block
before setting `is_full`), so retry the switch instead of throwing.

The exception still reaches the user unchanged; only the state the filter is
left in changes. The transient peak during the switch grows by the exact
set's own buffers, bounded by `exact_bytes_limit`.

ClickHouse#129186 had this fix (9a9df77 + 9583f6a); the scope cut af3c523 dropped it
together with the dense-bitset memory handling.

Related: ClickHouse#129092
Related: ClickHouse#129186

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new gtests now assert that the probe is checked, not skipped: a variant
that dropped the key set on a refused allocation also passed their all-true
masks.

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; 2 rounds, 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ Both new gtests end with an all-true mask, so a variant that drops the key set on a refused allocation would pass them too AGREE, fixed @ a84704c Both tests now also assert rows_checked == probe size and rows_skipped == 0; a catch-and-drop variant fails both on those lines
2 💡 The PR description said the transient peak is bounded by exact_bytes_limit; a transported partial bounds only its key bytes AGREE, fixed in the description Rewritten to the exact-set limits
3 💡 A transported partial serialized as a full exact set after a refused switch is rejected by the receiver with INCORRECT_DATA DISAGREE An ordinary exception, reachable only after the sender's build already threw MEMORY_LIMIT_EXCEEDED; before this change the same state threw LOGICAL_ERROR

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

Session id: cron:clickhouse-review-slot-9:20261120-161000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The two new gtests (RuntimeFilterLookup.AdaptiveFilter*) abort on master on every run with Logical error: 'Unexpected state of AdaptiveSetRuntimeFilter' (RuntimeFilterLookup.cpp:773). The SQL repro is race-dependent: 14/200 aborts on a master debug build.
b Root cause explained? Yes. switchToApproximateFilter emplaced the Bloom filter into the variant, so emplace destroyed the exact set before the constructor allocated the buffer; a refused allocation left the variant valueless. ISimpleTransform passes the exception downstream and feeds the next block into the same filter, which then finds no valid alternative (or, with the order fixed, a full exact set) and throws LOGICAL_ERROR.
c Fix matches root cause? Yes. The Bloom filter is built and filled in a local and moved in by a nothrow move, so the exact set survives a refused allocation; the next insert retries the switch from the full set, which still holds every key. No exception is caught.
d Test intent preserved / new tests added? Two gtests: the insert path and the mergeFrom path. No stateless test: memory limit plus a thread race would be flaky.
e Both directions demonstrated? Yes, four builds: master: both tests abort; reorder only: insert test aborts, merge test passes; retry only: both abort; both changes: both pass. 43 related runtime-filter gtests pass, the new pair passes 50 repeats. SQL repro: 14/200 aborts on master, 0/200 with the fix. A variant that drops the key set on a refused allocation fails both tests on their rows_checked / rows_skipped checks.
f Fix is general across code paths? Yes. Every caller of switchToApproximateFilter (insert, mergeFrom into an exact or dense-bitset destination) gets the reorder. switchToDenseBitset already fills a local first; dropKeySet cannot throw; deserialize builds its temporary before the emplace.
g Fix generalizes across inputs (params/datatypes/wrappers)? The changed code does not depend on the key type: every key type the adaptive filter accepts takes the same switch. Only (U)Int8/(U)Int16 keys take the dense bitset, which was already safe.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change; on success the filter is the same (same Bloom size, same keys, same switch point).
i Invariants and contracts preserved? An exception inside the adaptive filter now leaves a valid alternative holding every key inserted by calls that did not throw. The user still gets the same MEMORY_LIMIT_EXCEEDED. Locking is unchanged.

Session id: cron:clickhouse-impl-slot-40:20261120-130803

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d2260a]

Summary: ✅


AI Review

Summary

Reviewed PR #133269 at 5d2260a4195269a253ef67ed8be1cae8e1838abf, including all prior discussion. The change preserves the exact set until its replacement Bloom filter is filled and retries a failed conversion on subsequent insertion. The two regression tests exercise insertion and merge failures while checking retained keys and actual filter evaluation. No actionable findings.

Missing context / blind spots
  • ⚠️ Tests were not rerun locally because this checkout has no configured build. The author reports passing regression tests on the merged head; the current CI run is still in progress. Completed unit-test results would independently confirm execution.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 20, 2026
@cv4g cv4g self-assigned this Nov 20, 2026
@clickhouse-gh clickhouse-gh Bot added 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 20, 2026

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

@groeneai Thanks for restoring the exception-safety fix. Keeping the exact set usable until the replacement Bloom filter is ready makes sense. What seems avoidable is how large the exact set can grow before we start that conversion.

Could you change AdaptiveSetRuntimeFilter::insert to switch during insertion rather than after the entire block? For example, if the set is at its distinct-key limit, duplicates can still go through the exact path. At the first new key, we already know a switch is needed. Growing the hash table for the rest of the block increases peak memory without improving Bloom sizing—the Bloom size comes from the configured geometry and optional statistics hint, not from the final distinct count.

One option is to return the number of input rows consumed, seed the replacement from the bounded exact set, and feed it the remaining rows starting with that first new key. Please preserve the existing dense-bitset choice and make the failure behavior explicit: if allocating the replacement throws mid-block, the exact set contains only the consumed prefix. A test with duplicates at the limit followed by new keys would exercise that boundary, both on success and with a refused allocation.

Please implement this as a follow-up in order to not block the LOGICAL_ERROR fix as of commit a84704c. The goal is to avoid block-sized overshoot, not to give up exception safety or slow down bulk insertion for duplicate-heavy inputs. Start working on it, when this PR is merged and tag me on the PR when it's open, please.

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d2260a41 with master 3ee78be75 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. Once this PR is merged, I'll open the follow-up that makes AdaptiveSetRuntimeFilter::insert switch at the first new key past the limit, and tag you on it.

@groeneai

groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a84704c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05042_crash_handler_without_global_context not from this PR (it does not touch the crash handler): clickhouse-local hangs on macOS after SIGTSTP in isCFICheckTrap, added by #132527, and the test times out. The same timeout hit this job on 29 PRs since 17:13 UTC. The fix was merged after this run's merge commit was built, so it is not in the tested tree #133270 (external, merged)
PR praktika rollup of the row above #133270 (external, merged)

Apart from the first attempt, which stopped at the can be tested label check, CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261120-203023

@cv4g

cv4g commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

@groeneai Please merge the master branch. In CI run https://github.com/ClickHouse/ClickHouse/actions/runs/44780580104/job/136504729438?pr=133269 we got a failure that is tracked in #133246 and seems to be related to #132527 and #133270.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in 5d2260a (it includes #133270); the two new gtests still pass on the merged tree.

@cv4g
cv4g enabled auto-merge November 21, 2026 01:11
@stresshouse

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 29 queries analysed

PR verdict: not_sure. 1 measured difference(s) not attributable to this PR. clickbench Q31: The measured difference cannot be attributed to this PR from the available source evidence. In the tested merge e0405cad, the patch against its first parent 6a2b727a changes only two things: AdaptiveSetRuntimeFilter::insert, which now retries switchFromExactFilter when the exact set is full, and AdaptiveSetRuntimeFilter::switchToApproximateFilter, which now builds the Bloom filter before emplacing it. Both are in src/Processors/QueryPlan/RuntimeFilterLookup.cpp. The rest of the patch is gtests in src/Processors/QueryPlan/tests/gtest_runtime_filter_lookup.cpp. Runtime filters are only built on …

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 243 210 -13.6% <0.0001 aggregation: The measured difference cannot be attributed to this PR from the available source evidence. In the tested merge e0405cad, the patch against its first parent 6a2b727a changes only two things: AdaptiveSetRuntimeFilter::insert, which now retries switchFromExactFilter when the exact set is full, and AdaptiveSetRuntimeFilter::switchToApproximateFilter, which now builds the Bloom filter before emplacing it. Both are in src/Processors/QueryPlan/RuntimeFilterLookup.cpp. The rest of the patch is gtests in src/Processors/QueryPlan/tests/gtest_runtime_filter_lookup.cpp. Runtime filters are only built on …

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: 81189d0b-63ed-436a-b8b9-696d4ddd4133
  • MIRAI run: 1f20e41c-b465-434c-a904-83e472efe3c0
  • PR check IDs:
    • clickbench_578940_1795224052
    • clickbench_578946_1795224052
    • tpch_adapted_1_official_578952_1795224052
    • tpch_adapted_1_official_578974_1795224052

@cv4g
cv4g added this pull request to the merge queue Nov 21, 2026
Merged via the queue into ClickHouse:master with commit ab57613 Nov 21, 2026
195 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up is open: #133383. AdaptiveSetRuntimeFilter::insert now stops filling the exact set at the first new key past the limit (duplicates keep the exact path), and the replacement takes the exact keys plus the whole block. A refused replacement allocation leaves the exact set holding the rows up to and including that key; the gtests cover both sides.

alexey-milovidov pushed a commit to EmeraldShift/ClickHouse that referenced this pull request Nov 22, 2026
…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]>
alexey-milovidov pushed a commit to EmeraldShift/ClickHouse that referenced this pull request Nov 22, 2026
…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]>
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-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants