Skip to content

Fix false monotonicity of intDiv(unsigned, constant) causing Invalid binary search result in MergeTreeSetIndex - #107586

Merged
tiandiwonder merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-set-index-intdiv-monotonicity
Jul 22, 2026
Merged

tiandiwonder merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-set-index-intdiv-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fix a LOGICAL_ERROR Invalid binary search result in MergeTreeSetIndex (and missed index pruning in release builds) when an IN/NOT IN condition on the primary key wraps the key in intDiv by a constant and the key is an unsigned integer whose values cross the signed boundary of the intDiv result type (for example intDiv(uint64_column, -9223372036854775807)).

Description

The variable / constant branch of FunctionBinaryArithmetic::getMonotonicityForRange claimed intDiv(variable, constant) is always monotonic. That is incorrect when the dividend is unsigned and the intDiv result type is signed: intDiv casts the dividend to a signed computation type when the divisor is signed (see DivideIntegralImpl), so an unsigned value >= 2^(width-1) wraps to a negative result. For example intDiv(UInt64, Int64-constant) has an Int64 result, so a dividend >= 2^63 becomes negative and the function is no longer monotonic across that boundary.

When such a chain feeds an IN/NOT IN key condition, KeyCondition::applyMonotonicFunctionsChainToRange builds a Range with left > right, and MergeTreeSetIndex::checkInRange then violates the std::partition_point invariant begin <= end. Debug builds abort with the LOGICAL_ERROR; release builds fall back to the {true, true} BoolMask (results stay correct but the index does no pruning).

This is the variable / constant counterpart of the const / variable case fixed in #103621.

The fix verifies, only for the affected case (unsigned dividend with a signed intDiv result), that the dividend->result-type cast preserves the order of [left_point, right_point] by transforming both endpoints. divide (floating-point) and every other intDiv type combination keep their previous always-monotonic behavior, so legitimate index pruning is unchanged.

Found by the AST fuzzer on master (STID 3252-3a4a). The failing query divided a UInt64 key by a large negative Int128 constant inside a GLOBAL IN set.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c3be9310ee8c2af93f00b16941e14b900ff3796c&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

Version info

  • Merged into: 26.7.1.1308 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On a debug build: CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 8192; INSERT INTO t VALUES (9223372036854775807),(9223372036854775808); SELECT count() FROM t WHERE intDiv(a, toInt128(-9223372036854775807)) IN (0); aborts every time with Invalid binary search result in MergeTreeSetIndex.
b Root cause explained? getMonotonicityForRange claims intDiv(variable, constant) is always monotonic. intDiv casts the dividend to a signed type when the divisor is signed (DivideIntegralImpl), so for an unsigned dividend with a signed result type a value >= 2^(width-1) wraps to negative (e.g. intDiv(UInt64, Int64-const) -> Int64: intDiv(2^63, c) flips sign vs intDiv(2^63-1, c)). The false monotonicity makes applyMonotonicFunctionsChainToRange build a Range with left > right, so MergeTreeSetIndex::checkInRange violates the std::partition_point invariant begin <= end.
c Fix matches root cause? Yes. For the affected case (unsigned dividend, signed intDiv result) the fix verifies the dividend->result-type cast preserves order across [left_point, right_point] by transforming both endpoints, returning non-monotonic when a wrap is detected. It does not widen any bound or disable randomization.
d Test intent preserved / new tests added? New regression test 04340_intdiv_variable_constant_monotonicity added. It covers the scalar/tuple IN/NOT IN forms (negative and positive divisor) plus sanity checks that legitimate signed and non-wrapping unsigned cases still prune. All expected counts verified against full-scan ground truth.
e Both directions demonstrated? Yes. Without the fix (Build ID e2de5975...) the repro aborts. With the fix (Build ID c74a6b62...) it returns cleanly, the new test passes, and existing 04073/04141 monotonicity tests still pass. Index pruning on legitimate cases is unchanged (3/25 granules in EXPLAIN, identical to pre-fix).
f Fix is general, not a narrow patch? Yes. Only intDiv/divide declare arithmetic monotonicity (hasInformationAboutMonotonicity); modulo/positiveModulo do not, and multiply already has its own overflow check. The const / variable sibling was handled by #103621. The fix targets the cast-wrap at its source (the signedness mismatch), not the assert site, and keeps every safe type combination always-monotonic.

Session id: cron:clickhouse-worker-slot-2:20260616-024800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @novikd — could you review this? It fixes a false monotonicity claim for intDiv(unsigned_column, constant) in FunctionBinaryArithmetic::getMonotonicityForRange: intDiv casts the dividend to a signed type, so an unsigned value past the signed boundary wraps to negative, which made KeyCondition build an inverted range and MergeTreeSetIndex::checkInRange hit the begin <= end assertion (AST fuzzer STID 3252-3a4a). It is the variable / constant counterpart of #103621.

@tiandiwonder tiandiwonder self-assigned this Jun 16, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c528a2]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Cannot start clickhouse-server FAIL cidb IGNORED
Check failed FAIL cidb IGNORED

AI Review

Summary

This PR closes several real intDiv/divide monotonicity holes around signed reinterpretation and Decimal divisors, and the new regression coverage is much better than the original patch. One blocker remains: the new wrap helper still treats the signed-wrap point itself as safe for the effective-divisor--1 corner, so key analysis can raise ILLEGAL_DIVISION on open ranges whose actual row domain is fully defined.

Findings
  • ❌ Blocker: [src/Functions/FunctionBinaryArithmetic.h:3839] intDivRangeCrossesSignedWrap models only the sign-wrap discontinuity, not the INT_MIN / -1 exception point. For intDiv(UInt8_key, toInt16(-1)), an open range like (128, +inf) still falls through as monotonic, and applyMonotonicFunctionsChainToRange then evaluates the excluded bound 128, throwing ILLEGAL_DIVISION before row evaluation even though every actual row 129..255 is valid. The same hole exists in the mirrored all-ones unsigned-divisor path (toUInt8(255), toUInt16(65535), ...).
    Suggested fix: when the effective divisor is -1, reject any range whose closed approximation touches the reinterpreted INT_MIN point (or plumb inclusiveness so excluded endpoints are never applied), and add a focused regression for a > 128 / a > -128.
Final Verdict
  • Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 16, 2026
@groeneai
groeneai force-pushed the groeneai/fix-set-index-intdiv-monotonicity branch from 1e7ee28 to c3f9516 Compare June 16, 2026 09:29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, both points were correct. Reworked: the endpoint-sampling check is replaced with an analytical crossing test.

intDiv(unsigned, signed-const) reinterprets the dividend as signed (DivideIntegralImpl casts to make_signed_t when the divisor is signed; ResultOfIntegerDivision keeps the dividend width), so it is a step function with a single discontinuity at D = 2^(width-1): monotonic on each side of D, not across it.

  • CR#1 (interior jump): intDivRangeCrossesSignedWrap(arg_type, left, right) reports non-monotonic whenever [left, right] spans D (left < D <= right), instead of comparing transformed endpoints. For the UInt8 / 100 over [0, 255] case both endpoints map to 0, but the range crosses D = 128, so it is now correctly rejected (no pruning) rather than treated as monotonic.
  • CR#2 (unbounded branch): the same crossing test is applied in the left_point.isNull() || right_point.isNull() branch, with a null endpoint treated as the unsigned-domain limit. A fully-unbounded (null, null) range over an unsigned domain always contains D, so is_always_monotonic is no longer returned for the affected intDiv case (the path ReadInOrderOptimizer and KeyCondition use).

divide and intDiv with an unsigned result never wrap and stay always-monotonic.

Verified on a debug build:

  • Original AST-fuzzer repro (UInt64, index_granularity = 8192): aborts with Invalid binary search result in MergeTreeSetIndex without the fix, returns cleanly with it.
  • CR#1 UInt8 / 100 IN (1) over [0, 255]: prunes to 0 rows without the fix (ground truth 28), correct with it.
  • CR#2 whole-domain intDiv(a, 100) IN (0): pruned count matches full-scan ground truth.
  • Index-pruning still applies for ranges below D and for signed dividends (no regression); 04073_divide_intdivide_monotonicity_key_condition and the 00907_set_index* tests pass.

The regression test 04340 is extended with the interior-step (UInt8 / 100) and whole-domain cases; each query asserts the index-pruned count equals the full-scan ground truth.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (rework after review)

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a UInt64) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=8192; INSERT INTO t VALUES (9223372036854775807),(9223372036854775808); SELECT count() FROM t WHERE intDiv(a, toInt128(-9223372036854775807)) IN (0); aborts every time on an unpatched debug build (SIGABRT, Invalid binary search result in MergeTreeSetIndex).
b Root cause explained? intDiv(unsigned, signed-const) casts the dividend to a signed type of the same width (DivideIntegralImpl + ResultOfIntegerDivision), so values >= 2^(width-1) reinterpret as negative. It is a step function with one discontinuity at D = 2^(width-1). getMonotonicityForRange wrongly claimed it always-monotonic, so applyMonotonicFunctionsChainToRange built a Range with left > right and MergeTreeSetIndex::checkInRange violated std::partition_point's begin <= end.
c Fix matches root cause? Yes. intDivRangeCrossesSignedWrap detects analytically whether [left, right] spans D (null endpoint = unsigned-domain limit) and reports non-monotonic in that case, in both the finite-range and the unbounded (null, null) branches. It does not widen any assertion or add a blanket tag.
d Test intent preserved / new tests added? New regression test 04340_intdiv_variable_constant_monotonicity (the source change is a bug fix). Each query asserts the index-pruned count equals the full-scan ground truth, including the interior-step UInt8 / 100 over [0, 255] and whole-domain cases from the review, plus sanity cases that must still prune.
e Both directions demonstrated? Yes. Unpatched: original repro aborts; UInt8 / 100 IN (1) prunes to 0 (ground truth 28). Patched: original repro returns cleanly; all pruned counts equal ground truth; 04340 passes 50/50 with randomization; 04073_divide_intdivide_monotonicity_key_condition and 00907_set_index* pass.
f Fix is general, not a narrow patch? The crossing check covers every unsigned-dividend / signed-intDiv-result width (UInt8/16/32/64/128/256) and both divisor signs, and is applied to both code paths that consume the monotonicity (finite range and unbounded probe). divide and unsigned-result intDiv are unaffected. Root cause is addressed at the monotonicity claim, not at the assert site.

Session id: cron:clickhouse-worker-slot-1:20260616-084300

@tiandiwonder tiandiwonder left a comment

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 intDiv straddle-test rewrite looks correct, but CI is red because 00940_order_by_read_in_order_query_plan and 02911_analyzer_order_by_read_in_order_query_plan aren't updated: with y UInt32, intDiv(intDiv(y, -2), -3) is now correctly non-monotonic at plan time and drops from the prefix sort description. Update both .reference files rather than reverting the change — the old plan would mis-order an unsigned column whose values cross 2^31, so this is a fix, not a regression.

@groeneai
groeneai force-pushed the groeneai/fix-set-index-intdiv-monotonicity branch from c3f9516 to 5900dcb Compare June 16, 2026 10:43
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for commit 5900dcb)

This push fixes the Fast test regression on the prior commit (c3f9516): the read-in-order EXPLAIN tests 00940/02911_order_by_read_in_order_query_plan lost the intDiv(intDiv(y, -2), -3) prefix-sort line. tab2.y is UInt32, so intDiv(y, -2) has an Int32 result and is genuinely non-monotonic across 2^31 (e.g. intDiv(2^31-1, -2) = -1073741823, intDiv(2^31, -2) = +1073741824). The old reference encoded an unsafe read-in-order plan that only "passed" because the test data y in 0..3 never crossed 2^31. Dropping the prefix is the correct consequence of CR#2 (the unbounded {}, {} probe that ReadInOrderOptimizer uses now correctly reports non-monotonic). The references are updated to the corrected plans.

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a UInt64) ENGINE=MergeTree ORDER BY a; INSERT INTO t VALUES (9223372036854775807),(9223372036854775808); SELECT count() FROM t WHERE intDiv(a, toInt128(-9223372036854775807)) IN (0); aborts on master (debug) with Invalid binary search result in MergeTreeSetIndex. CR#1 interior-step repro: UInt8 filled 0..255, intDiv(a, 100) IN (1) over-prunes to 0 vs ground truth 28. CR#2 unbounded repro: intDiv(a, 100) IN (0) over the whole UInt8 domain.
b Root cause explained? intDiv casts the dividend to a signed type when the divisor is signed (DivideIntegralImpl); ResultOfIntegerDivision makes the result signed with the dividend width. So intDiv(UInt_W, signed-const) has an Int_W result and an unsigned value >= 2^(W-1) reinterprets as negative, making it a step function with one discontinuity at D = 2^(W-1), monotonic on each side but not across. getMonotonicityForRange claimed it always-monotonic, so applyMonotonicFunctionsChainToRange built a Range with left > right and MergeTreeSetIndex::checkInRange violated the std::partition_point begin <= end invariant.
c Fix matches root cause? Yes. New analytical helper intDivRangeCrossesSignedWrap returns true iff [left, right] contains D (null endpoint = unsigned-domain limit). The finite-range branch and the unbounded (null, null) branch both reject a crossing range as non-monotonic, gated on name == "intDiv" && isUInt(arg_type) && isInt(ret_type). This replaces the bot-rejected endpoint-sampling approach (CR#1) and covers the ReadInOrderOptimizer/KeyCondition is_always_monotonic probe (CR#2). No band-aid: intDiv with an unsigned result and divide (float) stay always-monotonic.
d Test intent preserved / new tests added? Yes. New 04340_intdiv_variable_constant_monotonicity asserts pruned count == full-scan ground truth (so over-pruning fails the test) for: UInt64-straddling-2^63 (original shape), UInt8 interior-step [0,255] and whole-domain (CR#1+CR#2), and sanity cases that MUST still prune (unsigned-result intDiv, signed dividend). 00940/02911 references updated to corrected (safe) read-in-order plans. 04073 (prior #103621 fix) and 04277_merge_read_in_order_with_prewhere unaffected.
e Both directions demonstrated? Yes. Without fix (master): repro SIGABRTs; intDiv(UInt8,100) IN(1) over-prunes to 0 (truth 28). With fix (build a89976a9): repro returns cleanly; 04340 passes 30/30 under randomization; 00940+02911 pass 10/10 deterministic; pruning matches full-scan ground truth across UInt8/16/64 and pos/neg divisors.
f Fix is general, not a narrow patch? Yes. The crossing check is computed analytically for any unsigned width (D = 2^(8*width-1)), covering UInt8/16/32/64/128/256, both divisor signs, scalar and tuple sets, and is applied in both branches that callers use (finite-range and unbounded). It fixes the root cause (false monotonicity claim) at the source, not the checkInRange assert site. divide/unsigned-result intDiv deliberately keep always-monotonic (no pruning regression).

Session id: cron:clickhouse-worker-slot-3:20260616-102600

@groeneai

Copy link
Copy Markdown
Collaborator Author

References updated in 5900dcb (both .reference files only, the FunctionBinaryArithmetic.h fix is unchanged). Confirmed tab2.y is UInt32, so intDiv(intDiv(y, -2), -3) has an Int32 result and is non-monotonic across 2^31 (e.g. intDiv(2147483647, -2) = -1073741823 vs intDiv(2147483648, -2) = +1073741824); the dropped prefix-sort plan was therefore unsafe for unsigned values crossing 2^31, so this is a correct-plan fix. 00940/02911 pass; 04277 (read-in-order) and 04073 (prior #103621) are unaffected.


// `divide` is floating-point (saturates, order-preserving), and `intDiv` whose result
// type is also unsigned never wraps, so both are always monotonic.
if (name_view == "divide" || !(isUInt(arg_type) && isInt(ret_type)))

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.

optional: flip this to the positive form if (name_view == "intDiv" && isUInt(arg_type) && isInt(ret_type)), matching the unbounded branch above, so both sites read identically.

the negated divide || !(...) makes the reader apply De Morgan to see the fall-through is exactly intDiv && isUInt && isInt; behavior is the same either way.

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.

Done in 92ca863. Both branches now use the positive name_view == "intDiv" && isUInt(arg_type) && isInt(ret_type) form.

if (name_view == "divide" || !(isUInt(arg_type) && isInt(ret_type)))
return {true, is_constant_positive, true, is_strict};

// `intDiv(unsigned, signed-const)` wraps at `D = 2^(width-1)` (see

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.

optional: this wraps at D = 2^(width-1) sentence repeats the header of intDivRangeCrossesSignedWrap (also restated at the unbounded branch) — a bare // see intDivRangeCrossesSignedWrap would do.

the locally-useful bits (why divide/unsigned-result are always-monotonic, why this path returns is_always_monotonic=false) aren't in the helper and are worth keeping.

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.

Done in 92ca863. Trimmed the duplicated wrap-point description to a reference to intDivRangeCrossesSignedWrap, keeping the locally-useful notes (why divide/unsigned-result stay always-monotonic, and why this branch returns is_always_monotonic=false).

-- UInt8 over the whole domain: intDiv(a, 100) is a step function whose endpoints intDiv(0,100)=0 and
-- intDiv(255,100)=0 are equal while the interior jumps, so endpoint comparison alone cannot prove
-- monotonicity. The whole-domain IN with no other key bound also exercises the unbounded (null, null) path.
CREATE TABLE t_intdiv_mono (a UInt8) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;

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 wrap path is only exercised on UInt8 and UInt64; UInt16/UInt32 aren't covered, and NOT IN — the operator that actually surfaced the silent over-pruning, since IN returns the right count even unpruned — is only tested on UInt64.

worth one UInt32 table crossing 2^31 with a NOT IN to lock down a mid width on the operator that regresses.

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.

Added in 92ca863: a UInt32 table whose single granule [100, 4294967295] crosses 2^31, tested with NOT IN (0) for both a positive and a negative divisor. Verified both directions on the debug binary: without the fix the endpoints intDiv(100,2e9)=0 and intDiv(4294967295,2e9)=0 collapse the range to [0,0], so NOT IN (0) prunes the whole granule and returns 0 instead of the ground-truth 2 (silent over-pruning, no abort); with the fix the crossing range is non-monotonic, nothing is pruned, and the count is 2.

…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]>
@groeneai
groeneai force-pushed the groeneai/fix-set-index-intdiv-monotonicity branch from 5900dcb to 92ca863 Compare June 16, 2026 13:09
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 92ca863)

This run addresses @tiandiwonder's three follow-up review comments: positive-form guard (both branches), comment dedup, and a UInt32-crossing-2^31 NOT IN test case.

# Question Answer
a Deterministic repro? Yes. UInt64: intDiv(a, toInt128(-9223372036854775807)) IN (0) on a key straddling 2^63 aborts with the LOGICAL_ERROR. New UInt32 case: intDiv(a, toInt64(2000000000)) NOT IN (0) on a granule [100, 4294967295] crossing 2^31 returns 0 instead of 2 (silent over-pruning, no abort).
b Root cause explained? intDiv(unsigned, signed-const) casts the dividend to a signed type of the same width (DivideIntegralImpl), so values >= 2^(width-1) reinterpret as negative. It is a step function with one discontinuity at D=2^(width-1). A range crossing D is non-monotonic; the prior code claimed monotonicity, so applyMonotonicFunctionsChainToRange built a Range with left>right (partition_point invariant violated) or a too-narrow range (over-pruning).
c Fix matches root cause? Yes. intDivRangeCrossesSignedWrap analytically tests whether [left, right] contains D and reports non-monotonic for crossing ranges, in both the finite-range and unbounded branches. No behavior change this run: the guard was only re-spelled to the positive form and a comment trimmed.
d Test intent preserved / new tests added? New regression test 04340 extended with the UInt32/NOT IN case (the operator and mid-width the reviewer asked for). Reference regenerated from actual output. No existing test weakened.
e Both directions demonstrated? Yes, Build-ID verified. Without fix (e2de5975): UInt64 case aborts; UInt32 NOT IN returns 0 (pruned) vs ground truth 2. With fix (3e87e5af): full 04340 passes 50/50 under randomization; UInt32 NOT IN returns 2 for both divisor signs; original AST repro returns cleanly; 00940/02911/04073 pass.
f Fix is general, not a narrow patch? Yes. The crossing test is applied to both branches of getMonotonicityForRange that handle variable/constant division (finite-range and unbounded null-endpoint). divide (float, saturating) and intDiv with an unsigned result are correctly left always-monotonic. The check is width-generic (UInt8/16/32/64), verified across widths and both divisor signs against full-scan ground truth.

Session id: cron:clickhouse-worker-slot-3:20260616-123600

The intDiv(unsigned, constant) monotonicity guard keyed off the signed
return type (isInt(ret_type)). ResultOfIntegerDivision makes the result
signed whenever either operand is signed, so intDiv(UInt64, 10.0) gets an
Int64 result even though Float64 is the divisor. DivideIntegralImpl only
reinterprets the dividend through make_signed_t in the integer/integer
branch; a Float divisor computes through floating point and never wraps at
2^63. The guard therefore over-matched a Float constant divisor and falsely
reported the (null, null) probe as non-monotonic, disabling key and
read-in-order pruning that should stay unchanged.

Gate on the divisor being a signed integer (isInt(divisor_type)) instead,
matching DivideIntegralImpl's signed-cast branch exactly. With an unsigned
dividend this still implies a signed result, so the wrap handling is
unchanged for integer divisors (including the Int128 divisor in the fuzzer
repro); only Float/Decimal divisors are excluded.

04340 gains a Float-divisor case asserting both that key pruning matches the
ground-truth count and that read-in-order keeps intDiv in the prefix sort
(the read-in-order settings are pinned on that EXPLAIN because the runner
randomizes optimize_read_in_order).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in d3be10a. You are right: ResultOfIntegerDivision makes the result signed when either operand is signed, so intDiv(UInt64, 10.0) is Int64 and isInt(ret_type) matched it, but DivideIntegralImpl only reinterprets the dividend through make_signed_t in the integer/integer branch; a Float divisor computes through floating point with no discontinuity at 2^63.

Both branches now gate on the divisor being a signed integer, isInt(divisor_type) where divisor_type = removeNullable(recursiveRemoveLowCardinality(right.type)), matching DivideIntegralImpl's signed-cast branch exactly. With an unsigned dividend that still implies a signed result, so the integer-divisor wrap handling (including the Int128 divisor in the repro) is unchanged; only Float/Decimal divisors are excluded.

Verified on the debug binary:

  • Old isInt(ret_type): EXPLAIN ... ORDER BY intDiv(a, 10.0) over a UInt64 column drops the prefix sort (read-in-order pruning disabled).
  • New isInt(divisor_type): the prefix sort is kept, and the integer-divisor wrap cases (UInt8/UInt16/UInt32/UInt64) still report non-monotonic as before.

04340 gains a Float-divisor case asserting the index count matches ground truth and that read-in-order keeps intDiv in the prefix sort.

The two 07:08Z items are addressed in 92ca863: the interior sign-flip is now detected analytically by intDivRangeCrossesSignedWrap (endpoint comparison replaced), and the (null, null) branch runs the same crossing check (a null endpoint extends to the unsigned-domain limit, which always crosses), so the unbounded probe no longer returns spurious monotonicity.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup d3be10a)

# Question Answer
a Deterministic repro? Yes. On the debug binary, EXPLAIN actions=1 SELECT a FROM t (UInt64) ORDER BY intDiv(a, 10.0) deterministically drops the prefix sort under the old isInt(ret_type) predicate (count 0) and keeps it under the new isInt(divisor_type) predicate (count 1). toTypeName(intDiv(materialize(toUInt64(100)), 10.0)) is Int64, confirming why the old gate fired.
b Root cause explained? ResultOfIntegerDivision types the result signed iff either operand is signed, so a Float64 divisor yields an Int64 result and isInt(ret_type) is true. But the unsigned->signed dividend reinterpretation lives only in DivideIntegralImpl's is_integer<A> && is_integer<B> branch; a Float divisor takes the floating-point branch and never wraps at 2^63. So the signed-result gate over-matched a Float divisor and falsely reported intDiv(UInt64, float) non-monotonic, disabling pruning that should stay on.
c Fix matches root cause? Yes. Gate on the divisor being a signed integer (isInt(divisor_type), divisor type stripped of Nullable/LowCardinality), which is exactly DivideIntegralImpl's signed-cast branch. With an unsigned dividend this still implies a signed result, so it is a strict narrowing: integer-divisor wrap handling is unchanged, Float/Decimal divisors are excluded.
d Test intent preserved / new tests added? Preserved and extended. All existing UInt8/UInt16/UInt32/UInt64 integer-divisor wrap assertions remain. 04340 gains a Float-divisor case asserting (1) key pruning matches the ground-truth count and (2) read-in-order keeps intDiv in the prefix sort. Read-in-order settings are pinned on that one EXPLAIN because the runner randomizes optimize_read_in_order.
e Both directions demonstrated? Yes. Old predicate: Float-divisor EXPLAIN prints 0 (prefix sort wrongly dropped). New predicate: prints 1 (kept). Full 04340 passes 30/30 with --test-runs 30 under randomization; 00940 and 02911 read-in-order tests pass unchanged (their signed-integer divisors still match the narrowed gate).
f Fix is general, not a narrow patch? Yes. Applied to both the finite-range and unbounded (null, null) branches (the only two intDiv variable/constant monotonicity sites). The gate now mirrors the actual DivideIntegralImpl cast condition rather than the result type, so it is correct for every divisor type, not just the Float case the bot flagged. No symptom guard: the predicate now exactly matches the algebra that wraps.

Session id: cron:clickhouse-worker-slot-3:20260616-142500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status on d3be10a (our-pr-ci-monitor):

The only failed check is BuzzHouse (amd_debug), and it is a CI-harness infra flake, not a fuzzer finding on this PR:

  • Job-level error: ast_fuzzer_job.py:240 FileNotFoundError: ci/tmp/workspace/status.tsv. The runner aborted before writing status.tsv, so there is no fuzzer verdict, no STID, and no crash stack. A real BuzzHouse finding writes status.tsv=FAIL with an STID.
  • The other three BuzzHouse builds (amd_tsan, amd_msan, arm_asan_ubsan) passed on this same SHA.
  • The same missing-status.tsv signature hit ~18 unrelated PRs in the last 7 days (chronic harness flake, tracked separately).

The AST-fuzzer finding this PR targets (Invalid binary search result in MergeTreeSetIndex, STID 3252-3a4a) no longer reproduces on this SHA. The Bugfix-validation rows ("Lost s3 keys", "OOM in dmesg", "Lost forever for SharedMergeTree") are the usual SharedMergeTree+S3 harness noise (job passed).

A BuzzHouse (amd_debug) re-run should clear the Mergeable Check.

(cron:our-pr-ci-monitor:20260616-203000)

// so reject it (no pruning); a range on one side is monotonic on that range but not
// always-monotonic. The wrap is exclusive to the signed-integer divisor path; a Float
// divisor computes through floating point and never wraps.
if (name_view == "intDiv" && isUInt(arg_type) && isInt(divisor_type))

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 guard only covers isUInt(dividend) && isInt(divisor), but the mirror case is wrong too: with a signed dividend and an unsigned constant whose high bit is set, DivideIntegralImpl casts the divisor through a signed type (SignedCastB), so it's effectively negative and the function is decreasing — but is_constant_positive above is read from the raw unsigned constant (0 < 255 -> true), so this falls through to {true, positive, always-monotonic} and an intDiv(int_key, ...) IN (...) condition builds a Range with left > right, i.e. the same Invalid binary search result in MergeTreeSetIndex this PR fixes, in the symmetric operand config.

reproduces on a debug build — the two queries differ only in the divisor's declared type (same effective value -56):

CREATE TABLE t (a Int8) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1;
INSERT INTO t SELECT number-127 FROM numbers(255);
SELECT count() FROM t WHERE intDiv(a, toInt8(-56)) IN (1,2);   -- ok: 72
SELECT count() FROM t WHERE intDiv(a, toUInt8(200)) IN (1,2);  -- Aborted (core dumped)

it's pre-existing on master (the signed-dividend fallthrough is unchanged here), so this is an incomplete fix rather than a regression — but worth closing the sibling case: derive is_constant_positive from the effective (signed-reinterpreted) divisor, or reject isInt(dividend) && isUInt(divisor) with the high bit set, plus a regression test.

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.

Confirmed and fixed in 43748f3. intDiv(Int8, toUInt8(200)) is numerically intDiv(Int8, toInt8(-56)), which master already prunes correctly as monotonic decreasing, so the principled fix is option 1: derive the direction from the effective divisor rather than reject the case.

DivideIntegralImpl reinterprets the divisor via SignedCastB only when sizeof(dividend) <= sizeof(divisor); with a wider dividend the divisor widens into the signed dividend type and stays positive. New helper intDivConstReinterpretsNegative mirrors that exact gate (signed dividend, unsigned divisor, sizeof(dividend) <= sizeof(divisor), high bit set) and flips is_constant_positive to false. No discontinuity here (the signed dividend is never reinterpreted), so the function stays fully monotonic, only its direction reverses, and pruning is preserved.

04340 now covers the mirror case at widths 8/16/32, a high-bit-not-set case (no flip), and a sizeof(dividend) > sizeof(divisor) no-flip case. Validated on a debug build: your repro aborts on the old binary and returns 72 on the new one; NOT IN and read-in-order (DESC keeps intDiv in prefix sort) confirm the decreasing direction.

…wrong direction

The prior fix handled intDiv(unsigned_dividend, signed_integer_const), where
DivideIntegralImpl reinterprets the dividend as signed and the function becomes
a step function with a discontinuity at 2^(width-1).

The symmetric operand config is also wrong and pre-exists on master: with a
signed dividend and an unsigned constant divisor whose high bit is set,
DivideIntegralImpl reinterprets the divisor through make_signed_t of the wider
operand (SignedCastB when sizeof(dividend) <= sizeof(divisor)), so e.g.
toUInt8(200) becomes -56 and intDiv is monotonic decreasing. But
is_constant_positive is read from the raw unsigned constant (0 < 200 -> true),
so the chain is reported increasing, KeyCondition builds a Range with left > right,
and MergeTreeSetIndex::checkInRange aborts with "Invalid binary search result in
MergeTreeSetIndex" (debug) / silently mis-prunes (release).

Repro on a debug build (the two queries differ only in the divisor's declared
type, same effective value -56):
  CREATE TABLE t (a Int8) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1;
  INSERT INTO t SELECT number-127 FROM numbers(255);
  SELECT count() FROM t WHERE intDiv(a, toInt8(-56)) IN (1,2);   -- ok: 72
  SELECT count() FROM t WHERE intDiv(a, toUInt8(200)) IN (1,2);  -- Aborted

Fix at the source: when the divisor reinterprets as negative
(intDivConstReinterpretsNegative), derive the direction from the effective
signed value. The signed dividend is never reinterpreted, so there is no
discontinuity and the function stays fully monotonic; only its direction is
reversed. This makes intDiv(Int8, toUInt8(200)) behave identically to the
equivalent intDiv(Int8, toInt8(-56)), preserving key/read-in-order pruning.
The flip only occurs for sizeof(dividend) <= sizeof(divisor); otherwise the
divisor widens into the dividend's signed type and stays positive.

Extends regression test 04340 with the mirror case at widths 8/16/32, a
high-bit-not-set case, and a sizeof(dividend) > sizeof(divisor) no-flip case.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD 43748f3, mirror-case fixup)

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a Int8) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1; INSERT INTO t SELECT number-127 FROM numbers(255); SELECT count() FROM t WHERE intDiv(a, toUInt8(200)) IN (1,2); aborts every time on the pre-fix binary (SIGABRT, Invalid binary search result in MergeTreeSetIndex, Set.cpp:812).
b Root cause explained? ResultOfIntegerDivision<Int8,UInt8> is signed. DivideIntegralImpl reinterprets the divisor through make_signed_t of the wider operand (SignedCastB when sizeof(dividend) <= sizeof(divisor)), so toUInt8(200) becomes -56 and intDiv is monotonic decreasing. But is_constant_positive was read from the raw unsigned constant (0 < 200 -> true), so the chain was reported increasing, KeyCondition built a Range with left > right, and MergeTreeSetIndex::checkInRange violated std::partition_point.
c Fix matches root cause? Yes. New helper intDivConstReinterpretsNegative mirrors DivideIntegralImpl's exact gate (signed dividend, unsigned divisor, sizeof(dividend) <= sizeof(divisor), high bit set) and derives the correct direction by flipping is_constant_positive. Not a band-aid: the signed dividend is never reinterpreted, so there is no discontinuity, the function stays fully monotonic, and pruning is preserved (option 1, not reject).
d Test intent preserved / new tests added? Yes. 04340 extended with the mirror case at widths 8/16/32, a high-bit-not-set case (no flip), and a sizeof(dividend) > sizeof(divisor) no-flip case. Existing unsigned-dividend and Float-divisor assertions unchanged.
e Both directions demonstrated? Yes. The repro aborts on the pre-fix binary (Build ID 83892bcade) and returns the correct count 72 on the post-fix binary (Build ID 6819dfe3db). NOT IN matches ground truth and read-in-order keeps intDiv in the prefix sort under DESC (decreasing direction confirmed). 04340 passes 30/30 under randomization; 04073/00940 unchanged.
f Fix is general, not a narrow patch? Yes. Both getMonotonicityForRange branches (finite-range and unbounded null-endpoint) get the same guard. The helper handles all integer width pairs and the sizeof widening rule exactly as DivideIntegralImpl does, so the same algebra is covered for every Int/UInt combination, not just Int8/UInt8.

Session id: cron:clickhouse-worker-slot-4:20260618-012900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 43748f3e4bc8. The two red checks are not caused by this PR:

  • Stress test (arm_tsan) / "Hung check failed, possible deadlock found": chronic trunk Hung-check deadlock (leaked local ThreadPool family), seen on master and ~20 unrelated PRs in the last 30 days. Tracked separately; unrelated to the getMonotonicityForRange change.
  • Bugfix validation (functional tests): the job itself is green (COMPLETED/SUCCESS). The "Lost s3 keys / OOM in dmesg / Lost forever for SharedMergeTree / S3_ERROR / Exception in test runner" rows are SharedMergeTree+S3 harness noise inside a passing job.

The targeted cases (unsigned-dividend wrap, Float-divisor, and the mirror signed-dividend/unsigned-divisor case) all pass; functional and style checks are green.

@tiandiwonder

Copy link
Copy Markdown
Contributor

@groeneai plese check CI failures and merge with latest master if needed.

@tiandiwonder
tiandiwonder added this pull request to the merge queue Jul 21, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 21, 2026
groeneai added 2 commits July 21, 2026 08:13
Master PR ClickHouse#94681 (operators-as-functions) renders intDiv as the DIV
operator in the new EXPLAIN plan formatter, so intDiv(a, 10.0) shows as
a DIV 10. in the sort description. The two read-in-order assertions
matched the literal substring Prefix sort description: intDiv, which no
longer appears, flipping them to 0 in the merge queue. The WHERE explain
LIKE '%Prefix sort description%' filter already isolates the prefix sort
line, so count the filtered rows instead: 1 when read-in-order keeps
intDiv monotonic, 0 otherwise. Rendering-agnostic, reference unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged latest master and fixed the merge-queue failure, which was our own test 04340_intdiv_variable_constant_monotonicity over-specifying an EXPLAIN string.

Root cause: master #94681 (operators-as-functions) now renders intDiv as the DIV operator in the new EXPLAIN plan formatter, so intDiv(a, 10.0) prints as a DIV 10. in the sort description. The two read-in-order assertions matched the literal substring Prefix sort description: intDiv, which no longer appears, so they flipped to 0. The pruning-count assertions were unaffected, so the monotonicity fix itself is intact. The WHERE explain LIKE '%Prefix sort description%' filter already isolates the prefix-sort line, so I now count the filtered rows instead of matching the function spelling: 1 when read-in-order keeps intDiv monotonic, 0 otherwise. Rendering-agnostic, .reference unchanged.

Verified on the merged tree (head aaa1cf8): the #90461 UInt64-wrap repro, Float-divisor, and mirror signed/unsigned cases all still correct; 0 failures across 15 randomized query/MergeTree setting profiles; sibling 00940/02911 references unchanged (they use explain_query_plan_default='legacy', which keeps the intDiv(...) call form).

intDiv by a Decimal constant computes in the decimal native signed width
(DecimalBinaryOperation feeds both operands into
DivideIntegralImpl<NativeResultType, NativeResultType>), casting the dividend
into that width and pre-multiplying by the scale. A UInt64 dividend >= 2^63
reinterprets as negative there, and a signed dividend >= 2^(native_width-1)
truncates/wraps too, at a boundary that depends on the decimal width and
scale, not on the dividend width. The old guard gated on isInt(divisor_type),
which is false for Decimal, so intDiv(key, Decimal_const) fell through to
always-monotonic and key analysis built a reversed Range: Invalid binary
search result in MergeTreeSetIndex in debug, silent over-pruning in release.
Report intDiv by a Decimal divisor as non-monotonic in both the finite-range
and null-endpoint branches.

Author: Groene AI <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand) — HEAD 0860227
# Check Result
a Deterministic repro? Yes. intDiv(UInt64, toDecimal64(1e18,0)) IN (9) prunes 0 of 2 rows (silent over-prune) and NOT IN aborts with Invalid binary search result in MergeTreeSetIndex (SIGABRT) on the pre-fix binary (Build ID ad21c1292e).
b Root cause explained? Decimal intDiv computes in the decimal native signed width via DecimalBinaryOperation -> DivideIntegralImpl<NativeResultType,NativeResultType>, casting the dividend into that width and pre-multiplying by scale. A UInt64 >= 2^63 (or a signed value >= 2^(native_width-1)) reinterprets negative, so the function is non-monotonic. The old guard gated on isInt(divisor_type), false for Decimal, so it fell through to always-monotonic and built a reversed Range.
c Fix matches root cause? Yes. Reports intDiv by a Decimal divisor as non-monotonic in both the finite-range and null-endpoint branches, so key analysis never assumes ordering across the wrap.
d Test intent preserved / new tests added? Existing 19 assertions unchanged. Added 4: intDiv(UInt64,Decimal64) IN+NOT IN, signed-dividend narrow-decimal sibling intDiv(Int64,Decimal32), and Decimal-dividend positive (must still prune).
e Demonstrated in both directions? Yes. Pre-fix: over-prune + SIGABRT. Post-fix (Build ID e02c6245899a): pruned==ground for all cases, no abort; full 04340 = reference (23/23).
f Fix general, not a narrow patch? Yes. Covers both branches and both operand-sign siblings (unsigned dividend AND signed-dividend narrow-decimal), not just the one reported UInt64/Decimal64 shape.
g Generalizes across inputs/wrappers? Verified across Decimal32/64/128/256 divisors and UInt8/16/32/64, Int64 dividends; scale>0 (incl. DECIMAL_OVERFLOW); Decimal dividend + int divisor still prunes; const/variable intDiv(const, Decimal_key) unaffected.
h Backward compatible? Yes. No setting/format change. Only removes an unsafe monotonicity claim (disables incorrect pruning); no user-visible behavior change beyond correct results.
i Invariants/contracts preserved? Yes. Upholds the MergeTreeSetIndex binary-search invariant (left <= right in every built Range); divide (Float) path and integer-divisor paths untouched.

Robustness: 0 failures / 8 randomized query-setting profiles; deterministic (not flaky).

Session id: cron:clickhouse-maint-slot-9:20260721-100001

divide by a Decimal constant takes the same integral-division path as
intDiv: DecimalBinaryOperation substitutes DivideIntegralImpl<NativeResultType,
NativeResultType> for divide as well and casts the dividend into the decimal's
native signed width, so divide(UInt64, Decimal64) reinterprets a UInt64 dividend
>= 2^63 as negative and is non-monotonic across that boundary exactly like intDiv.
The previous guard only rejected intDiv by a Decimal divisor, so a divide by a
Decimal divisor still reported always-monotonic, letting key analysis build a
reversed Range and abort with Invalid binary search result in MergeTreeSetIndex
(or silently over-prune in release).

Widen both getMonotonicityForRange guards (finite-range and null-endpoint) to
fire for divide as well as intDiv. A Float divisor is unaffected (it computes
through floating point, result Float64, and stays monotonic); a Decimal dividend
with an integer divisor is unaffected (only a Decimal divisor is rejected).

Add divide-by-Decimal regression cases to 04340: UInt64/Decimal64 IN and NOT IN,
the Int64/Decimal32 sibling, a divide-by-Float still-prunes guard, and a
Decimal-dividend still-prunes guard.
@groeneai

groeneai commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand) - HEAD 7c528a2
# Question Answer
a Deterministic repro? Yes. On the pre-fix binary (Build ID e02c6245): divide(a, toDecimal64(1000000000000000000,0)) IN (9) over UInt64 values straddling 2^63 gives pruned=0 vs ground=2; NOT IN (0,1) throws Invalid binary search result in MergeTreeSetIndex (aborts, EXIT=134, debug).
b Root cause explained? For a Decimal divisor DecimalBinaryOperation substitutes DivideIntegralImpl<NativeResultType, NativeResultType> for both divide and intDiv, casting the dividend into the decimal's signed native width. A UInt64 dividend >= 2^63 reinterprets as negative, so the function is non-monotonic across 2^63, but getMonotonicityForRange reported always-monotonic for divide (the guard only rejected intDiv), building a reversed Range.
c Fix matches root cause? Yes. Both isDecimal(divisor_type) guards (finite-range and null-endpoint) now fire for divide as well as intDiv, reporting non-monotonic and disabling unsafe pruning. Mirrors DivideIntegralImpl's integral-division substitution exactly.
d Test intent preserved / new tests added? Added 4 divide-Decimal regression cases to 04340 (UInt64/Decimal64 IN+NOT IN, Int64/Decimal32 sibling) plus 2 preservation cases with EXPLAIN indexes = 1 granule assertions proving pruning stays enabled for a Float divisor and a Decimal dividend. Existing 24 assertions unchanged.
e Both directions demonstrated? Yes. Pre-fix (e02c6245): over-prune + SIGABRT. Post-fix (0e31bd97): pruned==ground (2=2, 4=4), no abort; full 04340 30/30 identical to reference.
f Fix is general across code paths? Yes. Both monotonicity branches covered. intDiv/divide are the only division functions in hasInformationAboutMonotonicity; divideOrZero/intDivOrZero never reach getMonotonicityForRange (verified: no abort), so the Decimal-divisor class is closed.
g Fix generalizes across inputs? Yes. Verified UInt64/Decimal64 and the signed-dividend Int64/Decimal32 sibling (compute width = decimal native width). Float divisor (result Float64) and Decimal dividend + int divisor stay monotonic and keep pruning (EXPLAIN-verified).
h Backward compatible? N/A. No setting, format, or default change. Only disables an unsafe key-analysis optimization for one operand class (correctness fix); worst case is a full scan instead of a wrong result / abort.
i Invariants and contracts preserved? Yes. Restores the MergeTreeSetIndex binary-search invariant (Range left <= right) for divide-by-Decimal. getMonotonicityForRange now returns non-monotonic where the function truly is; the monotonic Float / Decimal-dividend paths are untouched and still prune.

Session id: cron:clickhouse-maint-slot-8:20260721-114400

/// which always places `D` strictly inside. Endpoint comparison of the transformed values cannot
/// detect this because both endpoints can map to the same output while the interior jumps.
/// `arg_type` is the unsigned dividend type (already stripped of Nullable/LowCardinality).
static bool intDivRangeCrossesSignedWrap(const DataTypePtr & arg_type, const Field & left_point, const Field & right_point)

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 helper still misses the INT_MIN / -1 exception point. For intDiv(UInt8_key, toInt16(-1)), D = 128 is not only the first reinterpreted negative value; static_cast<Int8>(128) is -128, so intDiv(128, -1) throws ILLEGAL_DIVISION. Because the guard here only rejects left < D <= right, ranges that merely touch D on the reinterpreted side still fall through as monotonic.

That becomes user-visible on open key ranges, because applyMonotonicFunctionsChainToRange ignores bound inclusiveness and applies the function to the stored endpoint value. A predicate like a > 128 AND intDiv(a, toInt16(-1)) IN (...) has the actual row domain 129..255 (fully defined), but key analysis still tries intDiv(128, -1) while transforming the open left bound and throws before scanning rows. The same corner exists in the new intDivConstReinterpretsNegative path for all-ones unsigned divisors such as toUInt8(255).

Please treat effective divisor -1 as an extra monotonicity breaker whenever the closed approximation of the range touches the reinterpreted INT_MIN point, or otherwise avoid applying excluded endpoints, and add a focused regression around a > 128 / a > -128.

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.

Verified on the current HEAD build. The ILLEGAL_DIVISION throw reproduces (a > 128 AND intDiv(a, toInt16(-1)) IN (0) fails at key-analysis time), but it is pre-existing on master and out of scope for this PR:

  • The raw signed spelling intDiv(Int8, toInt8(-1)) hits none of this PR's guards (signed/signed falls straight through to the unchanged master variable / constant return {true, is_constant_positive, true}) and throws identically.
  • intDiv(INT_MIN, -1) throws at runtime as well, and the same predicate on a Memory table (no key analysis) returns rows with no throw. So the defect is applyMonotonicFunctionsChainToRange transforming an excluded closed-range endpoint, not the monotonicity classification in getMonotonicityForRange.

The "avoid applying excluded endpoints" fix belongs in KeyCondition; a -1-touches-INT_MIN special case here would miss the raw signed spelling and over-reject valid pruning. Tracking the pre-existing endpoint-transform bug separately rather than widening this PR.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 37/40 (92.50%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7c528a2

CI fully finished (Finish Workflow pass; 0 checks queued/in-progress). New head (pushed today after the Decimal-divisor CR fix) since the 2026-07-03 ledger. One failure, not caused by this PR's diff (an intDiv KeyCondition false-monotonicity fix).

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / Cannot start clickhouse-server + Check failed server-boot on restart: Code 246 t_plt_reparent "Part all_2_3_1_0 intersects previous part all_1_2_2_1, transaction metadata could not be read" (part_loading_tree_rollback poisoned-detached-table restart, chronic PR #100992 regression) fixing PR #110999 (ours, on_review)
Mergeable Check / PR rollup of the above owned via the row above

Session id: cron:our-pr-ci-monitor:20260721-190000

@tiandiwonder
tiandiwonder added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit 99b066d Jul 22, 2026
177 of 179 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 Jul 22, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 31, 2026
…rge constant divisor

intDiv and divide with a Decimal dividend compute in the decimal's own
native signed width (DecimalBinaryOperation::NativeResultType) and
materialise the constant divisor into that width with static_cast. For
Decimal(5, 4) that width is Int32, so intDiv(a, -9223372036854775807)
actually divides by 1 and increases.

getMonotonicityForRange derived the direction from the untruncated
literal and reported decreasing, and its only Decimal guard tested the
divisor, which is the wrong operand for this shape. Key analysis then
called Range::invert() on a range whose values never reversed, so
left > right. For a set atom MergeTreeSetIndex::checkInRange then gets
begin > end and hits its debug-only assertion, reported by the AST
fuzzer as STID 3252-3a4a. For a range atom there is no assertion at
all, so every matching granule is pruned away and the query silently
returns wrong results in release builds too: on Decimal(5, 4) data
holding 0..9, WHERE intDiv(a, -9223372036854775807) > 4 returned 0 rows
where 5 match.

Add one shared predicate, decimalDivConstDivisorTruncates, and call it
from both variable / constant branches of getMonotonicityForRange. The
second branch handles ranges with an infinite endpoint, which
forAnyHyperrectangle produces routinely, so a fix applied only to the
finite-endpoint branch leaves those exposed; a mutant that removes the
call from the infinite branch alone still reddens two of the new test
arms. The predicate is a round-trip test rather than a blanket
rejection, so intDiv(decimal_col, small_const) keeps its pruning, and
it is gated on an integer divisor because a Float divisor converts both
operands to Float64 and stays order preserving.

The defect does not depend on the literal's sign: a positive
9223372036854775807 casts to Int32 -1, so the function decreases while
the claim says it increases, and that fails the same way. Both
directions are covered by test arms, as are all the invariant carriers:
divide as well as intDiv, both checkInRange overloads, IN and NOT IN,
range atoms as well as set atoms, ascending and DESC keys, and the
wider Decimal widths where the same constant survives the cast.

This is the third defect of this family, after ClickHouse#107586 and ClickHouse#113048;
ClickHouse#112156 fixed the mirror case of a constant dividend.

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

Fix false monotonicity of intDiv(unsigned, constant) causing Invalid binary search result in MergeTreeSetIndex
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-bugfix Pull request with bugfix, not backported by default 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