Skip to content

Fix wrong results of the query condition cache for lambdas that capture a column - #122966

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:qcc-lambda-capture-key
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:qcc-lambda-capture-key

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122804

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 wrong results when queries on the same table filter with different lambdas that capture a column, for example arrayExists(x -> x < v, arr) and then arrayExists(x -> x > v, arr): the query condition cache used one key for both, so the second query skipped granules with matching rows.

Description

On 26.8.2.7 (and 26.3.33.24), with default settings, the second query returns 0 instead of 10000:

CREATE TABLE t (k UInt64, v UInt64, arr Array(UInt64)) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 64;
INSERT INTO t SELECT number, number, [number, number + 1] FROM numbers(10000);
SELECT count() FROM t WHERE arrayExists(x -> x < v, arr); -- 0
SELECT count() FROM t WHERE arrayExists(x -> x > v, arr); -- 0, expected 10000

A lambda that captures columns is a FunctionCapture node. buildFilterActionsDAG renames it to its signature (Capture[UInt64](UInt64) -> UInt8(v)), and the exact ActionsDAG::Node::updateHash that the query condition cache keys on does not hash the lambda body, so both lambdas get the same key. Binding the lambda arguments in another order ((y, x) -> ... vs (x, y) -> ...) collides the same way.

#116781 hashes the capture and the body, as ActionsDAG::serialize describes them, but only in build-independent mode. This PR applies that hashing to exact hashes too. Every query condition cache key (MergeTree WHERE, PREWHERE, index analysis, File/S3 and data lake filters, Memory) and the in-memory plan statistics keys use this hash. Exact hashing only gains data, so only DAGs that contain a lambda get new hashes.

The new test fails on master in both cases (20/20 randomized runs) and passes with the fix (40/40); 310 related tests (query condition cache, lambdas, Auto-PR, join build-side statistics) show no new failure.

🤖 Generated with Claude Code


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

A lambda that captures a column is a FUNCTION node whose function_base is a
FunctionCapture. buildFilterActionsDAG re-adds functions with an empty name, so
the node is renamed to its signature, e.g. `Capture[UInt64](UInt64) -> UInt8(v)`,
and ActionsDAG::Node::updateHash hashed only names, types and children. So
`x -> x < v` and `x -> x > v` over the same columns got one query condition
cache key, and a MergeTree WHERE (or a File/S3 format filter) reused the other
lambda's "no row matches" marks and skipped matching granules.

Also hash the capture binding (captured column names and lambda argument names,
in order) and the lambda body, which is how ActionsDAG::serialize already
describes the same node.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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; 1 finding) and my own cold review of the diff.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test checks only result counts, so it would also pass if the cache were bypassed; suggested clearing the cache per pair and asserting a hit DISAGREE With the fix reverted the test fails in 30/30 randomized runs (both arms), and deleting the body loop or the argument loop reddens its own arm. On the fixed build, correct counts are the contract; a re-run of the priming query still hits its own entry (1 hit, 0 rows read). Clearing the instance-wide cache and asserting hits would need no-parallel: 03229_query_condition_cache_cte_constant_folding and 04836_system_cache_on_cluster_access_types clear it from parallel tests. The test of #96172 (same defect class, same function) also asserts results only.
2 💡 The captured-names loop is not covered by the test noted Kept for completeness, as serializeCapture describes the node. The planner builds the children in captured_names order, so no query reorders one without the other.

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

Session id: cron:clickhouse-review-self-slot-58:20260929-201800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05293_query_condition_cache_lambda_capture fails on master every time, including 30/30 randomized runs.
b Root cause explained? buildFilterActionsDAG renames a captured lambda to its signature, and Node::updateHash does not hash its body or binding, so different lambdas over the same columns share one query condition cache key.
c Fix matches root cause? Yes. The hash now covers the capture binding and the lambda body, in the one function every cache key uses. No guard, no bypass, no setting.
d Test intent preserved / new tests added? New test with two arms (different bodies; same body with arguments bound in another order). Each arm reddens when its part of the hash is deleted.
e Both directions demonstrated? Master: 0 0 0 0, with the victim query served from the other lambda's entry. Fix: 0 10000 0 10000; 50/50 randomized runs pass.
f Fix is general across code paths? Covers MergeTree WHERE, PREWHERE, index analysis, TopK salts and File/S3 filters (Parquet measured: 12999000 vs 49995000 on master, correct with the fix). Nested lambdas are covered by recursion.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured with Nullable, LowCardinality(String), tuples, mapExists, arrayAll/arrayCount/arrayFirstIndex, nested lambdas, JIT forced/off, PREWHERE off: all wrong on master, all correct with the fix.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. Only in-memory hashes of DAGs containing a lambda change.
i Invariants and contracts preserved? The hash stays a pure function of the node, so equal plans still hash equal (Auto-PR plan matching with a lambda measured unchanged). A lambda body compiled by JIT between two plan builds can cost one miss, never a wrong hit.

Session id: cron:clickhouse-impl-self-slot-57:20260929-192200

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [14a6261]

Summary: ✅


AI Review

Summary

Reviewed #122966 at 14a62611c8bf7d66e87b4a252c04e5e314f3a240. The change includes lambda bodies and capture bindings in exact ActionsDAG hashes, preventing different predicates from sharing query condition cache entries. The new SQL regression covers different bodies and reordered lambda parameters. No actionable findings. Tests were not run locally because this checkout has no ClickHouse binary or build directory; runtime evidence comes from the author's reported before/after validation.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
@yariks5s yariks5s self-assigned this Sep 29, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 14a62611c with master 587508f82 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 13.4 s +9.9 s (+282%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.3 s +5.3 s (+256%)
Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, 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.

Conflict in `ActionsDAG::Node::updateHash`, which master split into `updateOwnHash` and whose
lambda capture and body hashing (ClickHouse#116781) runs only in build-independent mode. That block now runs
in both modes, replacing this branch's own exact-mode copy: the query condition cache keys on
exact hashes of DAGs built by `buildFilterActionsDAG`, where a lambda node is named only by its
signature, so the exact hash also needs the body. Exact mode only gains data, so no two nodes that
hashed apart before hash alike now.

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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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