Skip to content

Fix wrong results after a JOIN poisons the query condition cache - #121946

Merged
fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:qcc-intervening-filter-guard
Nov 22, 2026
Merged

fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:qcc-intervening-filter-guard

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123845

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 silently wrong results from the query condition cache. Once a query with a JOIN, or with a filter above a LIMIT, had read a part, a later query using the same WHERE predicate on that part could return rows from fewer granules, or no rows at all. Reachable with default settings.

Description

On 26.9 with default settings, SELECT count() FROM t WHERE v > 5 returns 0 instead of 49994 once an earlier JOIN over the same part has run. use_query_condition_cache and enable_join_runtime_filters are both on by default:

CREATE TABLE t (v Int64) ENGINE = MergeTree ORDER BY v;
INSERT INTO t SELECT number FROM numbers(50000);
SELECT count() FROM t WHERE v > 5;                                 -- 49994
SELECT count() FROM t LOCAL RIGHT JOIN t AS a
  ON and(equals(v, a.v), not(equals(v, a.v))) WHERE v > 5;         -- 0, correct
SELECT count() FROM t WHERE v > 5;                                 -- 0, WRONG

Root cause: updateQueryConditionCache hashes the read step's filter_actions_dag and attaches that hash to the filter step above the read. The DAG is frozen at index analysis, but push-down and tryMergeFilters then rebuild that step with the JOIN's ON conjunct merged in, and a re-walk re-attaches the stale key to it. The ON conjunct empties the granule, which is then recorded as matching no row of the WHERE predicate.

The fix records which conditions filter_actions_dag was built from and refuses the key on a step whose condition is neither one of them nor an and of them. A refused write costs only the optimization, never a row. This completes #119823, which established the same invariant where the narrowing step is the read's PREWHERE.

Since 26.10 the ON conjunct stays above the join, so that query is correct there. On 26.10.3.7 and master two other shapes still return 0 instead of 500: join runtime filters pushing the outer filter down after index analysis (05453_query_condition_cache_filter_merged_after_collection), and an outer filter above a LIMIT or LIMIT BY (#123845, 05243_query_condition_cache_filter_above_limit). Both tests come from #122271.

Found by the AST fuzzer's Identity WHERE (NOT(NOT p)) oracle on master (report for f61f67b3). The JOIN test is added to #119823's own file, its existing assertions unchanged.


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

Version info

  • Merged into: 26.12.1.194-master (included in 26.12 and later)

groeneai and others added 2 commits September 24, 2026 09:22
`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]>
Delete the design/soundness narration above the new guard, the new member's write site and its accessor; keep one line on the frozen-DAG invariant at the guard and the member's own meaning.
@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 24, 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; 0 findings) plus my own cold read of the
diff before reading the implementation notes. Nothing blocking. The rows below are what I decided not to
change, recorded so the decisions are visible rather than implied.

# Sev Finding Verdict Evidence / action
1 💡 The guard is one-sided, so it also refuses a filter step rebuilt by merging two conditions that were both recorded, even though that key would have been sound AGREE, not changed Recovering it needs the conjunct structure of the rebuilt step. A refused write costs a cache entry, never a row, and tryMergeExpressions preserves the filter column name, so the re-walk keeps the job it was added for
2 💡 The recorded names sit beside the read step's own member while the key is hashed from the read's query info; three paths set the second without the first (clone, the normal-projection read, the parallel-replicas local read) AGREE, not changed Each of those leaves the record empty, so the guard refuses: fail-closed in every case. The parallel-replicas local read redoes index analysis and rebuilds both, and adoptFiltersFrom carries them, which an A/B against 05218_autopr_populates_query_condition_cache proved is required
3 ⚠️ Deriving the condition names from the frozen DAG would drop the new member and its carry sites entirely DISAGREE The two strings live in different naming domains. optimizePrimaryKeyConditionAndLimit passes getFilterColumnName() to addFilter, while buildFilterActionsDAG rewrites inputs into the storage domain, so a DAG-derived name matches nothing and the guard would refuse every write. Measured at the tag site: hashed greater(v, 5_UInt8) against tagged and(greater(__table2.v, 5_UInt8), ...). ActionsDAG::Node::updateHash including result_name rules out the node-hash variant too
4 ⚠️ Two FINAL-only paths call the base applyFilters() directly and could leave the recorded names stale, which the isFinal() early return happens to hide DISAGREE The risk does not exist, so nothing rests on that return: both fields are written inside the same if (!indexes) block, so they move together or not at all, and a later call with the analysis already cached updates neither. detachFilterActionsDAG() moves out the member only
5 💡 #116891 rewrites the same region of updateQueryConditionCache and is open AGREE, noted Different subject, no duplication, but a textual conflict for whoever merges second. It is worth a look from that PR's side
6 💡 Two things I noticed while reviewing and am not raising AGREE, declined The index-analysis write guard at ReadFromMergeTree.cpp:3754 does not list join_runtime_filters_for_index_analysis; it was positively refuted as this failure's site, since index analysis excluded nothing here. And checkIdentityWhere's message prints both row counts but not the differing values, so an occurrence needs the server log to diagnose. Neither has an observed user-reachable consequence, so I am not raising either and not promising a follow-up

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding.

Session id: cron:clickhouse-review-slot-9:20260924-092500

@clickhouse-gh clickhouse-gh Bot closed this Sep 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 5 statements, no fuzzer, on demand at fully default settings with a 50000-row table. Note it needs a real server: clickhouse local sizes the query condition cache to 0, so nothing can be poisoned there.
b Root cause explained? filter_actions_dag is frozen at index analysis, the filter steps above the read are then rebuilt and widened by push-down and tryMergeFilters, and the re-walk that exists to restore keys the merges dropped re-attaches the stale key to the widened step. FilterTransform then records "no matching rows" against the WHERE predicate alone.
c Fix matches root cause? Yes: it refuses the annotation exactly when the key does not describe the step, at the site that attaches it. No widened bound, no no-random-* tag, no guard at the symptom.
d Test intent preserved / new tests added? The 34 existing reference lines of the extended file are byte-unchanged (pure append). Two new arms, the second a control showing the first is an oracle and not a pair of constants.
e Both directions demonstrated? [ FAIL ] on the base binary (c8869683), [ OK ] on the fixed one (61440d79), same test through clickhouse-test, each server's buildId() asserted against its binary.
f Fix is general across code paths? All five writers of the cache were enumerated. This one is fixed; the PREWHERE-unmatched-marks writer is guarded by construction (FunctionApplyFilter is non-deterministic) and measured inert; the index-analysis writer is measured inert and positively refuted as this site; the format/row-group writer derives its key from the same DAG the reader excluded row groups with, so nothing can widen after the key is taken, and its test passes on both binaries. The gate keys on the invariant, not on JOIN or on __applyFilter, so it also covers the other two widening sources the re-walk is gated on.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not a type-dependent defect: the key is a hash of a predicate and the gate compares condition names, so no type, wrapper or value takes part. Verified across the fixture sizes that change reachability (200 rows with the probe threshold lowered, 50000 rows at pure defaults) and over both key and non-key predicates in the surrounding suite.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default, no cache key format change, so no SettingsChangesHistory.cpp entry; the cache is in memory, so there is no cross-version or on-disk concern. A refused write loses an optimization, never a row.
i Invariants and contracts preserved? The new invariant is that filter_actions_dag and the recorded condition names are assigned together and never apart; both assignment sites do so, and adoptFiltersFrom carries both, which is what keeps automatic parallel replicas populating the cache. Two FINAL-only paths call the base applyFilters() directly and would leave the names stale, but the annotation site returns on isFinal() before reaching the gate, so the only consumer cannot observe it.

Session id: cron:clickhouse-impl-slot-4:20260924-071200

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [56439ce]

Summary: ✅


AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR fixes a real wrong-results bug in the query condition cache by refusing to re-attach a cached condition hash to a later FilterStep whose predicate is no longer the one the read analyzed. I reviewed the current diff, the touched optimizer/read paths, the existing discussion, and the current PR CI state; the remaining bot thread is fixed by 56439ce9b1147feccc6889431ab49ba88c64edf4, and I did not find any unresolved correctness, safety, or performance issues that still warrant blocking the PR.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 24, 2026
@shankar-iyer shankar-iyer self-assigned this Sep 24, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 56439ce9b1147feccc6889431ab49ba88c64edf4 was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

…ter-guard

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/updateQueryConditionCache.cpp
The test is taken from ClickHouse#122271 unchanged. It covers the shape of ClickHouse#123845:
an outer filter separated from the read by a LIMIT, with the read's whole
condition in PREWHERE (explicit, or moved there after join runtime filters
were added). On master the granules emptied by the outer filter were
recorded as not matching the read's condition.

Co-authored-by: Kirill Shokhin <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9cae427

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
Build (arm_tidy, 3/4) / Build ClickHouse master build break since af19343b2516, not from this PR (it does not touch the file): unit_tests_dbms does not compile, gtest_functions_stress.cpp:2367: error: value of type 'const ResolvedAddress' is not contextually convertible to 'bool'; no diagnostic in the files of this PR #126269 (external, open)
Finish Workflow / new_tests_check.py both functional Bugfix validation jobs were dropped because of the build failure above #126269 (the owner of the first row)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126269 (the owner of the first row)

The build failure dropped 166 dependent jobs, so no functional test has run on this head yet.

Session id: cron:our-pr-ci-monitor:20261016-130004

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

…sh-down test

After the master merge, `03229_query_condition_cache_join_runtime_filter` failed in Fast test and in the private sync: master now keeps the self-join's always-false `ON` conjunct `not(equals(...))` as a post-join filter, so the plan assertion that pinned it merged into the build side's filter returned 0. The row counts of the arm are unchanged and correct, so keep them and drop only the plan assertion.

Add `05453_query_condition_cache_filter_merged_after_collection` from ClickHouse#122271: with `query_plan_filter_push_down = 0` the outer filter is pushed down only by join runtime filters, after the read's `filter_actions_dag` was collected, which is the case the `filterActionsDAGWasBuiltFrom` check guards.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121946&sha=f023dbbb345e0f0ab6dd76e75bd5f2fe3726aa54&name_0=PR&name_1=Fast%20test
@fm4v

fm4v commented Oct 28, 2026

Copy link
Copy Markdown
Member

Pushed 5175ef2 to fix the 03229_query_condition_cache_join_runtime_filter failure in Fast test (report) and in the private sync PR, both after the master merge.

Current master keeps the self-join's always-false not(equals(v, a.v)) as a post-join filter instead of merging it into the build side's greater(v, 5) filter (checked with EXPLAIN on 26.11.1.707), so the plan assertion of the "filter widened after index analysis" arm returned 0. The arm's row counts were correct and are kept; only the plan assertion is dropped, so the arm still exercises the bug on release branches that merge the conjunct.

Because the ON-conjunct repro from the description no longer reaches the widened filter on master, I added 05453_query_condition_cache_filter_merged_after_collection (from #122271): with query_plan_filter_push_down = 0, the outer WHERE s.b = 2 is pushed down only by join runtime filters, after the read's filter_actions_dag was collected. That is the case filterActionsDAGWasBuiltFrom guards. Its expected counts (500, 500, 500) do not depend on the plan.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. Without the fix, 05453 and 05243 return 0 instead of 500 on master 0525e0c7, 26.10.3.7 and 26.9.19.9, while the description's ON-conjunct query is wrong only on 26.9.19.9 (26.10 already keeps that conjunct as a post-join filter). So 26.10 needs this fix too, through those two paths. I updated the description accordingly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5175ef2

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 479 of 483 runs since 2026-10-26 22:00 UTC ended this way, on 301 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

Mergeable Check and CH Inc sync passed on this head, and both Bugfix validation (functional tests) jobs passed. CIDB has no other FAIL or ERROR row in this run.

Session id: cron:our-pr-ci-monitor:20261028-123007

…on cache guard

`filterActionsDAGWasBuiltFrom` matched the step to tag only by its filter
column name. After index analysis, predicate propagation and join runtime
filters run `tryMergeFilters` again, and it can merge two of the collected
filters (for example the pushed-down `WHERE` and the predicate copied from
the other side of an equi-join) into one step named `and(...)`. That name is
not in the record, so the re-walk refused the key and the cache was no
longer populated, although the merged step filters exactly the conjunction
`filter_actions_dag` hashes.

Accept a step whose condition is one of the collected conditions or an `and`
of them. A granule it empties has no row matching that conjunction, which
`filter_actions_dag` implies, so the entry is sound. An `and` with any other
operand, e.g. a join conjunct merged in later or a runtime filter, is still
refused.

Measured on a server with default settings: after
`SELECT count() FROM (SELECT k FROM t1 WHERE k > 50000) AS s JOIN t2 ON s.k = t2.k WHERE intDiv(t2.k, 1000) % 10 = 3`
the cache records the granules of `t2` the filter emptied on master and with
this change, and only the primary key pruning without it.

Also say "case" instead of "arm" in the test comments this PR added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fm4v
fm4v added this pull request to the merge queue Nov 22, 2026
Merged via the queue into ClickHouse:master with commit 99e1604 Nov 22, 2026
197 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 2026
@robot-clickhouse robot-clickhouse added 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 labels Nov 22, 2026
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A filter above LIMIT / LIMIT BY on a join's build side poisons the query condition cache under the key of the WHERE below it

5 participants