Skip to content

Adaptive lazy execution of short-circuit function arguments (continues #73776) - #114734

Open
alexey-milovidov wants to merge 150 commits into
masterfrom
continue-pr-73776-adaptive-lazy
Open

alexey-milovidov wants to merge 150 commits into
masterfrom
continue-pr-73776-adaptive-lazy

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

This continues #73776 by @lgbo-ustc, whose branch was ~17 months behind master and could no longer be merged mechanically (27 conflicting files in the hottest central code). The author's commits are preserved; on top of them this reconciles the change with the current master and reworks the plumbing.

Short-circuit evaluation decides statically which arguments of and, or, if and multiIf are executed lazily. Lazy execution is not free: the rows which are not needed are filtered out and the result is expanded back to the original size. When the filtered out part is small, or the argument itself is cheap, this overhead is larger than the work it saves.

This adds an opt-in adaptive mode: the execution of every function is profiled (elapsed time and processed rows), and every 20000 rows the decision is revisited per action - lazy execution is turned off when the estimated cost of the full execution is lower than the measured cost of the lazy execution, and turned back on when the per-row cost of the action grows significantly. Actions whose function can throw an exception on invalid input values (for example intDiv(1, 0)) are never switched to eager execution, so the short-circuit protection is preserved.

The mode is disabled by default and enabled with the new experimental setting enable_adaptive_short_circuit_lazy_execution. It currently takes effect only together with short_circuit_function_evaluation = 'force_enable': with the default enable mode, none of the lazily executed arguments is safe to switch to eager execution.

Changes on top of the original branch:

  • The flag no longer travels through ExpressionStep/FilterStep constructors, the query plan optimizations, the planner and the step serialization. It lives in ExpressionActionsSettings next to enable_lazy_columns_replication, which removes ~20 files from the change and all the ripple through QueryPlan/Optimizations.
  • ExpressionActions::execute and executeOnColumns stay const; the free executeAction became a member with three virtual hooks (shouldExecuteLazily, executeFunction, finalizeBlockExecution) which AdaptiveExpressionActions overrides.
  • The profile plumbing follows the current IExecutableFunction chain, including executeWithoutReplicatedColumns, which did not exist when the branch was written.
  • is_no_except is computed only when the setting is enabled, so nothing changes for the default path.

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental setting enable_adaptive_short_circuit_lazy_execution, which enables dynamic evaluation of whether a short-circuit function's argument should be lazily executed. The execution of the functions is profiled at runtime, and the lazy execution of an argument is disabled when it costs more than executing the argument on all the rows.

Related: #73776


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

lgbo-ustc and others added 29 commits March 11, 2025 08:53
…ouse into continue-pr-73776-adaptive-lazy

Reconcile #73776 by @lgbo-ustc with the current `master`. The branch was ~17 months
behind, and 27 files conflicted in the hottest central code, so besides resolving the
conflict markers the change is reworked to fit the current interfaces:

* The `enable_adaptive_short_circuit_lazy_execution` flag is no longer threaded through
  the `ExpressionStep`/`FilterStep` constructors, their serialization, the planner and
  the whole `QueryPlan/Optimizations` suite. It is a field of `ExpressionActionsSettings`
  next to `enable_lazy_columns_replication`, which is where the step already gets it
  from in `transformPipeline`. This drops ~20 files from the change.
* `ExpressionActions::execute` and `executeOnColumns` stay `const`. The free
  `executeAction` became a member with three virtual hooks - `shouldExecuteLazily`,
  `executeFunction` and `finalizeBlockExecution` - which `AdaptiveExpressionActions`
  overrides. Its profiling state is `mutable`, which is safe because an adaptive
  instance is created per pipeline stream and is never shared between threads.
* The `FunctionExecutionProfile` plumbing follows the current `IExecutableFunction`
  chain, including `executeWithoutReplicatedColumns`, which did not exist when the
  branch was written, and the `dry_run` argument which `ColumnFunction::reduce` gained.
* `is_no_except` is computed only when the setting is enabled, so the default path pays
  nothing for it.
* The setting is moved to the `26.8` block of `SettingsChangesHistory`, and the test is
  renumbered to `04893` because `03371` is taken.

Verified locally: `04893_adaptive_short_circuit_execution` matches the reference,
the adaptive decisions do fire (`Lazy execution is not beneficial for ...`), the
lazy execution of the arguments which can throw is preserved, and the first query of
`tests/performance/adaptive_short_circuit_execution.xml` runs 0.113 s -> 0.063 s.
Comment thread src/Interpreters/ExpressionActions.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 17, 2026 15:03

AI review of a later commit does not approve the PR, see the AI Review comment.

alexey-milovidov and others added 3 commits November 19, 2026 18:31
…`clone`

`ExpressionActions::clone` chose the clone's implementation from the settings, so
copying a plain instance built with `enable_adaptive_short_circuit_lazy_execution`
enabled (e.g. the table key expressions in `KeyDescription`, copied on
`IStorage::setInMemoryMetadata`) silently produced a stateful
`AdaptiveExpressionActions`, which could then be executed concurrently, e.g. by
`MergeTreePatchReaderMergeOnKey::readPatch` through the cached patch sorting key.

Make `clone` virtual: a plain instance is cloned into a plain one, and
`AdaptiveExpressionActions` overrides it to create a fresh adaptive instance.
Add `isAdaptive` and use it instead of the setting where the code decides
whether an instance needs a per-stream copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts:
* `ColumnFunction.cpp`: master added the reuse of the reduced shared nodes
  (`ReducedColumns`) to `reduceImpl`; this PR templated it on `with_profile`.
  The merged `reduceImpl<with_profile>` takes both the `ReducedColumns` and the profile.
* `ExpressionActions.cpp`: kept both the PR's scope and master's `shared_node` argument.
* `ActionsDAG.cpp`: master's `createLambdaExpressionActions`, wrapped into the PR's
  `ExpressionActionsPool`.

Semantic changes: master added the `uncompiled_actions_dag` parameter to the
`ExpressionActions` constructor; it is now passed through `ExpressionActions::create`
and `AdaptiveExpressionActions`, and `createLambdaExpressionActions` uses
`ExpressionActions::create`, so that a lambda body is adaptive with the setting (it
is used only as the prototype of an `ExpressionActionsPool`).

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

The table key expressions are plain `ExpressionActions` shared by the sinks of a
parallel insert; their copies made by `IStorage::setInMemoryMetadata` must stay plain.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 38a0a9c2155:

  • 50bf9d47b53: addresses the review. ExpressionActions::clone now keeps the concrete kind: plain instances stay plain, and AdaptiveExpressionActions overrides clone. A new isAdaptive replaces the setting checks in ExpressionActionsPool, IEJoinTransform and ReadFromMemoryStorageStep.
  • 994e07940d8: merged master and resolved conflicts:
    • ColumnFunction.cpp: master's ReducedColumns reuse is combined with this PR's reduceImpl<with_profile>.
    • ExpressionActions.cpp: added master's shared_node argument.
    • ActionsDAG.cpp: master's createLambdaExpressionActions, wrapped in the PR's ExpressionActionsPool.
    • Master's new uncompiled_actions_dag constructor parameter is now passed through ExpressionActions::create and AdaptiveExpressionActions.
  • 38a0a9c2155: new test 05836_adaptive_short_circuit_table_key_copy.

Locally, clickhouse builds, and all 26 adaptive_short_circuit / coalesce_short_circuit stateless tests pass against a server.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 8aa764799c4, a clean merge of master (master did not touch any of the PR's files, and the diff scope is unchanged).

The only failing test in the previous run was 05293_autopr_statistics_plan_based (second_run_used_replicas 0 instead of 1). It is not caused by this PR: it also failed on master and on many unrelated PRs over the past three days. It was fixed on master in a6c84af029f9 (pins enable_adaptive_codec_selection = 0, because the randomized codec selection changes the estimated bytes the cost model uses). This merge brings that fix in.

@alexey-milovidov

alexey-milovidov commented Nov 20, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Pushed 402c6c736f0: the only failing check was Style check / settings_changes_history. The version is now 26.12, so the history record of the new enable_adaptive_short_circuit_lazy_execution setting moved from 26.11 to 26.12. python3 -m ci.jobs.scripts.settings_history --base origin/master passes locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed ea8bd84aa0c, a clean merge of master. It touches Settings.cpp, Parquet/Reader.cpp, JoinStepLogical.cpp and TotalsHavingStep.cpp, which this PR also changes. Those files and SettingsChangesHistory.cpp compile, and the PR diff covers the same files as before.

The only failure in the previous run is unrelated: Stress test (amd_debug) hit Unexpected return type from accurateCastOrNull. Expected Nullable(Tuple(Array(Bool))). Got Nullable(Tuple(Array(Nullable(UInt8)))) inside ActionsDAG::evaluatePartialResult (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114734&sha=402c6c736f071dcbebba13727073341e3eefc2d3&name_0=PR&name_1=Stress%20test%20%28amd_debug%29). This is #132281, and the open PR #132543 fixes it.

alexey-milovidov and others added 2 commits November 22, 2026 23:21
`05444_adaptive_short_circuit_low_cardinality_rows` failed once out of 50 runs in the
flaky check with `Test runs too long (> 180s)`. The randomized `MergeTree` settings chose
`index_granularity = 2`, so the 200000 rows of the table were split into 100000 marks.
The first read of the table (with a cold cache) did 200000 buffer allocations and 200000
uncompressed cache misses, and under the thread fuzzer this single query took 236 seconds
of wall time for 39 seconds of CPU. The second query, which read from the cache, took
0.6 seconds. The slowness is in reading the table and not in the logic under test.

Set `index_granularity` and `index_granularity_bytes` explicitly, as
`05153_adaptive_short_circuit_profile_across_blocks` already does, in this test and in
the other tests of the feature which fill a `MergeTree` table with hundreds of thousands
of rows.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114734&sha=ea8bd84aa0ca1905a010869c143c906372286ebc&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29
#114734

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 11e2f0ff165:

  • 18ed14358f1 fixes the only failing test, 05444_adaptive_short_circuit_low_cardinality_rows, which failed once out of 50 runs in the flaky check with Test runs too long (> 180s) (report). In that run the randomized MergeTree settings chose index_granularity = 2, so the 200000-row table had 100000 marks. According to the query_log of the job, the first (cold cache) read of the table did 200000 buffer allocations and 200000 uncompressed cache misses, and under the thread fuzzer it took 236 s of wall time for 39 s of CPU. It was the query with enable_adaptive_short_circuit_lazy_execution = 0; the next, adaptive query took 0.6 s. So the slowness is in reading the table, not in the adaptive logic. The test now sets index_granularity and index_granularity_bytes explicitly, as 05153_adaptive_short_circuit_profile_across_blocks already does. The same is done in the five other tests of the feature which fill a MergeTree table with hundreds of thousands of rows (05059, 05230, 05289, 05617, 05836).
  • A clean merge of master. It touches eight files which this PR also changes (ProfileEvents.cpp, Settings.cpp, IFunctionAdaptors.cpp, Parquet/Reader.cpp, Parquet/Reader.h, ReadFromMergeTree.cpp, MergeTreeSplitPrewhereIntoReadSteps.cpp, StorageObjectStorageSource.cpp); they compile on the merged tree, and the PR diff covers the same 82 files as before.

The six edited tests pass locally on a build of the branch before the merge. CH Inc sync was also red; the new push restarts it.

# Conflicts:
#	src/Processors/QueryPlan/JoinStepLogical.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 4a23358fe2f, a merge of master. The PR was CONFLICTING: master renamed IEJoin to InequalityJoin, which touched the line in JoinStepLogical.cpp where this PR replaces std::make_shared<ExpressionActions> with ExpressionActions::create. The resolution keeps ExpressionActions::create with the new InequalityJoin naming; the PR's change in IEJoinTransform.cpp followed the rename to InequalityJoinTransform.cpp automatically. The diff scope is otherwise unchanged. All translation units touched by the PR compile on the merged tree; I did not link the binary or run the tests locally.

CI on the previous head (11e2f0ff165):

There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 No new commits were needed on this branch. On the current head 4a23358fe2f the Praktika report has no failed tests (Stress test (amd_tsan) is still running), there are no unresolved review threads, and the PR is MERGEABLE.

The only red check was CH Inc sync ("Failed. Needs manual intervention"): the sync PR was CONFLICTING in ColumnFunction.cpp, ActionsDAG.cpp, ExpressionActions.cpp and JoinStepLogical.cpp (the same IEJoin → InequalityJoin rename and neighbouring changes that conflicted here). I merged private master and this head into the sync branch; those four files have no private differences, so they take the public merge result. The changed lines of the sync PR against private master are identical to this PR against public master (82 files), and the sync PR is MERGEABLE again, so its CI has restarted. I did not build the private tree locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 98a00b2d517, a clean merge of master (no conflicts). ExpressionActions.cpp, HashJoin.cpp and Parquet/Reader.cpp, the files both sides touch, compile on the merged tree; I did not link the binary or run tests locally. The PR diff against master is unchanged.

The only failure on the previous head 4a23358fe2f was Stress test (amd_tsan), which timed out after 3 hours (report, job.log). The stress run itself finished and the server stopped at 10:07:10. The job then hung in collect_query_and_trace_logs: clickhouse-local --only-system-tables -q 'select * from system.metric_log format TSVWithNamesAndTypes' | zstd started at 10:08:42 and produced nothing until the job was killed at 11:15:24. The same step takes about 36 seconds in other amd_tsan runs. Because of the timeout there are no artifacts and no stack trace of the hung process.

I believe this is unrelated to the PR: everything it adds is gated by enable_adaptive_short_circuit_lazy_execution, which is off in that clickhouse-local invocation, and the same export step passed in all the other stress jobs of this commit. I found no existing issue for this hang, and no other Stress test job in CIDB over the last 20 days timed out at this step.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114734&sha=4a23358fe2fc89ed7537434861f50ee25e3a8542&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the clickhouse-local hang in collect_query_and_trace_logs after the Stress test (amd_tsan) run on 4a23358fe2f; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

This run left no artifacts, but the same export took 64-72 min in 3 other amd_tsan runs on 2026-11-20 and 2026-11-21 that still finished in time (1, 2, 3), and their clickhouse-server.log (where clickhouse-local logs) shows the cause. clickhouse-local --config-file=/etc/clickhouse-server/config.xml loads the stress default profile with ast_fuzzer_runs = 5, so after the export query it runs fuzzed copies of it before exiting. One of them, e.g. SELECT * FROM merge(REGEXP('(?i)SYSTEM'), 'metric_log'), spends over an hour building the plan for the system.metric_log child, since max_execution_time is only checked between Merge children (Timeout exceeded: elapsed 4248469 ms, maximum: 10000 ms). This PR has the 60 min stress phase of a pr-performance PR, so the job crossed 3 hours.

Fix: #133786 runs the export with --ast_fuzzer_runs 0, as stress.py and setup_log_cluster.sh already do for their own statements. The slow, uninterruptible merge() planning is a separate engine issue that I am looking at.

@groeneai

Copy link
Copy Markdown
Collaborator

The engine side from my previous comment: #134077 makes planning a Merge child linear in the number of ALIAS columns it reads (metric_log has about 2,480 of them). On a debug build with the default server config, the three fuzzed merge() queries from those runs failed with TIMEOUT_EXCEEDED after 98-107 s (max_execution_time = 10) before the change and finish in 1.9-3.2 s after it.

qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Nov 24, 2026
`collect_query_and_trace_logs` exports the system logs with
`clickhouse-local --config-file=/etc/clickhouse-server/config.xml`, which loads
the stress `default` profile (`ast_fuzzer_runs = 5`, `ast_fuzzer_any_query =
true`). After each export query `clickhouse-local` therefore runs up to 5
fuzzed variants of it synchronously before exiting. Their results are
discarded, so the export never needed them, and one of them can take over an
hour: in three `Stress test (amd_tsan)` runs a variant like
`SELECT * FROM merge(REGEXP('(?i)SYSTEM'), 'metric_log')` spent 64-72 min
building the plan for the `system.metric_log` child, since
`max_execution_time` is only checked between `Merge` children. On PR ClickHouse#114734
(60 min stress phase) that pushed the job past its 3 h timeout and no result
was uploaded.

Pass `--ast_fuzzer_runs 0`, as `stress.py` and `setup_log_cluster.sh` already
do for harness statements. The stress run itself keeps the fuzzer.

Validated with the stress profile over a populated server data directory:
the function ran 20 fuzzed queries on master and 0 with this change, with
identical exported files; `--ast_fuzzer_runs 5` brings them back.

Related: ClickHouse#114734 (comment)

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

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-experimental Experimental Feature pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants