Skip to content

Visit each node once when finding lazily executed short-circuit arguments - #133893

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/short-circuit-lazy-nodes-linear
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/short-circuit-lazy-nodes-linear

Conversation

@groeneai

@groeneai groeneai commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133492

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Planning a query with a short-circuit function (if, multiIf, and, or, ...) whose argument reuses a subexpression, such as nested subqueries computing a + a, now takes time linear in the size of the expression instead of exponential in its depth. Closes #133492.

Description

In #133492, if(x < 0, a25, 0) over 25 nested subqueries with a{k+1} = a{k} + a{k} takes 5.4-6.6 s on 26.11 instead of 0.43 s, and each level doubles it.

findLazyExecutedNodes (ExpressionActions.cpp) walks the lazily executable arguments of each short-circuit function. It remembered only the nodes it selected as lazy, so a node it expanded and did not select (here every plus) was expanded again on every path to it: 2^depth expansions of the DAG that query_plan_merge_expressions builds from the subqueries.

The walk now also remembers, per short-circuit function, the nodes it found not lazy and skips them. Within one walk such a node cannot become lazy later, so the set of lazy nodes does not change. An ALIAS is remembered only when nothing below it is lazy. The memo is per function because force_enable_lazy_execution can differ between functions. The src/ change is under 25 lines.

Validation (debug build), short_circuit_function_evaluation = 'enable': depth 25 3.93 s to 0.28 s, depth 40 0.29 s (disable: 0.25-0.29 s on both). A local copy of the old walk compared both sets on every planning and found no difference in the 118 short-circuit stateless tests with random settings, without them and with force_enable; it fires on a deliberately broken memo. New test 05871_short_circuit_shared_dag_planning_time: 10 nested subqueries, 2^30 paths (0.36 s; 103 s on master), and a node shared by two lazy arguments; 50/50 with random settings, also at the TSan stack budget.

Siblings: compile_expressions = 1 and and use the same walk and were exponential too; both are flat now. The other walks of this step are memoized. WHERE x > 0 AND a30 > 0 over the same subqueries is still exponential, also with short_circuit_function_evaluation = 'disable': that is #123724, not changed here.

🤖 Generated with Claude Code


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

…ents

`findLazyExecutedNodes` walks the lazily executable arguments of every
short-circuit function (`if`, `multiIf`, `and`, `or`, ...). It only
remembered the nodes it selected as lazy, so a node it expanded and did
not select was expanded again on every path that reaches it. On a shared
DAG such as nested `a_{k+1} = a_k + a_k` subqueries (merged into one DAG
by `query_plan_merge_expressions`), every `plus` is such a node, and
planning took time exponential in the depth (ClickHouse#133492: depth 25 took
5.4-6.6 s instead of 0.43 s).

Remember the nodes found not lazy executed as well and skip them like
nodes that cannot be lazy executed. Within one walk the flag
`force_enable_lazy_execution` is fixed, and a node found not lazy has no
lazy node in its subtree, so a second expansion would return the same
result: the set of lazy executed nodes does not change. An ALIAS is only
remembered when its child chain is not lazy, because a lazy one must keep
reporting `has_lazy_node` to its other parents. The memo is per
short-circuit function because the flag can differ between functions.

Closes ClickHouse#133492

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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).

# Sev Finding Verdict Evidence / action
1 ⚠️ 05871 could pass without the shared DAG if expression merging is off; pin it, assert the plan, add a time bound DISAGREE query_plan_merge_expressions is not randomized or overridden in CI. If merging were off, the second query would throw ILLEGAL_DIVISION (its intDiv would sit in a step with no short-circuit function), so the test goes red, not vacuous. Same shape as 05317_exponential_null_propagation. A max_execution_time bound cannot interrupt the planning walk.

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

Session id: cron:clickhouse-review-slot-10:20261123-210205

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f92fc72]

Summary: ✅


AI Review

Summary

The PR removes exponential traversal of shared, non-lazy expression nodes during short-circuit planning. The per-function cache preserves lazy propagation through aliases. The supplied before/after measurements support the performance claim, and 05871_short_circuit_shared_dag_planning_time passes in the head commit's Fast test report in 0.1 seconds. No actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue query generated for depth D, clickhouse local, debug master: 0.49 / 1.20 / 3.93 / 7.63 s at D = 21 / 23 / 25 / 26 with enable, 0.25-0.29 s with disable; D = 30 does not finish in 60 s. With query_plan_merge_expressions = 0 D = 25 takes 0.25 s.
b Root cause explained? Yes. findLazyExecutedNodes memoized only the nodes it selected as lazy. A node it expanded and did not select (every plus here) was expanded again on each path to it, 2^depth times on the merged DAG.
c Fix matches root cause? Yes. The walk also remembers the nodes it found not lazy, per short-circuit function. No limit, setting or guard.
d Test intent preserved / new tests added? New SQL test 05871_short_circuit_shared_dag_planning_time: the issue query at depth 30, and a node shared by two lazily executed arguments (it fails with a LOGICAL_ERROR when an ALIAS with a lazy child is memoized as not lazy).
e Both directions demonstrated? Yes, as timing: the depth-30 query takes 120 s on master in the test runner and 0.13 s with the fix; the second query fails under the broken-memo mutation and passes with the fix. 50/50 with random settings.
f Fix is general across code paths? Yes. Both recursive branches (FUNCTION, ALIAS) use the memo; compile_expressions = 1 and and went through the same walk and are now flat, force_enable was already linear. WHERE x > 0 AND a30 > 0 is exponential with short-circuit disabled too, so it is another layer, not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The walk depends on node identity only. A local copy of the old walk compared both lazy sets on every planning: no difference in 118 short-circuit tests with random settings, without them and with force_enable.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the set of lazily executed nodes is unchanged.
i Invariants and contracts preserved? Yes. processShortCircuitFunctions returns the same lazy set: within one walk force_enable_lazy_execution is fixed and a node found not lazy has no lazy node below it, so a second expansion returns the same result. The memo is local to one call.

Session id: cron:clickhouse-impl-slot-4:20261123-143701

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f92fc72b6 with master d31a6eff9 (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

The first query of `05871_short_circuit_shared_dag_planning_time` nested
30 subqueries, and planning 30 nested subqueries needs more than the 5%
of the stack that `checkStackSize` allows under TSan: the flaky check
failed 22 of 50 runs with `TOO_DEEP_RECURSION`.

Use 10 nested subqueries whose expression doubles the paths three times
per level instead: the DAG still has 2^30 paths, so master still takes
about 100 s (103 s in a debug build) and the fix 0.3 s. With the stack
limited to the TSan allowance, a debug build trips at 28 levels for
both shapes; the new test passed 50 of 50 runs there with random
settings, the old one failed every run.

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. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Short-circuit planning takes exponential time on a shared expression DAG

2 participants