Skip to content

Check that PREWHERE is covered by the query condition cache key, not only deterministic - #122804

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:qcc-prewhere-coverage-check
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:qcc-prewhere-coverage-check

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119823
Related: #119823 (comment)

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 a JOIN whose ON condition the optimizer had moved into the PREWHERE of a read: the query condition cache recorded granules, or Parquet row groups, as not matching that read's WHERE although only the moved condition had removed their rows. A Parquet read with a lambda in PREWHERE also no longer reuses the entry of one whose lambda differs only in its body.

Description

On 26.8, for a File(Parquet) table f (k UInt64, v Int64, w Int64) with 2000 rows number, number, number in row groups of 64, written more than 3 s earlier, running SELECT count() FROM f RIGHT JOIN (SELECT * FROM f WHERE v + w < 100) AS a ON f.v = a.v AND f.v + a.v >= 2048 WHERE f.v > 5 makes SELECT count() FROM f WHERE v + w < 100 AND v > 5 return 0 instead of 44. On master MergeTree does the same.

Through f.v = a.v, filter push-down turns the ON conjunct into v + v >= 2048 for the subquery's read and optimizePrewhere moves it into PREWHERE. Both cache writers key their entries on filter_actions_dag, built before that conjunct existed, while the gates from #119823 only checked that PREWHERE is deterministic, which it is.

Both writers (updateQueryConditionCache for MergeTree, FormatFilterInfo for file and object-storage reads) now require each PREWHERE conjunct to be a conjunct of the hashed condition (VirtualColumnUtils::isCoveredByFilter) made of the same function objects: an equally spelled copy built elsewhere may differ in shape or in captured settings. formatRow* and user-defined functions, which can read their arguments' names, and a lambda computed from columns never count as covered: the key spells such a lambda without its body, so on 26.8 arrayExists(x -> x != val, [5001, 7001]) in a Parquet PREWHERE reused the entry of x = val. The MergeTree WHERE key has the same flaw without PREWHERE, which needs its own fix. The change only adds refusals; both comments now say what is checked.

The new arms in both 03229_query_condition_cache_join_runtime_filter tests fail without the change; controls with IN, =, a nested function and a constant lambda still hit the cache. #121946 handles the same problem for the tagged filter step.


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

groeneai and others added 2 commits September 29, 2026 04:49
Both writers of the query condition cache key their entries on the hash of
`filter_actions_dag`, which `optimizePrimaryKeyConditionAndLimit` builds from
the filters present at that point. When join runtime filters are added, filter
push-down runs again, and the join-key equivalence can turn an `ON` conjunct
such as `t.v + a.v >= 2048` into `v + v >= 2048` for the other input's read,
which `optimizePrewhere` then moves into that read's PREWHERE. The gates added
in ClickHouse#119823 only checked that PREWHERE is deterministic, which such a conjunct
is, so the rows it removed were recorded as not matching the key: for MergeTree
through the re-tagged residual filter, for Parquet reads through
`FormatFilterInfo::condition_hash`. A later read with the same WHERE lost them.

Both writers now require every PREWHERE conjunct to be a conjunct of the hashed
condition (`VirtualColumnUtils::isCoveredByFilter`). The comparison is
structural: aliases are looked through, except as argument names of functions
that are not name-insensitive; a function's derived result name is ignored, also
as an argument, since the key spells it over the storage columns;
non-deterministic, PLACEHOLDER and ARRAY_JOIN nodes refuse, and so do
`formatRow*`, whose result holds the argument names it was built with, and every
function outside `FunctionFactory`: a lambda computed from columns, whose name
omits its body (a constant lambda is a column whose name holds it), and a
user-defined function, which may read its arguments' names (a WebAssembly UDF
with an argument declared by type only and `JSONEachRow` sends the runtime
column name). `__topKFilter` stays allowed for MergeTree, whose key is salted
with the TopK plan. The change only adds refusals. On the format path this also
keeps a read with such a lambda in PREWHERE from reusing the entry of a read
whose lambda differs only in its body; the MergeTree WHERE key has the same flaw
without PREWHERE and needs a separate fix to the key.

The Parquet cases reproduce on 26.8.2.7, the MergeTree case on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the format-path PREWHERE gate comment, the coverage helper's header and the hashing notes to the invariants they state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 29, 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; 6 findings over 4 rounds), plus my own review (row 5).
Bounce cap reached, published as-is; residual findings listed below.

# Sev Finding Verdict Evidence / action
1 ❌ The coverage hash identified a lambda by a name that, after a DAG rebuild, carries only its types, so lambdas with different bodies compared equal (VirtualColumnUtils.cpp) AGREE, fixed @ bd1799d a lambda computed from columns is never taken as covered
2 ⚠️ No test failed when that lambda refusal was reverted AGREE, fixed @ bd1799d the Parquet arm with x = val / x != val fails without it
3 ❌ Ignoring a nested function's name let formatRowNoNewline calls built with different argument names compare equal AGREE, fixed @ bd1799d formatRow* and functions that are not built in, such as user-defined ones, are never taken as covered
4 ⚠️ The lambda refusal also covered constant lambdas, whose name holds the body, so those reads lost the cache AGREE, fixed @ bd1799d only a lambda computed from columns is refused; a constant-lambda control hits
5 💡 The MergeTree WHERE key spells a captured lambda without its body even with no PREWHERE noted a flaw in the key itself, outside this diff; it needs its own fix
6 ⚠️ FunctionFactory::has matches case variants, so a user-defined function named like a case-insensitive built-in (ABS) passed as built in AGREE, fixed @ bd1799d the check uses the exact spelling CREATE FUNCTION checks (hasNameOrAlias)
7 💡 The formatRowNoNewline plan assertion also matched the subquery's own copy AGREE, fixed @ bd1799d the assertion needs both copies in PREWHERE

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20260929-045400

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9f3502]

Summary: ✅


AI Review

Summary

This PR prevents query condition cache poisoning when a read's PREWHERE contains predicates absent from the cached condition. The coverage check compares function identities and preserves ordinary cache use. No actionable findings remain at b9f3502ed80b42ac111865f2a12e6fc30bebe8a4. The previous expression-shape and captured-settings findings are addressed; their bot-authored threads have been resolved.

Missing context / blind spots
  • ⚠️ No local ClickHouse build was available. The current fast-test report passes 03229_query_condition_cache_join_runtime_filter and all six current-time condition tests, including split PREWHERE. The Parquet companion, 03229_query_condition_cache_join_runtime_filter_file, is excluded from fast tests; a completed full stateless run is needed to confirm that path at this head.
Final Verdict

Status: ✅ Approve. No code changes requested. Parquet runtime validation remains pending in full CI.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b9f3502ed80b42ac111865f2a12e6fc30bebe8a4 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 2 commits October 11, 2026 20:32
# Conflicts:
#	src/Formats/FormatFilterInfo.cpp
…ge-check

Master moved the `PREWHERE` gate in `updateQueryConditionCache` below the derivation of deterministic
time conditions and accepts a current-time `PREWHERE` there. Keep that, and additionally require the
`PREWHERE` to be covered by `filter_actions_dag` via `isCoveredByFilter`. On the derived time-condition
path, `isCoveredByFilter` now compares constants folded from non-deterministic functions such as `today()`
by value (new `allow_non_deterministic_constants` parameter), so a current-time conjunct moved to `PREWHERE`
still counts as covered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
`updateConditionHash` identified a function by its name, arguments and result
type. Two separately built copies with equal names can still differ:

- a function captures settings, which a subquery's own `SETTINGS` can change
  (`splitByChar` with `splitby_max_substrings_includes_remaining_string`,
  `visibleWidth` with `function_visible_width_behavior`, the inner function of a
  constant lambda), and some of them do not report those in `updateHash`;
- without argument counts, a preorder walk gives `(X AND (B OR C)) OR D OR E`
  and `(X AND (B OR C OR D)) OR E` the same bytes.

A JOIN's `ON` copy pushed into `PREWHERE` then counted as covered by the
subquery's `WHERE`, and the read cached granules as not matching that `WHERE`
although only the `ON` copy had removed their rows: a later plain read
returned 0 instead of 904.

Hash the function object itself. A PREWHERE conjunct that comes from the
hashed condition shares its function objects with it (the filter DAG reuses
`function_base`, also when it is built from an existing PREWHERE), so the
existing cache-hit controls still hit, while a copy built elsewhere no longer
counts as covered.

Found by the AI review on ClickHouse#122804.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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-review-human PR origin: human review feedback on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants