Skip to content

Reorder the arguments of short-circuit and/or when it is safe - #122508

Merged
alexey-milovidov merged 25 commits into
masterfrom
short-circuit-reorder-arguments
Oct 14, 2026
Merged

alexey-milovidov merged 25 commits into
masterfrom
short-circuit-reorder-arguments

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #55656

A reimplementation of #55656 (adaptive reordering of short-circuit and/or arguments) that addresses the concerns raised in its review:

  1. Reordering must not introduce exceptions (number != 0 AND intDiv(1, number) > 0, inner_type = 'Decimal' AND toInt8(...)). Here an argument is never evaluated on rows where it could throw and was not evaluated before, so the optimization is enabled by default (setting short_circuit_function_evaluation_reorder_arguments, default 1):
    • If the first argument is heavy and another one is cheap, the cheap one is executed on all rows (it was executed on all rows anyway, being not lazy), and the heavy one lazily, on a subset of its previous rows. This covers the example from [WIP]Reorder short circuit functions' arguments adaptively #55656: JSON_VALUE(s, '$.a') = '1' AND key < 100. This is not done when the heavy argument contains stateful functions or functions with observable side effects (like sleep), and in WHERE no atom is moved in front of such an atom, because it would be evaluated on fewer rows. The AND chain in WHERE, which FilterStep splits into consecutive filters, gets the same treatment: a cheap atom that cannot throw is split first; the other atoms keep their relative order.
    • Lazy arguments whose lazily executed part cannot throw (canThrow, now also exposed on IFunctionBase), is not stateful and has no observable side effects can move; the other lazy arguments act as barriers and keep all their preceding arguments in front of them.
  2. ExpressionActions::execute stays const. Per-argument statistics live in a small mutex-protected ShortCircuitArgumentStatistics object created for the action of a movable lazy argument and carried by its ColumnFunction.
  3. Statistics are collected on every block, not on a sample. For each movable argument and/or records the rows it was executed on, the rows still undecided after it, and the time, with decay. Arguments are ordered by time per decided row, i.e. cost / (1 - selectivity), which is the optimal order for independent filters (as suggested in the review of [WIP]Reorder short circuit functions' arguments adaptively #55656). An argument that has not been executed yet goes first once, to be measured.

The setting is added to the query condition cache salt, because (like short_circuit_function_evaluation) it decides whether a heavy argument may throw on rows it would skip. The new profile event ShortCircuitArgumentsReordered counts blocks on which the and/or functions evaluated their arguments in a non-written order; the reordering of the AND chain atoms by FilterStep, decided once per pipeline, is not counted.

Note: with the default short_circuit_function_evaluation = 'enable', most heavy functions still report canThrow through isSuitableForShortCircuitArgumentsExecution (i.e. "may throw"), so the adaptive order mostly applies in force_enable mode for now; it will apply more widely as functions describe canThrow precisely. The heavy-first/cheap-second case applies by default.

Local measurements (release build, numbers_mt(100000000)):

  • WHERE isValidUTF8(repeat(toString(number), 10)) AND number % 100 = 0: 0.14 s -> 0.06 s
  • WHERE NOT isValidUTF8(...) OR number % 100 != 0: 0.14 s -> 0.06 s
  • SELECT sum(isValidUTF8(...) AND number % 100 = 0): 0.14 s -> 0.06 s
  • adaptive order in force_enable mode, 3 cheap arguments: 0.09 s -> 0.07 s

Changelog category (leave one):

  • Performance Improvement

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

With short-circuit evaluation, a cheap argument of and/or is now evaluated before a heavy one, so that the heavy one (for example, JSON parsing in WHERE JSONExtractString(json, 'a') = 'x' AND id < 100) is evaluated only on the rows where the result is not decided yet. Lazily evaluated arguments that cannot throw are ordered by their measured cost and selectivity. The order never changes in a way that can introduce an exception. Controlled by the new setting short_circuit_function_evaluation_reorder_arguments, enabled by default.

🤖 Generated with Claude Code


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

Version info

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

A reimplementation of #55656 that addresses its review:
arguments are never evaluated on rows where they could throw and were not evaluated before, so the
optimization is enabled by default (setting `short_circuit_function_evaluation_reorder_arguments`).

- If the first argument of `and`/`or` is heavy while another one is cheap, the cheap one is executed on all
  rows (it was executed on all rows anyway) and the heavy one lazily, on a subset of its previous rows.
  The same for the AND chain in `WHERE`, which `FilterStep` splits into consecutive filters: a cheap atom
  that cannot throw is split first.
- Lazy arguments whose lazily executed part cannot throw, is stateless and has no side effects are ordered
  at runtime by the time per decided row (`cost / (1 - selectivity)`), measured on the previous blocks.
  Other lazy arguments keep all their preceding arguments in front of them.
- The statistics are kept in a mutex-protected `ShortCircuitArgumentStatistics` that is carried by the lazy
  argument's `ColumnFunction`, so `ExpressionActions::execute` stays const.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [382b316]

Summary: ✅


AI Review

Summary

PR #122508, reviewed at 382b316090a64e506e4535b9bcfc4ddaacae3286, evaluates cheap and/or arguments before heavy ones and adaptively orders safe lazy arguments by cost and selectivity. No unresolved findings remain. The fixes for nested logical expressions with shared arguments and mixed signed/unsigned division are present and covered by passing regression tests; both outstanding bot-authored threads were resolved. The earlier eager-predicate grouping concern describes behavior already present on master and is dropped.

Both new stateless tests passed in the current-head Fast test report. An additional 68 local checks using that job's binary passed, including 16 equivalence pairs covering nullable values, LowCardinality, guarded division, and both short-circuit modes. Three alternating measurements per setting on 50 million rows, with one thread and expression compilation disabled, preserved results and reduced median query time from 3.834 s to 0.213 s for the heavy-first WHERE predicate and from 3.958 s to 0.331 s for the corresponding SELECT expression.

Missing context / blind spots
  • ⚠️ Remaining build and test jobs for the reviewed head are still running. Their completion is needed for full CI validation; the local binary comes from Fast test.
  • ⚠️ The performance-report tool received HTTP 403 for the earlier comparison artifacts, so broad CI performance changes could not be independently reassessed. Accessible comparison artifacts or completed current-head performance jobs would close this gap; focused local measurements support the claimed optimization.
Final Verdict

Status: ✅ Approve. No new inline findings. Full CI completion remains pending.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query is flagged: clickbench Q20 is -41.4% faster (220 ms to 129 ms). CPU time fell by about the same share, so the query is doing less work, not just finishing sooner by chance. The delta is large enough that the verdict stands no matter what, and the PR fits it: it turns on short_circuit_function_evaluation_reorder_arguments by default, which runs cheap and/or arguments and WHERE AND-chain atoms before heavy ones, so the heavy predicates are evaluated on fewer rows. Q20's query text was not available to check that it has an AND chain the new logic can reorder (a single LIKE predicate would not qualify), and there is no master history for it, so the authors should confirm by comparing Q20 with short_circuit_function_evaluation_reorder_arguments = 0 and = 1.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 129 -41.4% <0.0001 cpu: CPU time roughly halved (2901 ms to 1539 ms), so less work is being done, matching a -41.4% change. The plausible cause is this PR's new default reordering of and/or arguments and WHERE AND-chain atoms.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6fa1121b-91c8-46d7-ab18-79c1cac6a0a1
  • MIRAI run: 44220343-9039-401a-ba6d-0f8377bc2d42
  • PR check IDs:
    • clickbench_68485_1791934282
    • clickbench_68506_1791934282
    • clickbench_68529_1791934282
    • tpch_adapted_1_official_68553_1791934282
    • tpch_adapted_1_official_68575_1791934282
    • tpch_adapted_1_official_68598_1791934283

alexey-milovidov and others added 5 commits October 3, 2026 11:19
…le side effects

A heavy first argument of `and`/`or` with `sleep` (or another function with observable side effects or state)
was made lazy and executed only on the rows that passed a cheap argument, and in `WHERE` a cheap atom was split
in front of such an atom. This changed how many times `sleep` was called, and broke
`04909_cancel_in_subquery_set_build_partial_result`, which relies on `sleep(1) = 0` being evaluated for every block:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122508&sha=fbe3debfe87b0f8ce8e576f4c2673b2343422997&name_0=PR&name_1=Fast%20test

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Functions/FunctionsLogical.cpp
`05218_query_plan_aggregation_having_prefilter` (added on master) expects
`HAVING throwIf(cnt = 3, 'boom') = 0 AND count() > 3` and the `intDiv` variant
to throw with `query_plan_aggregation_having_prefilter = 0`. With
`short_circuit_function_evaluation_reorder_arguments` (enabled by default in
this PR) the cheap `count() > 3` is split in front of the throwing conjunct,
so the exception is elided. Disable the reordering in these two arms, which
pin the behaviour without any optimization.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122508&sha=964394383250ab132390a12bb055fb1566d7ce50&name_0=PR&name_1=Fast%20test
PR: #122508

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 382b316090a64e506e4535b9bcfc4ddaacae3286 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

alexey-milovidov and others added 3 commits October 6, 2026 13:55
…e query setting

`FilterStep::describeActions` used to always split the AND chain as if
`short_circuit_function_evaluation_reorder_arguments = 1`, so `EXPLAIN` could
show an order that differs from the executed pipeline. Take the setting from
the query context instead.

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

- `05259_short_circuit_reorder_arguments`: with `compile_expressions = 1` (the
  default, also randomized in CI) the expression is JIT-compiled after
  `min_count_to_compile_expression` runs, which fuses the lazy arguments into
  one compiled function, so nothing is left to reorder. Disable JIT for the
  queries that check `ShortCircuitArgumentsReordered`.
- `05153_jit_decimal_integer_conversion_overflow`: the `05153_bool` shape
  `CAST(...) AND materialize(true)` has a heavy first argument, so with
  reordering the `CAST` becomes a lazy argument and is not compiled. Disable
  reordering for this shape, which pins JIT compilability.
- `04053_prewhere_statistics_decimal_overflow`: the cheap NOT-IN guard is now
  evaluated before the heavy `arraySum`, which hides the bug the arm expects.
  Disable reordering for the arm that expects `DECIMAL_OVERFLOW`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122508&sha=002720c9f551442d4e162001828b5085e525b8b7&name_0=PR
PR: #122508

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/ExpressionActions.cpp Resolved
Comment thread src/Interpreters/ExpressionActions.cpp Resolved
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
…ondeterministic functions

Functions that are not deterministic in the scope of the query (like `rand` or `blockSize`)
now block reordering of the arguments of `and`/`or` and of the AND chain in `FilterStep`,
in the same way as stateful functions and functions with observable side effects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/IFunctionAdaptors.h Resolved
Comment thread src/Functions/FunctionsLogical.cpp Resolved
…ns that do not describe `canThrow`

`IFunction::canThrow` falls back to `isSuitableForShortCircuitArgumentsExecution`, which reports cheap
functions that throw (for example `toBool` on unknown strings) as not throwing. That approximation is kept
for `ColumnReplicated`, but the reordering must not rely on it. Functions now describe the property in
`IFunction::canThrowIfKnown`, and `FunctionToFunctionBaseAdaptor::canThrow` answers `true` when it is not
described. Binary arithmetic on native numbers describes it, so that the common cheap conditions stay movable.

Also count the reorder of a heavy first argument behind a cheap one in `ShortCircuitArgumentsReordered`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or a known non-zero constant divisor

`DataTypesWithConstInfo` does not carry the value of the constant, so the base
`FunctionBinaryArithmetic::canThrowIfKnown` is now conservative for `intDiv`,
`modulo` and `positiveModulo`, and `FunctionBinaryArithmeticWithConstants`,
which holds the constant divisor, reports them as not throwing only when the
divisor is not zero (and not `NULL`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
…unt the `FilterStep` AND chain reordering

The AND chain split order in `WHERE` / `HAVING` is decided once when the pipeline is built,
not per block, so it does not fit the per-block event. Narrow the event description instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/ExpressionActions.cpp Resolved
Address review: in the `enable` mode, `and`/`or` could move a cheap eager
argument to the front past a lazy argument that contains stateful functions,
functions with observable side effects, or functions that are not
deterministic in the scope of the query. That lazy argument was then executed
on fewer rows, which can change the result, e.g.
`isValidUTF8(repeat(toString(number), 10)) AND intDiv(100, blockSize()) = 10 AND number % 2 = 1`.
Such arguments now act as barriers, like in `FilterStep`.

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

Copy link
Copy Markdown
Member Author

🕵 The Stress test (arm_release) failure (Logical error: 'Iceberg data file has 1 columns while its schema has 2 fields' in IcebergStorageSink::onFinish) is not caused by this PR. #121821 is open to fix it.

Comment thread src/Functions/FunctionsLogical.cpp Resolved
alexey-milovidov and others added 2 commits October 9, 2026 23:44
… after the final order is known

Previously, a block could be counted twice when both a cheap eager argument
was moved in front and the lazy arguments were reordered by statistics, and
not counted at all when several eager arguments were combined into
`__partial_result` ahead of a lazy argument that preceded them in the query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #125414: the oracle now writes each sub-query's output into a buffer that throws TOO_MANY_BYTES once it would exceed the existing 10 MiB cap, so the oracle skips the query instead of growing a string to tens of GiB. Locally, on master the TLP DISTINCT seed with this toFixedString(toLowCardinality(...), 1048575) column OOM-killed 3 of 3 servers; with the fix the server survived 500 seed runs at 2.6 GB peak.

`FunctionCapture` and `FunctionExpression` forwarded determinism and
statefulness of the lambda body but not `hasObservableSideEffects`, so a
predicate like `arrayExists(x -> sleepEachRow(0.001) = 0, [number])` looked
free of side effects, and the reordering of short-circuit arguments (both in
`and`/`or` and in the `FilterStep` AND chain) could evaluate `sleepEachRow`
on fewer rows than in the written order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 13, 2026 19:21
The `FilterStep` AND chain reordering moved the first atom that can be
evaluated on more rows to the front, even when the atoms it skipped were
cheap. A cheap atom that does not describe whether it can throw (like
`notEmpty`) was then overtaken by a cheap comparison, which loses the
written order (the more selective condition first) and saves nothing:
`constant_column_comparison` queries like
`notEmpty(SearchPhrase) AND SearchPhrase < '...'` became 17-30% slower.

Now a cheap atom is moved only in front of heavy atoms (those with
functions that are worth to execute lazily), like in `ExpressionActions`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122508&sha=latest&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%204%2F6)
#122508

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

Copy link
Copy Markdown
Member Author

🕵 Performance: constant_column_comparison #7/#8 (notEmpty(SearchPhrase) AND SearchPhrase < '...') were slower on every run of this PR and never on master (0 of about 590 master runs over the last 30 days). The cause was the FilterStep AND chain reordering: it moved the cheap, non-throwing comparison in front of notEmpty, which is just as cheap but more selective. It only skipped notEmpty because notEmpty does not describe canThrow. Fixed in a62a7d7: a cheap atom is now moved only in front of heavy atoms, and 05259_short_circuit_reorder_arguments checks this with EXPLAIN. The encrypt_decrypt and general_purpose_hashes slowdowns showed up only on the latest commit, on a single amd shard flagged disk-almost-full. Those queries have no and/or, so I am treating them as noise until the next run. The Stateless tests (arm_asan_ubsan, targeted) failure was a CIDB connection refusal during test selection.

Comment thread src/Columns/ColumnFunction.cpp Resolved
alexey-milovidov and others added 3 commits October 14, 2026 13:13
…nsigned divisor as not throwing if the divisor becomes negative

For a signed dividend, `DivideIntegralImpl::apply` casts the unsigned divisor to the signed type of the same
size, so e.g. `intDiv(toInt8(-128), toUInt8(255))` divides by minus one and throws `ILLEGAL_DIVISION`.
`canThrowIfKnown` described such an operation as not throwing, so the `FilterStep` AND chain reordering could
evaluate it before the guard that excluded the row. Now the constant divisor is known to be safe only if it
is non-zero and, for a signed dividend, stays positive after this cast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r` unless reordering chose another one

`ColumnFunction::reduce` skipped the pre-execution of the argument with disabled lazy execution for every
function with commutative arguments. If such an `and` was itself executed lazily (e.g. inside `if`) and a later
argument was already executed because it was shared with another output, `FunctionAnyArityLogical::executeImpl`
moved that argument to the front, so the first argument was executed on fewer rows, even with
`short_circuit_function_evaluation_reorder_arguments = 0` or for functions like `blockSize` and `sleepEachRow`.

Now `processShortCircuitFunctions` records which argument it chose to execute first, `ExpressionActions` passes
it to the `ColumnFunction` of a lazily executed function, and `reduce` pre-executes this argument, or the one
from `arguments_with_disabled_lazy_execution` if nothing was chosen, as before this change.

Also add a test for the `intDiv` of a signed dividend by an unsigned divisor that becomes negative after the cast.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit e191b1a Oct 14, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the short-circuit-reorder-arguments branch October 14, 2026 23:40
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
alexey-milovidov added a commit that referenced this pull request Oct 15, 2026
Resolve conflicts with the reordering of short-circuit `and`/`or` arguments
(#122508): `executeShortCircuit`
now both reorders the arguments by statistics and collects the execution
profile. The argument profiles record the position in the arguments passed to
`executeShortCircuit` and are mapped back to the original argument positions
afterwards, because the eager argument can now be moved to the front and the
lazy arguments can be executed in a different order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit to bacek/ClickHouse that referenced this pull request Nov 14, 2026
…n implied comparison

addComparisonFilter removes an existing filter when a new, later filter
implies it (`x != 0` removed by `x > 5`), but the surviving filter kept its
own original_index, and tryOptimizeAndCompareNotEqualsChain sorts the
rebuilt `and` by original_index. The condition the removed comparison
guarded therefore moved in front of every remaining guard. In

    x != 0 AND intDiv(10, x) > 0 AND x > 5

it became argument 0 of `and`, which short-circuit evaluation always runs on
all rows, so the query failed with `Division by zero` at default settings
(every release since 26.7; ClickHouse#122508's argument reorder hides only the cheap
shape on 26.10+, not `toUInt64(s)`-like heavy expressions).

A filter that replaces others now takes the earliest of their slots, at every
removal site: PRUNE_LEFT, STRENGTHEN_RIGHT, `=` clearing the `!=` map, the
four ordered `!=` erases and the two `!=` erases that strengthen `<=`/`>=`.
convertNotEqualsChainToNotIn already gives a merged NOT IN the minimum index
of the operands it replaces; the pruning path was the one place that did
not. Only the order of the `and` operands changes, never the operand set, so
two EXPLAIN lines of 04032_and_comparison_filter_optimization_2 move the
survivor into the removed comparison's slot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-performance Pull request with some performance improvements 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.

3 participants