Skip to content

Order join runtime filters after the other PREWHERE conditions when there are no statistics - #122452

Merged
fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-122403-runtime-filter-prewhere-order
Oct 7, 2026
Merged

fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-122403-runtime-filter-prewhere-order

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122403
Related: #122380

Changelog category (leave one):

  • Performance Improvement

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

Join runtime filters now run after the query's own PREWHERE conditions also for tables without column statistics, as they already did with statistics. Before, a runtime filter on a well-compressed join key could run first and read that key for every row, so enabling enable_join_runtime_filters could make a query read several times more data than without it.

Description

#122403 (@ fm4v): with enable_join_runtime_filters = 1 the reporter's join reads about 4x the bytes and fails max_bytes_to_read with TOO_MANY_BYTES, a limit it meets with the setting off. On master, for a table without statistics: 159.4 MB instead of 40.3 MB with enable_join_runtime_filters_index_analysis = 0, and 67.6 MB with the default 1 (29.8 MB with the fix).

Cause. MergeTreeWhereOptimizer orders the PREWHERE condition groups by cost per rejected row. With statistics a runtime filter is estimated to pass every row, so it goes last (#101653). Without statistics (auto_statistics_types = '', use_statistics = 0, or no part read has them, e.g. unmerged parts of a table above materialize_statistics_on_insert_max_table_size) the cost is the compressed column size alone, so the runtime filter on the sorted String key c1 (3.5 B/row) sorted ahead of time IN (...) (4.0 B/row) and read c1 for all 4M rows.

Change. A condition group made only of join runtime filters (__applyFilter, alone or in the OR isNull(key) of an ANTI join) now sorts after the query's own condition groups, also with allow_reorder_prewhere_conditions = 0, and, as with statistics, also when its column is the smaller one or it would be the more selective filter. Conditions on the primary key prefix still go last, and the size order among runtime filters is kept. With statistics, the reordering path changes only on a tie with a condition estimated to reject no rows.

Validation. The new test is the reporter's reproducer, scaled 4x down, plus a non-reordering arm and a LEFT ANTI JOIN on a Nullable key; each runtime-filter arm checks its filter ran. On master its three runtime-filter arms fail with TOO_MANY_BYTES; with the fix it passes 100/100 randomized runs, each reading the same bytes as without runtime filters. No new failures among 457 runtime filter, PREWHERE and statistics tests.


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

Version info

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

groeneai and others added 2 commits September 26, 2026 15:48
…here are no statistics

Without column statistics, MergeTreeWhereOptimizer orders the PREWHERE
condition groups by their compressed size alone. A join runtime filter is
expected to pass every row (the statistics estimator gives it selectivity
1.0, which sorts it last), but without an estimator that convention was
lost, so a runtime filter on a well-compressing join key could be read first
for every row, ahead of a selective condition of the query.

In ClickHouse#122403 the String key `c1` (3.5 B/row compressed) was read ahead of
`time IN (...)` (4 B/row): 159 MB instead of 40 MB with the same rows and
marks, so a query that met `max_bytes_to_read` without runtime filters
failed with TOO_MANY_BYTES with them. Tables whose parts carry no statistics
hit this on master too (for example parts written with
`materialize_statistics_on_insert = 0`, or `auto_statistics_types = ''`).

Add `Condition::is_runtime_filter` (every conjunct of the group is
`__applyFilter`, alone or inside the `OR isNull(key)` that an ANTI join
adds) to the ordering tuple right before `bytes_per_rejected_row`, and set
it in both the reordering and the non-reordering condition builders. Among
several runtime filters the size order is kept, and with statistics the
order only changes when a query condition is itself estimated to reject no
rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The arms that enable join runtime filters must now report RuntimeFilterRowsChecked > 0,
and the rf_off arm must report 0, so the check cannot pass with the filters not running.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding in the full pass, none in the delta recheck after the fix) plus my own cold review in each round (PR-description nits only, all fixed in it).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test would still pass if its queries silently stopped creating runtime filters: every check was an absence-of-regression check (05267_...sql, final query_log check) AGREE, fixed @ 0baed0a each query that enables runtime filters now also requires ProfileEvents['RuntimeFilterRowsChecked'] > 0, and the one that disables them requires = 0; each premise reddens when its query's enable_join_runtime_filters is flipped
2 ⚠️ Same finding, second half: require exact equal bytes or the exact PREWHERE order DISAGREE the defect is a 3.95x order flip (159,404,886 vs 40,324,070 bytes), which the 1.1 bound catches; exact equality would add a flake source (a merge between the two queries can move the granules that hold the passing rows), and a plan-text order check reddens whenever query_plan_merge_filters is randomized off (5% of runs), where the runtime filter is not in PREWHERE at all

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260926-175500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The reporter's fixture on AggregatingMergeTree/MergeTree without statistics and with enable_join_runtime_filters_index_analysis = 0: on master the runtime-filter join reads 159,404,886 bytes instead of 40,324,070 and fails max_bytes_to_read = 90000000 every run.
b Root cause explained? Without statistics the PREWHERE order falls back to compressed column size, which drops the "runtime filter passes every row" estimate, so the filter on the well-compressed key c1 is read for all rows before time IN (...).
c Fix matches root cause? Yes. The ordering key now places a group made only of runtime filters after the query's own condition groups, with or without statistics.
d Test intent preserved / new tests added? New test: the reporter's reproducer, a non-reordering arm, a LEFT ANTI JOIN on a Nullable key and a bytes check against the run without runtime filters. Each runtime-filter arm must also report RuntimeFilterRowsChecked > 0 and the arm without them 0, so turning any arm's runtime filters off or on makes the test fail. It fails on master.
e Both directions demonstrated? Master: 3 arms TOO_MANY_BYTES, bytes check red. Fix: 100/100 randomized runs, equal bytes with and without runtime filters in each, rows checked by the runtime filters > 0 in every run.
f Fix is general across code paths? One ordering key, set by both condition builders (reordering and allow_reorder_prewhere_conditions = 0); the statistics estimator already had this intent and is unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured on INNER and ANTI (Nullable key) filters, LZ4/ZSTD codecs, both string serializations, wide and compact parts, move_primary_key_columns_to_end_of_prewhere on/off, statistics missing from the metadata or only from the parts.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; only the PREWHERE order changes where a runtime-filter-only group competed with query conditions.
i Invariants and contracts preserved? The comparator stays a strict weak order, conditions and their read-step grouping are unchanged, results are identical (51 rows as without runtime filters).

Session id: cron:clickhouse-impl-slot-5:20260926-173100

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4293e8e]

Summary: ✅


AI Review

Summary

This PR changes MergeTreeWhereOptimizer so join runtime-filter-only condition groups sort after the query's own PREWHERE conditions when statistics are absent, and adds a focused regression test for the max_bytes_to_read regression from #122403. I reviewed the current PR head, the changed MergeTreeWhereOptimizer paths, the existing PR discussion, and the new test coverage; I did not find a correctness, performance, or metadata issue that still needs changes.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 4293e8e.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 47/49 (95.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 4293e8e2927d5cf3a31d967662813711099f7b14 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

The flaky check runs 18 copies of the test at once, and under TSAN the
4M-row `INSERT` into the `AggregatingMergeTree` took about 150 s per run,
so 5 of 20 runs failed `Test runs too long (> 180s)`.

Insert 1M rows over 25000 keys instead of 4M over 100000 (40 rows per key,
as before) and scale `max_bytes_to_read` from 90000000 to 22500000. Without
the fix the runtime-filter arms still read 3.4x the bytes of the arm without
runtime filters (40.3 MB against 11.8 MB) and fail with `TOO_MANY_BYTES`;
with the fix every arm reads the same bytes as without runtime filters.

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

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: aeafb7ca-76bc-48fc-b905-367435238493
  • MIRAI run: 4ef01ea4-ce34-4954-a1d0-5e18839b3bf2
  • PR check IDs:
    • clickbench_1997420_1790462627
    • clickbench_1997426_1790462627
    • clickbench_1997433_1790462627
    • tpch_adapted_1_official_1997444_1790462627
    • tpch_adapted_1_official_1997454_1790462627
    • tpch_adapted_1_official_1997490_1790462626

@fm4v
fm4v added this pull request to the merge queue Oct 7, 2026
Merged via the queue into ClickHouse:master with commit 22a3449 Oct 7, 2026
172 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
A correlated subquery that correlates by equality is decorrelated with the
correlated column rebuilt from the inner column, so its WHERE keeps one
`b.k = b.k` per key. The selectivity estimator priced each one as an unknown
condition (0.33), so a 5-key EXISTS over 10M rows estimated the inner table
at 39135 rows and chose a single-threaded HashJoin.

`equals(x, x)` of one DAG node whose type makes `=` reflexive and never NULL
(integers, Decimal, Enum, date and time types, String, FixedString, UUID,
IPv4, IPv6, also under LowCardinality) is now ALWAYS_TRUE in
ConditionSelectivityEstimator, and prunesNothingAtPlanTime treats it like a
runtime filter, so a filter made only of such conditions does not count for
the row estimate. Floats (NaN), Nullable and Tuple keep the default estimate.

This replaces the previous commit, which removed the conjunct from the plan.
Without it, the join runtime filter on the correlated key was no longer
grouped with a query condition on the same column, so on a table without
statistics MergeTreeWhereOptimizer ordered it after the other PREWHERE
conditions (ClickHouse#122452): TPC-H Q4 over Iceberg evaluated 24% more rows in
PREWHERE and was 16-20% slower in the performance comparison. Keeping the
conjunct leaves every plan as on master; only row estimates change.

Closes ClickHouse#122677

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AdeilH pushed a commit to AdeilH/ClickHouse that referenced this pull request Nov 6, 2026
A filter on a constant column of UNION ALL branches (`'s' AS sale_type` in
TPC-DS q4, q11, q74) reaches each branch as `materialize('s') = 's'`, next to
the branch's own conditions. `materialize` stops constant folding, and
`foldFilterPredicateThroughMaterialize` (ClickHouse#105987) folds only a filter that is
constant as a whole, so the conjunct stays. `ConditionSelectivityEstimator`
then priced it as a condition on an expression that is not a table column:
1% for `=` and 33% for `<`/`>`. In q74 `date_dim` was estimated at 3 rows
instead of 358, and join reordering built the hash table on the
`store_sales JOIN date_dim` side (14M rows at SF10) instead of `customer`.

`extractAtomFromTree` now decides `equals`, `notEquals`, `less`, `greater`,
`lessOrEquals`, `greaterOrEquals` of two constants with at least one behind
`materialize`, and `isNull`/`isNotNull` of such a constant, as ALWAYS_TRUE or
ALWAYS_FALSE. A constant-folded node under `materialize` counts too, since
`makeConvertingActions` puts the `_CAST` of a branch constant before
`materialize`.

Comparisons are decided with `accurateEquals`/`accurateLess`/
`accurateLessOrEqual`, only when both values have one totally ordered scalar
type after removing `LowCardinality`/`Nullable` (the type list of
`isAlwaysTrueEquality`, now shared) or are both integers. For these pairs the
`Field` comparison agrees with the comparison functions (Enum by value,
Decimal at the same scale, signed against unsigned through `accurate::lessOp`)
and cannot throw, so no try/catch is needed. Float, cross-type pairs (String
against Enum, see ClickHouse#121723), composite types and `IN` keep their default
estimate. A comparison with a NULL constant is not decided: it is NULL, not
FALSE, and ALWAYS_FALSE would turn into ALWAYS_TRUE under `NOT`.

As in ClickHouse#126131, only the estimate changes: the executed filter, results and
exceptions are the same. Removing the conjunct from the plan instead would
also move runtime filters and PREWHERE grouping (the first version of
ClickHouse#126131 slowed TPC-H Q4 over Iceberg that way, ClickHouse#122452), and would widen the
reach of ClickHouse#121723.

Analysis and original patch by snelheidai in ClickHouse#128482.

Closes ClickHouse#128482

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

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

@fm4v I found this PR by accident. At the off-site, the Join team agreed that we should ignore the no-statistics case - it's "garbage in - garbage out". This PR adds new code for this case. In future, could you please ping someone from the join team to review join-related PRs? We could have prevented this if we knew about this PR. Thanks!

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

The reviewers on this PR were my pick, not @ fm4v's: I chose them from the touched files (MergeTreeWhereOptimizer only), so the Join team was missed. From now on I cc someone from the Join team on every PR about joins or join runtime filters.

If you want the no-statistics ordering gone, I can open a PR that removes it (the is_runtime_filter key in MergeTreeWhereOptimizer and test 05267). It shipped in 26.10 and was not backported.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enable_join_runtime_filters=1 puts the runtime filter ahead of a selective PREWHERE condition: about 4x more bytes read, TOO_MANY_BYTES

6 participants