Skip to content

Do not populate the query condition cache under a join runtime filter - #119823

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-qcc-poisoning-join-runtime-filter-prewhere
Sep 21, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-qcc-poisoning-join-runtime-filter-prewhere

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115178
Related: #117968

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 JOIN had run: a join runtime filter (enable_join_runtime_filters) moved into a read's PREWHERE made 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 #95838 optimizePrewhere runs after runtime-filter push-down, so it moves that filter into the read's PREWHERE, while a conjunct MergeTreeWhereOptimizer refuses to move (one referencing every queried column, e.g. a view's HAVING) stays behind in a residual FilterStep.

updateQueryConditionCache tags that residual filter with a hash of filter_actions_dag, which lacks the runtime filter; its determinism guard cannot notice, because splitAndFillPrewhereInfo rebuilds the residual expression with __applyFilter as an input column. At execution the PREWHERE empties a granule, the tagged filter sees zero rows for it, and FilterTransform records "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 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. FormatFilterInfo keys the same cache for Parquet-backed file() 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; MergeTree still consults it, the format path (one hash, both directions) does not.

Found by the NoREC oracle of SQLancerPP (arm_release) on master f5ca6487fe203c3ea48559d014363235150afa46 (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 a MergeTree view and all 1429 from a Parquet file; this commit loses none.

05233_qcc_where_writer_row_policy_skip_index.sh pins the sibling writer, the residual WHERE one, which needs no such gate and is left alone: it keys on the whole filter_actions_dag, so a row policy is already part of the key (it is ANDed in before the filter walk), and a read with use_skip_indexes_on_data_read = 1 writes no entry at all because MergeTreeSelectProcessor attaches no MarkRangesInfo once the readers chain can skip marks ahead of PREWHERE (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

  • Backported to: 26.9.23.16

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent review passes over this change; findings adjudicated against the code.

❌ The same hole existed in the second writer of this cache. FormatFilterInfo::condition_hash
hashes the filter DAG captured before the runtime filter is moved in, while Parquet's matched-row-group
result reflects the later PREWHERE, so a file() or object-storage read on a join's probe side cached
an unsound row-group exclusion too: measured, all 1429 matching rows lost. It gets the same gate, plus a
regression test.

❌ Both tests now assert their own premise instead of inferring it. __applyFilter passes every row
until its lookup is ready, and the row-group arm established cache eligibility with a different
predicate and no join, so "the gated read cached nothing" could not be told apart from "the read was
never eligible". The arms now assert RuntimeFilterRowsChecked/RowsPassed, and execute the same join
with runtime filters off and require it to miss the cache.

⚠️ Disclosed trade: on the format path one token gates reads and writes alike, so a gated read stops
consulting the cache as well as populating it. Reusing an entry written by an earlier plain read would
be sound, since a runtime filter only narrows rows, but keeping a single token is what makes
write-eligibility unforgeable. MergeTree reads are unaffected.

💡 Noted, not changed: the invariant restored here is the one
04303_join_runtime_filter_query_condition_cache already documents, which leaked only once the filter
reached PREWHERE. #118703 moves isDeterministicAllowingTopKFilter into VirtualColumnUtils and adds
no PREWHERE gate, so whoever merges second re-points the call. Separately, by reading and not
reproduced, so out of scope here: the MarkRangesInfo attach feeding the WHERE write
(MergeTreeSelectProcessor.cpp:294) checks appliesMutationsBeforePrewhere alone, where the PREWHERE
write just below also requires !readersChainCanSkipMarksBeforePrewhere() && !row_level_filter.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ba8d2c5]

Summary: ✅


AI Review

Summary

This PR closes the remaining query condition cache poisoning case where a join runtime filter is moved into a read's PREWHERE, both for MergeTree reads and for the shared format/object-storage path. I did not find a remaining correctness or cache-keying issue in the current head, and the added regressions are focused enough to cover the previously questioned residual WHERE writer cases for row policies and use_skip_indexes_on_data_read = 1.

Final Verdict
  • Status: ✅ Approve
  • The implementation matches the stated contract, and the regression evidence in the PR is sufficient for the fixed paths.

LLVM Coverage Report

Measured on commit ba8d2c5.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 13, 2026
Comment thread src/Formats/FormatFilterInfo.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 13, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ba8d2c58c with master d14841253 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of de0734db6; 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.

Compile time of recompiled translation units

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

Job report

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]>
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
…oin-runtime-filter-prewhere

# Conflicts:
#	src/Formats/FormatFilterInfo.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d86b1bf

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: GroupingAggregatedTransform pushed bucket A twice (STID: 3994-4c1d) trunk-wide logical error, not from this diff: 143 rows over 111 distinct PRs and 21 distinct checks in 30d, 20 of them on master, first seen 2026-08-22 #119814 (external, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log infra: Code: 344 ... Transactions require Keeper to advertise LIST_WITH_STAT_AND_DATA, FILTERED_LIST, MULTI_READ and CHECK_STAT feature flags (SUPPORT_IS_DISABLED), reached here through DatabaseCatalog; the check's own configure() rolls those flags 50/50 while transactions.xml is always installed. 52 unrelated PRs in 30d, 0 master rows, first seen 2026-09-18 #120932 (mine, open)
Build profile diff infra, the CI logs cluster refuses the read (ci/jobs/build_profile_diff_job.py traceback); 342 red rows over 294 PRs in 24h, 0 on master, and no re-run clears it #121048 (external, open)

The red Mergeable Check and PR statuses are praktika rollups: they carry no failure of
their own and go green when the three rows above do.

Session id: cron:our-pr-ci-monitor:20260921-000159

alexey-milovidov and others added 2 commits September 21, 2026 02:40
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

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

Upgrade check reds on Error message in clickhouse-server.log with Code: 344 ... Transactions require Keeper to advertise \LIST_WITH_STAT_AND_DATA`, `FILTERED_LIST`, `MULTI_READ` and `CHECK_STAT` feature flagsraised out ofDatabaseCatalogwhile dropping a table. Unrelated to this PR, which only gates a query-condition-cache write, and fleet-wide: the same message reds theUpgrade check` of at least 20 other PRs over the last week (#120690, #120908, #120906, #121099, #119230, #120982, #120949, #106578, #118230, #117004, #119545, #119134, #118674, #120671, #116248, #119715, #118162, #118708, #113022, ...). I could not find a tracking issue for it.

The other two reds are already tracked and need nothing here: Stress test (arm_tsan) is #115986 (GroupingAggregatedTransform pushData), and Build profile diff is the infra failure #120462.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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: tests/config/install.sh always links config.d/transactions.xml, so every stress and upgrade server runs with allow_experimental_transactions=42, while configure() in tests/docker_scripts/stress_tests.lib rolled the embedded Keeper's filtered_list and multi_read 50/50 (KeeperContext force-enables FILTERED_LIST only when multi_read is on). upgrade_runner.sh calls configure() once per release, so the two servers roll independently and the pre-upgrade one can leave parts whose txn_version.txt carries a transactional creation_tid. Loading such a part on the restarted server runs MergeTreeData::loadDataPart -> VersionMetadata::validateInfo -> TransactionManager::instance(), whose constructor requires the four flags and fails closed, so the ATTACH aborts and later queries on the table get Code: 722. The requirement reached master with #117822 (2026-09-18 02:03 UTC), which pinned the flags in its integration tests; the shell harness shared by Stress test (*) and Upgrade check (*) was the one place it missed, and #120932 stops randomizing them there.

The report you linked is the run at 2026-09-20 21:22 UTC, 3h45m before that merge. This PR's head has contained e0b84a6 since the master merge at 02:40 UTC, so the next Upgrade check (amd_release) run here has the flags pinned; the runs still reddening elsewhere are on heads that predate it and pick it up with their next master merge. Nothing separate to open.

…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed a test-only fix for the two reds on a5a2fe9d in 05233_qcc_where_writer_row_policy_skip_index.sh, both mechanical.

Fast test reds -0 / +1 on the "the read writes no entry at all" assertion. The CI test profile sets max_rows_to_read = 20000000 (tests/config/users.d/limits.yaml), 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 rather than during the data read, and the index-analysis writer records one entry: 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 as written 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.

Verified on a local server running the --fast-test CI config, 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.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 21, 2026
Merged via the queue into ClickHouse:master with commit 92e5c4e Sep 21, 2026
177 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026

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

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.

This comment is hard to understand. It talks about runtime filters but the code checks something else. Something is wrong here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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, wrong

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

Same problem here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@caseypettingill

caseypettingill commented Oct 20, 2026 •

Copy link
Copy Markdown

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, clickhouse/clickhouse-server Docker images), two runs per version:

Version expected anti join actual (cache on) actual (cache off)
26.9.19.9 57360 57360 55793 57360
26.9.22.3 (latest 26.9) 57360 57360 55793 57360
26.8.31.2 LTS 57360 57360 57360 57360
26.11.1.290 (head) 57360 57360 57360 57360

The LEFT ANTI JOIN itself returns the right count. A later plain scan with the same key-range condition then returns fewer rows when use_query_condition_cache = 1. In our runs it needed max_threads = 1 and enable_join_runtime_filters = 1, plus old_keys written as key-ordered parts. 26.8 LTS is not affected, which fits the regression coming from #95838 as described above. The fix is in head.

Our workaround until then is use_query_condition_cache = 0. Because a wrong verdict leaks into later queries, it has to be set in user profiles, not per query.

Reproduction (run with clickhouse-client --multiquery)
-- Query condition cache + join runtime filter: a plain scan returns too few rows after an anti join.
-- Synthetic data. Run with clickhouse-client --multiquery.
SELECT version();
DROP DATABASE IF EXISTS qcc_repro SYNC;
CREATE DATABASE qcc_repro;
CREATE TABLE qcc_repro.old_keys (id UInt32, sys_period String) ENGINE = MergeTree ORDER BY (id, sys_period);
CREATE TABLE qcc_repro.new_keys (id UInt32, sys_period String) ENGINE = MergeTree ORDER BY (id, sys_period);
SYSTEM STOP MERGES qcc_repro.old_keys;
SYSTEM STOP MERGES qcc_repro.new_keys;
INSERT INTO qcc_repro.old_keys SELECT * FROM (SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('{"Lower": "', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '", "Upper": "', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '"}') AS sys_period FROM (SELECT number AS n FROM numbers(350000))) ORDER BY id, sys_period LIMIT 159561 OFFSET 0;
INSERT INTO qcc_repro.old_keys SELECT * FROM (SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('{"Lower": "', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '", "Upper": "', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '"}') AS sys_period FROM (SELECT number AS n FROM numbers(350000))) ORDER BY id, sys_period LIMIT 146483 OFFSET 159561;
INSERT INTO qcc_repro.old_keys SELECT * FROM (SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('{"Lower": "', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '", "Upper": "', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '"}') AS sys_period FROM (SELECT number AS n FROM numbers(350000))) ORDER BY id, sys_period LIMIT 40731 OFFSET 306044;
INSERT INTO qcc_repro.old_keys SELECT * FROM (SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('{"Lower": "', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '", "Upper": "', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '"}') AS sys_period FROM (SELECT number AS n FROM numbers(350000))) ORDER BY id, sys_period LIMIT 3225 OFFSET 346775;
INSERT INTO qcc_repro.new_keys SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('["', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '+00","', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '+00")') AS sys_period FROM (SELECT number AS n FROM numbers(0, 145824));
INSERT INTO qcc_repro.new_keys SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('["', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '+00","', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '+00")') AS sys_period FROM (SELECT number AS n FROM numbers(145824, 145824));
INSERT INTO qcc_repro.new_keys SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('["', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '+00","', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '+00")') AS sys_period FROM (SELECT number AS n FROM numbers(291648, 24272));
INSERT INTO qcc_repro.new_keys SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('["', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '+00","', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '+00")') AS sys_period FROM (SELECT number AS n FROM numbers(315920, 24272));
INSERT INTO qcc_repro.new_keys SELECT toUInt32(if(n % 8 < 3, 1, 2 + intHash32(n) % 50000)) AS id, concat('["', toString(toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)), '+00","', toString((toDateTime64('2020-01-01 00:00:00', 6, 'UTC') + toIntervalMicrosecond(n * 7919)) + toIntervalSecond(3600)), '+00")') AS sys_period FROM (SELECT number AS n FROM numbers(340192, 9808));
SYSTEM DROP QUERY CONDITION CACHE;
SELECT 'expected', count() FROM qcc_repro.new_keys WHERE (id > 16793 OR (id = 16793 AND sys_period >= '{"Lower": "2020-01-01 00:40:02.680033", "Upper": "2020-01-01 01:40:02.680033"}')) AND (id < 29963 OR (id = 29963 AND sys_period < '["2020-01-01 00:17:48.922458+00","2020-01-01 01:17:48.922458+00")')) SETTINGS use_query_condition_cache = 0;
SELECT 'anti join', count() FROM (SELECT id, sys_period FROM qcc_repro.old_keys WHERE (id > 16793 OR (id = 16793 AND sys_period >= '{"Lower": "2020-01-01 00:40:02.680033", "Upper": "2020-01-01 01:40:02.680033"}')) AND (id < 29963 OR (id = 29963 AND sys_period < '["2020-01-01 00:17:48.922458+00","2020-01-01 01:17:48.922458+00")'))) AS c LEFT ANTI JOIN (SELECT * FROM qcc_repro.new_keys WHERE (id > 16793 OR (id = 16793 AND sys_period >= '{"Lower": "2020-01-01 00:40:02.680033", "Upper": "2020-01-01 01:40:02.680033"}')) AND (id < 29963 OR (id = 29963 AND sys_period < '["2020-01-01 00:17:48.922458+00","2020-01-01 01:17:48.922458+00")'))) AS s ON s.id = c.id AND s.sys_period = c.sys_period SETTINGS max_threads = 1, use_query_condition_cache = 1, enable_join_runtime_filters = 1;
SELECT 'actual', count() FROM qcc_repro.new_keys WHERE (id > 16793 OR (id = 16793 AND sys_period >= '{"Lower": "2020-01-01 00:40:02.680033", "Upper": "2020-01-01 01:40:02.680033"}')) AND (id < 29963 OR (id = 29963 AND sys_period < '["2020-01-01 00:17:48.922458+00","2020-01-01 01:17:48.922458+00")')) SETTINGS use_query_condition_cache = 1;
SELECT 'actual, cache off', count() FROM qcc_repro.new_keys WHERE (id > 16793 OR (id = 16793 AND sys_period >= '{"Lower": "2020-01-01 00:40:02.680033", "Upper": "2020-01-01 01:40:02.680033"}')) AND (id < 29963 OR (id = 29963 AND sys_period < '["2020-01-01 00:17:48.922458+00","2020-01-01 01:17:48.922458+00")')) SETTINGS use_query_condition_cache = 0;
DROP DATABASE qcc_repro SYNC;

Tracking issue for the backport: #126951

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the report and the reproduction. I can't add labels on this repository, so this needs a maintainer to add v26.9-must-backport; the backport robot then opens the 26.9 PR.

Facts for whoever picks it up:

  • 26.9 is the only affected release branch. It was cut on 2026-09-16, five days before this PR merged; 26.10 contains the fix, and the reproduction above returns the right count on 26.8.32.13, 26.7.35.13 and 26.3.57.14.
  • This PR cherry-picks onto the current 26.9 head (8b433c1d42fb) without conflicts.
  • On a build of that head plus the cherry-pick, the reproduction returns 57360 (expected 57360). The same build with only this PR's two src/ changes reverted returns 55793, as does the official 26.9.23.14 build. So this PR alone fixes the reported case on 26.9.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 20, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 20, 2026
Backport #119823 to 26.9: Do not populate the query condition cache under a join runtime filter
alexey-milovidov pushed a commit to zhongyuankai/ClickHouse that referenced this pull request Oct 25, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 22, 2026
`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]>
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants