Skip to content

Analyzer: keep operand order when an OR chain of equalities is rewritten to IN - #121047

Open
qoega wants to merge 4 commits into
ClickHouse:masterfrom
qoega:json-fuzz-or-chain-to-in-order
Open

qoega wants to merge 4 commits into
ClickHouse:masterfrom
qoega:json-fuzz-or-chain-to-in-order

Conversation

@qoega

@qoega qoega commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Analyzer: preserve operand order when rewriting an OR chain of equalities into IN, so short-circuit evaluation of neighboring operands is not broken.

Documentation entry for user-facing changes

No documentation change needed.

Detailed description / Documentation

LogicalExpressionOptimizerPass::tryReplaceOrEqualsChainWithIn collected equality chains on the same expression, and, when the chain reached the threshold, appended the resulting IN node after all remaining operands of the OR. Bail-outs also appended the untouched equalities back at the end. OR is evaluated left to right with short-circuit semantics, so a query like

SELECT * FROM t WHERE x = 0 OR intDiv(1, x) != 0 OR x = 2 OR x = 3;

was rewritten as intDiv(1, x) != 0 OR x IN (0, 2, 3) and started failing with Division by zero, while the two-equality version worked. The rewrite must not change the relative order of an operand that was previously guarded by an earlier operand.

Fix: the IN now takes the slot of the first equality it replaces, bail-outs keep their equalities in their own slots, and the empty slots left behind are dropped. A regression test is added and one existing reference is updated to match the preserved ordering.

Closes: #121024

cc @groeneai — fuzz-lab find (JSON AST fuzzer)

🤖 Generated with Claude Code


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

…written to IN

`LogicalExpressionOptimizerPass::tryReplaceOrEqualsChainWithIn` appended the new
`IN` (and, on every bail-out, the untouched equalities) after all other operands
of the `or`. `or` is evaluated lazily from left to right, so
`x = 0 OR intDiv(1, x) != 0 OR x = 2 OR x = 3` became
`intDiv(1, x) != 0 OR x IN (0, 2, 3)` and failed with `Division by zero` under the
default settings, while the same query with two equalities worked.

The `IN` now takes the slot of the first equality of its chain, bail-outs keep the
equalities in their own slots, and the empty slots are dropped.

Found by `json_ast_sql_execution_fuzzer` (differential oracle).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [94a69d9]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05237_or_chain_to_in_keeps_operand_order FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 19, 2026
@qoega

qoega commented Sep 21, 2026

Copy link
Copy Markdown
Member Author

Relaying a measurement from the fuzzer author on the "later equality behind a throwing operand" concern.

The OR short-circuit is not strictly positional — cheap arguments (the equalities) are evaluated eagerly, and a lazily-evaluated argument (intDiv) only on rows where none of the cheap ones is true, wherever it stands in the chain. Measured on the branch with the rewrite disabled (optimize_min_equality_disjunction_chain_length = 100), i.e. the engine's own behaviour before any rewrite:

SELECT (number = 0) OR (intDiv(1, number - 2) != 0) OR (number = 2) OR (number = 3) FROM numbers(4)   ->  1 1 1 1
SELECT (number = 0) OR (intDiv(1, number - 2) != 0) OR (number = 5) FROM numbers(4)                    ->  Division by zero
SELECT ... SETTINGS short_circuit_function_evaluation = 'disable'                                       ->  Division by zero

So a later number = 2 already protects intDiv(1, number - 2) for row 2 today, and merging it into the leading IN changes nothing observable. What broke in the original finding (#121024) was different: the IN was appended after the division, making the division the first (always fully evaluated) argument. Placing the IN at the first equality's slot fixes exactly that.

The "contiguous runs only" variant was tried and reverted — it only weakens the optimization (x IN tuple(0) OR ... OR x IN (2, 3)) without a semantics benefit. 05237 in the follow-up commit documents both shapes (the reviewer's non-throwing one, plus ... OR (number = 5) which does throw and does need the guard).

The follow-up commit adding those test cases is on the branch (00c47c09201) and will land on this PR once the fork push clears (currently blocked on the fuzzer host waiting for a live SSH agent).

qoega and others added 2 commits September 21, 2026 23:02
The short-circuit `or` evaluates its cheap arguments eagerly and a lazily
evaluated argument only on the rows where they are all false, so a later
equality already protects a throwing operand; the case that broke was the
`IN` appended behind the division, which made the division the first (always
evaluated) argument. Document both shapes in the test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
QueryTreeNodes or_operands;
const auto & arguments = function_node.getArguments().getNodes();

/// The operands keep their original positions: `or` is evaluated lazily from left to right

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only fixes the query-tree pass. The same OR-to-IN rewrite is still live in src/Interpreters/LogicalExpressionsOptimizer.cpp:274-364, where addInExpression still appends the merged IN after the existing operands.

That path is still reachable in supported code: ProjectionDescription::calculateByQuery and getAggregatingProjectionInfo both build an InterpreterSelectQuery over projection ASTs, and ignoreASTOptimizations() does not skip LogicalExpressionsOptimizer because TreeRewriter::analyzeSelect runs it before the ignore_ast_optimizations gate (src/Interpreters/TreeRewriter.cpp:1461-1463, 1535-1544). So a projection definition containing x = 0 OR intDiv(1, x) != 0 OR x = 2 OR x = 3 still gets reordered during projection build or projection matching and can still change short-circuit behavior or surface ILLEGAL_DIVISION.

Please either mirror the slot-preserving fix in the AST optimizer or stop applying this rewrite on those legacy entrypoints, and add a projection-based regression so the invariant is closed end-to-end.

-- A guard written after the division does not protect it, with or without the rewrite.
SELECT (intDiv(1, number) != 0) OR (number = 0) OR (number = 2) OR (number = 3) FROM numbers(4); -- { serverError ILLEGAL_DIVISION }

-- A later equality behind a throwing operand: the short-circuit `or` evaluates its cheap arguments (the equalities)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new test still never exercises the rebuild path where one equality chain in an or is declined while another chain in the same node is merged. That is the path keep_equals_functions is fixing, and it is also the second reproducer from issue #121024.

02702_logical_optimizer_with_nulls covers a NULL arm on the same chain, but it does not pin the multi-chain case that used to append the declined equalities behind the throwing operand. A regression there would keep 05237 green. Please add the mixed lossy/non-lossless example from the issue discussion (for example number = 0 OR intDiv(1, number) != 0 OR number = -1 OR number = -2 OR (number + 10) = 11 OR ...) or an equivalent two-chain case.

… is rewritten to IN

Mirrors the analyzer fix in `LogicalExpressionOptimizerPass::tryReplaceOrEqualsChainWithIn`.
`LogicalExpressionsOptimizer::addInExpression` appended the new `IN` after every other OR
operand, so `x = 0 OR intDiv(1, x) != 0 OR x = 2 OR x = 3` became
`intDiv(1, x) != 0 OR x IN (0, 2, 3)` and failed with `Division by zero` under the default
settings. `TreeRewriter::analyzeSelect` runs `LogicalExpressionsOptimizer` BEFORE the
`ignore_ast_optimizations` gate, so the bug is reachable from projection materialization
(`ProjectionDescription::calculateByQuery`) even though the projection path passes
`.ignoreASTOptimizations()`.

The IN now takes the slot of the first equality of its chain. The other equalities keep
their own slots and are erased by `cleanupOrExpressions`, preserving the relative order of
all remaining operands (declined chains, non-equality operands, and the inserted `IN`s of
other chains).

The regression test for the analyzer side (`05237_or_chain_to_in_keeps_operand_order`)
now also covers the declined-chain rebuild path (second repro from issue ClickHouse#121024), the
legacy AST path with `enable_analyzer = 0`, and a projection whose WHERE forces the rewrite
during `calculateByQuery`.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@qoega

qoega commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Review follow-up landed as 94a69d98a49. Addresses the AI-reviewer BLOCKER + MAJOR.

BLOCKER (legacy AST path) — fixed. src/Interpreters/LogicalExpressionsOptimizer.cpp addInExpression now mirrors the analyzer-side slot-preserving pattern. Instead of operands.push_back(in_function), it scans the OR function's operands for the leftmost pointer that appears in equality_functions (which is already sorted by address for cleanupOrExpressions's binary_search) and inserts the IN at that slot. Non-matching operands and the other chains' INs keep their original relative order; cleanupOrExpressions then removes the other equalities as before. Reachable in production via TreeRewriter::analyzeSelect → LogicalExpressionsOptimizer, called from ProjectionDescription::calculateByQuery / getAggregatingProjectionInfo before the ignore_ast_optimizations gate, so projections were still rewriting without the slot-preserving behaviour.

MAJOR (test coverage) — fixed. tests/queries/0_stateless/05237_or_chain_to_in_keeps_operand_order.{sql,reference} gains three blocks on top of the existing analyzer cases:

  1. Declined-chain rebuild under the analyzer (second repro from Analyzer's tryReplaceOrEqualsChainWithIn moves the IN behind other operands — defeats short-circuit guards under default settings (x = 0 OR intDiv(1, x) != 0 OR x = 2 OR x = 3 → Division by zero) #121024): one OR has a merged number chain and a declined toString(number) chain under optimize_min_equality_disjunction_chain_length = 3; one SELECT + an EXPLAIN QUERY TREE dump_ast to pin the slot.
  2. Legacy AST-path SELECTs with enable_analyzer = 0 — three mirrors of the analyzer SELECTs plus the declined-chain one. These throw ILLEGAL_DIVISION on the pre-fix binary; passing proves the AST slot-preserving fix is in.
  3. Projection path: PROJECTION p (SELECT k, v WHERE (k = 0) OR (intDiv(1, k) != 0) OR (k = 2) OR (k = 3)) + an INSERT with enable_analyzer = 0, optimize_min_equality_disjunction_chain_length = 2. Without the fix the projection materialization throws Division by zero on row k = 0 because the IN would be appended after the intDiv instead of absorbing its slot.

Added -- Tags: no-parallel-replicas, consistent with 03203_optimize_disjunctions_chain_to_in.sql.

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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). fuzz Problem found by one of the fuzzers pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants