Repository navigation
Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it - #113512
Conversation
A gtest wiring the intended processor chain under the real pipeline executor: a fake build source emits epoch-tagged chunks, an `EpochBuildCollector` consumes them (standing in for filling the join state) and emits one seal chunk per finished epoch, and a `ReadOnSealTransform` consumes seals as its ordinary data input and only then "reads" the sealed epoch. Gating is expressed as a pipeline edge the executor can see: no `Status::Async`, no side-channel wakeups, and the pool is never asked for an unsealed epoch. The test asserts that every epoch is sealed exactly once and in order, that the reader reads each epoch exactly once strictly after its seal, and that data leaves the chain in epoch order. Co-Authored-By: Claude Fable 5 <[email protected]>
The runtime filter payload collected from the build side (here a [min, max] envelope, in the real version possibly a set or a bloom filter) is state, not data, so it lives in `EpochInfo` and the seal chunk itself is empty. The collector now knows the epoch schedule (the planner's split points in the real version) and seals epochs the build side has no rows for with an empty payload — punctuation liveness. The reader skips such epochs without reading anything: the empty-build fast path. The test covers gap epochs, the trailing gap, and checks the envelope covers exactly the build values of each epoch. Co-Authored-By: Claude Fable 5 <[email protected]>
`ReadOnSealTransform` now drives an `IEpochReader` interface instead of fabricating chunks itself: `startEpoch(epoch, envelope)` on a seal, then one `readNext` per work() call until the epoch is exhausted (an empty chunk). This is the seam the real MergeTree implementation fills by cutting the epoch's ranges from a read pool, refining them with the seal payload through the ranges-refiner contract, and reading incrementally (the same shape as `MergeTreeSelectProcessor::read`). Co-Authored-By: Claude Fable 5 <[email protected]>
Reuse the runtime filter infrastructure as the build-side collector of seal-driven reading instead of inventing a parallel one: - `IRuntimeFilter` gets `isReady` (all build streams merged) and a minimal `getRecordedKeyValues` (the exact distinct key values, null when the set overflowed into a bloom filter or the filter is negated). - `IRuntimeFilterLookup::add` returns whether the call completed the filter; with `filters_to_merge = streams - 1` and one add per stream exactly one caller observes the completion. - `BuildRuntimeFilterTransform` gets an optional seal output port: the transform that completes the filter emits one empty chunk tagged with `RuntimeFilterSealInfo` (carrying the ready filter), the others finish the port without data, so resizing the seal ports to one stream yields exactly one seal. Without the port the behavior is unchanged. The seal signals through an ordinary pipeline edge that the build side is complete and gated probe-side reading may start, so the executor sees the dependency; the consumers are the next step. Co-Authored-By: Claude Fable 5 <[email protected]>
A ranges refiner (the PR 1 read-pool contract) driven by a runtime filter collected from the build side of a JOIN: the recorded exact key values become a `key IN (...)` primary key condition applied to every cut through `markRangesFromPKRange`. An empty key set drops all ranges (nothing on the probe side can match); a filter without recorded values (e.g. overflowed into a bloom filter) keeps the ranges unchanged and only the existing row-level filter applies. The filter is delivered by setFilter when the build side completes; in seal-gated reading the pipeline edge guarantees this happens before any cut of the gated side, so no synchronization is needed in the refiner. Co-Authored-By: Claude Fable 5 <[email protected]>
The probe side of a hash JOIN marked by the new markSealGatedReading optimization reads through SealGatedReadTransforms: nothing is read until FillingRightJoinSideTransform emits the completion seal through its optional seal port, and the runtime filter delivered with the seal then prunes whole mark ranges by the primary key (RuntimeFilterReadRangesRefiner) before read tasks are cut. The gating is a pipeline edge: pending seal inputs are carried by Pipe, wired by joinPipelinesRightLeft, and terminated fail-open (NullSource) where gating is unsupported. Enabled by the experimental setting enable_join_seal_gated_reading (default off). Co-Authored-By: Claude Fable 5 <[email protected]>
…ed reading After #109085: RuntimeFilterReadRangesRefiner builds its primary key condition with the shared convertRuntimeFilterToKeyConditionDAG (which also covers the bloom-overflow case through the [min, max] envelope) instead of hand-rolling the IN-set DAG, and markSealGatedReading detects the probe-side __applyFilter conjunct with findAppliedRuntimeFilters, extracted from registerLeftSideIndexAnalysisSecondPass. Since the filter records key values only on request (enable_join_runtime_filters_index_analysis defaults to off), the marking now turns the recording on through BuildRuntimeFilterStep::enableKeyRangeTracking. Co-Authored-By: Claude Fable 5 <[email protected]>
The test pins the gated path (multi-threaded read pool, deterministic join order, read-time index analysis off) and asserts: gated and ungated results match, the probe side is read through SealGatedReadTransforms (EXPLAIN PIPELINE), the runtime filter drops almost all marks at task-cut time (ReadPoolRangeRefinerDroppedMarks + read_rows contrast against the ungated reference), and the ungatable join shapes stay fail-open with correct results. Co-Authored-By: Claude Fable 5 <[email protected]>
Two pruning shapes against a 90M-row probe table, gated vs ungated: 100 sparse build keys (the exact IN-set from the seal prunes all but ~100 granules, ~4x locally) and a 1M-key band overflowing the exact-values limit (pruning through the [min, max] envelope of the bloom filter, ~6x locally). A read-time index-analysis variant of the sparse query is included for comparison with the granule-level pruning of the same runtime filter. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [d3176bc] Summary: ✅
AI ReviewSummaryThis PR adds PR Metadata
Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit d3176bc.
Changed lines: Changed C/C++ lines covered: 252/531 (47.46%) · Uncovered code |
- Move the enable_join_seal_gated_reading settings-history entry to the 26.8 block and drop a duplicated analyzer_compatibility_allow_non_aggregate_in_having line the merge left in the 26.7 block. - MergeTreeReadTaskInfo::data_part became data_part_info: take the part for markRangesFromPKRange via getDataPart, like the sibling refiner does. - Use typedefs marked with STYLE_CHECK_ALLOW_STD_CONTAINERS for the raw-pointer port and transform lists of the seal wiring. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113512&sha=0c226aac6b1dac5e2d52ae3c7f9b7a769e148727&name_0=PR PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
…time pruning Seal-gated reading now covers readInOrder as well: every per-part source is replaced by a SealGatedReadTransform and the refiner is installed on the in-order pool, so single-threaded and primary-key-ordered probe reads prune at task-cut time like the multi-threaded pool path. The gating decision moved to initializePipeline, where plan-mark invalidations (parallel replicas enabled after the mark, reading split into layers for a sharded join, FINAL, streaming) are known; ungatable shapes keep falling back to ungated reading. On a gated read, the read-time index analysis by the same runtime filter is skipped as redundant - the refiner is already granule-exact through the primary key (descriptors of other joins are kept). Co-Authored-By: Claude Fable 5 <[email protected]>
Gated with pruning asserts: the default pool, the prefetched pool, the in-order pool in single-stream, primary-key-order and reverse-order modes. Fail-open with correct results: parallel replicas, a join sharded by primary key ranges, and FINAL (a ReplacingMergeTree probe verifies the read stays correct and deduplicated). Co-Authored-By: Claude Fable 5 <[email protected]>
The refiner built its KeyCondition with the column-names-and-expression overload, which treats every key column as ascending; on a reverse-sorted primary key (ORDER BY (k DESC)) the refinement pruned wrong marks and the gated join lost matching rows. Use the KeyDescription overload, which honors the per-column sort directions. Also take the key column type from the pushed-down __applyFilter conjunct (carried through the plan mark) instead of looking the column up in the table metadata, which would throw for a name matching an expression key. Covered by a reverse-sorted-key case in the stateless test. Co-Authored-By: Claude Fable 5 <[email protected]>
| return; | ||
| } | ||
|
|
||
| auto res = processor->read(); |
There was a problem hiding this comment.
SealGatedReadTransform calls MergeTreeSelectProcessor::read() directly, so the gated path no longer goes through MergeTreeSource's Linux async machinery (MergeTreeSource.cpp:139-240: prepare() returning Status::Async, background scheduling, and schedule()). When use_asynchronous_read_from_pool is enabled, enable_join_seal_gated_reading now forces those reads back onto executor threads and also defeats the max_streams_for_merge_tree_reading path that assumes async I/O.
That is a noticeable regression on the exact workloads this PR is trying to speed up. The gated wrapper needs to preserve the async-source behavior as well, e.g. by extending / wrapping MergeTreeSource instead of reading synchronously here.
There was a problem hiding this comment.
That's true, but I think we don't need this feature. It's disabled by default, and should be covered partly by prefetches.
We can implement it later if needed
An ANTI join builds a NOT-contains filter which can never prune positively, and a key type without the [min, max] envelope (e.g. String) loses its exact value set once it overflows into a bloom filter; gating such probes only delays them and then scans unpruned. markSealGatedReading now consults BuildRuntimeFilterStep::canSealPrunePrimaryKey: positive containment semantics, and either an envelope-tracking key type or a hash-table statistics hint that the build side fits into the exact set. The stateless test covers both declined shapes; the statistics hint is pinned off there to keep the decision run-independent. Co-Authored-By: Claude Fable 5 <[email protected]>
The flaky check on the ASan build hit the 180s per-test limit. Shrink the probe tables from 1M to 250k rows and the index granularity from 128 to 32, which keeps the same ~7800 marks (so the mark-pruning asserts are unchanged) while cutting the inserts, merges and full scans 4x. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113512&sha=f37a4109ba2f151095bcd5316b9b6206663eb2f3&name_0=PR PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
Measured on the CI perf host and locally: seal gating and the read-time index analysis by the same runtime filter are on par in single-query latency on local storage, for both the exact-set and the range-envelope shape. The probe side cannot run far ahead of the build even ungated - the join does not consume it until the hash table is ready, so port backpressure stalls the probe sources after about a chunk per stream, which bounds the unpruned head start of the read-time path. The comment overstating the gated path is adjusted accordingly; the structural difference (no read or prefetch issued for pruned ranges at all, and the punctuation seam for epoch-based collocated joins) is what the gating is for. CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/113512/f37a4109ba2f151095bcd5316b9b6206663eb2f3/performance_comparison_amd_release_master_head_2_6/report.html PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
…check The flaky check runs the new test in several parallel instances; on the debug build each took 330+s and was killed even after the previous shrink. Cut the probe tables to 50k rows with index_granularity 8, which preserves ~6250 marks (the pruning asserts and their thresholds keep their meaning) at a fifth of the row volume; one run now takes ~1.3s on a release build. Also pin enable_analyzer = 1 like the other runtime-filter tests: without the analyzer there are no runtime filters and no gating, so the coverage run with the old analyzer failed the structural asserts (the results themselves stayed correct, fail-open). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113512&sha=821622c7e772c2966392e0bbe5dbdfd607980d02&name_0=PR PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
Move the enable_join_seal_gated_reading settings-history entry to the 26.9 block, and include <deque> in gtest_seal_driven_reading.cpp explicitly: a header stopped providing it transitively, so with _LIBCPP_REMOVE_TRANSITIVE_INCLUDES only the forward declaration was in scope (local builds of the clickhouse target do not compile the unit tests, which is why the tidy job caught it first). CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113512&sha=6c1e58add2275b1e8da2fdc6bad8f713cbb7778d&name_0=PR PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
| if (seal_gate_refiner) | ||
| prefetched_pool->setReadRangesRefiner(seal_gate_refiner); | ||
| else | ||
| prefetched_pool->setReadRangesRefiner(createIndexReadRangesRefiner(index_build_context, storage_snapshot->metadata, settings)); |
There was a problem hiding this comment.
This replaces the existing read-pool refiner instead of composing with it. If use_indexes_refiner_in_read_pools = 1 and this read also has a projection index or ordinary skip-index pruning, the seal-gated path drops IndexReadRangesRefiner entirely here (the same pattern repeats in the plain and in-order pools below). Results stay correct because reader-level filtering still runs later, but we lose task-cut pruning and prefetch avoidance for those indexes, so enabling enable_join_seal_gated_reading can silently regress the very workload this PR is trying to speed up. Please chain the seal refiner with the existing IndexReadRangesRefiner, or reject the setting combination explicitly until that composition exists.
…ing test A LEFT SEMI join does not short-circuit on an empty build side the way INNER does (alwaysReturnsEmptySet covers only INNER and RIGHT kinds), so it relies on the empty-set runtime filter to avoid scanning the whole probe table: measured 50000 rows read with runtime filters disabled versus 0 with them enabled. The review concern about getRecordedKeyValues collapsing an empty exact set to "no predicate" was fixed upstream by the runtime filter rework merged yesterday: the empty set is preserved as a typed zero-row column and buildRuntimeRangePredicate turns it into a constant-false IN, so the seal-gate refiner prunes everything; the row-level filter additionally closes the probe pipeline on the constant-false condition. Co-Authored-By: Claude Fable 5 <[email protected]>
The merge conflict resolution kept both sides of the include block; the clang-tidy readability-duplicate-include check rejects that. Keep one sorted copy with actionsDAGUtils.h slotted in. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113512&sha=709f6a76ae1b0ccf7431b50343fba248ec913a34&name_0=PR PR: #113512 Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/Optimizations/Optimizations.h
# Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp
`BuildRuntimeFilterTransform::finish` ran only after `ISimpleTransform::prepare` closed the output port on end-of-stream. Downstream treats that close as "this stream's build is complete": once the last build stream closes, `HashJoin::publishSharedRuntimeFilters` copies the filter's metadata and the seal for gated probe-side reading is emitted. In that window they could observe an unmerged filter (no recorded values/range), so a seal-gated read would wait for the build and then scan unpruned (and `chassert(filter->isReady())` in `RuntimeFilterReadRangesRefiner` could fail in debug builds). Now `prepare` publishes the filter before delegating once the input is finished and the last chunk is consumed, so the port close happens-after the publication; `finish` became idempotent because the cancellation path can reach it again. Co-Authored-By: Claude Fable 5 <[email protected]>
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) - semantic merge fixes in non-conflicting files: src/Processors/QueryPlan/BuildRuntimeFilterStep.h Also resolved conflicts in: - `src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp` - `src/Processors/QueryPlan/ReadFromMergeTree.cpp` - `src/Processors/QueryPlan/RuntimeFilterLookup.cpp` Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts: # src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp # src/Processors/QueryPlan/ReadFromMergeTree.cpp
| /// (Multi-key non-ANTI joins are unaffected: they build one per-column filter per key, and each | ||
| /// is reported here. Single-key ANTI filters reported here stay fail-open at read time: | ||
| /// the negating filter exposes neither recorded key values nor a key range.) | ||
| if (key_arg->type != ActionsDAG::ActionType::INPUT) |
There was a problem hiding this comment.
This new matcher now drops runtime filters whose probe key is a primary-key expression instead of a bare column. After composing through the intervening ExpressionSteps, a join on a table like ORDER BY toDate(ts) leaves the __applyFilter(..., toDate(ts)) argument as a function node, so this continue prevents the descriptor from ever reaching ReadFromMergeTree. That silently disables both the existing enable_join_runtime_filters_index_analysis pruning and the new seal-gated pruning for expression primary keys, even though RuntimeFilterReadRangesRefiner now builds KeyCondition from the full KeyDescription specifically to support them.
Please preserve matched primary-key expression outputs here (or match the merged tree against primary_key.expression) instead of requiring the final node to be a bare INPUT.
There was a problem hiding this comment.
Claude:
This is a pre-existing scope limit of the runtime-filter index analysis, not something this matcher disables — and the matcher is not the binding constraint here.
Expression primary keys are not supported by the feature at all, on master or on this branch. Verified on a table with ORDER BY toDate(ts) (100k-row probe, 10-row build side):
- Probe key =
toDate(ts)(the PK expression itself): not registered — but master's matcher has the identicalkey_arg->type != INPUTcheck, so nothing regressed. - Probe key = bare
ts: the descriptor is registered (this function drops nothing), yet it dies later at theruntime_prune_primary_keygate inReadFromMergeTree, which matches descriptors against PK column names (tsis nottoDate(ts)). No "Index analysis engaged" log,read_rows= full table in every variant (exact IN-set and min/max range paths both). - Control with
ORDER BY ts: prunes 100k → ~1k read rows through both paths.
So preserving matched expression outputs here would not enable anything by itself: the whole descriptor pipeline — registration, runtime_prune_primary_key, buildRuntimeRangePredicate (which reconstructs the key as dag.addInput(column_name, type)), and the seal-gating PK-prefix cover — works on (column name, type) pairs matched against PK column names. The bare-INPUT restriction is also deliberate collision safety: registering a computed key under its plan-level name (toDate(__table1.ts)) either never matches the PK sample-block name or, worse, an accidental name match could prune wrongly.
One correction to the comment's premise: the KeyDescription overload in the refiner was adopted for reverse-sorted (DESC) keys, not expression keys.
Supporting expression primary keys would be a feature extension across all these layers (descriptors carrying an expression fragment over physical columns, predicates built over that fragment so KeyCondition matches structurally, prefix cover by structure rather than name), and it would benefit the existing read-time index analysis exactly as much as the seal gating. Everything today stays fail-open — no wrong pruning, just no pruning — so I would keep it out of this PR and track it as a follow-up.
…top-K dynamic filtering settings - `max_bytes_before_external_set` / `max_bytes_ratio_before_external_set` join the external sort/group by/distinct family. The bytes threshold is drawn low (1 byte to 64 MiB) so that sets actually spill. - `enable_join_seal_gated_reading` (experimental) is enabled with 30% probability. - `enable_group_by_top_k_dynamic_filtering` is disabled with 5% probability. The last two are forced off when their parent settings are off. Related: #123860 Related: #113512 Related: #121145 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lter and GROUP BY settings A spilled `IN` set keeps no explicit elements, so five more tests of the index analysis by the set pin `max_bytes_before_external_set = 0`. `04653_join_seal_gated_reading` also pins `join_runtime_filter_exact_values_limit`: with bloom-only filters nothing gets gated. `05316_nested_settings_clamped_for_aggregation` pins `optimize_trivial_group_by_limit_query`. `04337_runtime_filter_lookup_before_finished` pins `enable_join_seal_gated_reading = 0`: its early build-side break sends the seal with an unfinished runtime filter, and `RuntimeFilterReadRangesRefiner::setFilterImpl` asserts that the filter is ready, which aborts the debug server. That is a real bug in seal-gated reading (#113512), to be reported separately. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106734&sha=bacd1d3c5bbeb2408d98bdbce9fb4ea89d9f331d&name_0=PR PR: #106734 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude
Motivation
JOIN runtime filters (
enable_join_runtime_filters) filter probe-side rows only afterthey were read: the row-level
__applyFilterconjunct discards non-matching rows, andthe read-time index analysis from #109085 (
enable_join_runtime_filters_index_analysis)skips granules inside already-created read tasks. In both cases the probe side starts
reading concurrently with the build side, before the filter exists, so the early tasks
are read unpruned.
This PR adds a stronger, structural variant for the case when the probe-side join key is
a prefix of the table's primary key: the probe side does not read anything until the
build side completes, and the completed filter then prunes whole mark ranges by the
primary key before read tasks are created.
Approach
The gating is expressed as an edge of the query pipeline, not as a waiting state:
FillingRightJoinSideTransformgets an optional "seal" output port. Exactly one of theconcurrent filling transforms — the one that completes the build — emits a single seal
chunk carrying the completed runtime filter in its chunk info; the rest just finish.
ReadFromMergeTreeare replaced bySealGatedReadTransforms: source-like processors whose only input is the seal. Untilthe seal arrives, the executor has nothing to schedule below them, so the read pools
never cut a task. On the seal, the filter is handed to a
RuntimeFilterReadRangesRefiner(installed on the read pool), which turns it into a primary key
KeyCondition— an exactIN-set, or the[min, max]envelope when the exact set overflowed into a bloom filter —and drops non-matching mark ranges at task-cut time, reusing the refiner contract of the
MergeTree read pools.
markSealGatedReadingfinds hash joins whose pushed-down__applyFilterconjunct references a probe-side primary key column, and marks the joinstep and the reading step.
JoinStep::updatePipelinethen wires the seal to the pendingseal inputs collected by the
Pipe.join,
YShaped/by-shards pipelines, cancellation) is fed from aNullSourceand readsungated with row-level filtering only. FINAL, parallel replicas, and joins sharded by
primary key ranges are not gated.
Both the default multi-threaded pool and the in-order reading paths are gated (including
max_threads = 1and reads in primary key order). On a gated read, the read-time indexanalysis by the same runtime filter is skipped as redundant — the refiner is already
granule-exact through the primary key; filters of other joins are kept.
Enabled by the experimental setting
enable_join_seal_gated_reading(default off) on topof
enable_join_runtime_filters. This is also groundwork for epoch-based (punctuated)collocated joins, where the same reader will consume a stream of per-epoch seals.
Results
On a 90M-row probe table (
ORDER BY k, warm cache;tests/performance/join_seal_gated_reading.xml,CI perf host numbers):
IN-set path): 172 ms → 12 ms[min, max]envelope path): 645 ms → 54 msCompared with the read-time granule pruning by the same runtime filter
(
enable_join_runtime_filters_index_analysis+use_skip_indexes_on_data_read), thesingle-query latency on local storage is on par (the probe side cannot run far ahead of the
build even ungated: the join does not consume it until the hash table is ready, so port
backpressure stalls it after about a chunk per stream). The structural difference of gating
is that no read or prefetch is issued for pruned ranges at all, and that it is the seam for
the per-epoch seals of collocated joins.
The stateless test
04653_join_seal_gated_readingasserts result equality with ungatedexecution, the pipeline structure,
ReadPoolRangeRefinerDroppedMarks/read_rowscontrast,the fail-open shapes, and the suppression of the redundant read-time analysis.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added an experimental setting
enable_join_seal_gated_reading(default off). When enabled together withenable_join_runtime_filtersand the probe-side join key is a prefix of the table's primary key, the probe side of a hash JOIN starts reading only after the build side completes, and the completed runtime filter prunes whole mark ranges by the primary key before read tasks are created, instead of only filtering rows after they were read.Workflow [PR]
Sync PR [sync-upstream/pr/113512]
Version info
26.10.1.1833-master(included in26.10and later)