Skip to content

Do not extract a lambda-hidden non-deterministic predicate below a join - #112700

Merged
novikd merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-join-filter-pushdown-unsafe-predicate
Sep 8, 2026
Merged

novikd merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-join-filter-pushdown-unsafe-predicate

Conversation

@groeneai

@groeneai groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116930
Related: #117248
Related: #117249
Related: #117756

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 the default-enabled use_join_disjunctions_push_down silently dropping rows when the filter above
a join hides a non-deterministic function inside a lambda body, as in
arrayExists(z -> rand(z) % 2 = 0, [a]). The extracted pre-filter was pushed below the join while the
original filter stayed on top, so the lambda was drawn twice per row and only rows passing both draws
survived.

Description

At shipped defaults, no SETTINGS clause, 200000-row tables:

SELECT count() FROM t_left_big LEFT JOIN t_right_big ON t_left_big.a = t_right_big.a
WHERE arrayExists(z -> rand(z) % 2 = 0, [t_left_big.a]);
-- 50006, but 99975 with query_plan_filter_push_down = 0

onlyDependsOnAvailableColumns gated only on input-name availability and ARRAY_JOIN, with no
determinism test. Constant folding turns the lambda into a ColumnFunction in a COLUMN node, and its
body is a separate DAG, so a test that inspects FUNCTION nodes cannot see it. allNodeFunctions from
#117756 covers both shapes in one call.

The predicate is isDeterministicInScopeOfQuery, matching getConjunctionNodes, so now/today/
currentUser keep their push-down; measured, the stricter isDeterministic loses the pre-filter for
randConstant(a). Statefulness needs no test here: tryPushDownFilter returns early on
hasStatefulFunctions, which #117756 made lambda-aware.

#117249 guards this same function for the visible-rand case; this subsumes it. Built with its
FUNCTION-only check in place of this call, the hidden-lambda row still fails while the visible one
passes. If #117249 lands first, upgrading its check to this call gives the same effect.

Three carriers of the same invariant are deliberately not touched: the plan-time JOIN-conversion guard
in Utils.cpp, whose fix in #117248 is character-identical to the one this branch used to carry; and,
neither reachable at defaults, the inlined copy of the predicate in AggregationPushdown.cpp (needs
enable_cascades_optimizer = 1) and ActionsDAG::hasNonDeterministic, which asks the different
across-queries question.

Test 05139_join_partial_push_down_nondeterministic_lambda asserts the count band for the visible and
the hidden call, and that a deterministic predicate and a query-constant lambda keep their pre-filter.
Both defect rows fail on master.


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

Version info

  • Merged into: 26.9.1.978 (included in 26.9 and later)

groeneai and others added 4 commits July 30, 2026 22:47
Three checks decide whether a WHERE conjunct may be evaluated below a JOIN, and
each one inspected only the outer ActionsDAG.

A lambda body is not part of that DAG. A capturing lambda keeps it in an
ActionsDAG owned by its FunctionCapture, and a lambda whose unsafe call consumes
the lambda parameter cannot be hoisted out, so it is folded to a
ColumnConst(ColumnFunction(FunctionExpression)) - a COLUMN node, which the main
gate's own type == FUNCTION clause could not even reach. Neither wrapper
overrides isDeterministicInScopeOfQuery or isStateful, so both reported
themselves safe whatever the body computed.

getConjunctionNodes therefore classified such a conjunct as pushable, and
because splitActionsForJOINFilterPushDown ends with removeUnusedConjunctions the
conjunct was moved rather than copied: it was never evaluated on the post-join
row set, so an outer join fabricated rows that escaped a filter that no longer
constrained them.

onlyDependsOnAvailableColumns, the disjunction path that is enabled by default,
had no determinism test at all. There even a bare, fully visible
WHERE rand(a) % 2 = 0 was copied below the join while being kept above it, so it
was drawn twice per row and about a quarter of the rows survived instead of about
a half. That half of the defect involves no lambda.

hasStatefulFunctions, the step-level veto in tryPushDownFilter, was blind the
same way.

One shared helper, inspectLambdaBodies, walks the bodies reachable from a node,
follows nested lambdas through the captured columns of a ColumnFunction, and
reports the two unsafe classes separately, because the consumers relax them
differently. Non-determinism is rejected per conjunct in both classifiers, with
the existing allow_non_deterministic_functions parameterisation preserved.
Statefulness is rejected at the pre-gate only: the veto there is all-or-nothing
for a whole step, and rejecting statefulness per conjunct instead would let a
deterministic sibling move and hand the stateful function a different input row
set, which would be a behaviour change beside a correctness fix. The helper never
throws, unlike the serialization code it borrows the unwrap from, because an
unrecognized shape is simply not a lambda.

The new helper is called from filterPushDown.cpp rather than folded into
ActionsDAG::hasStatefulFunctions, so the other callers of that method keep their
exact current behaviour.

Present unchanged from 25.8 through master.

Co-Authored-By: Claude Fable 5 <[email protected]>
… guard

Review round 1 found that the hidden-lambda rejection in
onlyDependsOnAvailableColumns had no test row failing when it alone was
removed: every hidden-lambda row read the fabricated-NULL or plan-shape
oracle, while the surviving-row-count oracle (the only one that can observe
the partial path copying a conjunct below the join) was used only by rows
with a visible rand, which the node's own metadata already rejects.

Row B3 closes that cell: B1's shape with the rand moved into a lambda body.
Deleting only the hidden-lambda rejection reddens B3 and no other row.

The row pins use_join_disjunctions_push_down because it observes only the
partial path, and both test runners can turn that path off: clickhouse-test
randomizes the setting directly, and the stress runner's randomized
compatibility reverts it below the 26.1 block where its default flipped.
Without the pin the row reads 1 whatever the optimizer does.

Also record two deliberate design choices in comments: inspectLambdaBodies
shares no visited state with the DAG-wide entry point, and the cheap
metadata test must stay the first disjunct so the DAG walk stays off the
common path.

Co-Authored-By: Claude Fable 5 <[email protected]>
The B1 row is the only one that observes the partial push-down path's
own-metadata determinism rejection. The main path rejects a visible
non-deterministic function node on master already, so B1's verdict can move
only via the partial path, and that path is entirely inside a block gated on
use_join_disjunctions_push_down. B1 left the setting unpinned, so on any draw
where the setting is off both of its arms evaluate the visible rand exactly
once, the ratio is about 1, and the row passes even with the rejection deleted.

Two channels turn the setting off in CI: the functional runner randomizes it
directly at about 5% of draws, and the stress runner's randomized compatibility
value reverts its pre-26.1 default, which 72 of its 84 draws do. Pin it on the
push-down-enabled arm only, leaving the reference arm at defaults.

Measured on a build with only that rejection deleted: the pinned row reads 0
while the unpinned row reads 1 under a session SET, a client option and
compatibility='25.1'. The same mutation reddens B1 and no other row, so each of
the two rejections in that classifier carries its own coverage.

Also reword the A-oracle comments, which claimed the fabricated-NULL oracle
observes both push-down paths. It observes the main path's move only: the
partial filter lands on the preserved side, so a copy fabricates no NULL. The
copy is observed by B1 and B3.

Co-Authored-By: Claude Fable 5 <[email protected]>
Filter push-down now leaves an unsafe predicate above the JOIN instead of
moving it below. The very next optimization reads that filter to decide
whether a LEFT JOIN can become an INNER one, and its own determinism guard,
dagContainsNonDeterministicFunction, scans only the outer DAG. So the fix
newly hands the hidden-lambda class to a guard that cannot see it, and the
rewrite would then drop rows on the strength of one fabricated dry-run row.

Add a whole-DAG entry point for the non-determinism class beside the existing
stateful one and consult it from that single choke point, which covers all six
call sites. The cheap outer scan stays first, so the common path is unchanged.

Measured: for a LEFT JOIN whose filter hides rand in a lambda body, master
converts the join to INNER while the visible form is already vetoed. That
asymmetry is what identifies the class as a consequence of retaining the
predicate rather than a pre-existing gap. The same guard also repairs a
wrong-results case where roughly half the rows were dropped.

Tests: J1 asserts the join kind survives the hidden form, J2 pins the visible
control, J3 asserts a deterministic lambda body still lets the rewrite happen.
A9 covers the capturing-lambda carrier, where the unsafe call consumes both the
lambda parameter and an outer column so the body stays in a FunctionCapture
rather than folding to a column; the branch that enters it had no witness for
this class before. J1 pins query_plan_convert_outer_join_to_inner_join because
the runner draws it off in about 5 percent of runs and a randomized
compatibility below 24.4 reverts its default.

Also correct an in-diff comment that described the disjunct order as
short-circuiting on the common path, which is the opposite of what it does.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, 8 findings adjudicated)

Before opening this PR I ran four rounds of independent review: a cold read of the resulting code by
a reviewer that did not write it, plus an adversarial second-model pass each round. Eight findings
were raised in total. Six were agreed and fixed, one is disagreed with evidence and split to its own
issue, one is a comment nit noted below. Every round re-verified the previous round's fix rather than
trusting the report.

Agreed and fixed

  • ❌ The disjunction path's hidden-lambda rejection had no test row that failed when that guard alone
    was removed. Its sibling rejection was catching every existing row. Fixed by adding a row whose
    predicate hides the call in a lambda, mutation-tested against that one guard.
  • ❌ The row witnessing the disjunction path's own-metadata rejection did not pin the setting that
    gates the path it tests, so it was vacuous on a measurable fraction of runs: the test runner turns
    that setting off in about 5% of draws, and the randomized compatibility setting reverts its
    default on 72 of 84 possible values. Pinned, and the pin proven load-bearing on three channels.
  • ❌ Leaving a hidden-lambda predicate above the join, which is what this fix does, hands it to the
    JOIN-kind conversion pass that runs immediately afterwards. That pass decides whether a LEFT JOIN
    can become INNER by evaluating the filter on one fabricated row, and its guard scanned the outer
    DAG with the same blind spot. Before this fix the predicate was pushed below the join, so it was
    absent from the DAG that guard reads; afterwards it is present. The visible form of the same
    predicate was already vetoed there on master, and that asymmetry is what makes this consequence
    belong to this PR. Fixed by giving the guard the same body walk, with one live row and two
    controls, one of which asserts a deterministic lambda still permits the conversion.
  • ⚠️ The capturing-lambda entry point of the new helper had no witness: every unsafe row put the call
    on the lambda parameter alone, which folds to a column and takes the other entry. Which shape
    reaches it was determined empirically rather than assumed, and a row was added.
  • 💡 Two comment defects: one claimed an oracle observes both defects when the measurements show it
    observes only one, and one described a short-circuit that does not happen on the common path.

Disagreed, with evidence, and split out

  • ❌ A stateful function that is deterministic in query scope still permits the JOIN-kind
    conversion.
    The mechanism is real and I verified it fully: that guard tests only determinism,
    never isStateful, and 17 functions in the tree are stateful while reporting themselves
    deterministic in query scope. But it is not a consequence of this PR. For the determinism case the
    visible form was already safe on master, so only the hidden form was newly exposed, which is a new
    class. For statefulness the visible form is already mis-converted on master today: the push-down
    veto already sees a visible stateful call and refuses, so such a predicate is already retained
    above the join with none of this diff applied, and the conversion guard already misses it there.
    Visible and hidden end in the same miss, so the gap is pre-existing and symmetric. The conversion
    verdict also does not require evaluating the unsafe atom at all, since an ordinary sibling atom is
    what folds falsy on the fabricated row. Finally, the guard is shared by four call sites including
    one about distributed exchanges, so vetoing statefulness there would silently stop conversions for
    predicates with no lambda involvement, which is a behaviour change this PR does not claim. Tracked
    separately rather than folded in, one concern per pull request.

Noted, not blocking

  • 💡 A comment on the new call site says the helper costs one typeid_cast per node. For a COLUMN
    node it first inserts into a set and then performs up to two casts. This is plan-time only and the
    cost is immaterial, so the code is unchanged and only the comment overstates its precision.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. One clickhouse local --queries-file run of the new test. The fabricated-NULL rows read exactly 0 on every run of a correct build and 469-530 on master. Not a percentage.
b Root cause explained? Yes. Two checks classify a WHERE conjunct as pushable from outer-DAG metadata, and a lambda body is not in the outer DAG (FunctionCapture holds it in its own ActionsDAG; a lambda consuming the lambda parameter is folded to a ColumnConst(ColumnFunction), a COLUMN node). The disjunction path additionally had no determinism test at all, even for fully visible predicates. On the main path removeUnusedConjunctions then moves the conjunct, so it is never evaluated on the join result. Correctly retaining it above the join then exposes the immediately following JOIN-kind conversion pass, whose guard dagContainsNonDeterministicFunction scanned the outer DAG the same way.
c Fix matches root cause? Yes. The determinism test is completed where it already lives, in both classifiers and in the conversion guard, and the statefulness test at the existing step-level veto. No widened bound, no test tag, no guard at the symptom site.
d Test intent preserved / new tests added? New test 04658_join_filter_push_down_unsafe_predicate: 20 rows, 9 of which fail on master, 11 controls each pinning a specific must-not-regress property. No existing test weakened or removed.
e Both directions demonstrated? Yes. Every row was run on a pristine master build and on the fixed build with the same command. Oracle A (fabricated NULLs) goes about 500 to exactly 0; Oracle B (surviving row count) goes ratio 0.498 to 1.003; the hidden-stateful plan row goes 2 filters below the join to 0.
f General across code paths? Yes. The classifier set is closed: grepping getConjunctionNodes|onlyDependsOnAvailableColumns|splitActionsFor over src/ returns only those two functions plus splitFilter.cpp, which makes no push-down decision. One shared helper serves both, covering the generic split and all three JOIN-side splits, at both values of use_join_disjunctions_push_down.
g Generalizes across inputs? The helper keys on the lambda container node type, never on a data type, so no Nullable, LowCardinality, Array or Map wrapper can be stripped but missed. Covered: folded lambda (COLUMN), capturing lambda (FUNCTION), nested lambda reached through getCapturedColumns, ColumnFunction with and without the ColumnConst wrapper, hoisted forms, deterministic bodies, and both unsafe classes.
h Backward compatible? A wrong-results fix. Affected queries return different, correct results, and some lose a push-down they should never have had. No setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? The helper is const-only, cycle-safe over both ActionsDAG and IColumn pointers, saturates early, and never throws: unlike the serialization code it borrows the ColumnConst/ColumnFunction unwrap from, an unrecognized shape is skipped, which is the correct direction for an optimizer predicate. The only behavioural change is that a conjunct hiding an unsafe body moves from allowed to rejected, restoring the pre-optimization behaviour. The statefulness veto stays step-level, so the row set a stateful function sees is unchanged.

Twelve mutations were run, each with a predicted failing set. Four predictions were wrong and the
measurements are reported rather than the predictions adjusted: dropping the main-path term also
reddens the disjunctions-off row, because that row pins use_join_disjunctions_push_down = 0 and so
isolates the main path; dropping the whole disjunction-path veto reddens only the row-count oracle,
because with the main-path fix present the conjunct is copied to the preserved side alone and
fabricates no NULLs; moving statefulness into the per-conjunct classifier reddens the two hidden
stateful rows rather than the visible one, since a visible stateful conjunct is still caught by the
plain step-level veto; and neutering the capturing-lambda entry reddens three rows rather than one,
because aiEmbed declines constant folding and so already reached that entry through the
statefulness channel, leaving only the non-deterministic class unwitnessed there. Three mutations
isolate one rejection each: deleting only the disjunction path's hidden-lambda rejection reddens the
hidden-lambda row-count row and only that row, deleting only its own-metadata rejection reddens the
visible row-count row and only that row, and deleting only the conversion-guard consult reddens the
join-kind row and only that row. No mutation reddened a control row, so the fix is not over-broad.

A 56-test sweep scoped by feature (the four gating settings plus the lambda-and-join tests) was run
twice on the same tree, once with only the conversion-guard consult reverted. Both arms ran the same
56 tests, with no test present in one arm only: no fix-only regressions, one improvement (this PR's
own test), and five failures shared by both arms that are sandbox artifacts. Reference churn is
confined to the new test's own reference, and all sixteen pre-existing verdict lines in it are
byte-identical.

The first tag-free 50-run randomized pass failed 11 times out of 50, which found a real fragility in
the new test rather than in the fix: query_plan_join_swap_table = 'true' and a nonzero
query_plan_optimize_join_order_randomize seed both force a join swap that inserts a runtime-filter
step below the join, which the plan-shape rows would count as a pushed filter. Both are now pinned
with the reason in a comment, the exact failing 182-setting draw passes, liveness was re-checked
after pinning, and a fresh 50-run pass is 50 out of 50 with no tag.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @yariks5s, could you review this? The two filter push-down classifiers tested isDeterministicInScopeOfQuery on outer-DAG nodes only, but a lambda body lives in a separate ActionsDAG owned by FunctionCapture or in a folded ColumnFunction, so a conjunct such as arrayExists(z -> rand(z) % 2 = 0, [a]) was classified pushable and moved below the join, where removeUnusedConjunctions then dropped it from the post-join filter; the disjunction path had no determinism test at all, even for a fully visible rand.

@yariks5s yariks5s self-assigned this Jul 31, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0fd79f]

Summary: ✅


AI Review

Summary

This PR narrows the remaining fix to the disjunction-side partial JOIN filter push-down: onlyDependsOnAvailableColumns now rejects predicates whose visible node or lambda body is not isDeterministicInScopeOfQuery, and the new stateless test covers the visible, folded-lambda, and FunctionCapture carriers plus the query-constant control. I did not find a correctness, safety, or coverage gap in the current three-file diff.

Final Verdict

✅ No blocking or major findings in the current diff.

LLVM Coverage Report

Measured on commit f0fd79f.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 4/4 (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 Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 72/75 (96.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3b14c6f

Every failure below has an owner: a fixing PR (ours 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
(none) 174 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260803-180000

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 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.

@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 4, 2026
groeneai and others added 7 commits September 7, 2026 19:45
Master fixed the main filter push-down and the step-level stateful veto in
4f223c8 (ClickHouse#117756): getConjunctionNodes and hasStatefulFunctions now go
through allNodeFunctions, which enters a lambda body, so the ActionsDAG.cpp and
filterPushDown.cpp changes here are redundant and the local lambdaBodySafety
helper has no remaining caller.

The Utils.cpp guard on dagContainsNonDeterministicFunction is conceded to
ClickHouse#117248, whose replacement expression is character-identical to the one this
branch carried, and which ships its own test and credits issue ClickHouse#117016.

partialJoinFilterPushDown.cpp is reverted here too, so this commit compiles on
its own once the helper is gone; the next commit re-adds the guard in master's
own idiom.
`use_join_disjunctions_push_down` extracts a per-side partial predicate and
pushes it below the join with `addFilterOnTop`, which leaves the original filter
in place. A conjunct that is non-deterministic within the query is therefore
drawn twice per row, independently, and only a row that passes both draws
survives, so `WHERE rand(a) % 2 = 0` returns about a quarter of the rows instead
of about half. `onlyDependsOnAvailableColumns` gated only on input-name
availability and ARRAY_JOIN, with no determinism test of any kind.

The predicate is `isDeterministicInScopeOfQuery`, matching `getConjunctionNodes`
and `dagContainsNonDeterministicFunction`: `now`/`today`/`currentUser` are
per-row constant within a query and keep their push-down.

`allNodeFunctions` rather than a test on `node.function_base` because constant
folding turns the lambda of `arrayExists(z -> rand(z) % 2 = 0, [a])` into a
`ColumnFunction` living in a COLUMN node, whose own metadata says nothing about
the body, and the body is a separate DAG. A test that inspects FUNCTION nodes
only classifies that conjunct as pushable.

Statefulness needs no test here: `tryPushDownFilter` returns early when the
filter expression `hasStatefulFunctions`, and 4f223c8 made that walk
lambda-aware, so a stateful call never reaches this extraction.

The check can only turn a `true` answer into `false`, so the worst outcome of a
misclassification is a pre-filter that is not extracted, never a new wrong
result.
Four rows over one 200000-row fixture. B1 draws a visible `rand`, B3 draws one
hidden in an `arrayExists` lambda: both compare the surviving row count with the
push-down on and off, and without the guard the ratio is about 0.5 rather than 1,
which at this size is about 16 standard deviations from the asserted 5% band.

B2 runs the same oracle on a deterministic predicate, so a red B1 or B3 is the
optimizer and not the fixture. B4 asserts the other direction, that a
deterministic lambda is still extracted: a blanket refusal would keep B2 green,
because B2's count does not depend on whether the extraction happens, so the row
counts the plan lines mentioning the lambda instead. Its filter is a disjunction
whose every branch spans both sides of the join, which the main push-down cannot
move, so the per-side extraction is the only thing that can add a plan element.

`use_join_disjunctions_push_down` and `enable_join_runtime_filters` are pinned in
each query's own SETTINGS clause, not by a SET: the runner passes randomized
settings on the client command line, and those are per-query settings that
outrank a SET issued earlier in the session. `enable_analyzer` cannot go there
(INCORRECT_QUERY when a subquery changes it) and the runner never randomizes it.

The file is renamed from 04658_join_filter_push_down_unsafe_predicate, which
covered carriers this branch no longer fixes.
The four rows could not tell `isDeterministicInScopeOfQuery` from the stricter
`isDeterministic`: two of them draw `rand`, which fails both, and the other two
use functions accepted by both. Built with the predicate weakened to
`isDeterministic`, the file stayed green, so a change that loses this pre-filter
for every function that is non-deterministic only across queries (41 of them
under src/Functions, among them `now`, `today`, `currentUser`, `queryID` and
`randConstant`) had no test in its way. `isDeterministic` is also the live
spelling at the sibling copy-below-a-join site in
propagatePredicateAcrossEquiJoin.cpp and in `ActionsDAG::hasNonDeterministic`,
so unifying these predicates later is a real regression path.

`randConstant` draws once per query, so duplicating the extracted copy cannot
change any row's verdict and the extraction is legitimate; under the stricter
reading it would be refused. The row asserts that the extraction still happens,
and reads 0 under that weakening.

Its lambda captures a column, so the check reaches the body through a
`FunctionCapture` node, where the hidden-`rand` row reaches it through a folded
`ColumnFunction`: both carriers of the one `allNodeFunctions` walk are now
driven from the test. It replaces the deterministic-lambda row rather than
joining it, because a blanket refusal reddens it just as it reddened that one,
and it additionally reddens the weakening.

Co-Authored-By: Claude Opus 5 <[email protected]>
`FunctionExpression::isDeterministicInScopeOfQuery` and
`FunctionCapture::isDeterministicInScopeOfQuery` are two separate virtual
overrides that happen to call the same free helper, so a regression in one is
invisible to a row that only drives the other. B1 drives a plain `rand` FUNCTION
node and B3 the folded `ColumnFunction` a non-capturing lambda becomes, while B4
drives a capture that must be accepted. Nothing drove a capture that must be
refused.

The new row is B3's count band with the lambda capturing a column, which turns
its carrier into a `FunctionCapture` FUNCTION node: the plan prints
`Capture[UInt64, UInt8, UInt8](UInt64) -> UInt8(a, 2, 0)` for it and prints no
capture for B3. Blinding this guard to FUNCTION nodes while leaving its folded
COLUMN path alone reddens the new row and B1 and leaves B3 green, so the two
rows separate the two carriers of the one `allNodeFunctions` walk.

Weakening `FunctionCapture::isDeterministicInScopeOfQuery` itself to `true` does
not redden any row, and that is a property of the other caller rather than of
this test: the same virtual is read by the main push-down
(`ActionsDAG.cpp:3263`), which moves a filter below the join and removes the
original instead of copying it. For a predicate reading only the preserved side
of a left join a move leaves the row count unchanged, so no count band can see
it. Measured on the 200000-row fixture: 99702 surviving rows with the push-down
on against 99950 with it off, and the filter gone from above the join entirely.

B4's comment loses the paragraphs recoverable from the SQL, since `-- { echo }`
reprints it in the reference and the file gains a row in the same commit.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous version of this row was a count band on a predicate touching only
the preserved side of a left join, and that shape cannot witness a regression of
the virtual the guard delegates to. `FunctionCapture::isDeterministicInScopeOfQuery`
is read by two callers: the guard added here, which copies the extracted
predicate below the join and keeps the original above, and the main push-down at
`ActionsDAG.cpp:3263`, which moves the predicate and removes the original. A copy
draws a per-row value twice and moves the surviving count to about a quarter of
the input; a move draws it once and leaves the count unchanged. Both callers were
eligible for the old shape, so when the virtual was weakened to `true` the main
push-down took the predicate and moved it, and the band read the same 99702
against 99950 that a correct refusal reads. The row's comment claimed a
regression in either override had to redden a row, which that measurement
disproves.

A disjunction spanning both sides of the join cannot be moved below it by the
main push-down at all, so on that shape the partial path is the only optimizer
that can act. The row now asserts that the plan prints `arrayExists` the same
number of times with `use_join_disjunctions_push_down` on as with it off, which
says the guarded extraction refused the capturing lambda and says nothing about
any other optimizer. Weakening either the guard or the virtual it delegates to
now reddens it.

B4 is the non-vacuity witness: it asserts the strict inequality on this same
shape with `randConstant`, a value drawn once per query that must still be
extracted, so a plan that stopped printing the lambda at all, or an extraction
that degraded into refusing every lambda, reddens B4 before this row could go
green for the wrong reason. `enable_join_runtime_filters` is pinned in both arms,
as B4 does, because this is a plan-shape oracle rather than a count band.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Do not push a non-deterministic or stateful predicate below a JOIN Do not extract a lambda-hidden non-deterministic predicate below a join Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review notes

Rescoped to the one defect no open PR covers: the lambda leg of the disjunction push-down. The
ActionsDAG.cpp and filterPushDown.cpp hunks this branch used to carry are dropped as superseded by
4f223c8 (#117756), and the Utils.cpp guard is conceded to #117248, whose expression was
character-identical to the one carried here. What remains is +6/-0 in
partialJoinFilterPushDown.cpp plus one test.

isDeterministicInScopeOfQuery rather than the stricter isDeterministic is deliberate: swapping them
leaves every other row green while losing the pre-filter for functions that are non-deterministic only
across queries (now, currentUser, randConstant). The row asserting that a query-constant lambda
keeps its pre-filter is what catches that swap.

Each carrier of a lambda has its own rejection row. Building
FunctionCapture::isDeterministicInScopeOfQuery as true reddens the capture row; building the guard
blind to FUNCTION nodes reddens the visible and the capture rows and leaves the folded
ColumnFunction row green.

Statefulness deliberately gets no test at this site: tryPushDownFilter already returns early on
hasStatefulFunctions, which #117756 made lambda-aware, before the partial path is reached.

One review finding disagreed with, on evidence: isConstant is representation-sensitive rather than
non-deterministic, and the shape that exhibits it is column-free (isConstant(1) = 0), which #117569
already refuses at this same site through isUsefulToPreFilterWith.

Related: rather than Closes: for #116930 is deliberate, since #117249 already claims that issue and
its reproducer is the visible-rand leg.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0fd79f3e with master 55c256363 (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

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

Job report

@novikd novikd self-assigned this Sep 8, 2026
@novikd
novikd added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit cd52baa Sep 8, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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 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.

5 participants