Repository navigation
Reorder the arguments of short-circuit and/or when it is safe - #122508
Conversation
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]>
|
Workflow [PR], commit [382b316] Summary: ✅
AI ReviewSummaryPR #122508, reviewed at 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, Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings. Full CI completion remains pending. |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
…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]>
Build profile diff (arm_release)Commit See the job log for details. |
…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]>
…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]>
…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]>
…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]>
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]>
|
🕵 The |
… 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]>
|
The fix is in #125414: the oracle now writes each sub-query's output into a buffer that throws |
`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]>
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]>
|
🕵 Performance: |
…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]>
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]>
…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]>
Related: #55656
A reimplementation of #55656 (adaptive reordering of short-circuit
and/orarguments) that addresses the concerns raised in its review: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 (settingshort_circuit_function_evaluation_reorder_arguments, default1):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 (likesleep), and inWHEREno atom is moved in front of such an atom, because it would be evaluated on fewer rows. The AND chain inWHERE, whichFilterStepsplits into consecutive filters, gets the same treatment: a cheap atom that cannot throw is split first; the other atoms keep their relative order.canThrow, now also exposed onIFunctionBase), 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.ExpressionActions::executestays const. Per-argument statistics live in a small mutex-protectedShortCircuitArgumentStatisticsobject created for the action of a movable lazy argument and carried by itsColumnFunction.and/orrecords 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 eventShortCircuitArgumentsReorderedcounts blocks on which theand/orfunctions evaluated their arguments in a non-written order; the reordering of the AND chain atoms byFilterStep, decided once per pipeline, is not counted.Note: with the default
short_circuit_function_evaluation = 'enable', most heavy functions still reportcanThrowthroughisSuitableForShortCircuitArgumentsExecution(i.e. "may throw"), so the adaptive order mostly applies inforce_enablemode for now; it will apply more widely as functions describecanThrowprecisely. 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 sWHERE NOT isValidUTF8(...) OR number % 100 != 0: 0.14 s -> 0.06 sSELECT sum(isValidUTF8(...) AND number % 100 = 0): 0.14 s -> 0.06 sforce_enablemode, 3 cheap arguments: 0.09 s -> 0.07 sChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With short-circuit evaluation, a cheap argument of
and/oris now evaluated before a heavy one, so that the heavy one (for example, JSON parsing inWHERE 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 settingshort_circuit_function_evaluation_reorder_arguments, enabled by default.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122508]
Version info
26.10.1.2422-master(included in26.10and later)