Skip to content

Limit the stack walk in updateQueryConditionCache - #122271

Closed
kirillshokhin wants to merge 1 commit into
masterfrom
fix-update-qcc-stack-walk
Closed

kirillshokhin wants to merge 1 commit into
masterfrom
fix-update-qcc-stack-walk

Conversation

@kirillshokhin

@kirillshokhin kirillshokhin commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #123845

updateQueryConditionCache walks the stack of parent nodes from the read step up to the first FilterStep and tags the found step with the hash and the condition of the read's filter_actions_dag. However, it does not check if the found filter step's condition is covered by the filter_actions_dag.

As a result, the filter records empty marks as not matching the filter_actions_dag's condition, although the filter evaluated a stronger one: the filter_actions_dag's condition and its own. Thus the query condition cache gets poisoned.

For example:

SELECT count() FROM (SELECT a, b FROM tab PREWHERE a = 1 LIMIT 10000000) WHERE b = 2; -- populates QCC for condition `a = 1` with marks dropped by `a = 1 AND b = 2`
SELECT count() FROM (SELECT a, b FROM tab PREWHERE a = 1 LIMIT 10000000) WHERE b = 3; -- uses poisoned QCC `a = 1` entry

optimizePrimaryKeyConditionAndLimit does not collect past the LIMIT, so the filter_actions_dag covers only a = 1, but WHERE b = 2 is the first FilterStep above the read. The same happens on the re-walk after join runtime filters, once optimizePrewhere has moved the inner WHERE into PREWHERE.

See https://fiddle.clickhouse.com/30288fb3-1869-4648-9a61-3e2ae106a0f2 for a complete reproducible example.

To fix it, updateQueryConditionCache now walks up only through ExpressionSteps without arrayJoin, mirroring optimizePrimaryKeyConditionAndLimit behavior, and tags the first FilterStep reached, if any. This way we guarantee not to tag FilterStep that was not reachable when optimizePrimaryKeyConditionAndLimit ran. The mirroring is not complete: updateQueryConditionCache stops at ArrayJoinStep/ObjectFilterStep while optimizePrimaryKeyConditionAndLimit does not, so we lose QCC for such queries.

Another repro, not covered by this fix, is tagging a FilterStep pushed down by the push-down that join runtime filters force regardless of the settings. It requires query_plan_filter_push_down = 0 to prevent inclusion of the filter into the read's filter_actions_dag. See https://fiddle.clickhouse.com/70962114-d460-4973-90af-f5bcc026031b.

Related: #116891

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):

Fix wrong results from the query condition cache when a filter above a LIMIT was cached with the key of the condition below it, e.g. with an explicit PREWHERE in a subquery.


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

`updateQueryConditionCache` tagged the first `FilterStep` anywhere above
the read with the key hashed from the read's `filter_actions_dag`, whether
or not that filter's condition was collected into it.

Marks the filter empties were then recorded as not matching the key's
condition, although the filter evaluated a stronger one: that condition
and its own. Later queries skipped them and returned wrong results:

    SELECT count() FROM (SELECT a, b FROM t PREWHERE a = 1 LIMIT 100000) WHERE b = 2;
    SELECT count() FROM (SELECT a, b FROM t PREWHERE a = 1 LIMIT 100000) WHERE b = 3; -- 0 instead of 500

`optimizePrimaryKeyConditionAndLimit` does not collect past the `LIMIT`, so
the key covers only `a = 1`, but `WHERE b = 2` is the first `FilterStep`
above the read. The same happens on the re-walk after join runtime filters,
once `optimizePrewhere` has moved the inner `WHERE` into PREWHERE.

Walk up only through `ExpressionStep`s, which the collection also passes,
and tag the `FilterStep` reached there, if any.

A filter merged into the chain after the collection is still tagged: see
`tests/queries/bugs/query_condition_cache_filter_merged_after_collection.sql`.
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ca8a80]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

This patch fixes the LIMIT/PREWHERE stack-walk bug by only tagging a FilterStep reached through the same expression-only chain that optimizePrimaryKeyConditionAndLimit can analyze, which is the right direction for the wrong-results case described in the PR. I did not find a correctness issue in that fix itself, but the extra merged-after-collection repro is added under a non-executed query directory, so the PR still lacks runnable evidence for that sibling path.

Tests
  • ⚠️ [tests/queries/bugs/query_condition_cache_filter_merged_after_collection.sql:1] tests/queries/bugs is not part of the executed functional suites: clickhouse-test, changed-test selection, and bugfix validation all target tests/queries/0_stateless. So this new repro does not provide executable regression coverage for the merged-after-collection case that the source comment still points at. Move it into tests/queries/0_stateless once it passes there, or drop the dead repro/comment if that scenario is already obsolete.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: replace the non-running tests/queries/bugs/query_condition_cache_filter_merged_after_collection.sql repro with an executed tests/queries/0_stateless regression once the scenario is fixed, or remove the dead repro/comment if the case is no longer real.

LLVM Coverage Report

Measured on commit 1ca8a80.

Metric Baseline Current Δ
Lines 88.20% 88.10% -0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 24/24 (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 25, 2026
@@ -0,0 +1,41 @@
-- The query condition cache key of a read is built from its `filter_actions_dag`, collected early in the second pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This repro does not run in our functional test pipeline: clickhouse-test, changed-test selection, and bugfix validation all enumerate tests/queries/0_stateless, not tests/queries/bugs. That means the extra merged-after-collection case this PR calls out still has no executable regression coverage.

If this sibling path is still relevant, please move it into tests/queries/0_stateless once it passes there; if it is already obsolete, please drop the dead file/comment instead of leaving a non-running "test" behind.

@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 25, 2026
@rschu1ze

rschu1ze commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

@shankar-iyer If you find some time, could you please take a look at this PR?

@kirillshokhin The PR message is slop, please rewrite so it clearly mentions:

  • what problem does the PR fix (minimal reproducible example) - it's not clear at the moment,
  • how does it fix it?
  • any side effects or noteworthy things?

@kirillshokhin
kirillshokhin marked this pull request as draft September 28, 2026 12:35
@kirillshokhin

Copy link
Copy Markdown
Contributor Author

I've updated the description, hope it makes more sense now.

I've marked the PR as a draft while I resolve the merge conflicts and check whether #121946 provides a better fix for the same problem.

@kirillshokhin
kirillshokhin deleted the fix-update-qcc-stack-walk branch October 16, 2026 10:54
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
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]>
fm4v added a commit to groeneai/ClickHouse that referenced this pull request Oct 28, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

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

2 participants