Repository navigation
Do not populate the query condition cache under a join runtime filter - #119823
alexey-milovidov merged 11 commits into
Conversation
A join runtime filter (`enable_join_runtime_filters`, on by default) plants an `__applyFilter(_runtime_filter_<hash>, key)` filter above a MergeTree read. Since ClickHouse#95838 the PREWHERE optimization runs after runtime filters are pushed down, so `optimizePrewhere` moves that filter into the read's PREWHERE while a conjunct it cannot move (one referencing every queried column, e.g. a view's HAVING) stays behind in a residual `FilterStep`. `updateQueryConditionCache` then tags that residual filter with a hash taken from `query_info.filter_actions_dag`, which does not contain the runtime filter. The existing guard on the filter step cannot notice: `splitAndFillPrewhereInfo` rebuilds the residual expression with `__applyFilter` as an *input* column, and `isDeterministicAllowingTopKFilter` returns true for an input node. At execution the PREWHERE empties a granule, the tagged filter sees zero rows for it, and `FilterTransform::writeIntoQueryConditionCache` records "no row matches <the WHERE condition>" for a granule that does contain matching rows. Later plain reads of the same view silently return fewer rows; nothing is logged. Gate the tag on the read step's PREWHERE with the same predicate the filter step already uses. A deterministic PREWHERE is part of `filter_actions_dag`, so the recorded key covers it; `__topKFilter` is allowed on purpose and its key is salted with the TopK plan; a join runtime filter is neither, because its contents are the build side's key set for one particular execution. Such a read therefore stops populating the cache (it still consults it), which is why the key cannot instead be salted the way the TopK filter's is. `FormatFilterInfo` keys the same cache for reads served by a data format, and had the identical hole: it hashes `filter_actions_dag` alone while storing the PREWHERE the plan ends up with. `optimizePrewhere` is generic over `SourceStepWithFilter`, so a runtime filter reaches a Parquet-backed read's PREWHERE too, and `getMatchedBuckets` derives unmatched row groups from the post-PREWHERE row count - a whole row group then gets recorded as matching nothing. It gets the same gate, which covers `File`, `url()` and object storage through the one shared constructor. There it can use plain determinism, because `optimizeTopK` installs `__topKFilter` only through a `ReadFromMergeTree *`. Found by the `NoREC` oracle of `SQLancerPP (arm_release)` on master f5ca648: a view read twice with a predicate true for every non-NULL row answered 6 rows one way and 5 the other. Locally, 500k rows and a one-key dimension table lose 9362 of 71428 rows (62066 vs 71428) of a `MergeTree` view, and a ten-row-group `File(Parquet)` table loses all 1429 matching rows (0 vs 1429), on the parent commit; both agree with the fix. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewIndependent review passes over this change; findings adjudicated against the code. ❌ The same hole existed in the second writer of this cache. ❌ Both tests now assert their own premise instead of inferring it.
💡 Noted, not changed: the invariant restored here is the one |
|
Workflow [PR], commit [ba8d2c5] Summary: ✅
AI ReviewSummaryThis PR closes the remaining query condition cache poisoning case where a join runtime filter is moved into a read's Final Verdict
LLVM Coverage ReportMeasured on commit ba8d2c5.
Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · Uncovered code |
Two coverage gaps in the tests, no change to the fix itself. `enable_join_runtime_filters_index_analysis` prunes marks in the readers chain (a `MergeTreeSkipIndexReader` whose predicate is built from the runtime filter) instead of only by moving `__applyFilter` into the read's PREWHERE, and the test pinned that setting off. The mode is also on its way to becoming the default (ClickHouse#117375). It is not a second defect: the new arm passes on the fixed binary, with read-time pruning demonstrably active (2 of 62 marks read, 8192 rows checked by the runtime filter). It is a stronger oracle than the existing one, though. On the parent commit it records a cache entry and the view returns 58555 of 71428 rows, where the arm that moves the filter into PREWHERE loses 9362; the residual filter carries the runtime filter as an ActionsDAG input there, so only the new PREWHERE check withholds the tag. The Parquet arm proved that the filter reaches PREWHERE and that the gate declines, but never that the filter had been built. `FunctionApplyFilter` passes every row while it is not ready, and in that state no row group is emptied and every assertion of the arm holds for the wrong reason, on the parent commit too. It now asserts `RuntimeFilterRowsChecked > 0` and `RuntimeFilterRowsPassed < RuntimeFilterRowsChecked` (measured 1429 and 0), with the runtime-filter-free join as the negative control, matching what the `MergeTree` sibling already does. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 17 s compile time in total, 8 of them have a recent master baseline. |
The test failed deterministically in the `old analyzer` stateless lanes.
Its plan assertions read `EXPLAIN` from a subquery and carried
`enable_analyzer = 1` in that subquery's own `SETTINGS`, while the lane
sets the session value to 0 (`tests/config/users.d/analyzer.xml`).
`validateAnalyzerSettings` (src/Interpreters/executeQuery.cpp:1143)
rejects a subquery that changes `enable_analyzer` relative to the top
level, so three arms died with `Code: 80 ... INCORRECT_QUERY` instead of
running. The `.sql` sibling was unaffected because it sets the value at
session level with `SET`.
The pin now sits on the client invocation, as in the other stateless
shell tests that need the analyzer, and the redundant query-level copies
are gone. Tagging the test out of the lane would instead have dropped
this lane's coverage of the code path the PR changes.
Measured against a server running that lane's profile (`SELECT
getSetting('enable_analyzer')` = false, `SELECT 1 QUALIFY 1` rejected
without the pin and accepted with it): the test fails there before this
change with the CI error and passes after it, 75 randomized runs, plus 50
randomized runs of each join-runtime-filter test and the whole query
condition cache family under the default profile. The lane is now a live
oracle rather than a silenced one: built from the parent commit's source,
the test reddens there on exactly the two lines it reddens on with the
new analyzer (1429 rows read as 0, and the recorded cache miss).
Co-Authored-By: Claude Opus 5 <[email protected]>
…oin-runtime-filter-prewhere # Conflicts: # src/Formats/FormatFilterInfo.cpp
…oin-runtime-filter-prewhere
…oin-runtime-filter-prewhere
CI finish ledger - d86b1bfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The red Session id: cron:our-pr-ci-monitor:20260921-000159 |
…oin-runtime-filter-prewhere
Master removed the query analysis that preceded the analyzer (ClickHouse#120311), so `enable_analyzer` is an obsolete setting frozen at `1` and the `old analyzer` lane the `.sh` test's session-level pin worked around no longer exists. Both tests pass locally against the merged branch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…row policies and skip indexes Addresses the review finding that the sibling `WHERE` writer could still record a mark range as non-matching after rows or marks disappeared ahead of the filter. Both named states were measured and neither is unsound, so no guard is added; instead the two properties that make them sound are pinned as a regression, next to the existing `03229_query_condition_cache_row_policy.sh` and `04275_104781_qcc_prewhere_skip_index_attribution.sql`: * A row policy is ANDed into `filter_actions_dag` before the filter walk (`optimizePrimaryKeyConditionAndLimit` calls `addFilter(getRowLevelFilter()->actions, ...)`), so a restricted read keys on a different condition than an unrestricted one. The restricted read writes an entry, the unrestricted read of the same query text still returns the full 50 rows and reports `QueryConditionCacheHits = 0`. * With `use_skip_indexes_on_data_read = 1` a skip-index reader sits ahead of `PREWHERE` in the readers chain, and `MergeTreeSelectProcessor` then attaches no `MarkRangesInfo` at all (the fix for issue ClickHouse#104781), so such a read writes nothing - measured as 0 rows in `system.query_condition_cache`. A liveness case proves the zero is the guard and not a dead test: the same shape with the pruning off writes one entry and that entry is reused, `QueryConditionCacheHits > 0`, with the indexes both off and back on. `optimize_use_implicit_projections = 0` and `optimize_move_to_prewhere = 0` are pinned per query so CI randomization cannot route the counts through `_exact_count_projection` or move the predicate onto the `PREWHERE` writer, which would make every assertion vacuous. 9/9 passes locally, including runs with randomized settings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119823&sha=d86b1bf5737c36745bb3643a678a1b9d736c05c1&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The other two reds are already tracked and need nothing here: |
|
The fix is merged: #120932 (2026-09-21 01:07:44 UTC). No tracking issue exists; I went from the 2026-09-18 onset straight to that PR, whose description carries the analysis. It is also the owner of that row in my CI ledger comment above, which I posted 50 minutes before the merge, so it reads "open" there. Root cause: The report you linked is the run at 2026-09-20 21:22 UTC, 3h45m before that merge. This PR's head has contained |
…tabase()`
Two mechanical CI failures of the new test, both reproduced locally against a
server running the `--fast-test` CI config and fixed here.
`Fast test` reds on `-0 / +1` at the "the read writes no entry at all" assertion.
The CI test profile (`tests/config/users.d/limits.yaml`) sets
`max_rows_to_read = 20000000`, and `ReadFromMergeTree::supportsSkipIndexesOnDataRead`
returns false whenever a row limit is set with `read_overflow_mode = throw`, so
`use_skip_indexes_on_data_read = 1` is a no-op in every CI lane. The minmax index
then runs during index analysis instead of during the data read, and the
index-analysis writer records the 62 excluded granules as one entry: measured
condition `and(equals(v, 3_UInt8), less(w, 100_UInt8))`, 62 of 63 marks
non-matching. That entry is sound, it is simply written by the other writer, so
the assertion describes a configuration CI never runs. `max_rows_to_read = 0` is
the same pin `03533_skip_index_on_data_reading.sql` uses for this feature.
`Style check` reds on the `various` leg: `various_checks.sh` accepts
`current_database` next to `currentDatabase` or to an unbraced
`$CLICKHOUSE_DATABASE`, and `'${CLICKHOUSE_DATABASE}'` matches neither.
`currentDatabase()` is the form the other 199 shell tests use and resolves to the
same database here.
Verified both directions on one binary: the unfixed test reproduces the CI diff
byte for byte, the fixed test is 1/1 with randomization off and 6/6 with it on,
dropping only the `max_rows_to_read` pin restores `-0 / +1`, and reverting only
`currentDatabase()` restores the style message.
|
Pushed a test-only fix for the two reds on
Verified on a local server running the |
|
|
||
| /// PREWHERE runs before the tagged filter sees a row, so a granule that filter empties may still | ||
| /// hold rows only PREWHERE removed. Sound while the PREWHERE condition is in `filter_actions_dag` | ||
| /// (the hash covers it) or is `__topKFilter` (key salted with the TopK plan); a runtime filter is neither. |
There was a problem hiding this comment.
This comment is hard to understand. It talks about runtime filters but the code checks something else. Something is wrong here.
There was a problem hiding this comment.
You are right, and it is not only the comment. The code checks that the PREWHERE is deterministic and assumes it is then part of filter_actions_dag (the PR description says so). That is false: a JOIN can push a deterministic ON conjunct down after filter_actions_dag is built, and optimizePrewhere moves it into PREWHERE. Default settings, current master:
CREATE TABLE t (k UInt64, v Int64, w Int64) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 64;
INSERT INTO t SELECT number, number, number FROM numbers(2000);
SELECT count() FROM t WHERE v + w < 100 AND v > 5; -- 44
SELECT count() FROM t RIGHT JOIN (SELECT * FROM t WHERE v + w < 100) AS a
ON t.v = a.v AND t.v + a.v >= 2048 WHERE t.v > 5; -- 0, correct
SELECT count() FROM t WHERE v + w < 100 AND v > 5; -- 0, wrongHere the build side's PREWHERE is v > 5 AND v + v >= 2048, but the key covers only v + w < 100 AND v > 5. This PR only adds refusals, so it did not cause this; #121946 (open) is the same class for the filter step. I will make the check test coverage instead of determinism, rewrite both comments to say what is checked, and link the PR here.
There was a problem hiding this comment.
The fix is #122804: both writers now require each PREWHERE conjunct to be a conjunct of the hashed condition, and both comments say what is checked.
| { | ||
| /// PREWHERE runs before the row count this hash describes, so a row group PREWHERE empties looks | ||
| /// like one the hashed condition rejected. A PREWHERE collected with the read's filters is inside | ||
| /// `filter_actions_dag`, so the hash covers it; a join runtime filter is moved in afterwards. |
There was a problem hiding this comment.
Same here: prewhere_covered is the same determinism check. The three queries above over CREATE TABLE f (k UInt64, v Int64, w Int64) ENGINE = File(Parquet) SETTINGS output_format_parquet_row_group_size = 64 (once the file is more than 3 seconds old) also return 44, 0, 0. With PREWHERE off they return 44, 0, 44, so on this path the gap is exactly this check. The follow-up fixes both.
|
Thanks for this fix. Could it be backported to 26.9? We hit this in production on 26.9.19.9, as silent row loss in an application-level key-range diff (about 1.1% of rows missing). It still reproduces on the latest 26.9 stable. Results of the self-contained reproduction below (synthetic data, default server config,
The Our workaround until then is Reproduction (run with
|
|
Thanks for the report and the reproduction. I can't add labels on this repository, so this needs a maintainer to add Facts for whoever picks it up:
|
Backport #119823 to 26.9: Do not populate the query condition cache under a join runtime filter
`updateQueryConditionCache` hashes the read step's `filter_actions_dag` and
attaches that hash to the filter step above the read, without checking that the
step's own predicate is what the hash describes. Three things make them diverge:
* `ReadFromMergeTree::applyFilters` rebuilds `filter_actions_dag` only on its
first call, because `indexes` caches index analysis, so the DAG is frozen at
that point;
* filter push-down and `tryMergeFilters` then replace the steps above the read
with a new `FilterStep` whose predicate is `and(child, parent)`, dropping the
key;
* the re-walk that exists to restore those dropped keys re-attaches one derived
from the frozen DAG onto the widened step.
A `JOIN` supplies the widening conjunct: once the join is inner, push-down moves
its `ON` conjunct below the `WHERE`, and the merge folds both into one filter.
`FilterTransform` empties the granule because of the `ON` conjunct and records
"no matching rows" under the hash of the `WHERE` predicate alone, so every later
read of that part with that predicate skips the granule. At default settings a
`SELECT count() FROM t WHERE v > 5` over 50000 rows then returns 0 instead of
49994; `enable_join_runtime_filters` has been on by default since 26.2 and
`use_query_condition_cache` is on by default, so no other setting is needed.
Record which filter conditions the DAG was built from and refuse to attach the
key to a step that is not one of them. The soundness requirement is one-sided: an
entry means "no row of this granule matches C", so the write is sound exactly when
C implies the step's predicate. The DAG describing more than the step does stays
sound and is the common case, because the read's PREWHERE and row-level filter are
in the DAG too. A refused write loses the optimization, never a row.
`adoptFiltersFrom` carries the names with the DAG, which is what keeps automatic
parallel replicas populating the cache: it builds its candidate plan with
`query_plan_optimize_primary_key` off and hands its reads the analysis that way.
This completes ClickHouse#119823, which established the same invariant for the case where
the narrowing step is the read's PREWHERE and left the merged-filter case open.
Found by the AST fuzzer's `Identity WHERE (NOT(NOT p))` oracle on master, which
reported it because `not(not(p))` hashes to a different key and so kept reading
the rows the reference had lost.
Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #115178
Related: #117968
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query silently returning fewer rows after an unrelated
JOINhad run: a join runtime filter (enable_join_runtime_filters) moved into a read'sPREWHEREmade the read record a "no matching rows" verdict in the query condition cache for granules, or Parquet row groups, whose rows only that runtime filter had removed. Such a read no longer populates the cache.Description
enable_join_runtime_filters(default on) plants an__applyFilter(_runtime_filter_<hash>, key)filter above a read. Since #95838optimizePrewhereruns after runtime-filter push-down, so it moves that filter into the read'sPREWHERE, while a conjunctMergeTreeWhereOptimizerrefuses to move (one referencing every queried column, e.g. a view'sHAVING) stays behind in a residualFilterStep.updateQueryConditionCachetags that residual filter with a hash offilter_actions_dag, which lacks the runtime filter; its determinism guard cannot notice, becausesplitAndFillPrewhereInforebuilds the residual expression with__applyFilteras an input column. At execution thePREWHEREempties a granule, the tagged filter sees zero rows for it, andFilterTransformrecords "no row matches<the WHERE condition>" for a granule that does hold matching rows. Later plain reads silently lose them.The fix gates the tag on the read step's
PREWHERE, using the predicate the filter step already uses. A deterministicPREWHEREis part offilter_actions_dag, so the recorded key covers it;__topKFilteris allowed on purpose and its key is salted with the TopK plan; a join runtime filter is neither, because its contents are the build side's key set for one particular execution.FormatFilterInfokeys the same cache for Parquet-backedfile()and object-storage reads and had the identical hole, where the filter empties a whole row group, so it gets the same gate. Such a read stops populating the cache;MergeTreestill consults it, the format path (one hash, both directions) does not.Found by the
NoRECoracle ofSQLancerPP (arm_release)on masterf5ca6487fe203c3ea48559d014363235150afa46(report): a view read twice with a predicate true for every non-NULL row answered 6 rows one way and 5 the other. Reduced locally, the parent commit loses 9362 of 71428 rows from aMergeTreeview and all 1429 from a Parquet file; this commit loses none.05233_qcc_where_writer_row_policy_skip_index.shpins the sibling writer, the residualWHEREone, which needs no such gate and is left alone: it keys on the wholefilter_actions_dag, so a row policy is already part of the key (it is ANDed in before the filter walk), and a read withuse_skip_indexes_on_data_read = 1writes no entry at all becauseMergeTreeSelectProcessorattaches noMarkRangesInfoonce the readers chain can skip marks ahead ofPREWHERE(the fix for #104781). The test asserts both, plus a liveness case in which the same shape without the data-read pruning does write an entry and reuse it, so neither zero can rot into a dead assertion.Workflow [PR]
Sync PR [sync-upstream/pr/119823]
Version info
26.9.23.16