Skip to content

Fix LOGICAL_ERROR Invalid binary search result in MergeTreeSetIndex for divide(0, x) - #103621

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-divide-zero-by-variable-monotonicity
Apr 29, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-divide-zero-by-variable-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Apr 28, 2026 •

Copy link
Copy Markdown
Collaborator

The AST fuzzer was repeatedly tripping a LOGICAL_ERROR: Invalid binary search result in MergeTreeSetIndex in debug builds when an IN / NOT IN expression on the primary key wrapped the key column in a divide (or intDiv) call with a constant zero numerator.

FunctionBinaryArithmetic::getMonotonicityForRange claimed that divide(0, x) was monotonic for any input range:

if (accurateEquals(constant, Field(0)))
    return {true, true, false, false}; // 0 / 0 is undefined, thus it's not always monotonic

The comment said the function is "not always monotonic" but the code returned is_monotonic = true. 0 / x is 0 for any x != 0 but undefined at x = 0 (NaN/Inf for divide, division-by-zero exception for intDiv), so the function is genuinely non-monotonic on any range that includes 0.

KeyCondition::applyMonotonicFunctionsChainToRange trusted the false claim and produced a Range with left > right, which violated the binary-search invariant begin <= end in MergeTreeSetIndex::checkInRange. Debug builds aborted with a LOGICAL_ERROR at src/Interpreters/Set.cpp:809. Release builds silently fall back to the {true, true} BoolMask via the #else branch of #ifndef NDEBUG at src/Interpreters/Set.cpp:810-812, producing correct query results with the same (no-op) pruning effectiveness as the post-fix code. So the user-visible behavior in stable release is unchanged — this is an internal correctness improvement, not a release-visible regression fix.

The fix applies the same range-checking pattern that the c != 0 branch uses two lines below: only claim monotonicity when the input range is strictly above or strictly below 0; otherwise return non-monotonic. This also covers intDiv(0, x), which shares the code path.

Sample fuzzer-generated queries from CIDB (STID 3252 family — 13 distinct PRs over 120 days, 0 master hits):

Local repro on commit c474a1f36f5 (debug build):

CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT number FROM numbers(10);
SELECT count() FROM t WHERE divide(0, a) NOT IN (1.0, 2.0);
-- Logical error: 'Invalid binary search result in MergeTreeSetIndex'

After the fix the same query returns 10 and the new regression test 04141_divide_by_zero_constant_monotonicity passes 50/50 iterations with randomized client settings. Existing tests 03835_todate_monotonicity_boundary, 04073_divide_intdivide_monotonicity_key_condition, 03399_divide_zero_or_null, 03532_divideOrNull_jit_crash, and 03314_divide_decimal_short_circuit continue to pass unchanged.

Note on Bugfix validation (functional tests)

The original LOGICAL_ERROR is gated by #ifndef NDEBUG in src/Interpreters/Set.cpp:806-812 and only fires in debug / sanitizer builds. Stable release builds take the #else branch and produce correct results, so the bug cannot be reproduced by the bugfix-validation framework which runs the modified test against a release master binary. The categorization here is Improvement rather than the user-visible category to reflect that release users see no behavior change; the value of this change is internal correctness (no false monotonicity claim, no Range with left > right, no debug-build LOGICAL_ERROR from the AST fuzzer).

Related: #90461

Sample CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103620&sha=c474a1f36f5287959d4c1a484a2b0999e2ef1c11&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Changelog category (leave one):

  • Improvement

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

Improved correctness of monotonicity inference for divide(0, x) and intDiv(0, x): previously the functions were unconditionally reported as monotonic, but 0 / x is non-monotonic on any range that includes 0 because 0 / 0 is undefined (NaN/Inf for divide, division-by-zero exception for intDiv). The false claim caused KeyCondition::applyMonotonicFunctionsChainToRange to produce ranges with left > right, which tripped a LOGICAL_ERROR Invalid binary search result in MergeTreeSetIndex in debug builds when an IN / NOT IN expression on the primary key wrapped the key in divide(0, key) or intDiv(0, key). Release builds were unaffected — the assertion is gated by #ifndef NDEBUG.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No documentation needed — internal correctness improvement with no user-facing behavior change in release builds.

Version info

  • Merged into: 26.5.1.175

`FunctionBinaryArithmetic::getMonotonicityForRange` for `divide` and `intDiv`
unconditionally reported `0 / x` as monotonic (`is_monotonic = true`) regardless
of the value range. But `0 / x` evaluates to 0 for any `x` != 0 and is undefined
(NaN/Inf) at `x` = 0, so the function is non-monotonic on any range that includes
0.

`KeyCondition::applyMonotonicFunctionsChainToRange` then trusted the false claim
and produced a Range with `left > right`, which violated the binary-search
invariant `begin <= end` in `MergeTreeSetIndex::checkInRange` and tripped a
`LOGICAL_ERROR: Invalid binary search result in MergeTreeSetIndex` in debug
builds (in release builds the index analysis silently fell back to the
`{true, true}` BoolMask, missing potential pruning).

Apply the same range-checking pattern that the `c != 0` branch uses: only claim
monotonicity when the input range is strictly above or strictly below 0;
otherwise return non-monotonic. This also covers `intDiv(0, x)` since the same
code path serves both functions.

Adds regression test
`04141_divide_by_zero_constant_monotonicity` covering the scalar form, the
tuple form (matching the original AST fuzzer query), and a sanity check that
the legitimate `divide(c, x)` cases remain unaffected.

CI reports for STID 3252 family hits:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103620&sha=c474a1f36f5287959d4c1a484a2b0999e2ef1c11&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
ClickHouse#90461
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a) Deterministic repro? Yes. On commit c474a1f36f5 (debug build):

CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT number FROM numbers(10);
SELECT count() FROM t WHERE divide(0, a) NOT IN (1.0, 2.0);
-- Logical error: 'Invalid binary search result in MergeTreeSetIndex'.

triggers the LOGICAL_ERROR every run. Same for the original AST fuzzer query (divide(divide(isNull(-2), assumeNotNull(7)), a), b) NOT IN (...) after the inner divide(0, 7) is folded to 0.

b) Root cause explained? FunctionBinaryArithmetic::getMonotonicityForRange returned {is_monotonic = true, ...} for divide(0, x) regardless of the value range. 0 / x evaluates to 0 for any x != 0 but is undefined (NaN/Inf) at x = 0, so the function is non-monotonic on any range that crosses 0. KeyCondition::applyMonotonicFunctionsChainToRange consumed the false claim and produced a Range with left > right, which violated the begin <= end invariant in MergeTreeSetIndex::checkInRange::std::partition_point and tripped the LOGICAL_ERROR.

c) Fix matches root cause? Yes — the fix corrects the monotonicity claim itself (the root cause), not the downstream symptom in MergeTreeSetIndex. It applies the same range-checking pattern that the c != 0 branch uses two lines below: only claim monotonicity when the range strictly excludes 0.

d) Test intent preserved? / New tests added? New file 04141_divide_by_zero_constant_monotonicity.sql with five cases: (1) scalar divide(0, a) NOT IN, (2) tuple form, (3) the original AST fuzzer query in folded form, (4) sanity check for divide(1, a) with a range crossing 0 (still non-monotonic, still works), (5) sanity check for divide(2, a) with a range strictly above 0 (legitimately monotonic, must still work). No existing tests modified.

e) Demonstrated in both directions? Yes. On unfixed binary: all three "0 / a" queries throw LOGICAL_ERROR. On fixed binary: 50/50 iterations of 04141 pass, the original AST fuzzer query returns the expected result, and 03835_todate_monotonicity_boundary, 04073_divide_intdivide_monotonicity_key_condition, 03399_divide_zero_or_null, 03532_divideOrNull_jit_crash, 03314_divide_decimal_short_circuit continue to pass unchanged.

f) Fix is general, not a narrow patch? Same code path serves both divide and intDiv (line if (name_view == "divide" || name_view == "intDiv")), so both are fixed by the same change. The mirror branch variable / constant already handles c = 0 correctly (returns non-monotonic). The single-point case (accurateEquals(left_point, right_point)) already handles divide(0, 0) correctly. multiply(0, x) does not have the same boundary problem (0 * x = 0 is genuinely constant for all x). I did not attempt to fix unrelated STID 3252 variants triggered by toDate, toDateTime32, or direct Date IN (out_of_range_value) cases — those are separate code paths and need their own fixes.

session: cron:clickhouse-ci-task-worker:20260428-004500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @alexey-milovidov — could you review this? It fixes the chronic AST fuzzer LOGICAL_ERROR Invalid binary search result in MergeTreeSetIndex (STID 3252 family — 13 PRs / 120 days, 0 master hits) by correcting FunctionBinaryArithmetic::getMonotonicityForRange for divide(0, x) and intDiv(0, x): those functions are non-monotonic across ranges that include 0 (because 0 / 0 is undefined), so the unconditional is_monotonic = true was wrong. Apply the same range check the c != 0 branch already uses. Same family that #98276 closed via the toDate boundary fix; that PR did not cover the divide path.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf5f0a8]

Summary: ✅


AI Review

Summary

This PR fixes monotonicity inference for divide(0, x)/intDiv(0, x) when ranges include 0, preventing invalid range construction that triggered a debug-only LOGICAL_ERROR in MergeTreeSetIndex path analysis. The implementation and regression coverage look consistent with the issue scope, and I did not find additional blocker/major problems.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 28, 2026
The previous comment claimed `0/0` is undefined as `NaN`/`Inf`, which is
only accurate for `divide`. For `intDiv`, `0/0` raises a division-by-zero
exception rather than producing `NaN`/`Inf`. Reword to clarify both
behaviors so future maintainers don't get confused.

No functional change.
…ERROR

The LOGICAL_ERROR `Invalid binary search result in MergeTreeSetIndex` is gated
by `#ifndef NDEBUG` in `src/Interpreters/Set.cpp:806-812` (the `#else` branch
returns `{true, true}`). In release builds the chain produces correct results
via the BoolMask fallback, so the user-visible behavior is unchanged.

The Bugfix validation framework runs the modified test against a release master
binary and therefore cannot reproduce the original `LOGICAL_ERROR`. Adding a
test comment so future maintainers don't waste time trying to make the test
trip the assertion in release.

No code change, comment only.
The previous workflow run captured the PR body at trigger time, before
the changelog category was updated from 'Bug Fix' to 'Improvement'. This
empty commit retriggers the workflow so `filter_job.py` sees the new
body and correctly skips the `Bugfix validation (functional tests)` job
(the bug is gated by `#ifndef NDEBUG` and cannot be reproduced in the
release master binary used by bugfix validation).
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Apr 28, 2026
Bot review: the fix in `FunctionBinaryArithmetic::getMonotonicityForRange`
is in the shared `divide`/`intDiv` branch, but the regression test only
exercised `divide`. Add parallel `intDiv(0, a)` cases to lock in behavior
for the sister function and prevent asymmetric regressions.

`intDiv` has different runtime semantics — `intDiv(0, 0)` raises
`ILLEGAL_DIVISION` rather than returning `NaN`/`Inf` — but the index-analysis
path is the same. Pre-fix the range-includes-zero `intDiv(0, a)` queries
tripped `Invalid binary search result in MergeTreeSetIndex` at
index-analysis time on debug builds; post-fix the analysis safely reports
non-monotonic and the runtime evaluation of `intDiv(0, 0)` on the `a = 0`
row legitimately throws `ILLEGAL_DIVISION`.

Two cases added on the existing `[0, 9]` table (scalar and tuple form,
both `-- { serverError ILLEGAL_DIVISION }`) plus one positive-range
sanity test on the `[1, 10]` table to cover the legitimate monotonic
branch.

Verified locally: 50/50 passes with randomized client/MergeTree settings.

Addresses inline review on ClickHouse#103621
@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (8/8) · Uncovered code

Full report · Diff report

@shankar-iyer shankar-iyer self-assigned this Apr 29, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Apr 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 29, 2026
Merged via the queue into ClickHouse:master with commit 0adfc08 Apr 29, 2026
165 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 Apr 29, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 16, 2026
…ndex

FunctionBinaryArithmetic::getMonotonicityForRange claimed intDiv(variable,
constant) is always monotonic. That is wrong when the dividend is unsigned and
the intDiv result type is signed: intDiv casts the dividend to a signed type
when the divisor is signed (DivideIntegralImpl), and ResultOfIntegerDivision
makes the result signed with the dividend width. So an unsigned value
>= 2^(width-1) reinterprets as negative. For example intDiv(UInt64, Int64-const)
has an Int64 result, and intDiv(2^63, c) flips sign relative to
intDiv(2^63 - 1, c). intDiv(unsigned, signed-const) is therefore a step function
with a single discontinuity at D = 2^(width-1): monotonic on each side of D but
not across it.

When such a chain feeds an IN/NOT IN key condition,
applyMonotonicFunctionsChainToRange builds a Range with left > right, and
MergeTreeSetIndex::checkInRange hits the std::partition_point invariant
begin <= end. In debug builds this aborts with the LOGICAL_ERROR
'Invalid binary search result in MergeTreeSetIndex'; in release builds
checkInRange falls back to {true, true} (no pruning).

Found by the AST fuzzer on master (STID 3252-3a4a): a UInt64 key divided by a
large negative Int128 constant. This is the variable/constant counterpart of
the const/variable case fixed in ClickHouse#103621.

The fix detects whether the range [left_point, right_point] crosses the
discontinuity D analytically (intDivRangeCrossesSignedWrap), treating a null
endpoint as the unsigned-domain limit. A crossing range is reported as
non-monotonic (no pruning); a range on one side of D stays monotonic on that
range but is not always-monotonic. This is applied in both the finite-range
branch and the unbounded (null, null) branch that ReadInOrderOptimizer and
KeyCondition use to probe is_always_monotonic.

An earlier version of this fix compared only the transformed endpoints, which
is insufficient: intDiv is a step function whose endpoints can map to equal
values while the interior changes direction (e.g. UInt8 / 100 over [0, 255]),
so endpoint comparison can still report spurious monotonicity and over-prune
interior rows. The analytical crossing check replaces it.

divide (floating-point) and intDiv with an unsigned result never wrap and stay
always-monotonic as before.

Related: ClickHouse#90461

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 16, 2026
…ndex

FunctionBinaryArithmetic::getMonotonicityForRange claimed intDiv(variable,
constant) is always monotonic. That is wrong when the dividend is unsigned and
the intDiv result type is signed: intDiv casts the dividend to a signed type
when the divisor is signed (DivideIntegralImpl), and ResultOfIntegerDivision
makes the result signed with the dividend width. So an unsigned value
>= 2^(width-1) reinterprets as negative. For example intDiv(UInt64, Int64-const)
has an Int64 result, and intDiv(2^63, c) flips sign relative to
intDiv(2^63 - 1, c). intDiv(unsigned, signed-const) is therefore a step function
with a single discontinuity at D = 2^(width-1): monotonic on each side of D but
not across it.

When such a chain feeds an IN/NOT IN key condition,
applyMonotonicFunctionsChainToRange builds a Range with left > right, and
MergeTreeSetIndex::checkInRange hits the std::partition_point invariant
begin <= end. In debug builds this aborts with the LOGICAL_ERROR
'Invalid binary search result in MergeTreeSetIndex'; in release builds
checkInRange falls back to {true, true} (no pruning).

Found by the AST fuzzer on master (STID 3252-3a4a): a UInt64 key divided by a
large negative Int128 constant. This is the variable/constant counterpart of
the const/variable case fixed in ClickHouse#103621.

The fix detects whether the range [left_point, right_point] crosses the
discontinuity D analytically (intDivRangeCrossesSignedWrap), treating a null
endpoint as the unsigned-domain limit. A crossing range is reported as
non-monotonic (no pruning); a range on one side of D stays monotonic on that
range but is not always-monotonic. This is applied in both the finite-range
branch and the unbounded (null, null) branch that ReadInOrderOptimizer and
KeyCondition use to probe is_always_monotonic.

An earlier version of this fix compared only the transformed endpoints, which
is insufficient: intDiv is a step function whose endpoints can map to equal
values while the interior changes direction (e.g. UInt8 / 100 over [0, 255]),
so endpoint comparison can still report spurious monotonicity and over-prune
interior rows. The analytical crossing check replaces it.

divide (floating-point) and intDiv with an unsigned result never wrap and stay
always-monotonic as before.

As a consequence, read-in-order no longer treats intDiv(UInt32 column,
negative constant) as monotonic, so its sort-key prefix is dropped in
00940/02911_order_by_read_in_order_query_plan. That prior plan was unsafe:
intDiv(UInt32, negative-const) has an Int32 result and is non-monotonic across
2^31, so reading in order would have produced wrong row order on data crossing
that point (the test data y in 0..3 never crossed it, so the bug was latent).
The .reference files are updated to reflect the corrected plans.

Related: ClickHouse#90461

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 16, 2026
…ndex

FunctionBinaryArithmetic::getMonotonicityForRange claimed intDiv(variable,
constant) is always monotonic. That is wrong when the dividend is unsigned and
the intDiv result type is signed: intDiv casts the dividend to a signed type
when the divisor is signed (DivideIntegralImpl), and ResultOfIntegerDivision
makes the result signed with the dividend width. So an unsigned value
>= 2^(width-1) reinterprets as negative. For example intDiv(UInt64, Int64-const)
has an Int64 result, and intDiv(2^63, c) flips sign relative to
intDiv(2^63 - 1, c). intDiv(unsigned, signed-const) is therefore a step function
with a single discontinuity at D = 2^(width-1): monotonic on each side of D but
not across it.

When such a chain feeds an IN/NOT IN key condition,
applyMonotonicFunctionsChainToRange builds a Range with left > right, and
MergeTreeSetIndex::checkInRange hits the std::partition_point invariant
begin <= end. In debug builds this aborts with the LOGICAL_ERROR
'Invalid binary search result in MergeTreeSetIndex'; in release builds
checkInRange falls back to {true, true} (no pruning).

Found by the AST fuzzer on master (STID 3252-3a4a): a UInt64 key divided by a
large negative Int128 constant. This is the variable/constant counterpart of
the const/variable case fixed in ClickHouse#103621.

The fix detects whether the range [left_point, right_point] crosses the
discontinuity D analytically (intDivRangeCrossesSignedWrap), treating a null
endpoint as the unsigned-domain limit. A crossing range is reported as
non-monotonic (no pruning); a range on one side of D stays monotonic on that
range but is not always-monotonic. This is applied in both the finite-range
branch and the unbounded (null, null) branch that ReadInOrderOptimizer and
KeyCondition use to probe is_always_monotonic.

An earlier version of this fix compared only the transformed endpoints, which
is insufficient: intDiv is a step function whose endpoints can map to equal
values while the interior changes direction (e.g. UInt8 / 100 over [0, 255]),
so endpoint comparison can still report spurious monotonicity and over-prune
interior rows. The analytical crossing check replaces it.

divide (floating-point) and intDiv with an unsigned result never wrap and stay
always-monotonic as before.

As a consequence, read-in-order no longer treats intDiv(UInt32 column,
negative constant) as monotonic, so its sort-key prefix is dropped in
00940/02911_order_by_read_in_order_query_plan. That prior plan was unsafe:
intDiv(UInt32, negative-const) has an Int32 result and is non-monotonic across
2^31, so reading in order would have produced wrong row order on data crossing
that point (the test data y in 0..3 never crossed it, so the bug was latent).
The .reference files are updated to reflect the corrected plans.

The intDiv guard is spelled in the positive form intDiv && isUInt && isInt in
both branches for readability, and 04340 covers a UInt32 range crossing 2^31
under NOT IN (the operator that exposes the silent over-pruning).

Related: ClickHouse#90461

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ndex

FunctionBinaryArithmetic::getMonotonicityForRange claimed intDiv(variable,
constant) is always monotonic. That is wrong when the dividend is unsigned and
the intDiv result type is signed: intDiv casts the dividend to a signed type
when the divisor is signed (DivideIntegralImpl), and ResultOfIntegerDivision
makes the result signed with the dividend width. So an unsigned value
>= 2^(width-1) reinterprets as negative. For example intDiv(UInt64, Int64-const)
has an Int64 result, and intDiv(2^63, c) flips sign relative to
intDiv(2^63 - 1, c). intDiv(unsigned, signed-const) is therefore a step function
with a single discontinuity at D = 2^(width-1): monotonic on each side of D but
not across it.

When such a chain feeds an IN/NOT IN key condition,
applyMonotonicFunctionsChainToRange builds a Range with left > right, and
MergeTreeSetIndex::checkInRange hits the std::partition_point invariant
begin <= end. In debug builds this aborts with the LOGICAL_ERROR
'Invalid binary search result in MergeTreeSetIndex'; in release builds
checkInRange falls back to {true, true} (no pruning).

Found by the AST fuzzer on master (STID 3252-3a4a): a UInt64 key divided by a
large negative Int128 constant. This is the variable/constant counterpart of
the const/variable case fixed in ClickHouse#103621.

The fix detects whether the range [left_point, right_point] crosses the
discontinuity D analytically (intDivRangeCrossesSignedWrap), treating a null
endpoint as the unsigned-domain limit. A crossing range is reported as
non-monotonic (no pruning); a range on one side of D stays monotonic on that
range but is not always-monotonic. This is applied in both the finite-range
branch and the unbounded (null, null) branch that ReadInOrderOptimizer and
KeyCondition use to probe is_always_monotonic.

An earlier version of this fix compared only the transformed endpoints, which
is insufficient: intDiv is a step function whose endpoints can map to equal
values while the interior changes direction (e.g. UInt8 / 100 over [0, 255]),
so endpoint comparison can still report spurious monotonicity and over-prune
interior rows. The analytical crossing check replaces it.

divide (floating-point) and intDiv with an unsigned result never wrap and stay
always-monotonic as before.

As a consequence, read-in-order no longer treats intDiv(UInt32 column,
negative constant) as monotonic, so its sort-key prefix is dropped in
00940/02911_order_by_read_in_order_query_plan. That prior plan was unsafe:
intDiv(UInt32, negative-const) has an Int32 result and is non-monotonic across
2^31, so reading in order would have produced wrong row order on data crossing
that point (the test data y in 0..3 never crossed it, so the bug was latent).
The .reference files are updated to reflect the corrected plans.

The intDiv guard is spelled in the positive form intDiv && isUInt && isInt in
both branches for readability, and 04340 covers a UInt32 range crossing 2^31
under NOT IN (the operator that exposes the silent over-pruning).

Related: ClickHouse#90461

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 pr-improvement Pull request with some product 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.

4 participants