Skip to content

Keep detecting an always-false equals chain when comparison pruning is off - #121065

Merged
fm4v merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-always-false-equals-chain-without-pruning
Sep 23, 2026
Merged

fm4v merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-always-false-equals-chain-without-pruning

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121007
Closes: #121012

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

Fixed a performance regression where a query whose WHERE requires the same expression to equal two different constants stopped being recognized as always false when compatibility was set below 26.7, or when optimize_redundant_comparisons was disabled explicitly. Such a query executed its full plan, including joins and aggregations it should have skipped. Closes #121007, closes #121012.

Description

optimize_redundant_comparisons (new in 26.7, #99736) gates all of addComparisonFilter behind one early return, including the detection that two equals on the same expression carry different values. The collapse predates the setting: v26.6.1.1193-stable performs it ungated and declares no such setting. The setting is recorded in the 26.7 block of SettingsChangesHistory.cpp, so every compatibility below 26.7 loses a fold 25.12 genuinely had, and the reporter's always-false filter runs a full LEFT JOIN plus argMax. An explicit optimize_redundant_comparisons = 0 loses it too. Present in 26.7, 26.8 and the 26.9 branch. #121012 is the same lever on a second query from that workload, verified on its own reproducer.

So detect that one contradiction regardless of the setting; pruning, boundary folding and strengthening stay gated. On the reporter's reproducer (2.2M rows, debug build) 2,200,000 rows read and 244-280 ms become 0 rows and 44-76 ms; the result stays 0 rows.

@wudidapaopao, on the issue I said I would ungate contradiction detection wholesale; this is narrower, because detection and mutation are entangled in the enabled path. Three deviations, each pinned by a test. Two stay narrower than 26.6: a duplicate a = 1 AND a = 1 is still not deduplicated (pure evaluation cost, no result change), and Int32 a = 3 AND a = 3.5 still does not fold, because reusing the lossless-conversion requirement is what keeps 26.6's wrong result for Float64 a = 1 AND a = 1.0 away. One reaches further: a contradiction optimize_and_compare_chain derives now folds the AND with pruning off, which is what its appended plain conjunct is for; 26.6 never derived one. Happy to split it differently.

No performance test: the oracle here is structural (rows read, and the join's right side not executing), which a timing test could not be; I will add one on request.


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

Version info

  • Merged into: 26.10.1.500-master (included in 26.10 and later)
  • Backported to: 26.9.2.18, 26.8.11.29

groeneai and others added 2 commits September 19, 2026 13:18
…s off

`optimize_redundant_comparisons` (new in 26.7, ClickHouse#99736) gates the whole of
`addComparisonFilter` behind an early return at the top of the function: with
the setting off, every operand is parked in `opaque_filters` unanalysed, so the
function never returns ALWAYS_FALSE, `found_conflict` is never set, and the AND
is never collapsed to a constant false.

Detecting that two `equals` on the same expression carry different values is
older than that setting. `v26.6.1.1193-stable` calls
`tryOptimizeAndEqualsNotEqualsChain` with no setting gate at all, and declares
no `optimize_redundant_comparisons` (grep -c = 0); ClickHouse#99736 deleted that function
and folded its contradiction check into the new, gated analysis. Since the
setting is recorded in the 26.7 block of SettingsChangesHistory.cpp, every
`compatibility` below 26.7 now removes a fold that 25.12 genuinely performed,
and a query whose WHERE is always false executes its full plan. On the reported
reproducer that is a LEFT JOIN onto an `argMax ... GROUP BY` subquery over 2.2M
rows: 2,200,000 rows read where 0 are needed, 51 ms -> 3641 ms on the
customer's data.

So detect that one contradiction regardless of the setting, and leave pruning,
boundary folding and strengthening (all genuinely introduced with it) gated.
Neutralizing the history entry instead would be wrong: v26.7.1.1315-stable both
ships the setting and records it in its own newest block, so the placement is
correct, and that route also leaves an explicit `optimize_redundant_comparisons
= 0` regressed.

Why comparing against a single stored representative is equivalent to a full
pairwise scan, which is what keeps the disabled path linear in the operands of
the AND: the only question asked is whether two `equals` on this expression
carry different values, every `equals` is compared against the representative,
and `found_conflict` is only ever set, never cleared. The representative is
recorded as a position rather than a pointer or iterator because
`opaque_filters.push_back` reallocates; in disabled mode that vector only ever
grows, since no erase path reaches it.

The new block sits below every existing keep-opaque guard (nullable result,
non-lossless conversion, NaN constant), so the disabled path is a strict subset
of the enabled one and inherits any guard added above it, and it reaches the
collapse through the single existing `found_conflict` site, so that site's
non-convertible-operand veto still keeps a TYPE_MISMATCH the unoptimized query
would raise from being suppressed. For EQUALS vs EQUALS
`compareComparisonFilters` returns only PRUNE_RIGHT or ALWAYS_FALSE, never a
STRENGTHEN_*, so nothing is mutated on this path.

Three narrowings are deliberate. A duplicate `a = 1 AND a = 1` is still not
deduplicated with pruning off, although 26.6 dropped it: that is pure
evaluation cost with no result change. A non-convertible constant (`Int32 a = 3
AND a = 3.5`) still does not fold, because reusing the enabled path's
lossless-conversion requirement is what keeps 26.6's wrong result for `Float64 a
= 1 AND a = 1.0` away. And a contradiction `optimize_and_compare_chain` derives
now folds the AND with pruning off, which is what its appended plain conjunct is
for; 26.6 never derived one.

Twelve reference lines change across the three 04032* files, every one an
`optimize_redundant_comparisons = 0` case holding two `equals` on the same
expression with different, losslessly convertible values.

Closes: ClickHouse#121007
Closes: ClickHouse#121012

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the block comment restating the setting split, cut the new field doc and the addComparisonFilter, method and header doc clauses to one line each.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@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; 2 findings;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ The ungated fold suppresses NO_COMMON_TYPE for a non-constant String expression compared with numeric constants, so s = 1 AND s = 2 returns 0 rows where s = 1 alone raises the error (LogicalExpressionOptimizerPass.cpp:936-950) DISAGREE Real, but it predates this PR and is not specific to the setting being off. The new branch reaches ALWAYS_FALSE only when both operands carry a lossless converted_value (:928 parks the rest), and with that set step 2 is a no-op for equals (:611-613, :654-659), so both modes reach the identical compareComparisonFilters verdict (:943 vs :958) and collapse at the one found_conflict site (:2013): a strict subset of what the default already folds, and the setting has defaulted to true since 26.7. 26.6 folded it too, via type-sensitive ConstantNode::isEqual. Requiring executability in the disabled path alone would reintroduce the setting-dependent result :2005-2012 forbids. @ wudidapaopao, if you want it required in both modes, that is a change to the enabled path and I will send it separately
2 ⚠️ The compatibility = '25.12' case only asserts the folded plan, which both setting values produce, so it does not prove the disabled-setting behaviour (05230_always_false_equals_chain_without_pruning.sql:20) DISAGREE First half is right; that behaviour is pinned by five sibling statements that set the value explicitly (lines 12, 16, 26, 35-37, 41, 46-49). Both suggested pins carry a liability: asserting the effective setting pins SettingsChangesHistory.cpp:288, which this PR deliberately leaves alone; asserting that duplicate equalities stay unpruned pins a narrowing the description offers to withdraw. A range contradiction under compatibility = '25.12' has neither, and I will add it if you want the carrier pinned
3 💡 The sentence added to src/Core/Settings.cpp says the contradiction is detected "independently of this setting" without the lossless-conversion condition, so it reads as if Int32 a = 3 AND a = 3.5 would fold with the setting off AGREE, noted Not blocking; the description states that narrowing explicitly. On request it becomes "A contradiction between two equals on the same expression with losslessly convertible constants (for example, a = 1 AND a = 2) is detected independently of this setting."

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260919-170900

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a5ad9a3]

Summary: ✅


AI Review

Summary

This PR restores the always-false equals-chain fold when optimize_redundant_comparisons is disabled or older compatibility settings map it to false, so contradictory filters can skip needless work again. That direction is reasonable, but the current implementation also lets the disabled-pruning path erase other conjuncts that are still supposed to execute, so it can turn a query that should raise into one that silently returns zero rows.

Findings

❌ Blockers

  • src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:932 The new disabled-pruning branch can mark i = c1 AND i = c2 as contradictory and let the later collapse replace the whole AND with 0 even when another comparison in the same chain still has to execute. A concrete case is WHERE (i = 1) AND (i = 2) AND (throwIf(i = 0) = 0) with optimize_redundant_comparisons = 0: throwIf is deterministic, its constant side converts cleanly, and the collapse no longer sees any !converted_value veto, so the query stops raising FUNCTION_THROW_IF_VALUE_IS_NON_ZERO. That violates the eager-exception contract already covered in tests/queries/0_stateless/03562_short_circuit_for_and_or.sql. The fold needs an additional guard for throw-capable / side-effectful conjuncts, not just the current non-convertible-constant check.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit a5ad9a3.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@fm4v fm4v assigned fm4v and unassigned fm4v 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
@fm4v
fm4v requested a review from novikd September 19, 2026 18:23
return AddComparisonFilterResult::ADDED;
}

if (!enable_pruning)

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 still needs a "safe to skip" check before the whole AND is collapsed to 0.

With optimize_redundant_comparisons = 0, this branch can now return ALWAYS_FALSE for i = 1 AND i = 2, and the later guard only vetoes the fold when some other comparison failed constant conversion. That misses deterministic-but-throwing / side-effectful conjuncts on other expressions. For example:

SELECT count()
FROM values('i Int32', (0))
WHERE (i = 1) AND (i = 2) AND (throwIf(i = 0) = 0)
SETTINGS enable_analyzer = 1, optimize_redundant_comparisons = 0, optimize_and_compare_chain = 0;

throwIf is an ordinary deterministic function, so it reaches opaque_filters with a converted constant and does not trip the !filter.converted_value veto at the collapse site. The query is therefore rewritten to 0 and stops raising FUNCTION_THROW_IF_VALUE_IS_NON_ZERO, even though eager exception behavior is still part of the contract (tests/queries/0_stateless/03562_short_circuit_for_and_or.sql covers the same principle for AND 0).

I think the ungated fold needs to reject any remaining conjunct whose subtree can throw or has observable side effects, not just non-convertible comparisons.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I measured this instead of reasoning about it, and the example does not distinguish a folded plan from an unfolded one. Every arm below is clickhouse local, fixture values('i Int32', (0)), enable_analyzer = 1, optimize_and_compare_chain = 0; orc is optimize_redundant_comparisons.

1. The query in the comment returns 0 on every tree, including trees that do not fold. master without this PR (015bf1203d344), this PR, 26.6.5.73, 26.7.6.57 and 26.8.2.7, at orc = 0 and orc = 1: 0 in all of them, and also with short_circuit_function_evaluation set to enable, disable or force_enable. The cause is operand order, not the fold. With the contradiction removed, so that this pass has nothing to fold on either binary:

SELECT count() FROM values('i Int32', (0)) WHERE (i = 1) AND (throwIf(i = 0) = 0);  -- 0, all three sc modes
SELECT count() FROM values('i Int32', (0)) WHERE (throwIf(i = 0) = 0) AND (i = 1);  -- Code: 395, all three

A false leading conjunct means the trailing throwIf never executes, whatever the setting does.

2. With the throwing conjunct leftmost, where it does execute, the suppression is the shipped default, and 26.6's behaviour. WHERE (throwIf(i = 0) = 0) AND (i = 1) AND (i = 2):

tree orc = 0 orc = 1 (default since 26.7)
26.6.5.73 (setting does not exist, fold unconditional) 0 n/a
26.7.6.57, 26.8.2.7, master Code: 395 0
this PR 0 0

The intDiv(1, i) = 0 variant gives the identical table with Code: 153 in place of 395, and so does the AND in SELECT position. So the exception is already absent at the default of 26.7, 26.8 and master, and was absent in 26.6, where the fold was unconditional. What this PR changes is that orc = 0 stops disagreeing with them. Keeping the conjunct in the disabled path only would restore exactly the setting-dependent result difference that the comment at the collapse site forbids and that this PR exists to remove. Requiring it of both paths changes the default of three releases and reverts 26.6: worth discussing separately, but it is not this change.

3. 03562_short_circuit_for_and_or.sql does not cover this shape. Its AND 0 case is SELECT (SELECT throwIf(1)) AND 0, under that file's own header Test live prefix arguments are not skipped: a scalar subquery, executed during analysis. It still raises on this PR's binary at both setting values. The file never sets optimize_redundant_comparisons, and the runner does not randomise it, so it always runs where this branch is not taken. The per-row analogue behaves the other way here: WHERE (throwIf(i = 0) = 0) AND 0 and WHERE 0 AND (throwIf(i = 0) = 0) both return 0 rows without raising, and ConstantNode(0u) is the shape the fold produces.

Controls, so none of the arms above is vacuous: with the contradiction removed and throwIf reachable, Code: 395 is raised in both operand orders.

I am not changing the code for this finding.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a5ad9a3fe with master e4dac56eb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d719d425b; 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

8 translation units recompiled, 21 s compile time in total, 8 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a5ad9a3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 6/6) / optimize_time_filter_with_preimage #2 measurement verdict, not a regression of this diff: job info 3 too long, 2 unstable; 1 confirmed regression(s) on the performance dashboard, client_time 0.0722 to 0.0840 s (+16.3%). The dashboard-verdict gate added by #120927 reds a master_head shard on a confirmed_regression; that query is called slower on 226 distinct pull requests and on 47 distinct true-master heads (96 master rows) in the last 7 days, so the verdict tracks the benchmark rather than this branch #121090 (mine, open)
Mergeable Check, PR praktika rollups of the row above (Failed: Performance Comparison (arm_release, master_head, 6/6)) #121090 (mine, open)

Session id: cron:our-pr-ci-monitor:20260920-053046

@fm4v
fm4v added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 0f8279a Sep 23, 2026
519 of 695 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #121065 to 26.9: Keep detecting an always-false equals chain when comparison pruning is off
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @novikd @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
Cherry pick #121065 to 26.8: Keep detecting an always-false equals chain when comparison pruning is off
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Answered in full on the issue: #121770 (comment)

The wrong fold is real, but it does not come from this PR. It reproduces with no SETTINGS clause at all on 26.7.6.57, 26.8.2.7 and on pre-merge master 95a6488, where EXPLAIN QUERY TREE already shows the AND folded to UInt64_0. #117293 guards it at all three call sites, including the branch this PR added. The arms this PR contributes are non-default setting combinations of a fold that is already wrong at stock settings, so I read it as not affecting the backport, and I am not opening a competing fix.

fm4v added a commit that referenced this pull request Sep 23, 2026
Backport #121065 to 26.8: Keep detecting an always-false equals chain when comparison pruning is off
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…uals chain when comparison pruning is off
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

7 participants