Repository navigation
Conversation
…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.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260919-170900 |
|
Workflow [PR], commit [a5ad9a3] Summary: ✅
AI ReviewSummaryThis PR restores the always-false Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit a5ad9a3.
Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code |
| return AddComparisonFilterResult::ADDED; | ||
| } | ||
|
|
||
| if (!enable_pruning) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 threeA 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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 21 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger - a5ad9a3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260920-053046 |
0f8279a
Backport #121065 to 26.9: Keep detecting an always-false equals chain when comparison pruning is off
|
@groeneai @novikd @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Cherry pick #121065 to 26.8: Keep detecting an always-false equals chain when comparison pruning is off
… when comparison pruning is off
|
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 |
Backport #121065 to 26.8: Keep detecting an always-false equals chain when comparison pruning is off
…uals chain when comparison pruning is off
Closes: #121007
Closes: #121012
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a performance regression where a query whose
WHERErequires the same expression to equal two different constants stopped being recognized as always false whencompatibilitywas set below26.7, or whenoptimize_redundant_comparisonswas 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 ofaddComparisonFilterbehind one early return, including the detection that twoequalson the same expression carry different values. The collapse predates the setting:v26.6.1.1193-stableperforms it ungated and declares no such setting. The setting is recorded in the 26.7 block ofSettingsChangesHistory.cpp, so everycompatibilitybelow 26.7 loses a fold 25.12 genuinely had, and the reporter's always-false filter runs a fullLEFT JOINplusargMax. An explicitoptimize_redundant_comparisons = 0loses 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 = 1is still not deduplicated (pure evaluation cost, no result change), andInt32 a = 3 AND a = 3.5still does not fold, because reusing the lossless-conversion requirement is what keeps 26.6's wrong result forFloat64 a = 1 AND a = 1.0away. One reaches further: a contradictionoptimize_and_compare_chainderives now folds theANDwith 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
26.10.1.500-master(included in26.10and later)26.9.2.18,26.8.11.29