Skip to content

Fix wrong results for intDiv by an effective -1 in key analysis - #112151

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-intdiv-minus-one-monotonicity
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-intdiv-minus-one-monotonicity

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #90461

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

Fixes wrong results for queries where a MergeTree primary key expression is wrapped in intDiv with an effective divisor of -1. intDiv(x, -1) maps the signed minimum of the computation width onto itself instead of onto the maximum, so it is not monotonic on any range containing that minimum, but it was reported as monotonic. Primary-key analysis therefore pruned a granule that did hold a matching row, and ORDER BY intDiv(x, -1) returned mis-sorted rows through the read-in-order optimization. Both now return correct results.

Description

intDiv(x, -1) is mathematically -x, which is not representable at the signed minimum of the computation width: TYPE_MIN / -1 overflows and folds back onto TYPE_MIN, while TYPE_MIN + 1 maps to TYPE_MAX. The function is therefore neither non-decreasing nor non-increasing on any range containing that minimum.

FunctionBinaryArithmeticWithConstants::getMonotonicityForRange already models two other intDiv wraps (intDivRangeCrossesSignedWrap for an unsigned dividend, intDivConstReinterpretsNegative for an unsigned divisor) but never modelled this result wrap, so it reported the function monotonic there. multiply already carries the equivalent guard in its check_overflow lambda (/// TYPE_MIN / -1 is UB for native signed types.); intDiv simply lacked it.

Two user-visible, silent, default-reachable symptoms (no error, RC=0):

CREATE TABLE t (a Int64) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;
INSERT INTO t VALUES (-9223372036854775808), (-9223372036854775807), (-5), (5);

-- primary-key pruning drops the matching row
SELECT count() FROM t WHERE intDiv(a, toInt64(-1)) = toInt64(-9223372036854775808);
-- before: 0   after: 1   (ENGINE = Memory, which runs no key analysis, returns 1)

-- ORDER BY returns mis-sorted rows via read-in-order
SELECT intDiv(a, toInt64(-1)) FROM t ORDER BY intDiv(a, toInt64(-1));
-- before: -5, 5, MAX, MIN   after: MIN, -5, 5, MAX

The fix adds three helpers next to the existing ones and two guards in each of the two branches that decide intDiv's monotonicity:

  • intDivWrapsInsteadOfThrowing — is this operand pair one that divides by an effective -1 and takes the FPE-suppressing vectorized path? The wrap is produced only by DivideIntegralByConstantImpl::vectorConstant, which short-circuits b == -1 and deliberately avoids throwIfDivisionLeadsToFPE. With a signed dividend those registered specializations are an Int32/Int64 dividend with a native signed divisor. Every other scalar operand pair throws ILLEGAL_DIVISION instead — at runtime as well as during analysis, verified on ENGINE = Memory — so it is not a monotonicity problem and is deliberately left alone here.
  • intDivCompoundDividendWrapsInsteadOfThrowing — the same wrap one type wrapper up. An Array/Tuple dividend divided by a scalar constant is evaluated element-wise, so an element type that wraps carries the same defect, while getMonotonicityForRange sees only the outer type and the scalar predicate above cannot detect it. Nesting is followed recursively, and a tuple is a carrier as soon as any one of its elements is. Measured carriers: Array(Int64), Array(Int32), Array(Array(Int64)), Array(LowCardinality(Int64)), Tuple(Int64, Int64) and the mixed Tuple(Int64, Int8) — each returned the wrong count() and a mis-sorted ORDER BY before this change. A compound dividend with a Float, Int128 or high-bit-unsigned divisor throws ILLEGAL_DIVISION and is not a carrier. Because the endpoints are Array/Tuple Fields whose element-wise containment of the wrap point is not cheaply modelled, a compound carrier is reported non-monotonic unconditionally, mirroring the Decimal-divisor case immediately above.
  • intDivRangeContainsResultWrapPoint — does the analysed range contain that minimum? Decided per side, so a range like [0, +Inf) genuinely excludes it and keeps being pruned.

A range containing the wrap point now reports {false, true, false, false} (non-monotonic, no pruning), exactly as multiply does on overflow. A range excluding it stays monotonic on that range, but is_always_monotonic becomes false: it means "monotonic on the whole input range", and the whole domain of a signed type always contains its minimum.

Cost, stated explicitly

The unbounded-endpoint verdict is what ReadInOrderOptimizer reads, and it has no range to narrow with, so ORDER BY intDiv(x, -1) loses the read-in-order optimization even when the minimum is absent from the data (measured: such a query uses InReverseOrder today and Default after this change). That is unavoidable at this layer — the whole column may contain the minimum and the unbounded probe cannot know — and it is the same trade intDivRangeCrossesSignedWrap already makes for unbounded unsigned ranges. It is a deliberate correctness-over-optimization choice, not a free fix.

Ordinary intDiv pruning is unaffected, and the test asserts that: a positive divisor, a divisor that is not effectively -1, unsigned/unsigned, a Float divisor, a half-bounded range excluding the minimum, and a single-point range at the minimum all keep pruning exactly as before, with the granule counts pinned — ten EXPLAIN indexes = 1 assertions in all, including two that pin an Array dividend with a positive divisor and an Array(UInt8) dividend, so the new compound guard is provably keyed on the element type and the constant rather than on "is compound".

Deliberately out of scope

  • Code 153 throws at other widths. No verdict this function can return fixes them. If the analysed range excludes the minimum a correct guard must report the range monotonic (otherwise valid pruning is lost), and KeyCondition::applyFunction then evaluates the chain over the entire index column, so an out-of-range minimum still in that column still throws. If the analysed range contains the minimum at a throwing width, the query throws at runtime too (the ENGINE = Memory oracle exits with the same error), so it was never analysis-injected. Same reason single_point partition pruning is untouched: applyMonotonicFunctionsChainToRange short-circuits monotonicity when single_point, so nothing inside getMonotonicityForRange can reach it.
  • The two sibling intDiv predicates read the outer dividend type too. intDivRangeCrossesSignedWrap gates on isUInt(arg_type) and intDivConstReinterpretsNegative on isInt(arg_type) && isUInt(divisor_type), so an Array/Tuple dividend fails both exactly as it failed the scalar wrap predicate before this change. They model different mechanisms (a step function at 2^(w-1) for an unsigned dividend, and a direction flip for a high-bit-unsigned divisor), so extending them is a separate concern with its own root cause and its own test matrix, and is tracked separately rather than bundled here.
  • Two further defects found while investigating this one, each with its own root cause and therefore its own PR rather than being bundled here: the const / variable branch reports the inverted direction on a strictly-negative range (wrong results for intDiv and divide, no wrap involved), and throwIfDivisionLeadsToFPE compares a floating-point dividend against numeric_limits<Float>::min(), which is the smallest positive value, so intDiv(2.2250738585072014e-308, -1.0) throws spuriously.

groeneai and others added 2 commits July 27, 2026 10:31
…nalysis

intDiv(x, -1) is mathematically -x, which is not representable at the
signed minimum of the computation width: TYPE_MIN / -1 overflows and folds
back onto TYPE_MIN, while TYPE_MIN + 1 maps to TYPE_MAX. The function is
therefore neither non-decreasing nor non-increasing on any range containing
that minimum.

getMonotonicityForRange already models two other intDiv wraps
(intDivRangeCrossesSignedWrap for an unsigned dividend,
intDivConstReinterpretsNegative for an unsigned divisor) but never modelled
this result wrap, so it reported the function monotonic there. MergeTree
primary-key analysis then pruned a granule that did hold a matching row, and
ReadInOrderOptimizer, which probes with unbounded endpoints and reads only
is_monotonic/is_positive, read the part in reverse order and emitted
mis-sorted rows. Both symptoms are silent: no error, and the query succeeds.

multiply already carries the equivalent guard in its check_overflow lambda;
intDiv simply lacked it.

The reason these widths are silent rather than a Code 153 throw is that
DivideIntegralByConstantImpl::vectorConstant short-circuits b == -1 and
deliberately bypasses throwIfDivisionLeadsToFPE. That specialization is
registered only for (UInt64|UInt32|Int64|Int32) by a divisor of the same
signedness, so with a signed dividend the affected set is exactly an
Int32/Int64 dividend with a native signed divisor. Every other operand pair
throws instead, at runtime as well as during analysis, so it is not a
monotonicity problem and is left alone here.

Two helpers are added next to the existing ones, and one guard in each of the
two branches that decide intDiv's monotonicity. The containment test is
decided per side, so a half-bounded range such as [0, +Inf) genuinely excludes
the minimum and keeps being pruned. A range excluding the minimum stays
monotonic on that range, but is_always_monotonic becomes false: it means
monotonic on the whole input range, and the whole domain of a signed type
always contains its minimum.

Cost: the unbounded-endpoint verdict is what ReadInOrderOptimizer reads, and
it has no range to narrow with, so ORDER BY intDiv(x, -1) loses read-in-order
even when the minimum is absent from the data. That is unavoidable at this
layer and is the same trade intDivRangeCrossesSignedWrap already makes for
unbounded unsigned ranges.

Co-Authored-By: Claude Fable 5 <[email protected]>
… minimum

An Array/Tuple dividend divided by a scalar constant is evaluated
element-wise: executeArrayWithNumericImpl and tupleIntDivByNumber unpack to
the element type and re-enter the arithmetic, so the DivideIntegralByConstantImpl
specialization is selected per ELEMENT. An element type that wraps instead of
throwing therefore carries exactly the same defect as the scalar case.

getMonotonicityForRange only ever sees the OUTER dividend type, so the scalar
predicate could not detect it: hasInformationAboutMonotonicity gates on the
function name alone, and BinaryArithmeticOverloadResolver builds the
WithConstants specialization from "one argument is a constant" with no type
test at all. An Array(Int64) key therefore fell through to the unchanged
always-monotonic verdicts and stayed mis-pruned.

Measured carriers, each returning the wrong count() and a mis-sorted ORDER BY
against an ENGINE=Memory oracle: Array(Int64), Array(Int32),
Array(Array(Int64)), Array(LowCardinality(Int64)), Tuple(Int64, Int64) and the
mixed Tuple(Int64, Int8). A compound dividend with a Float, Int128 or
high-bit-unsigned divisor throws ILLEGAL_DIVISION rather than wrapping and is
not a carrier; Map, Array(Nullable(...)) and a compound divisor are rejected
earlier.

A compound carrier is reported non-monotonic unconditionally. The endpoints
are Array/Tuple Fields whose element-wise containment of the wrap point is not
cheaply modelled, mirroring the Decimal-divisor case immediately above, and no
width is ever derived from a compound type.

Also pin the granule counts for the three preserved-pruning cases that were
result-only (a single-point range at the minimum and both unsigned/unsigned
cases), so a change that silently stopped pruning them can no longer ship
green, and finish a stale comment correction in the sibling bounded branch.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 2 review rounds, 8 findings, all adjudicated (click to expand)

Before opening this PR I reviewed it independently (a cold reviewer that never edits the code, plus a
separate second-model gate) over two rounds and one fix round. Every finding is listed with its
verdict and the evidence the verdict rests on. Round 1 found a blocker and a major and the PR was
sent back; round 2 came back clean.

Totals: 8 findings — 1 blocker, 1 major, 6 nits. All 8 were accepted, none disputed. The two
substantive items were fixed in the code; the six nits were metadata or disclosure corrections to
this description.

❌ Blocker (round 1, fixed in the second commit)

The carrier predicate was scalar-only, so a compound dividend stayed mis-pruned.
intDivWrapsInsteadOfThrowing opened on the OUTER dividend type, so an Array(Int32/Int64) or
Tuple(..., Int64, ...) key skipped both new guards and fell through to the unchanged
always-monotonic verdicts. hasInformationAboutMonotonicity gates on the function name alone and the
overload resolver builds the WithConstants specialization from "one argument is constant" with no
type test, while the element-wise handling lives in executeImpl — so getMonotonicityForRange
never sees an element type, and the specialization that wraps is selected per ELEMENT.

Measured, keyed count() vs an ENGINE = Memory oracle on the same data: Array(Int64),
Array(Int32), Array(Array(Int64)), Array(LowCardinality(Int64)), Tuple(Int64, Int64) and the
mixed Tuple(Int64, Int8) all returned 0 against oracle 1, plus a mis-sorted ORDER BY, on the
first commit exactly as on master. A compound dividend with a Float, Int128 or high-bit-unsigned
divisor throws ILLEGAL_DIVISION and is not a carrier; Map, Array(Nullable(...)) and a compound
divisor are rejected earlier. Fixed by a third helper that unwraps Array/Tuple recursively and
applies the unchanged scalar predicate per element, with the shipped comment's "every other operand
pair throws" universal narrowed to scalar pairs.

The remedy returns non-monotonic unconditionally for a compound carrier rather than deciding
containment per element — not a shortcut: getSizeOfValueInMemory raises for a container type, and
comparing an Array/Tuple Field against an integer Field raises BAD_TYPE_OF_FIELD, so a
per-element attempt inside this function would be an exception on a valid query.

⚠️ Major (round 1, fixed in the second commit)

Three of the six advertised preservation cases were result-only, so this description promised
granule counts it did not pin.
A result comparison cannot see lost pruning — a full scan returns
the same count — and the broadest mutation ("intDiv is never monotonic") reached none of the three.
Fixed by widening those fixtures so a non-matching predicate has marks to reject and pinning
Granules: 0/8, 2/256 and 2/67; the EXPLAIN indexes = 1 assertion count went from 5 to 10.

Half of that finding was refuted and recorded so it was not acted on: the affected assertions are
not vacuous. Mutating the guard away fails all 11 count rows, mutating only the Int32 gate fails
exactly the four Int32 rows, and the ORDER BY row compares keyed output against the oracle, so a
plan that does not read in reverse produces the oracle order and the row passes only when the answer
is correct.

💡 Nits — all corrected in this description or in a comment

  • The helper bullet list said "two helpers ... one guard" and kept the pre-round universal "every
    other operand pair throws", both falsified by the compound fix. Corrected, with the third helper
    and its measured carrier list added.
  • The granule promise is now checkable (it states the assertion count and names the two Array
    over-fire controls that prove the compound guard is keyed on the element type, not on
    "is compound").
  • The two sibling intDiv predicates (intDivRangeCrossesSignedWrap,
    intDivConstReinterpretsNegative) read the outer dividend type too, so they share the same
    blindness. They model different mechanisms and are tracked separately rather than bundled here —
    now disclosed under "Deliberately out of scope" instead of left implicit.
  • A stale comment correction had been applied to only one of the two symmetric sibling branches; both
    now agree. The surviving Float sentence was deliberately kept, because the compound measurement
    says it is still true.
  • The title was shortened to 63 characters and the changelog entry rewritten in the present tense per
    docs/changelog_entry_guidelines.md.

Verification the rounds rest on

Both directions per case on two Build-ID-verified binaries; the committed test fails by assertion
with 19 diverging rows on a pristine master server while every preservation row passes there (which
is what proves the granule assertions pin pre-existing behaviour) and is [ OK ] on the fixed build.
An 8-mutation matrix maps each mutation to the exact row set it breaks, including an over-fire
control; the restore rebuilt bit-identically. 50 randomized runs, 0 failures.

One mutation is worth reporting because it failed harder than predicted: removing the compound guard
from only the unbounded-endpoint branch does not merely mis-sort — matchesExactContinuousRange()
probes with unbounded endpoints and requires is_always_monotonic, so it then contradicts the
truthful bounded branch and raises Inconsistent KeyCondition behavior. The two guards belong
together, and that is now measured rather than assumed.

Session id: cron:clickhouse-review-slot-11:20260727-162500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% deterministic, no randomization needed. CREATE TABLE t (a Int64) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1; INSERT INTO t VALUES (-9223372036854775808),(-9223372036854775807),(-5),(5); SELECT count() FROM t WHERE intDiv(a, toInt64(-1)) = toInt64(-9223372036854775808); returns 0 on master and 1 after the fix; the ENGINE=Memory twin (no key analysis) returns 1 both times. RC=0 in every direction — the defect is a silent wrong answer, never an error.
b Root cause explained? Yes. intDiv(x, -1) is mathematically -x, which is unrepresentable at the signed minimum of the computation width: TYPE_MIN / -1 overflows and folds back onto TYPE_MIN while TYPE_MIN + 1 maps to TYPE_MAX, so the function is neither non-decreasing nor non-increasing on any range containing that minimum. FunctionBinaryArithmeticWithConstants::getMonotonicityForRange decided variable / constant monotonicity from the divisor's sign alone — it already modelled two other intDiv wraps (intDivRangeCrossesSignedWrap, intDivConstReinterpretsNegative) but never this result wrap — so it reported the function monotonic. Key analysis then pruned a granule holding a matching row, and ReadInOrderOptimizer (unbounded probe, reads only is_monotonic/is_positive) read the part in reverse and emitted mis-sorted rows. These widths are silent rather than Code 153 because DivideIntegralByConstantImpl::vectorConstant short-circuits b == -1 and deliberately bypasses throwIfDivisionLeadsToFPE.
c Fix matches root cause? Yes. The missing result-wrap model is added in the same function that already owns intDiv's two other wrap models, mirroring the guard multiply already carries in its check_overflow lambda (/// TYPE_MIN / -1 is UB for native signed types.). Not a widened bound, not a no-random-* tag, not a data-size reduction, not a guard at the prune/crash site.
d Test intent preserved / new tests added? Yes. No existing test is weakened or modified. New stateless test 04648_intdiv_minus_one_monotonicity: 45 reference lines = 17 wrong-result carrier rows, 2 ORDER BY carrier rows, and 23 control rows asserting the optimization is PRESERVED where the guard must not fire, of which 10 are EXPLAIN indexes = 1 granule assertions and 3 pin the read-in-order type — so a "safe fallback that quietly disables intDiv pruning" would fail. Every carrier and every control is a measured single-purpose detector: an 8-mutation matrix maps each mutation to the exact row set it breaks (h -> the 7 compound rows, h_bounded -> the 6 compound counts, h_nullep -> aborts, h_tuple -> the 2 Tuple rows, h_nested -> the nested-Array row, h_wide -> the 2 compound preservation granule rows, d -> 12 preservation rows, i -> the single-point granule row).
e Both directions demonstrated? Yes. Per-case on two Build-ID-verified binaries — unfixed master snapshot 9ebd11fe9bc8d547 (whose copy of the changed file is md5-identical to the merge-base) vs fixed 497737591e7b6eff — every carrier goes keyed 0 -> 1 with the oracle constant at 1, and the ORDER BY results go [-5,5,MAX,MIN] -> [MIN,-5,5,MAX] (scalar) and [[-5],[5],[MAX],[MIN]] -> [[MIN],[-5],[5],[MAX]] (compound). At test level: the committed test run against a server on pristine master FAILS by assertion with 19 diverging rows (11 scalar counts, 6 compound counts, both ORDER BY rows) while every preservation row PASSES there — which is what proves the granule assertions pin pre-existing behaviour — and is [ OK ] on the fixed binary.
f Fix is general across code paths? Yes. Both branches that decide intDiv monotonicity are guarded (bounded variable / constant and the null-endpoint branch, the latter being what matchesExactContinuousRange and ReadInOrderOptimizer read). The equal-endpoint branch is a measured NON-carrier (a table holding only the minimum answers keyed == oracle on master) and is asserted as a control, now with its granule count pinned too. The same defect one type wrapper up is covered by a third helper: an Array/Tuple dividend divided by a scalar constant is evaluated element-wise, so an element type that wraps carries the identical defect while getMonotonicityForRange sees only the outer type. Measured carriers (keyed 0 vs oracle 1, plus a mis-sorted ORDER BY, unfixed by the scalar guard alone): Array(Int64), Array(Int32), Array(Array(Int64)), Array(LowCardinality(Int64)), Tuple(Int64, Int64) and the mixed Tuple(Int64, Int8); nesting is followed recursively and a tuple is a carrier as soon as any one element is. Fixed at the source — the monotonicity report — not at the prune site. The Code 153 throw carriers at other widths are provably unfixable here (a min-excluding range must stay monotonic, and KeyCondition::applyFunction then evaluates over the ENTIRE index column; a min-containing range throws at runtime too, ENGINE=Memory included) and are disclosed as out of scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Asserted: dividend widths Int32, Int64; divisor widths Int8/Int16/Int32/Int64; wrappers Nullable(Int64) and LowCardinality(Int64) (pinning the removeNullable(recursiveRemoveLowCardinality(...)) stripping); both the = and IN spellings (KeyCondition::checkInRange and MergeTreeSetIndex::checkInRange); boundary values TYPE_MIN and TYPE_MIN + 1. Compound dividends are asserted as well — Array(Int64), Array(Int32), Array(Array(Int64)) (nesting), Array(LowCardinality(Int64)) (wrapper inside the container), Tuple(Int64, Int64) and Tuple(Int64, Int8) (mixed element types, only one of which wraps). Inputs the guard must NOT fire on are asserted too, each with its granule count or read-in-order type pinned: unsigned/unsigned (UInt8/toUInt8(255), UInt16/toUInt16(65535)), Float divisor, Int128 divisor, Int16 dividend, divisor -2, minimum absent from the data, half-bounded range excluding the minimum (single- and multi-column keys), a single-point range at the minimum, and two compound non-carriers (an Array(Int64) dividend with a positive divisor and an Array(UInt8) dividend) that prove the compound guard is keyed on the element type and the constant rather than on "is compound". Compound shapes that are NOT carriers because they throw ILLEGAL_DIVISION rather than wrapping silently were measured and left alone: Array(Int8), Array(UInt64) at 2^63, Array(Int128), and any compound dividend with a Float, Int128 or high-bit-unsigned divisor; Map, Array(Nullable(...)) and a compound DIVISOR are rejected earlier with Code 43/Code 44.
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, no serialization or format change, so no SettingsChangesHistory.cpp entry is due. The only behaviour changes are that a previously wrongly-pruned query now returns correct rows (reading more granules in that narrow case) and that ORDER BY intDiv(x, -1) loses read-in-order — disclosed in the PR body as a deliberate correctness-over-optimization trade, matching what intDivRangeCrossesSignedWrap already does for unbounded unsigned ranges.
i Invariants and contracts preserved? Yes. The invariant is intDiv reports monotonic only on ranges where it really is monotonic. Monotonicity's documented contract is upheld on every path: is_always_monotonic means "monotonic on the WHOLE input range", and the whole domain of a signed type always contains its minimum, so it is now false whenever the divisor is an effective -1. The pre-existing Decimal rejection stays ordered BEFORE the new guards, so getSizeOfValueInMemory is never reached for a Decimal, and the compound guard is ordered AFTER the scalar one so a scalar dividend never enters the container unwrapping. For a compound carrier the verdict is the unconditional {false, true, false, false} — the endpoints are Array/Tuple Fields whose element-wise containment of the wrap point is not cheaply modelled, so no width is ever computed from a compound type. That the two guards must agree is measured rather than assumed: removing the compound guard from only the null-endpoint branch makes matchesExactContinuousRange() (which probes with NULL/NULL and requires is_always_monotonic) contradict the truthful bounded branch and abort with Inconsistent KeyCondition behavior. No allocation, no lock, no new error path; all three helpers are pure, total over the types they are reached with, and the container recursion terminates on the type tree.

Session id: cron:clickhouse-review-slot-11:20260727-162500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @george-larionov — could you review this? intDiv reported itself monotonic on ranges containing the signed minimum when the divisor is an effective -1, where TYPE_MIN / -1 folds back onto TYPE_MIN instead of mapping to TYPE_MAX, so MergeTree key analysis silently pruned a granule holding a matching row and ORDER BY intDiv(x, -1) returned mis-sorted rows; it adds the missing wrap model next to the two intDiv wraps getMonotonicityForRange already carries. @nihalzp — this is the wrap sibling of the direction defect you fixed in #106136.

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

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9eb28b4]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR correctly fixes the intDiv(signed, -1) monotonicity lie for scalar keys and extends that specific fix to Array/Tuple dividends. I found one remaining blocker: the same compound-dividend blind spot is still present in the other two intDiv monotonicity predicates, so compound Array/Tuple keys can still be mis-analysed for the pre-existing unsigned-dividend/signed-divisor step case and the signed-dividend/high-bit-unsigned-divisor direction-flip case.

Findings

❌ Blockers

  • [src/Functions/FunctionBinaryArithmetic.h:3941] The new compound-dividend logic only covers intDivWrapsInsteadOfThrowing. executeArrayWithNumericImpl / tupleIntDivByNumber also re-enter the scalar arithmetic for the other two intDiv carriers, but intDivRangeCrossesSignedWrap and intDivConstReinterpretsNegative still inspect only the outer arg_type. As a result, Array/Tuple keys still hit the same wrong-answer / Invalid binary search result failures as the scalar cases already covered by tests/queries/0_stateless/04340_intdiv_variable_constant_monotonicity.sql.
    Suggested fix: factor the compound recursion so it can apply all three intDiv carrier predicates to element types, then add Array/Tuple variants of the existing scalar regressions from 04340_intdiv_variable_constant_monotonicity.sql.
Final Verdict

❌ Changes requested

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
/// ANY of its elements is: the verdict is about the outer comparison, and one wrapping element is
/// enough to break its order. Nesting is followed recursively (`Array(Array(Int64))` is a measured
/// carrier), stripping Nullable/LowCardinality at each level like the scalar path does.
static bool intDivCompoundDividendWrapsInsteadOfThrowing(

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 fixes the "outer type hides the element type" bug only for intDivWrapsInsteadOfThrowing, but the same blind spot is still present in the other two intDiv monotonicity carriers. executeArrayWithNumericImpl and tupleIntDivByNumber re-enter the scalar arithmetic on the element type, yet intDivRangeCrossesSignedWrap still checks isUInt(arg_type) on the outer type and intDivConstReinterpretsNegative still checks isInt(arg_type) && isUInt(divisor_type) on the outer type.

That means compound keys are still mis-analysed for the scalar shapes already covered by tests/queries/0_stateless/04340_intdiv_variable_constant_monotonicity.sql: e.g. Array(UInt64) / Tuple(UInt64, ...) with a signed divisor that crosses 2^(w-1) still falls through to the default always-monotonic verdict, and Array(Int8) / Tuple(Int8, ...) with toUInt8(200) still misses the direction flip. Those remain wrong-answer / Invalid binary search result cases for Array/Tuple keys for the same reason this helper was needed for Array(Int64) / -1.

The compound handling needs to be generalized across all three intDiv carrier predicates, not added only for the result-wrap one, and the new test should add Array/Tuple variants of the scalar cases from 04340_intdiv_variable_constant_monotonicity.sql.

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 — the mechanism is real for both shapes named here. I measured all four against an
ENGINE = Memory oracle, on this PR's head (9eb28b4f, Build ID 497737591e7b6eff) and on the
pristine merge-base (1d4408f7); the two agree, so none of this is introduced by the change:

shape keyed oracle
Array(UInt64) / toInt64(1000000000000000000), values straddling 2^63 0 1
Tuple(UInt64, UInt64) / same 0 1
Array(Int8) / toUInt8(200) 0 1
Tuple(Int8, Int8) / same 0 1

The direction-flip half is worse than described above: the IN / NOT IN spelling of
Array(Int8) / toUInt8(200) does not merely over-prune, it aborts with
Logical error: 'Invalid binary search result in MergeTreeSetIndex' (rc=134 on a debug build).

I am still not widening this PR, and I would rather put the two reasons on record than just assert
them.

1. The suggested remedy is not sufficient — a third mechanism sits underneath it

For a compound dividend the element-wise map has to be injective, not merely monotonic, because
the compound comparison is lexicographic: once two inputs' leading elements collapse onto the same
output, the compound order is decided by a later element that carries no relation to the input order.
Measured with an ordinary positive divisor — no wrap, no reinterpretation, no effective -1 anywhere:

CREATE TABLE k (a Array(Int64)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;
CREATE TABLE m (a Array(Int64)) ENGINE = Memory;
INSERT INTO k VALUES ([10,100]),([11,5]),([12,0]),([20,0]);
INSERT INTO m VALUES ([10,100]),([11,5]),([12,0]),([20,0]);
SELECT count() FROM k WHERE intDiv(a, toInt64(10)) = [toInt64(1), toInt64(0)];  -- 0
SELECT count() FROM m WHERE intDiv(a, toInt64(10)) = [toInt64(1), toInt64(0)];  -- 2

EXPLAIN indexes = 1 selects Granules: 0/4; the dropped rows are [11,5] and [12,0]. Same for a
range predicate (> [toInt64(1), toInt64(0)]: 1 vs 2) and for Tuple(Int64, Int64). Controls:
intDiv(a, toInt64(1)) is injective and correct, multiply(a, toInt64(3)) and
multiply(a, toInt64(-1)) are injective and correct, and arity 1 is correct. So the discriminator is
injectivity of the element map crossed with arity >= 2; the result wrap and the direction flip are two
instances of it, and generalising only those two predicates leaves this open.

2. A blanket rejection of compound dividends would delete pruning this PR deliberately keeps

This PR pins two compound preservation controls precisely because the guard has to key on the element
type and the constant rather than on "is compound": Array(Int64) with divisor 10 asserting
Granules: 11/100, and Array(UInt8) with toUInt8(255) asserting Granules: 2/256. Both
re-measured green just now. Rejecting compound outright reddens them.

A per-element decision inside these predicates is also not available:
intDivRangeContainsResultWrapPoint and intDivRangeCrossesSignedWrap derive a width via
IDataType::getSizeOfValueInMemory(), which throws LOGICAL_ERROR for a container type
(src/DataTypes/IDataType.cpp:122-125), and accurateLessOrEqual on an Array/Tuple Field
against an integer Field throws BAD_TYPE_OF_FIELD (src/Common/FieldAccurateComparison.cpp:144,
:241 — the visitor has no container arm). That is why the guard added here returns an unconditional
non-monotonic verdict for a compound carrier instead of deciding per element, and any generalisation
faces the same constraint. Arity cannot be read off the type either: a single Array column can hold
[5] and [10,100] in the same table, so a type-level predicate cannot know it.

So: mechanism conceded, all four shapes confirmed as carriers, and the sibling-predicate blindness is
already disclosed in the description under "Deliberately out of scope". It has a different root cause
and needs its own test matrix, so per the one-concern-per-PR convention it belongs in its own change
rather than growing this one. I have opened a follow-up carrying the measurements above, the third
(injectivity) mechanism, and the constraint that any fix must not redden the two preservation controls.
If a single PR is preferred, say so and I will fold it in here instead.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 40/41 (97.56%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9eb28b4

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

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Hung check failed, possible deadlock found server stopped answering SELECT 1 for ~6 min after the stress phase (21:17:28Z first timeout, 21:23:19Z give-up); the lldb dump taken at give-up shows the server process fully idle (1 TCPHandler in poll, 9 BgSchPool threads in a condition-variable wait, no query threads), fatal.log empty, no sanitizer report a fix task is pending (investigating at full effort - fixing-PR link to follow here)

Not PR-caused. This signature is trunk-wide and independent of this diff: over the last 30 days
CIDB has 1247 hits across 474 distinct pull requests and 203 master rows, spread over 13 Stress
flavours (arm_tsan alone: 391 hits / 192 pull requests / 41 master rows). This PR only changes
intDiv/divide monotonicity reporting in key analysis, which cannot idle a server.

The one merged sub-cause fix for this family that I know of (the unkillable hang in random
distribution functions, merge commit 81f6bc5) is already an ancestor of the tested head, so
it does not cover this instance and I am not linking it as the owner.

All other checks are green: 159 success, 17 skipped, Style check success, Mergeable Check
success, CH Inc sync success, and all four Stateless tests (*, flaky check) jobs pass.

Session id: cron:our-pr-ci-monitor:20260728-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing: superseded by #113048.

This PR stopped key analysis from claiming monotonicity for intDiv(x, -1) at the signed
minimum, so MergeTree would not prune a granule holding a matching row. #113048 fixed the same
defect one layer down: DivideIntegralByConstantImpl::vectorConstant now throws
ILLEGAL_DIVISION at the minimum instead of silently wrapping, so the wrong result this PR
prevented is no longer reachable.

I merged master and measured it with two builds differing only by this PR's change to
getMonotonicityForRange. Nothing distinguishes them: keyed count vs a Memory oracle at the
Int64 and Int32 minimum, Nullable, divisor widening, Array/Tuple dividends,
ORDER BY intDiv(a, -1), DISTINCT intDiv(a, -1), and the four pruning-preservation controls
all give identical output, and this PR's own test aborts identically on both. An instrumented
build shows the scalar guard is still reached and still returns true; it just no longer changes
any outcome.

Two further reasons not to land it as written:

Master still reports intDiv(Int64, -1) as always-monotonic, which is inaccurate, but every
path that could observe it now throws first. #112231 covers the case where that exception is
caught: it degrades a failed chain application to "cannot prune" and threads
chain_application_failed so the binary search does not assume exactness. It does not need this
PR as a prerequisite, so nothing is blocked by closing this.

Worth noting separately: #113048 carries no backport label, and 26.7 and 26.6 do not contain it,
so the silent wrap is still present on those branches.

@groeneai groeneai closed this Aug 21, 2026
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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants