Repository navigation
Fix LOGICAL_ERROR Invalid binary search result in MergeTreeSetIndex for divide(0, x) - #103621
Conversation
`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
Pre-PR validation gatea) Deterministic repro? Yes. On commit 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 b) Root cause explained? c) Fix matches root cause? Yes — the fix corrects the monotonicity claim itself (the root cause), not the downstream symptom in d) Test intent preserved? / New tests added? New file e) Demonstrated in both directions? Yes. On unfixed binary: all three "0 / a" queries throw LOGICAL_ERROR. On fixed binary: 50/50 iterations of f) Fix is general, not a narrow patch? Same code path serves both session: cron:clickhouse-ci-task-worker:20260428-004500 |
|
cc @rschu1ze @alexey-milovidov — could you review this? It fixes the chronic AST fuzzer LOGICAL_ERROR |
|
Workflow [PR], commit [cf5f0a8] Summary: ✅ AI ReviewSummaryThis PR fixes monotonicity inference for ClickHouse Rules
Final VerdictStatus: ✅ Approve |
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).
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
LLVM Coverage Report
Changed lines: 100.00% (8/8) · Uncovered code |
…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]>
…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]>
…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]>
…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]>
The AST fuzzer was repeatedly tripping a
LOGICAL_ERROR: Invalid binary search result in MergeTreeSetIndexin debug builds when anIN/NOT INexpression on the primary key wrapped the key column in adivide(orintDiv) call with a constant zero numerator.FunctionBinaryArithmetic::getMonotonicityForRangeclaimed thatdivide(0, x)was monotonic for any input range:The comment said the function is "not always monotonic" but the code returned
is_monotonic = true.0 / xis 0 for anyx!= 0 but undefined atx= 0 (NaN/Inffordivide, division-by-zero exception forintDiv), so the function is genuinely non-monotonic on any range that includes 0.KeyCondition::applyMonotonicFunctionsChainToRangetrusted the false claim and produced aRangewithleft > right, which violated the binary-search invariantbegin <= endinMergeTreeSetIndex::checkInRange. Debug builds aborted with aLOGICAL_ERRORatsrc/Interpreters/Set.cpp:809. Release builds silently fall back to the{true, true}BoolMaskvia the#elsebranch of#ifndef NDEBUGatsrc/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 != 0branch uses two lines below: only claim monotonicity when the input range is strictly above or strictly below 0; otherwise return non-monotonic. This also coversintDiv(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):
WHERE (divide(divide(isNull(-2), assumeNotNull(7)), a), b) NOT IN ((9223372036854775806, '0.500000'), (2147483646, 'y')){_schema_hash}placeholder for S3 table engine #98265:WHERE ((isNull(2) / id) NOT IN (10, 50000, 90000)) ...Local repro on commit
c474a1f36f5(debug build):After the fix the same query returns 10 and the new regression test
04141_divide_by_zero_constant_monotonicitypasses 50/50 iterations with randomized client settings. Existing tests03835_todate_monotonicity_boundary,04073_divide_intdivide_monotonicity_key_condition,03399_divide_zero_or_null,03532_divideOrNull_jit_crash, and03314_divide_decimal_short_circuitcontinue to pass unchanged.Note on
Bugfix validation (functional tests)The original
LOGICAL_ERRORis gated by#ifndef NDEBUGinsrc/Interpreters/Set.cpp:806-812and only fires in debug / sanitizer builds. Stable release builds take the#elsebranch 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 isImprovementrather 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, noRangewithleft > right, no debug-buildLOGICAL_ERRORfrom 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved correctness of monotonicity inference for
divide(0, x)andintDiv(0, x): previously the functions were unconditionally reported as monotonic, but0 / xis non-monotonic on any range that includes 0 because0 / 0is undefined (NaN/Inffordivide, division-by-zero exception forintDiv). The false claim causedKeyCondition::applyMonotonicFunctionsChainToRangeto produce ranges withleft > right, which tripped aLOGICAL_ERRORInvalid binary search result in MergeTreeSetIndexin debug builds when anIN/NOT INexpression on the primary key wrapped the key individe(0, key)orintDiv(0, key). Release builds were unaffected — the assertion is gated by#ifndef NDEBUG.Documentation entry for user-facing changes
No documentation needed — internal correctness improvement with no user-facing behavior change in release builds.
Version info
26.5.1.175