Skip to content

Fix LOGICAL_ERROR on runtime filter lookup before build finished - #107108

Merged
alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/runtime-filter-lookup-before-build-finished-v2
Oct 4, 2026
Merged

alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/runtime-filter-lookup-before-build-finished-v2

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Add the RuntimeFilterLookupsBeforeBuildFinished profile event, counting blocks that a JOIN runtime filter passed through unfiltered because its build side had not finished yet (for example with join_overflow_mode = 'break' and a finite max_rows_in_join / max_bytes_in_join), and regression tests for that window.

Description

Found by the AST fuzzer (STID 2210-585c).

A JOIN runtime filter is built on the right (build) side by N parallel BuildRuntimeFilterTransform streams. The filter becomes findable in the IRuntimeFilterLookup after the FIRST stream registers it, but it is ready (RuntimeFilter::isReady) only after the LAST stream merges its partial filter. Normally the join's pull discipline guarantees the build side is fully consumed before the probe side runs, but when the join stops reading the build side early (join_overflow_mode = 'break' with a finite max_rows_in_join / max_bytes_in_join, or an empty/short-circuited right side) the probe side can reach the registered filter while it is still unfinished. The runtime filter is a best-effort optimization: correctness always comes from the JOIN itself, so passing the block through unfiltered is the correct behaviour in that window.

Current master already implements the fix itself as part of the runtime filter rework: __applyFilter passes all rows through when the registered filter is not ready yet, RuntimeFilter::finishInsert finalizes the underlying set/bloom filter before publishing readiness, the index-analysis accessors getRecordedKeyValues / getRecordedKeyRanges return nothing until the filter is ready, and a late merge into an already published shared fixed-hash-table filter is ignored. RuntimeFilter::find keeps the LOGICAL_ERROR as an invariant that consumers must check isReady first.

This PR adds the observability and regression coverage for that window:

  • The RuntimeFilterLookupsBeforeBuildFinished profile event, incremented in FunctionApplyFilter when a registered but unfinished filter is passed through.
  • The runtime_filter_skip_finish_insert fail point, which holds a filter in the registered-but-unfinished state deterministically.
  • 04337_runtime_filter_lookup_before_finished: drives a real JOIN pipeline with join_overflow_mode = 'break' and a tiny max_bytes_in_join over a multi-part build table, repeated so the probabilistic race is hit with high probability; a binary that probes the unfinished filter aborts.
  • 04614_join_runtime_filters_index_analysis_partial_filter: the read-time exact IN-set pruning path must not expose a partially merged key set.
  • 04615_join_runtime_filters_shared_fixed_hash_table_pruning: the shared fixed-hash-table publication may race the last build streams; results must stay exact and pruning must engage.
  • 04681_runtime_filter_lookup_unfinished_witness: uses the fail point to make the pass-through branch observable through the profile event, and asserts the join row counts.

Report (AST fuzzer, amd_debug, targeted): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103322&sha=eeec76f833a27b148d130ef8f504ac362f26caef&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29


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

Version info

  • Merged into: 26.10.1.1489-master (included in 26.10 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? The crash is an inherent race (no fixed-iteration deterministic SQL repro), but it reproduces on master HEAD: rf_build(k UInt64) with multiple parts + rf_probe 2M rows, SELECT count() FROM rf_probe p ANY INNER JOIN rf_build b ON p.k=b.k SETTINGS max_bytes_in_join=1, join_overflow_mode='break', join_algorithm='hash', enable_join_runtime_filters=1, max_threads=16 hit the exact LOGICAL_ERROR (~1/27 runs). The race is then made deterministic at the unit level: gtest_runtime_filter_lookup constructs a filter with filters_to_merge=1 (never finished) and calls find() — pre-fix this throws on demand, every time.
b Root cause explained? A runtime filter is built by N parallel BuildRuntimeFilterTransform streams; it is visible via RuntimeFilterLookup::find(name) after the FIRST stream's finish(), but inserts_are_finished is only set after the LAST stream merges (filters_to_merge->0). With join_overflow_mode='break', FillingRightJoinSideTransform closes its input early, the build finish_counter reaches isLast(), and the probe side starts and calls FunctionApplyFilter->IRuntimeFilter::find() while inserts_are_finished==false -> LOGICAL_ERROR.
c Fix matches root cause? Yes. The runtime filter is best-effort; correctness always comes from the JOIN. find() now returns const-true (pass all rows) when not finished, instead of throwing — covering ALL early-termination paths (break, empty/short-circuited right side), not just one. finishInsert() is reordered to finalize before publishing readiness so find() never sees a half-built filter. Not a guard against one symptom.
d Test intent preserved / new tests added? New gtest_runtime_filter_lookup added: find-before-finished passes all rows (contains + not-contains polarities), and finished filter still correctly filters. No existing test weakened.
e Both directions demonstrated? Pre-fix: FindBeforeBuildFinishedPassesAllRows throws LOGICAL_ERROR at RuntimeFilterLookup.cpp:83. Post-fix: all 3 gtests pass; 100/100 racing SQL queries clean with the server surviving; 5 existing runtime-filter functional tests match their references.
f Fix is general, not a narrow patch? Yes. The fix is at the single choke point (IRuntimeFilter::find()) through which every filter polarity (ExactContains, ExactNotContains, Approximate) and every early-termination path flows, so all sibling cases are covered by one change. Traced upstream: the bad state (find-before-finished) is legitimately possible by design (concurrent build/probe with early break), so pass-through is the correct handling, not a mask.

Session id: cron:clickhouse-worker-slot-28:20260610-231742

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @vdimir — could you review this? It fixes the LOGICAL_ERROR "lookup values in runtime filter before building it was finished" (AST fuzzer STID 2210-585c, reproducible on master): when a join stops reading the build side early (e.g. join_overflow_mode='break'), the probe side can call IRuntimeFilter::find() before all N build streams have merged. Since the runtime filter is best-effort, find() now passes all rows through instead of throwing, and finishInsert() finalizes before publishing readiness.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [542998c]

Summary: ✅


AI Review

Summary

This PR adds RuntimeFilterLookupsBeforeBuildFinished, a fail point, and targeted stateless coverage around the already-merged fail-open handling for unfinished runtime filters. Most of the observability and test work looks solid, but the shared fixed-hash-table publication race from the earlier review is still present in the current code, so the PR still leaves one important pruning-loss path unresolved.

Findings

⚠️ Majors

  • src/Interpreters/HashJoin/HashJoin.cpp:2799 still publishes a SharedFixedHashTable filter without checking that the existing runtime filter is finished first. Because late merges are still dropped after replacement in src/Processors/QueryPlan/RuntimeFilterLookup.cpp:790, a publication that wins this race can still permanently lose exact-value/range pruning for the rest of the query. Suggested fix: either defer replace until existing->isReady() is true, or populate the shared filter's recorded values/range directly from the fixed hash table instead of snapshotting the unfinished filter.
Final Verdict

⚠️ Needs changes: one previously reported major is still present in the current tree.

LLVM Coverage Report

Measured on commit 542998c.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI on 055aea66d034 is finished. No PR-caused failures. The three red items are all the ongoing arm_asan_ubsan, azure, sequential infrastructure outage, not this change:

  • Server died + Segmentation fault (STID: None) + 02724_show_indexes ERROR are all on the single Stateless tests (arm_asan_ubsan, azure, sequential) job.
  • That job's Server died/segfault signature has hit 95 distinct PRs / 126 occurrences / 11 master in the last 30h (CIDB) — a systemic ASan secondary-allocator OOM in the azure runner, with no ClickHouse frames in the crash and 02724_show_indexes an innocent bystander running when the server OOM'd.
  • The runtime-filter fix is exercised by the amd/arm debug, asan, tsan and msan jobs, all of which are green. A real crash in the changed RuntimeFilterLookup path would not be confined to the one azure job.

Ready for review.

@groeneai
groeneai force-pushed the fix/runtime-filter-lookup-before-build-finished-v2 branch from 055aea6 to e325ea4 Compare June 12, 2026 07:19
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI is fully green on the rebased HEAD e325ea4 (Finish Workflow = success, 0 test failures). The earlier failures noted above were the 2026-06-10/11 arm_asan_ubsan azure infrastructure outage on the pre-rebase commit 055aea6; rebasing onto current master cleared them. No PR-caused failures.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, please replace the unit test with a functional test.

@groeneai
groeneai force-pushed the fix/runtime-filter-lookup-before-build-finished-v2 branch from e325ea4 to 0a2da52 Compare June 27, 2026 01:40
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done. Replaced the unit test with a functional test: tests/queries/0_stateless/04337_runtime_filter_lookup_before_finished.sql.j2.

It joins a multi-part build table with join_overflow_mode='break' and max_bytes_in_join=1 so the join stops reading the build side early, and repeats the query so the probe hits find() before the build is finished. Verified both directions on a debug build: reverting the find() guard aborts the server on the LOGICAL_ERROR (5/5 full-test runs); with the fix it passes (clickhouse-test --test-runs 20, all green, server alive). The gtest is removed.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Probabilistic per query (~50-70% server abort on debug), made reliable by repeating the breaking join 30x in one test: P(miss) on unfixed ~ 0.5^30. Build: MergeTree probe (2 parts) JOIN MergeTree build (8 parts), join_algorithm='hash', join_overflow_mode='break', max_bytes_in_join=1, max_threads=16, enable_join_runtime_filters=1.
b Root cause explained? The build filter becomes visible to find() on the first stream's finish(), but inserts_are_finished only flips after the last stream merges. With join_overflow_mode='break' + tiny max_bytes_in_join, the join stops reading the build side early, so FillingRightJoinSideTransform closes and the probe calls find() while inserts_are_finished is still false. Pre-fix find() threw LOGICAL_ERROR. (Note: disabling spilling via max_bytes_before_external_join=0 closes the window, so the test leaves spilling at default.)
c Fix matches root cause? Yes. find() returns const-true (pass all rows) when the build side is unfinished, and finishInsert() finalizes before publishing inserts_are_finished. Correctness comes from the JOIN; the filter is best-effort. Fix unchanged from the approved revision (byte-identical).
d Test intent preserved / new tests added? Replaced the gtest with a functional test per the maintainer request, covering the same behavior (find-before-finished must not throw) through a real JOIN pipeline.
e Both directions demonstrated? Yes. Unfixed (reverted find() guard, Build ID 33f15638): 5/5 full-test runs abort the server with Trying to lookup values in runtime filter before building it was finished. Fixed (Build ID fa10bf19): clickhouse-test --test-runs 20 all green, server alive.
f Fix is general across code paths? Yes. The guard is in the single shared IRuntimeFilter::find() / finishInsert(), covering both contains and not-contains polarities; no sibling code path duplicates the throw.
g Fix generalizes across inputs? The unfinished-build window is independent of key type; the const-true pass-through is type-agnostic. N/A beyond that for this fix.
h Backward compatible? Yes. No setting default, format, or on-disk change. Only removes an internal LOGICAL_ERROR on a best-effort optimization path.
i Invariants and contracts preserved? Yes. The JOIN remains the source of correctness (it drops non-matching rows); finishInsert() reorder ensures find() never observes a half-built filter (finished flag implies finalized state).

Session id: cron:clickhouse-worker-slot-1:20260627-004000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0a2da52

Every failure below has an owner: a fixing PR (ours 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
AST fuzzer (amd_debug) / Block structure mismatch in IntersectOrExceptStep (STID 0993-2cc2) logical error found by the AST fuzzer (debug abort): two INTERSECT ALL branches differ only in their WHERE predicate and one branch's c column constant-folds to a Const, so the branch headers diverge (Int64(size=0) vs Const(size=0, Int64(size=1))) #107719 (ours, open)
Mergeable Check / PR aggregators reflecting the AST-fuzzer red n/a
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

This PR's diff (RuntimeFilterLookup.cpp runtime-filter-lookup-before-finished fix + the new functional test 04337_runtime_filter_lookup_before_finished) does not touch INTERSECT/UNION query planning. The AST fuzzer finding is a separate trunk bug whose exact signature (a constant-folded branch in IntersectOrExceptStep) is the charter of the open fix PR #107719.

Session id: cron:our-pr-ci-monitor:20260627-053000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0a2da52

Every failure below has an owner: a fixing PR (ours 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
AST fuzzer (amd_debug) / STID 0993-2cc2 Block structure mismatch in IntersectOrExceptStep stream: different columns flaky / trunk: a branch constant-folds to a Const column, so the two IntersectOrExceptStep inputs disagree on full-vs-const. Chronic 0993-* family across 20+ unrelated PRs incl. master; unrelated to this PR's runtime-filter change #107719 (ours, open)
CH Inc sync / PR — rollup / CH Inc sync (private, not actionable)

None PR-caused: this PR changes only RuntimeFilterLookup (find() returns pass-through when the filter is not yet built) plus a gtest; the IntersectOrExceptStep block-structure mismatch is an unrelated query-plan fuzzer finding.

Session id: cron:our-pr-ci-monitor:20260629-043000

@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

@alexey-milovidov

Copy link
Copy Markdown
Member

The amd_debug flaky check was timing out on the new functional test (04337_runtime_filter_lookup_before_finished): it exceeded the 180s per-run limit (185–218s), dominated by the 30 JOIN repetitions (~115s/run, ~452k rows read per join in the debug build).

Pushed 9722f46: shrank the probe from 400000 to 120000 rows (~2.6× fewer rows read per join → typical debug run ~50s). The race-reproducing structure is deliberately left intact — 8 build parts, join_overflow_mode='break' with max_bytes_in_join=1, max_threads=16, and all 30 repetitions. Verified against a pre-fix binary that the trimmed test still reproduces the LOGICAL_ERROR (7/15 single runs vs 0/15 for the previous, larger version), so the regression is still caught — just faster.

This doesn't touch the fix itself or the open design discussion at RuntimeFilterLookup.cpp.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @alexey-milovidov, the trim looks right. Keeping the 8 build parts + join_overflow_mode='break'/max_bytes_in_join=1 + 30 repetitions preserves the early-termination window and the independent trials, so pass-all-when-unfinished is still exercised; shrinking only the probe scan is the right lever. Your 7/15 pre-fix repro on the trimmed test confirms the regression is still caught. Not re-pushing over 9722f46.

The RuntimeFilterLookup.cpp design point raised earlier remains open for whenever you and vdimir want to weigh in; happy to switch to disabling the filter on early build termination instead of the find() guard if that is preferred.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed both points in 59e9ead (test only; fix source and the open RuntimeFilterLookup.cpp design thread untouched):

  1. Pinned max_bytes_before_external_join = 1000000000 in the test. As noted, the flaky-check harness randomizes it between 0 and 1000000000, and 0 closes the unfinished-filter window; pinning the harness's own nonzero value stops randomization from silently disabling the reproducer. (A tiny value like 1 is not usable here: it forces grace-hash spilling into too many buckets and raises LIMIT_EXCEEDED before find() is ever reached.)

  2. Raised repetitions 30 -> 60; probe left at 120000 (the 9722f46 trim) so the 180s limit is respected.

Verified in a debug build, both directions, deterministic:

  • Unfixed (find() guard reverted to the original throw): 10/10 single runs abort the server with the LOGICAL_ERROR (was 7/15 before this change).
  • Fixed: 10/10 single runs pass; a full 60-rep run takes ~0.5s, well under the 180s per-run limit.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 59e9ead

Every failure below has an owner: a fixing PR (ours 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
(none) CI fully finished on this head (the strengthened 04337 test + probe-trim) with no test or job-level failures —
CH Inc sync — CH Inc sync (private, not actionable)

No PR-caused failure. The prior AST-fuzzer STID 0993-2cc2 (fixing PR #107719) did not recur on this SHA.

Session id: cron:our-pr-ci-monitor:20260707-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 5a3b8f5: the amd_debug flaky check was timing out on 04337_runtime_filter_lookup_before_finished again (> 180s per run, dominated by the 60 JOIN repetitions the race needs). Tagged the test long, which exempts the 180s flaky-check limit and runs it fewer times under flaky check. The reproducer is unchanged: all pinned settings (max_bytes_before_external_join=1e9, query_plan_join_swap_table=0, join_overflow_mode='break', max_bytes_in_join=1, max_threads=16) and the 8-part build side stay intact. Verified the fixed binary still passes the full rendered 60-rep query (server alive, ~1s), and the earlier both-directions check (unfixed aborts, fixed passes) is unaffected since only the tag changed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5a3b8f5

Every failure below has an owner (a fixing PR). This PR's own diff (runtime-filter find() guard + functional test 04337) is not implicated in any of them.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Can't set alias of A of B (STID 1493-3ccb) logical error, trunk (7 unrelated PRs in 30d) #109223 (ours, open)
Integration tests (amd_msan 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky, trunk (57 master + dozens of PRs in 30d) #110030 (ours, open)
Integration tests (amd_tsan 3/6) / same test flaky, trunk (same family) #110030 (ours, open)
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B) adjudication for 6d7d029

Two rounds of an independent second-model review were run against the resulting code. Findings and dispositions:

Finding Severity Disposition
getRecordedKeyValues reads exact_values without the inserts_are_finished publication guard that getRecordedKeyRanges has blocker AGREE, fixed in 6d7d029 (the guard added by this change)
Regression test overflowed the exact set to a bloom filter (100k keys > 10k limit), so it never exercised the exact-value path major AGREE, fixed: dim reduced to 4000 keys (below the 10000 exact-values limit); verified pruning goes through the exact IN-set
Correctness comparison used uncorrelated scalar subqueries that fold to a constant, so numbers(20) repeated one execution major AGREE, fixed: replaced with a direct count() = 4000 assertion plus a granules-dropped engagement check
getRecordedKeyRanges reads has_range before the atomic acquire blocker DISAGREE (out of scope): pre-existing code not modified by this PR; our new guard checks the flag first. Raised for maintainers in the review thread.

Verification: fixed Build-ID 2555bd9a; 04614 plus the existing 04490/04611/04612 index-analysis tests pass; 04337 (the original find() test) passes; 04614 passes 50/50 randomized runs.

return nullptr;
/// Read the set only after the last build stream published it (seq_cst acquire); before that a
/// merge stream may still be mutating it. Same publication guard as getRecordedKeyRanges().
if (!inserts_are_finished.load())

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.

This nullptr is not only a temporary fail-open for the unfinished window. HashJoin::publishSharedRuntimeFilters() snapshots existing->getRecordedKeyRanges() / getRecordedKeyValues() once into SharedFixedHashTableRuntimeFilter at HashJoin.cpp:2657-2666, then replace() drops the unfinished Set/Bloom filter. If post-build runs before the last BuildRuntimeFilterTransform::finish() (the same window this PR is fixing), every later add() merges into the shared filter's no-op merge(), so key32/key64 joins that convert to FixedHashMap permanently lose exact-value/range pruning for the rest of the query instead of only during the unfinished phase.

Please either delay the shared-filter replacement until the original runtime filter is finished, or derive the recorded exact values / key range directly from the fixed hash table when publishing the shared filter.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified. The asymmetry is real: SharedFixedHashTableRuntimeFilter::merge() is a no-op (RuntimeFilterLookup.h:342), and publishSharedRuntimeFilters() snapshots the recorded values/range once (HashJoin.cpp:2662-2663) then replace()s the original, so a later add() is lost.

In the current code this is a pruning/perf concern, not wrong results:

  • Both snapshot getters already fail open before the finish flag. getRecordedKeyRanges() guards on inserts_are_finished (RuntimeFilterLookup.cpp:76) and getRecordedKeyValues() got the same guard in 6d7d029 earlier today. So in the unfinished window the snapshot is empty, not partial, and the read-time path prunes nothing rather than on a partial IN-set.
  • The published filter's row probe uses probe_fn, built from the fully populated FixedHashMap in runPostBuildPhase(), so join results stay complete regardless of the snapshot.

Residual: if publishSharedRuntimeFilters() runs before the last BuildRuntimeFilterTransform::finish(), the shared filter is published with an empty recorded set and loses index pruning for the rest of the query (perf, on the experimental fixed-hash-table path). Whether that ordering is reachable is the same question as the open discussion on this file: instrumented runs today showed the read-time granule-pruning consumer never observed an unfinished filter (0 of 400+ runs) while the row-level find() did (293), i.e. the read-time consumers run after the pipeline barrier.

Your three options (delay the replacement until finished, derive the recorded values from the fixed hash table at publish, or keep per-consumer fail-open) are a design choice that ties into the still-open discussion on this file about fixing the ordering invariant vs failing open per consumer. This is the fourth finding of that same class, so rather than keep adding per-consumer guards I would prefer maintainer direction on the approach. Holding further changes for that.

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.

🕵 Implemented the first of your two options in f31279b: HashJoin::publishSharedRuntimeFilters now skips the replacement while the original filter is unfinished (IRuntimeFilter::insertsAreFinished), and logs a trace when it does. Keeping the original Set/bloom filter is strictly better than publishing a shared filter with an empty snapshot: the original finishes and prunes on its own, so no pruning is lost for the rest of the query.

Also applied the second major from the AI review summary in the same commit: getRecordedKeyRanges now loads inserts_are_finished before reading has_range/range_min/range_max, so the publication flag actually guards the range fields the build side writes.

New test 04615_join_runtime_filters_shared_fixed_hash_table_pruning drives a build side through the fixed-hash-table conversion and the shared-filter publication (verified locally: Converted join hash map to fixed hash map (range: 7999, keys: 4000) + Published shared fixed-hash-table runtime filter) and asserts both exact results and that granule pruning still engages afterwards (RuntimeFilterGranulesDropped = 718 of 781 considered). Note that reaching the conversion at all requires max_bytes_ratio_before_external_join = 0, which is why the earlier index-analysis test did not cover this path.

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.

This still looks present in the current tree. HashJoin::publishSharedRuntimeFilters still goes straight from lookup->find to lookup->replace without any existing->isReady() guard or deferred-publication path in src/Interpreters/HashJoin/HashJoin.cpp:2799. And RuntimeFilter::merge still drops late merges once the lookup entry has been replaced by a SharedFixedHashTable in src/Processors/QueryPlan/RuntimeFilterLookup.cpp:790. So the original “publish before the last BuildRuntimeFilterTransform::finish() loses pruning metadata for the rest of the query” problem does not appear to be fixed yet.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 11/13 (84.62%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04325 BACKUP hang created: #115531. Root cause was not in this PR: PocoHTTPClientGCPOAuth reused the data-transfer timeouts member for its bearer token round trip, so the token mint inherited the one hour request timeout BackupIO_S3 sets for large transfers and blocked in the TLS header read.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e336396a5a99cbe9d2be50fe411e05b71b3c21de

CI is fully finished on this head: 174 unique check-runs, 156 success, 18 skipped by digest, one
failure. Config Workflow, Style check, Code Review and Finish Workflow are all success.
The one failure has an owner and is not caused by this branch.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: A data stream row of AlignStreams has no matching metadata stream row (block number A, block offset B) (STID 0250-16db) trunk regression, server abort. The assertion lives in src/Storages/MergeTree/Streaming/ReadingPlan/AlignStreams.cpp and arrived with merged #116128, which split the streaming read round into aligned metadata and data streams. The signature first appears 2026-08-26 and measures 31 rows over 28 distinct pull requests plus 3 distinct master commits in 30 days, across 9 different Stress test arms. This diff touches HashJoin.cpp, RuntimeFilterLookup.{cpp,h}, FailPoint.cpp, ProfileEvents.cpp and four stateless tests, and nothing under src/Storages/MergeTree/Streaming. #116531 (external, open)

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107108&sha=e336396a5a99cbe9d2be50fe411e05b71b3c21de&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

The six Bugfix validation (functional tests, amd64/aarch64) FAIL rows are not failures: they
carry check_status = success, the documented inversion where this PR's regression test is
expected to fail against the master binary, which is the proof the bug reproduces.

Session id: cron:our-pr-ci-monitor:20260828-080000

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

Copy link
Copy Markdown
Member

🕵 Refreshed the branch onto current master (merge 12bee7bf9499) — clean, zero conflicts, and the fix re-applied intact.

Correction to the previous ledger entry. The sole red on e336396a was Stress test (arm_tsan) / A data stream row of AlignStreams has no matching metadata stream row, attributed there to #116531 as owner. That PR is now closed unmerged, so it never carried a fix. The trunk regression was instead resolved by reverting the PR that introduced it: #116128 was reverted by #116909 (2f88f4e6ad32), which closed issue #116846 on 2026-08-28. The assertion string no longer exists anywhere under src/, and this master merge pulls the revert in, so that red should clear on the next run.

Verification on the merged tree:

  • RuntimeFilterLookup.cpp.o, HashJoin.cpp.o, FailPoint.cpp.o, ProfileEvents.cpp.o all compile clean.
  • The four regression tests keep unique filenames (no number collisions with the tests master has since added at 04337/04614/04615/04681), and every setting they use still exists.
  • check_style.py: 13/15 pass; the two failures are local-environment only (broken symlinks inside my untracked build/ directory, and the settings-history check refusing to run without the CI changed_files hook).

No code changes in this push. The one open item remains the design question on RuntimeFilterLookup.cpp — @vdimir, when you have a moment, could you confirm the direction? Both the review bot and @groeneai favoured retaining the fail-open contract (Direction A), on the grounds that a pipeline-level wait cannot complete a deliberately truncated build (join_overflow_mode = 'break', empty / short-circuited right side) and would still need this same "filter unavailable" path.

@rschu1ze rschu1ze self-assigned this Sep 8, 2026
…lookup-before-build-finished-v2

Master rewrote the runtime filter classes (`RuntimeFilter` with a mutex-protected
`RuntimeFilterBuildState`) and already carries most of this fix: `finishInsert` finalizes
before publishing readiness, `getRecordedKeyValues` / `getRecordedKeyRanges` return nothing
until the filter is ready, `RuntimeFilter::merge` ignores a late merge into an already
published shared fixed-hash-table filter, and `__applyFilter` passes all rows through when
the registered filter is not ready yet (`RuntimeFilter::isReady`).

Conflict resolution keeps master's versions of `RuntimeFilterLookup.cpp` / `.h` and
re-applies only what master lacks: the `runtime_filter_skip_finish_insert` fail point in
`RuntimeFilterLookup::add`, and the `RuntimeFilterLookupsBeforeBuildFinished` profile event,
which now lives in `FunctionApplyFilter` next to the pass-through branch. The
`HashJoin::publishSharedRuntimeFilters` skip for unfinished filters is dropped in favour of
master's approach (publish, and ignore the late merge). Test comments are updated to the
current code, and the witness test pins `join_runtime_filter_from_fixed_hash_table = 0` so
the held Set/bloom filter is not replaced by a prebuilt shared filter.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 17, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (merge 5cca83dec196, 4600 commits). Two conflicts in RuntimeFilterLookup.cpp / .h: master rewrote the runtime filter classes and, in doing so, already carries the fix this PR was for. __applyFilter now passes all rows through when the registered filter is not ready (RuntimeFilter::isReady), finishInsert finalizes before publishing readiness, the index-analysis accessors return nothing until the filter is ready, and a late merge into an already published shared fixed-hash-table filter is ignored. RuntimeFilter::find keeps the LOGICAL_ERROR as an invariant, which also answers the open design thread from @vdimir.

The resolution keeps master's versions of both files and re-applies only what master lacks:

  • the RuntimeFilterLookupsBeforeBuildFinished profile event, now incremented in FunctionApplyFilter next to the pass-through branch;
  • the runtime_filter_skip_finish_insert fail point in RuntimeFilterLookup::add;
  • the four regression tests, with comments updated to the current code. 04681 now pins join_runtime_filter_from_fixed_hash_table = 0 so the held filter is not replaced by a prebuilt, ready shared filter.

The HashJoin::publishSharedRuntimeFilters skip for unfinished filters is dropped in favour of master's approach. The PR description and changelog category are updated accordingly (Improvement: profile event plus tests). Built the merged branch, all four tests pass, including three randomized-settings reruns each.

The single red on the previous head 12bee7bf was Stress test (arm_release): an AST Fuzzer oracle mismatch (TLP Aggregate) on approx_top_k from 05097_ast_fuzzer_oracle_apply_aggregate, no JOIN or runtime filter involved. The fix #118489 was merged on 2026-09-10 and reverted by #119957 on 2026-09-14 because it made 05141_oracle_skips_aggregate_aliases flaky, so the false mismatch is back on master.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107108&sha=12bee7bf9499c87f8d4ca3efffc9331ed28a36b6&name_0=PR&name_1=Stress%20test%20%28arm_release%29 and provide a fix in a separate PR (a re-fix of #118489 that does not reintroduce the 05141 flake). If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated. The Stress test (arm_release) red on 12bee7bf is the AST fuzzer oracle, and the job's own clickhouse-server.err.log contains exactly one <Fatal> line in the whole file:

2026.09.09 00:26:52.616716 <Fatal> ASTFuzzer: AST Fuzzer oracle mismatch detected!
Fuzzed query: SELECT max(__table1.i) AS `max(i)`, approx_top_k(__table1.d) AS `max(d)`
  FROM test_q2m9w7h8p6g3.oracle_apply_agg AS __table1 WHERE __table1.i > 1
TLP Aggregate oracle mismatch!

Code: 906 AST_FUZZER_ORACLE_MISMATCH, log comment 05097_ast_fuzzer_oracle_apply_aggregate.sql. No SIGSEGV, no abort and no logical error anywhere in that log: the fuzzer replaced the base query's max(d) with approx_top_k(d), and the mismatch follows from that substitution alone.

The fix is already in progress and approved: #119465 (@qoega, 2026-09-11). It suppresses this signature by a different route than #118489: rather than naming functions in the deny-list, it re-reads the reference query on the mismatch path only and drops the report when that read does not reproduce. Measured before I posted it: 5/5 mismatches on unpatched master, 0/5 with the patch, and 5/5 again with referenceReproduces stubbed to return true; on the patched binary the same query still reports ASTFuzzerOracleChecks 27 / ASTFuzzerOracleMismatches 0, so the oracles keep running. approx_top_k is not reproducible even inside one process: 8 consecutive reference reads gave 8 distinct results on a single active part. Write-up: #119465 (comment)

It cannot reintroduce the 05141 flake: the diff is src/Interpreters/QueryOracleChecker.{cpp,h} only, +51/-16, with no test files and no IFactoryWithAliases change, so neither 05140 nor 05141 returns.

It has not merged because of one unrelated red, Integration tests (amd_tsan, 2/6) / test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore (9 failures in 30 days: 7 unrelated pull requests plus 2 master runs; fix open in #119448), which Mergeable Check reflects.

Master exposure meanwhile: 4 CI runs hit this false mismatch since the revert, 2 on master (2026-09-14 15:55Z, 2026-09-15 06:11Z) and 2 on pull requests, the latest 2026-09-16 23:25Z.

If you would rather have #118489's deny-list re-landed on top of that guard, say so and I will open it. Over 30 days of CI data it would not cover anything #119465 misses: of the order-dependent aggregates the oracle's static list does not name, only approx_top_* has any observed mismatch at all.

A shared fixed-hash-table runtime filter is published already finished and
replaces the registered Set/bloom filter, so with the setting at its default the
probe reaches a ready filter and the unfinished-lookup window this test covers is
never entered. 04681 pins the same setting for the same reason.

Measured on 5cca83d (debug, clickhouse-test with randomized settings, 20
runs x 60 joins each): unpinned, all 1200 queries report RuntimeFiltersCreated
and none report RuntimeFilterLookupsBeforeBuildFinished; pinned, every one of the
20 runs enters the branch (302 of 1200 queries, 1427 lookups). On a binary with
the __applyFilter not-ready guard removed, the unpinned test passes 3 x 60
queries, while the pinned test aborts the server with "Trying to lookup values in
runtime filter before building it was finished".

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

Copy link
Copy Markdown
Collaborator Author

The re-land asked for here is open: #120508

It restores #118489's approx_top_k / approx_top_sum deny-list entries and the factory alias resolution, with the two differences that keep #119957's revert reason from returning:

  • 05141 no longer depends on a query that can throw. Its validity gate ran one unfuzzed query purely to read its exit status but redirected nothing, so a server error on it reached the test's stderr, which fails the test whatever stdout says. anova was the only partial aggregate probed, and getFStatistic() throws BAD_ARGUMENTS once the read yields no more rows than groups, the empty read included, so no fixture shape rules it out. The gate is now stderr-safe and that probe is gone; min_by, array_agg, array_concat_agg and medianTDigest cover the same resolution path.
  • The quantileDeterministic de-listing is not re-landed: in the same job as the 05141 failure, master recorded an oracle mismatch on medianDeterministic(v, 1) over oracle_alias_agg, which is 05141's own fixture and positive control.

50 randomized runs of each test are 100/100 green and stderr-clean.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e08e9cb850426b650f38d6ce60d8d498fa6d0743

CI is fully finished on this head: 177 unique check-runs, 152 success, 21 skipped by digest, 4 red.
Config Workflow, Fast test, Style check, Code Review, Finish Workflow and CH Inc sync are
all green. Both red jobs below have a fixing PR, and neither is caused by this branch.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 2270-38be) trunk defect, server abort. The chunk header names s AggregateFunction(countResample(10, 5, 1), UInt64, UInt64), i.e. the parameterisation whose state serializes to zero bytes and reaches ISource::prepare one column short. Measured over 30 days: 55 rows on 46 distinct pull requests plus 6 distinct master commits, across 11 check flavours. This diff touches FailPoint.cpp, ProfileEvents.cpp, FunctionApplyFilter.cpp, RuntimeFilterLookup.cpp and four stateless tests, nothing on the aggregate-state or chunk-shape path. #119728 (ours, open)
Build profile diff infra, and the job exits before any comparison runs: RuntimeError: CI logs cluster query failed from the binary_sizes read in has_pr_data (build_profile_diff_job.py:723). 219 distinct pull requests by other authors hit that same frame in the last 24 hours. #120121 (ours, open)

Mergeable Check and PR are rollups, red only because of the Stress test (arm_msan) row.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107108&sha=e08e9cb850426b650f38d6ce60d8d498fa6d0743&name_0=PR

Session id: cron:our-pr-ci-monitor:20260917-080221

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (542998cc64e, no conflicts; the PR diff is unchanged). The only red on 8be364da was Performance Comparison (arm_release, master_head, 5/6) flagging optimize_time_filter_with_preimage query #4 (+25.6%): that test has no JOIN, so the runtime-filter code this PR touches (a profile-event increment on the not-ready branch of __applyFilter, and a fail point in RuntimeFilterLookup::add) is not on its path. The merge reruns it.

Verified locally on the merged tree (RelWithDebInfo build): 04337, 04614, 04615, 04681 pass 4/4 runs each (one with --no-random-settings, three randomized).

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

Ok, this is no-op right now.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into ClickHouse:master with commit 5418980 Oct 4, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product 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.

6 participants