Skip to content

Cover a non-deterministic lambda in HAVING push-down and file pruning with tests - #117747

Merged
alexey-milovidov merged 15 commits into
masterfrom
fix-lambda-nondeterminism-filter-pushdown-117262
Sep 21, 2026
Merged

alexey-milovidov merged 15 commits into
masterfrom
fix-lambda-nondeterminism-filter-pushdown-117262

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

A lambda used to report the properties of IFunctionBase from its own defaults, not from the functions it calls, so a non-deterministic call inside a lambda body was invisible to every consumer of isDeterministicInScopeOfQuery. The filter push-down guard in ActionsDAG::getConjunctionNodes therefore moved a HAVING predicate such as arrayExists(x -> rand(x) % 2 = 0, arr) below the aggregation, where it is evaluated once per input row instead of once per group, and every group survived:

SELECT count() FROM (
  SELECT number % 10 AS g FROM numbers(1000) GROUP BY g
  HAVING arrayExists(x -> rand(x) % 2 = 0, materialize([1]))
);
-- always 10; a binomial around 5 with query_plan_filter_push_down = 0

The source part of the fix landed on master meanwhile, in a more general form: #117756 made FunctionCapture and FunctionExpression derive isDeterministic, isDeterministicInScopeOfQuery and isStateful from the functions of their body, recursing into COLUMN nodes holding a constant-folded lambda, and #117248 brought the same walk to the remaining consumers: VirtualColumnUtils (file/url/object-storage pruning and the query condition cache), isNodeDeterministic in ReadFromMergeTree (row policy before FINAL) and the plan-time join conversions, together with a row policy test.

What is left here are the two tests that no test on master covers:

  • 05212_lambda_nondeterminism_filter_push_down: the aggregation route from the issue, including a lambda that captures a column, a nested no-capture lambda that depends on the outer lambda argument, and the EXPLAIN plan shape.
  • 05213_file_pruning_nondeterministic_lambda: VirtualColumnUtils::isDeterministicInScopeOfQuery gates which part of a filter may be used to decide which files a file query reads at all. Before the fix, arrayExists(x -> rand(x) % 2 = 0, materialize([1])) was drawn once per file and wiped out whole files on top of the per-row draw: over 16 files of 2000 rows it kept about a quarter of the rows instead of about a half. The test asserts the ratio one-sided at 45 %, which the per-row verdict clears by a wide margin and a per-file verdict would need 15 of 16 files to survive their draw. It was checked against a control binary without the fix, where it fails on the lambda assertion and passes on its controls.

Closes: #117262
Related: #117756
Related: #117248

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.322-master (included in 26.10 and later)

A lambda reports the properties of `IFunctionBase` from its own defaults, not from the
functions it calls, so a non-deterministic call inside a lambda body was invisible to
every consumer of `isDeterministicInScopeOfQuery`. The filter push-down guard in
`getConjunctionNodes` therefore moved a `HAVING` predicate such as
`arrayExists(x -> rand(x) % 2 = 0, arr)` below the aggregation, where it is evaluated
once per input row instead of once per group, and every group survived.

`FunctionCapture` and `FunctionExpression` now derive `isDeterministic`,
`isDeterministicInScopeOfQuery` and `isStateful` from their inner DAG. A lambda whose
captured columns are all constant is materialized as a constant `ColumnFunction` and has
no function node at all, so the conjunction walk additionally inspects such columns.

Closes: #117262
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8674de]

Summary: ✅


AI Review

Summary

This PR is now tests-only: it adds 05212_lambda_nondeterminism_filter_push_down to cover analyzer-side HAVING filter push-down with non-deterministic lambdas, and 05213_file_pruning_nondeterministic_lambda to cover file() pruning through VirtualColumnUtils. After checking the current diff against the full thread history, I did not find any remaining correctness or coverage gaps in the updated tests.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
Comment thread src/Functions/FunctionsMiscellaneous.h Resolved
@zlareb1

This comment was marked as low quality.

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

Two more consumers of the same blind spot, so they do not get lost when this merges — both are still bypassed by the folded-capture shape after this PR, because the fix is per-consumer and these sites keep walking only FUNCTION nodes:

  1. Plan-time join conversions. dagContainsNonDeterministicFunction in src/Processors/QueryPlan/Optimizations/Utils.cpp skips a no-capture lambda folded to a constant column holding a ColumnFunction — the exact shape in this PR's own test — so convertOuterJoinToInnerJoin and convertAnyJoinToSemiOrAntiJoin treat the filter as deterministic, and tryConvertOuterJoinToInnerJoinLegacy has no determinism guard at all: isFilterAlwaysFalseForDefaultValueInputs constant-folds the filter over default values and executes the non-deterministic lambda once at plan time. With query_plan_convert_outer_join_to_inner_join = 1 (the default), a LEFT JOIN whose WHERE hides rand inside a lambda converts to INNER on a single plan-time draw and silently drops every not-matched row. Open as Plan-time join conversions (LEFT to INNER, ANY to SEMI/ANTI) flip a coin when the filter hides rand inside a lambda — non-determinism in FunctionCapture bypasses the guard, rows silently dropped #117016; re-verified today on a 26.9.1.1 build with SELECT count() FROM t1 LEFT JOIN t2 ON t1.k = t2.k WHERE t2.v > 0 OR arrayExists(x -> rand(x) % 2 = 0, [t2.v]) — at defaults about half the runs return the INNER-shaped count (all not-matched rows gone), while the control with the conversion disabled can never produce it (the not-matched rows are filtered per row, so the count is matched + Binomial(not_matched, 1/2)).

  2. The row-policy-before-FINAL gate. isNodeDeterministic in src/Processors/QueryPlan/ReadFromMergeTree.cpp checks only FUNCTION nodes, so under apply_row_policy_after_final = 1 (the default) a row policy whose condition hides non-determinism inside a folded lambda over sorting-key columns is judged deterministic and applied before FINAL, which can flip the dedup winner. The capture-as-FUNCTION shape is fixed by this PR's override; only the folded shape remains.

Both would also be closed at once by the single-point option: make FunctionCapture::isSuitableForConstantFolding refuse the fold when any inner FUNCTION node is not deterministic in the scope of the query, so the capture stays a FUNCTION node and the overrides added here are consulted by every existing walker.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
alexey-milovidov and others added 4 commits September 10, 2026 12:38
…minism-filter-pushdown-117262

The source fix of this branch landed on master meanwhile, in a more general
form, through #117756 (`Keep a non-deterministic lambda on its side of
\`ARRAY JOIN\` too`): `FunctionCapture` and `FunctionExpression` derive
`isDeterministic`, `isDeterministicInScopeOfQuery` and `isStateful` from the
functions of their body, the walk recurses into `COLUMN` nodes holding a
`ColumnFunction` and into the lambdas nested in them as captured columns, and
`getConjunctionNodes` uses that shared walk (`allNodeFunctions`).

Both conflicts are therefore resolved in favour of master: this branch's
`lambdaBodySatisfies` and `columnHoldsNonDeterministicLambda` are dropped as
duplicates of the shared helpers in `src/Functions/FunctionsMiscellaneous.h`.
The regression test of the aggregation route, which no test on master covers,
is kept.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The number 05063 was taken by three tests that landed on master meanwhile, so the test
is renumbered to 05175.

The review asked for a nested case. A lambda nested in another lambda captures nothing
while depending on the outer lambda argument, so it stays a `ColumnFunction` among the
captured columns of the outer one instead of being hoisted to the top level of the
filter; both the value oracle (`rowNumberInAllBlocks() >= 20` passes nothing above the
aggregation and everything below it) and the `EXPLAIN` assertion now cover that shape.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The review asked for a nested case. A lambda nested in another lambda captures nothing
while depending on the outer lambda argument, so it stays a `ColumnFunction` among the
captured columns of the outer one instead of being hoisted to the top level of the
filter, where the walk of `getConjunctionNodes` would see it anyway. Both the value
oracle (`rowNumberInAllBlocks() >= 20` passes nothing above the aggregation and every
group below it) and the `EXPLAIN` assertion now cover that shape.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… before `FINAL`

Two more consumers of the determinism of a filter walked only `FUNCTION` nodes, so a
lambda without non-constant captured columns — folded into a constant `ColumnFunction`,
a `COLUMN` node — was invisible to them, and the overrides of `FunctionExpression` were
never asked. Both now use the shared `allNodeFunctions`, which looks into such a column
and into the lambdas nested in it as its captured columns:

- `VirtualColumnUtils::isDeterministicInScopeOfQuery` gates which part of a filter may be
  used to decide which files a `file`/`url`/object-storage query reads at all. A
  predicate such as `arrayExists(x -> rand(x) % 2 = 0, materialize([1]))` was drawn once
  per file and wiped out whole files, on top of the per-row draw that follows: over 16
  files of 2000 rows it kept about a quarter of the rows instead of about a half, and a
  single-file query returned 0 about half of the time. `isDeterministic`, the
  across-queries variant next to it, keeps its own check for a non-deterministic constant
  such as a folded `now()`.
- `isNodeDeterministic` in `ReadFromMergeTree` decides whether a row policy may be
  applied before `FINAL`. A policy over sorting-key columns is applied for every row of a
  dedup group, so two draws that disagree flip the row that wins the group.

Tests `05176_row_policy_after_final_nondeterministic_lambda` and
`05177_file_pruning_nondeterministic_lambda`; both were checked against a control binary
without the fix, where they fail on the lambda assertion and pass on their controls.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you — all four points of the first comment and both of the second are settled now, and the shape of this pull request changed because the source fix landed on master meanwhile.

What is on master already. #117756 landed the recursive walk in a shared form: allColumnFunctions / allNodeFunctions / allLambdaBodyFunctions in src/Functions/FunctionsMiscellaneous.h look into a COLUMN node holding a constant-folded lambda and into the lambdas nested in it as its captured columns; FunctionCapture and FunctionExpression derive isDeterministic, isDeterministicInScopeOfQuery and isStateful from their body through them; and getConjunctionNodes uses the same walk. Merging master here therefore drops this branch's own lambdaBodySatisfies and columnHoldsNonDeterministicLambda as duplicates.

1. The nested shape. Your correction of the bot's example is exactly right, and the escaping shape you gave is now the assertion in 05175_lambda_nondeterminism_filter_push_down: arrayExists(x -> arrayExists(y -> rowNumberInAllBlocks() >= 20, [x]), materialize([1])), with both the value oracle (nothing above the aggregation, every group below it) and the EXPLAIN plan shape. The bot's own example is not asserted, precisely because it does not escape.

2. The virtual-column pruning site. Fixed in this pull request: VirtualColumnUtils::isDeterministicInScopeOfQuery now uses the shared walk. Measured on a 16-file × 2000-row file() fixture with a control binary: without the fix the predicate is used for pruning (uniq(_file) came out 5–13 of 16, count about a quarter of the rows, and a single-file query returned 0 about half the time); with it, createPathAndFileFilterDAG returns nothing for that predicate, uniq(_file) is 16 and the count is a clean binomial around a half. Test 05177_file_pruning_nondeterministic_lambda asserts the ratio one-sided at 45 %, which the per-row verdict clears by a wide margin and a per-file verdict would need 15 of 16 files to survive their draw. isDeterministic, the across-queries variant next to it, keeps its own separate check for a non-deterministic constant such as a folded now().

The row-policy-before-FINAL gate (point 2 of your second comment) is fixed here too — isNodeDeterministic in ReadFromMergeTree — with 05176_row_policy_after_final_nondeterministic_lambda asserting that the folded shape stays deferred while a deterministic lambda over the sorting key is still applied before FINAL.

3. The upgrade face. Confirmed on a build of this branch: CREATE TABLE ... PARTITION BY arraySum(x -> x + rand(x) % 2, arr) % 10 is now rejected, and editing the stored metadata of an existing table to that key makes ATTACH throw Expression must be deterministic but it contains non-deterministic part __lambda: for Partition key. That is the master behaviour from #117756, not something this pull request adds, and it is already tracked as #118488 (reject at CREATE, still load at ATTACH), so I am leaving it there rather than widening this change.

4. The legacy analyzer's HAVING-to-WHERE move — agreed that it is out of scope for a plan-level guard; thank you for filing #117758.

Plan-time join conversions (point 1 of your second comment) are #117248, which is open with the Utils.cpp walk and its tests. On your single-point suggestion — refusing the fold in FunctionCapture::isSuitableForConstantFolding — that turned out to be needed for a different reason and is in that pull request: folding freezes a non-deterministic body for the whole query, so the fold now additionally requires every body function to be deterministic in the scope of the query. It does not replace the per-consumer walks, though, because a FunctionExpression also reaches those consumers through paths that never went through the fold.

05175 and 05176 are claimed by other open pull requests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1c41fd81e with master ba9fc1724 (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.

Compile time of recompiled translation units

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

Job report

@rschu1ze rschu1ze self-assigned this Sep 14, 2026
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
alexey-milovidov and others added 2 commits September 14, 2026 09:28
…minism-filter-pushdown-117262

Both conflicts resolved in favour of master, which already carries the same determinism walks with an additional `node->isDeterministic()` check.
The source fix of this pull request landed on `master` through #117756 and
#117248, and the latter also brought a row policy test with the same shape as
`05188_row_policy_after_final_nondeterministic_lambda`
(`05182_row_policy_after_final_lambda_nondeterminism`), so that test is dropped.
The aggregation push-down test and the file pruning test are renumbered to a
free range, since `05187` and `05189` were claimed on `master` meanwhile.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title See non-deterministic functions inside lambda bodies Cover a non-deterministic lambda in HAVING push-down and file pruning with tests Sep 14, 2026
@alexey-milovidov alexey-milovidov removed the pr-bugfix Pull request with bugfix, not backported by default label Sep 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (2147 commits behind, both conflicts in ReadFromMergeTree.cpp and VirtualColumnUtils.cpp resolved in favour of master). The determinism walks this pull request added to those two files landed on master through #117248, with the extra node->isDeterministic() check the review bot asked for, so this pull request no longer changes any source file. It now carries only the two tests that master does not cover: the aggregation push-down route from #117262 (05212) and the file() pruning route (05213); the row policy test was dropped as a duplicate of 05182_row_policy_after_final_lambda_nondeterminism from that pull request. Since the fix is already on master, the changelog category is changed to Not for changelog (bug-fix validation cannot reproduce a bug that master no longer has). Both tests pass locally against the merged binary, also with randomized settings. The iceberg integration failures of the previous run were fleet-wide on 2026-09-10 and are gone since 2026-09-12.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-testing Test content only (no production code). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 14, 2026
The review bot asked to pin the optimizer setting in the positive
queries and the `EXPLAIN`s of
`05212_lambda_nondeterminism_filter_push_down`, so that the test
exercises the push-down regardless of the session profile, with the
`= 0` controls as the only place where the setting is disabled.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pinned query_plan_filter_push_down = 1 in the positive cases of 05212 as the review asked, and merged master (136 commits behind). The only red of the previous run, Stress test (arm_tsan) with Invalid number of columns in chunk pushed to OutputPort on a countResample(10, 5, 1) state, is unrelated to these two tests: it is #119727, with the fix in flight in #119728. @groeneai, if that fix lands before the next run here, nothing more is needed; otherwise please link its status.

@groeneai

Copy link
Copy Markdown
Collaborator

#119728 has not landed, so here is its status.

It is open at 381822043494, CI on that head is fully green, and it now waits on re-review only. Your CHANGES_REQUESTED of 2026-09-13 18:34Z is implemented: the head no longer relaxes the chassert in KeyHolderHelpers.h (that file is out of the diff entirely) and instead rejects the violating parameterisations at creation, an empty -Resample range and a *Matrix aggregate function called with no arguments.

Until it merges the producer stays on master: 05211_backup_log_zero_byte_data_file builds its tables from countResample(10, 5, 1) states, so the arm_tsan Stress leg of the run in flight here is likely to be red again for the same reason. To quiet master without waiting for the source fix, I am splitting that fixture rewrite into a test-only pull request as you asked on #119858, and the link will go on that thread.

…rol observable in `05213`

`05212` exercises the plan-level `HAVING` push-down of the analyzer, while the
legacy analyzer moves `HAVING` into `WHERE` on its own (#117758), so the test
now sets `enable_analyzer = 1` instead of relying on the session default.

The deterministic control of `05213` only showed that `_file = 'data1.csv'`
returns 2000 rows, which is also what an unpruned scan returns. It now adds a
file that does not parse as `UInt32` to the glob, so the query only succeeds
when the pruning drops that file before it is read, and adds a control with a
deterministic lambda over `_file` so the test fails if the guard starts to
refuse every lambda instead of only the non-deterministic ones.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the status on #119728. The last run here came back fully green, so the countResample stress failure did not recur in it; if it shows up again before that fix merges, it stays the same known, unrelated #119727. Meanwhile both review threads on the tests were adopted in 9895c57 (analyzer pinned in 05212, observable pruning control with a deterministic lambda in 05213).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (323 commits behind, no conflicts; the pull request stays tests-only). The single red of the previous run, 05182_join_order_conflict_detector_cast_null_propagation under the randomized auto_statistics_types = uniq_v2 MergeTree setting, is unrelated to this change and was fixed on master by #120084, which this merge pulls in.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single red of the last run, Stress test (arm_msan) with Cannot start clickhouse-server after the stress phase, is unrelated to this tests-only change: the restarted server cannot attach test_7.t_pfl_05079, the table that master's own 05079_parse_aggregate_function_typed_param creates with a quantile(0.5::Decimal32(1)) state column, because the level was persisted into the metadata as the quoted string '0.5' and reparses as a String (CANNOT_CONVERT_TYPE). Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117747&sha=6a9ad0e9ecbe5cd08d19abdabd33c36172a18088&name_0=PR&name_1=Stress%20test%20(arm_msan). The fix is already in flight in #119810 (quantile parameters printed with their types so the state type name round-trips), which has not landed on master yet, so this branch is not merged again for it. @groeneai, please link the status of that fix here if it changes.

@groeneai

Copy link
Copy Markdown
Collaborator

#119810 has not landed yet, so here is its status.

It is open at d9c814ef99c3, mergeable against master with no conflicts, and CI on that head is fully green (no failed job or test row for that commit). Review is requested and not submitted yet, so it waits on review only.

Once it is on master and this branch picks it up, this red goes away: test_7.t_pfl_05079 is created inside the same run, so with the level printed as quantile(0.5::Decimal32(1)) the restarted server attaches the table. Metadata already written with the quoted spelling is not repaired by that change (the stored text does not change), which does not matter for a stress run.

The signature is also not specific to this branch, and it grew once 05079 landed on master on 2026-09-13: 42 failed rows in the last 14 days over 35 pull requests, 5 runs on master itself and 11 stress flavours (16 rows on 09-13, 21 on 09-14; first hit 09-08 13:35Z, latest 09-15 06:36Z).

I will post here again when it merges or is superseded.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the status on #119810. Since that fix is green and only waits on review, this branch stays as is; once it lands on master I will merge master here so the Stress test (arm_msan) restart red (test_7.t_pfl_05079 attach) clears. Nothing else is pending: no unresolved review threads, and the pull request remains tests-only (05212, 05213).

@groeneai

Copy link
Copy Markdown
Collaborator

#119810 merged into master at 2026-09-19 04:21 UTC as fcbf73ea6f6725cbdfcb5e319a3bf32640bd50fe.

master now keeps the cast in the persisted type name: the 05079 reference reads AggregateFunction(quantile('0.5'::Decimal32(1)), Float64) where it read quantile('0.5') before, so the spelling reparses and a restarted server can attach test_7.t_pfl_05079.

This branch's head 6a9ad0e9ecb predates that commit, so the Stress test (arm_msan) restart red stays until a master merge picks it up. The signature is still appearing on other branches that do not have the fix yet (the last one I see is 2026-09-19 03:04 UTC), so a run started before the merge is not a counter-example.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (2839 commits behind, no conflicts; the pull request stays tests-only — 05212, 05213). This picks up #119810 (fcbf73ea6f6725cbdfcb5e319a3bf32640bd50fe), so the sole red of the previous run — Stress test (arm_msan) failing to restart the server because test_7.t_pfl_05079 could not be attached (quantile('0.5') reparsed as a String) — is expected to clear on this head. Thanks for tracking it.

New head: 0972d842444b. No unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI on 0972d842444b: the only failing test in all three red jobs is 05227_storage_settings_unknown_name (10 rows across Stateless tests (arm_asan_ubsan, targeted), (amd_debug, parallel) and (arm_binary, parallel); the targeted job stopped at Too many test failures for the same reason). It is unrelated to this pull request — this branch is tests-only (05212_lambda_nondeterminism_filter_push_down, 05213_file_pruning_nondeterministic_lambda), and both of those pass in every flavour that ran them.

05227_storage_settings_unknown_name is red fleet-wide on master since #118423; the failure is reproducible without randomized settings and the diff is only about whether a SETTINGS name = DEFAULT reset is stored in the CREATE TABLE text.

@groeneai, the fix is already in progress in #121163 — linking it here. It is not on master yet, so merging master into this branch would not clear the red; I will re-merge once #121163 lands.

Nothing to push here.

@groeneai

Copy link
Copy Markdown
Collaborator

Agreed, nothing to push here. #121163 is mine: CI on 51e07b3101c1 is fully green (the PR run finished at 13:20 UTC with no failed job and no failed test), the change is test-only (05227_storage_settings_unknown_name.sql and its reference, nothing else), and it is mergeable against master with no conflicts, so it waits on review only.

I will post the merge sha in this thread once it lands.

alexey-milovidov and others added 2 commits September 20, 2026 19:30
`ArrayExistsToHasPass` rewrites `arrayExists(x -> x = constant, arr)` into
`has(arr, constant)` whenever `optimize_rewrite_array_exists_to_has` is on,
which it is by default. The control in
`05213_file_pruning_nondeterministic_lambda` therefore never reached
`VirtualColumnUtils` as a lambda-bearing predicate, so a regression that
refused every lambda in `createPathAndFileFilterDAG` would still have passed
it.

Give the lambda a body the pass cannot match, `startsWith(x, 'data1.')`, and
pin `optimize_rewrite_array_exists_to_has = 0` for the query on top of that.
Verified with `clickhouse local` that the predicate still prunes: the glob
contains a file that does not parse as `UInt32`, and the query returns 2000
rows instead of failing with `INCORRECT_DATA`, while a predicate that cannot
prune does read that file and fails.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI Review major on 05213_file_pruning_nondeterministic_lambda in b8674de682ce.

The finding was right: ArrayExistsToHasPass matches exactly the x -> x = constant shape, so with the default optimize_rewrite_array_exists_to_has = 1 the "deterministic lambda still prunes" control reached VirtualColumnUtils as has([_file], 'data1.csv') and carried no lambda at all — a regression that refused every lambda in createPathAndFileFilterDAG would have passed it.

Both remedies the review offered are applied: the body is now startsWith(x, 'data1.'), which the pass cannot match because it requires an equals body, and optimize_rewrite_array_exists_to_has = 0 is pinned on the query on top of that. The dot in data1. keeps the match to data1.csv only, so the expected 2000 is unchanged and the reference file is untouched.

Verified with clickhouse local on the same 16-file glob plus the unparsable databad.csv: the new lambda returns 2000, meaning the pruning really dropped the bad file before reading it, while a predicate that cannot prune does read it and fails with INCORRECT_DATA.

Also note that 05227_storage_settings_unknown_name is no longer a concern here — #121163 merged as 1d7d23fc7105 and is already contained in this branch through the master merge in e2c24f610fdc, whose run was green. Thanks @groeneai.

The pull request remains tests-only (05212, 05213). New head: b8674de682ce.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 21, 2026
Merged via the queue into master with commit 9c14674 Sep 21, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-lambda-nondeterminism-filter-pushdown-117262 branch September 21, 2026 02:45
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
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-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

query_plan_filter_push_down moves a filter with rand inside a lambda below the aggregation — the determinism guard does not see into lambda bodies

5 participants