Skip to content

Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it - #113512

Merged
KochetovNicolai merged 40 commits into
masterfrom
seal-driven-reading
Oct 8, 2026
Merged

KochetovNicolai merged 40 commits into
masterfrom
seal-driven-reading

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Aug 5, 2026 •

Copy link
Copy Markdown
Member
Claude

Motivation

JOIN runtime filters (enable_join_runtime_filters) filter probe-side rows only after
they were read: the row-level __applyFilter conjunct discards non-matching rows, and
the 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:

  • FillingRightJoinSideTransform gets an optional "seal" output port. Exactly one of the
    concurrent 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.
  • On the probe side, the sources of a gated ReadFromMergeTree are replaced by
    SealGatedReadTransforms: source-like processors whose only input is the seal. Until
    the 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 exact
    IN-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.
  • The plan-level pass markSealGatedReading finds hash joins whose pushed-down
    __applyFilter conjunct references a probe-side primary key column, and marks the join
    step and the reading step. JoinStep::updatePipeline then wires the seal to the pending
    seal inputs collected by the Pipe.
  • Everything fails open: a gated read whose seal cannot be wired (the build side of a
    join, YShaped/by-shards pipelines, cancellation) is fed from a NullSource and reads
    ungated 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 = 1 and reads in primary key order). 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; filters of other joins are kept.

Enabled by the experimental setting enable_join_seal_gated_reading (default off) on top
of 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):

  • 100 sparse build keys (exact IN-set path): 172 ms → 12 ms
  • 1M build keys in a narrow band (bloom overflow, [min, max] envelope path): 645 ms → 54 ms

Compared with the read-time granule pruning by the same runtime filter
(enable_join_runtime_filters_index_analysis + use_skip_indexes_on_data_read), the
single-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_reading asserts result equality with ungated
execution, the pipeline structure, ReadPoolRangeRefinerDroppedMarks/read_rows contrast,
the fail-open shapes, and the suppression of the redundant read-time analysis.

Changelog category (leave one):

  • Improvement

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 with enable_join_runtime_filters and 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

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

KochetovNicolai and others added 10 commits July 29, 2026 16:34
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3176bc]

Summary: ✅


AI Review

Summary

This PR adds enable_join_seal_gated_reading, wiring a build-completion seal into hash-join probe reads so MergeTree can prune mark ranges before scheduling tasks. The overall design is coherent and most of the earlier correctness issues were fixed, but the current revision still has two material performance regressions and one new regression in the existing runtime-filter pruning path, so I would request changes before merging.

PR Metadata
  • Changelog category should be Experimental Feature, not Improvement: this PR introduces a new experimental setting rather than improving an existing production feature.
  • Changelog entry is required for that category, and the current entry is specific enough, so only the category needs to change.
Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:896] The new __applyFilter matcher now insists on a bare INPUT after composing through ExpressionSteps, so a probe key that is itself a primary-key expression (for example ORDER BY toDate(ts)) gets dropped before it ever reaches ReadFromMergeTree. That silently disables both enable_join_runtime_filters_index_analysis and the new seal-gated pruning on expression primary keys, even though the refiner now uses the full KeyDescription precisely to support them. Preserve matched primary-key expression outputs, or match the merged tree against primary_key.expression, instead of resolving everything down to physical columns only.
  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:799] A gated read still replaces the existing read-pool refiner instead of composing with it. With use_indexes_refiner_in_read_pools = 1, that drops the projection/skip-index task-cut pruning that the non-gated read would keep, so enabling enable_join_seal_gated_reading can regress the same local-MergeTree workloads it is supposed to speed up. Chain the seal refiner with the existing IndexReadRangesRefiner, or reject this setting combination until the composition exists.
  • [src/Storages/MergeTree/SealGatedReadTransform.cpp:84] [dismissed by author -- https://github.com/Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it #113512#discussion_r3735585212] The gated path still calls MergeTreeSelectProcessor::read() directly instead of going through MergeTreeSource, so it drops the Linux async-read scheduling path behind use_asynchronous_read_from_pool and runs those reads back on executor threads. Because the feature is explicitly about reducing probe-side I/O cost on local MergeTree reads, losing the existing async/pread-threadpool machinery is still a real regression even behind an off-by-default setting. Either preserve the MergeTreeSource behavior when gated, or explicitly disable seal gating for async-pool reads.
Tests
  • ⚠️ Add a focused stateless case where the probe table uses an expression primary key (for example ORDER BY toDate(ts)) and the join key is that same expression. The new coverage only exercises physical-key prefixes, so this regression is currently unpinned.
  • ⚠️ Add a focused case with use_indexes_refiner_in_read_pools = 1 to pin that seal gating composes with the existing projection/skip-index refiner instead of replacing it.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: keep runtime-filter pruning working for expression primary keys, compose the seal refiner with the existing read-pool refiner (or reject that setting combination), and avoid regressing the async MergeTreeSource path when seal gating is enabled.

LLVM Coverage Report

Measured on commit d3176bc.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 252/531 (47.46%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 5, 2026
KochetovNicolai and others added 2 commits August 6, 2026 14:16
- 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]>
@KochetovNicolai KochetovNicolai changed the title [WIP] Seal driven reading [WIP] Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it Aug 6, 2026
@KochetovNicolai KochetovNicolai added pr-performance Pull request with some performance improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Aug 6, 2026
KochetovNicolai and others added 5 commits August 6, 2026 17:36
…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();

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

KochetovNicolai and others added 4 commits August 7, 2026 19:50
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]>
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 7, 2026
…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]>
@KochetovNicolai KochetovNicolai changed the title [WIP] Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it Seal-gated reading: gate the probe side of a hash JOIN on the runtime filter and prune read ranges by it Aug 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
KochetovNicolai and others added 2 commits September 9, 2026 10:36
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]>
Comment on lines +771 to +774
if (seal_gate_refiner)
prefetched_pool->setReadRangesRefiner(seal_gate_refiner);
else
prefetched_pool->setReadRangesRefiner(createIndexReadRangesRefiner(index_build_context, storage_snapshot->metadata, settings));

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

KochetovNicolai and others added 2 commits September 10, 2026 13:28
…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]>
KochetovNicolai and others added 3 commits September 11, 2026 15:14
# 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]>
@CurtizJ CurtizJ self-assigned this Sep 14, 2026
alexey-milovidov and others added 2 commits September 26, 2026 23:41
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

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

LGTM

/// (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)

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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 identical key_arg->type != INPUT check, so nothing regressed.
  • Probe key = bare ts: the descriptor is registered (this function drops nothing), yet it dies later at the runtime_prune_primary_key gate in ReadFromMergeTree, which matches descriptors against PK column names (ts is not toDate(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.

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Oct 8, 2026
Merged via the queue into master with commit da0ca72 Oct 8, 2026
153 checks passed
@KochetovNicolai
KochetovNicolai deleted the seal-driven-reading branch October 8, 2026 13:36
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
PedroTadim added a commit that referenced this pull request Oct 9, 2026
…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]>
PedroTadim added a commit that referenced this pull request Oct 9, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-improvement Pull request with some product improvements 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.

4 participants