Skip to content

Exclude synthesized dynamic filters from PREWHERE effectiveness events - #131075

Merged
leshikus merged 6 commits into
ClickHouse:masterfrom
olegkkruglov:issue-131041-prewhere-events-dynamic-filters
Nov 13, 2026
Merged

leshikus merged 6 commits into
ClickHouse:masterfrom
olegkkruglov:issue-131041-prewhere-events-dynamic-filters

Conversation

@olegkkruglov

@olegkkruglov olegkkruglov commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #131041
Related: #130645

The PREWHERE-effectiveness ProfileEvents added in #130645
(GranulesReadByPrewhereReaders, GranulesSkippedByPrewhereReaders,
RowsSkippedByPrewhereReaders) marked every read step built from
prewhere_info as the query PREWHERE. But an optimizer can inject dynamic
filters into prewhere_info that are not part of the user's query predicate,
and those were counted too:

  • the __topKFilter of ORDER BY <non-key column> LIMIT n
    (use_top_k_dynamic_filtering), and
  • the __applyFilter join runtime filter pushed into the probe-side scan.

As a result, a query with no user PREWHERE/WHERE predicate reported nonzero
granule and row skip counts. The issue reports the ORDER BY ... LIMIT case;
the join runtime filter is the same bug and was found while fixing it.

Now a read step is counted toward these events only when it evaluates a user
query-predicate conjunct; a step whose conditions are solely synthesized
dynamic filters is not attributed to PREWHERE. A query without a user
predicate reports nothing, and a real PREWHERE is still counted.

Covered by a new stateless test
05572_prewhere_events_exclude_dynamic_filters.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

The PREWHERE effectiveness profile events (GranulesReadByPrewhereReaders, GranulesSkippedByPrewhereReaders, RowsSkippedByPrewhereReaders) no longer count the internal dynamic filters of ORDER BY ... LIMIT (top-K) and join runtime filters; a query without a PREWHERE now reports zero for them.


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

Version info

  • Merged into: 26.11.1.2158-master (included in 26.11 and later)

The PREWHERE granule/row ProfileEvents marked every step built from
`prewhere_info` as the query PREWHERE, so the dynamic filters an optimizer
injects into `prewhere_info` were counted too: the `__topKFilter` of
`ORDER BY ... LIMIT` and the `__applyFilter` join runtime filter. A query
with no user `PREWHERE`/`WHERE` predicate then reported nonzero granule and
row skip counts.

Count a step only when it evaluates a user query-predicate conjunct; a step
whose conditions are solely synthesized dynamic filters is not attributed to
PREWHERE. Add test `05572`.
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 12, 2026
@leshikus leshikus added the can be tested Allows running workflows for external contributors label Nov 12, 2026
@leshikus
leshikus self-requested a review November 12, 2026 16:06
@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bcff611]

Summary: ✅


AI Review

Summary

The change excludes synthesized top-K and join runtime filters from PREWHERE effectiveness events and combines attribution across granule fragments. No actionable findings remain at bcff61139c45604a87f81a6e6667cc4ad8a0fa0e; the earlier inline findings are addressed. The exact-head fast-test report confirms that 05572_prewhere_events_exclude_dynamic_filters and the existing granule-counting and mutation-attribution regressions passed. Broader CI remains pending.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bcff61139 with master acd88ab8f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.59 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 12.1 s +8.4 s (+228%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.1 s +5.0 s (+240%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -255.3 s (-6%) in total before that adjustment.

Job report

…cate

The earlier fix only zeroed the counts for queries whose `PREWHERE` is
entirely a synthesized dynamic filter. Two cases where a dynamic filter
runs alongside or after a real user predicate were still mis-attributed.

1. Chain-level granule counter. When the user condition is in `WHERE`,
   `optimizePrewhere` moves both it and a join runtime filter `__applyFilter`
   into `PREWHERE` as two steps (user predicate first, runtime filter second).
   `MergeTreeReadersChain::read` measured surviving rows per granule after the
   whole chain, so granules the runtime filter emptied counted as dropped by
   `PREWHERE`. Snapshot the survivors at the output of the last query-`PREWHERE`
   reader (`last_query_prewhere_reader_index`), symmetric to the existing
   "entering" snapshot, so a later synthesized step's granule drops are excluded.

2. Fused mixed step. With `enable_multiple_prewhere_read_steps = 0` the user
   `c % 2 = 0` and the top-K `__topKFilter` share one fused step whose rejections
   cannot be separated. The step flag was "any conjunct is a user predicate",
   which attributed the whole fused step, including top-K's rejections. Flip it
   to "no conjunct is a dynamic filter" (`prewhereIsEntirelyQueryPredicate`,
   `none_of`): a fused step mixing user and synthesized conjuncts is fail-closed
   and reports nothing rather than over-counting.

Extend `05572_prewhere_events_exclude_dynamic_filters` with both cases, using
`PREWHERE c % 2 = 0` as the oracle: it keeps half of every granule, so the user
predicate drops no granule and any granule drop is provably a leak.
The previous fix snapshotted surviving rows per granule at the last query-
PREWHERE reader's output. That is still a boundary: it excludes a dynamic
filter that runs *after* the last user step, but not one *between* two user
steps. With `PREWHERE c % 2 = 0 WHERE a < 199999` and a join runtime filter,
`optimizePrewhere` produces the steps `c % 2 = 0` -> `__applyFilter` -> `a < 199999`;
the runtime filter's granule drops were baked into the end snapshot and
attributed to PREWHERE, reporting `(25, 24, 100000)` where neither user
predicate empties a granule.

The root cause is that granule attribution read a single end-of-chain
snapshot, so it could not tell which step emptied a granule. The per-step row
counter never had this problem. Make the granule counter per-step too: walk
the steps from the first to the last query-PREWHERE reader, find the first step
that empties each granule, and count it as dropped by PREWHERE only when that
step is a query-PREWHERE step, never a dynamic filter -- whether the filter
runs before, between, or after the user steps. This replaces the boundary
snapshot (`rows_surviving_prewhere`) and handles the interleaved case the same
way as the appended and fused ones.

Extend `05572_prewhere_events_exclude_dynamic_filters` with the interleaved
case; it now reports `(25, 0, 100000)`.
The per-step attribution still mis-credited a granule when a dynamic filter
only partially emptied it and a later user step rejected the remnant. With
`PREWHERE c % 2 = 0 WHERE a > 100` and a join runtime filter the steps are
`c % 2 = 0` -> `__applyFilter` -> `a > 100`; the runtime filter leaves only
`b in (42, 100)` of granule 0, then `a > 100` rejects both and emptied the
granule. But 4045 rows of that granule satisfy both user predicates, so the
user predicate alone does not empty it -- the runtime filter did. The granule
was wrongly counted as dropped by PREWHERE (and the count depended on
`max_block_size`, because a granule split into fragments hid the effect).

A granule counts as dropped by PREWHERE only when the user predicate alone
empties it, which can be asserted only if no non-user filter removed any of
its rows. Replace the "first step that empties the granule" rule with a
contamination flag: while walking from the first to the last query-PREWHERE
reader, mark a granule once any non-user (dynamic filter) step reduces its
survivors. A granule is dropped only if it is empty after the last user step
and was never thinned by a dynamic filter. Row-level policies, mutations and
lightweight deletes run before PREWHERE and are already excluded via the
`entering` snapshot, so the between-steps non-user steps are exactly the
synthesized dynamic filters. The existing mark combiner OR-s the per-fragment
markers, so a granule split across blocks is dropped only when every fragment
was cleanly emptied by the user predicate, making the result block-size
independent.

Extend `05572_prewhere_events_exclude_dynamic_filters` with the partially
filtered granule at `max_block_size` 65409 and 4096; both report
`(25, 0, 100002)`.
… chain

A synthesized dynamic filter that runs before the first user step -- a leading
`__topKFilter` in a split plan -- was outside the contamination walk, which
started at the first user step. With `PREWHERE c = 1 ORDER BY b LIMIT 10` the
steps are `__topKFilter(b)` -> `c = 1`; top-K keeps ten rows per granule, all
with `c = 0`, so `c = 1` rejects the remnant and empties the granule -- yet
every granule keeps thousands of `c = 1` rows, so the user predicate alone
never empties it. The granule was still attributed to PREWHERE.

Mark each prewhere step that carries a synthesized dynamic filter with a new
`PrewhereExprStep::is_synthesized_dynamic_filter` flag, set where the dynamic
filters are already recognised (the splitter and the single-step path). In
`MergeTreeReadersChain`, walk the per-granule survivor counts from the first
reader instead of the first user step, and contaminate a granule whenever a
dynamic-filter step reduces its survivors, wherever that step runs. Row-level
policies, on-fly mutations and lightweight deletes do not carry the flag, so
they still do not contaminate -- they run before PREWHERE and are excluded via
the entering snapshot. A granule is counted as dropped only if it is empty
after the last user step and was never touched by a dynamic filter.

Add the leading split-step top-K case (reported on the previous commit) to
`05572_prewhere_events_exclude_dynamic_filters`; it reports `(25, 0, 170)`.
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Nov 13, 2026
A granule split across read blocks, where a leading `__topKFilter` empties one
whole fragment, was still mis-attributed. The emptied fragment has zero rows
entering the user step, so `forEachGranuleMark` skipped it and its contamination
never reached the mark; if another fragment of the same granule was cleanly
emptied by the user predicate, the mark was finalized as dropped by `PREWHERE`.
With `PREWHERE c = 1 ORDER BY b LIMIT 10` at `max_block_size = 4096` on a table
whose granule halves land in separate blocks, this reported `(10, 9, 36864)`
although every granule keeps 4096 rows satisfying `c = 1`.

Track the granule verdict per mark with three flags OR-ed across all fragments:
`read` (rows reached the user predicate), `survived` (a row survived it), and
`contaminated` (a synthesized dynamic filter removed rows from it). Feed a
fragment that a dynamic filter emptied before the user step too -- it carries
`contaminated` to the mark without being counted as read. A granule is counted
as dropped only if it was read, nothing survived, and it was never contaminated.
`forEachGranuleMark` now yields the granule index and a caller-supplied visit
gate instead of gating on the entering count, so zero-entering contaminated
fragments are visited. This folds the before/between/after and split-fragment
cases into one rule.

Add the split-fragment case to `05572_prewhere_events_exclude_dynamic_filters`;
it reports `(10, 0, 36864)`.

@leshikus leshikus left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good

@leshikus
leshikus enabled auto-merge November 13, 2026 05:24
@leshikus
leshikus added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit d954e9a Nov 13, 2026
204 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 14, 2026
`tryBuildPrewhereSteps` groups adjacent PREWHERE conjuncts that read the same
columns into one read step. A user predicate on a join key (`less(b, 8192)`)
and the join runtime filter `__applyFilter` on that same key were therefore
fused into one step. Since ClickHouse#131075 a step carrying any synthesized dynamic
filter is marked `is_query_prewhere = false`, which excludes the whole step
from the PREWHERE-effectiveness events (`GranulesReadByPrewhereReaders`,
`GranulesSkippedByPrewhereReaders`, `RowsSkippedByPrewhereReaders`). The fused
step then reported `0 0 0` even though the user predicate dropped 96% of the
granules.

Replace the `__topKFilter`-specific `follows_top_k_filter` split rule with a
symmetric one: a synthesized dynamic filter and a user predicate never share a
step, regardless of `read_ahead_columns`. Each is attributed on its own; the
shared column is still read once through `group_read_step`. This also covers a
build-side-key predicate the planner pushes into the probe scan
(`WHERE d.x < 8192`) and a user conjunct on the `ORDER BY` column when the
caller passes `read_ahead_columns = false`, both of which the old top-K rule
missed.

Covered by a new case in `05572_prewhere_events_exclude_dynamic_filters`.

Closes: ClickHouse#131263
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. external Author is not a member of the ClickHouse organization pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PREWHERE profile events count ORDER BY ... LIMIT top-K filter rejections

5 participants