Repository navigation
Fix wrong intDiv/divide monotonicity for a constant dividend - #112156
alexey-milovidov merged 18 commits into
Conversation
…vidend `FunctionBinaryArithmetic::getMonotonicityForRange` reported the wrong `is_positive` in its `const / variable` branch, so key analysis inverted the transformed range exactly when it must not, the range matched no granule, and matching rows were silently dropped with no error and exit code 0. Reproduced at completely default settings: a 20000-row Int32-keyed MergeTree with `intDiv(toInt32(-1000000), a) >= 11` returned 0 rows where the ground truth is 10909. For `c / x` on an interval excluding 0, `d/dx (c/x) = -c/x^2` has sign `-sign(c)` for every `x != 0`, so the direction is the same on the negative and the positive branch and only the values differ. The code negated the flag in the positive-range arm only. The two arms are now one return with a single negation; the strict range guards that exclude 0 are unchanged. Three further defects share that branch and are fixed together, because no subset is shippable: * `intDiv` casts its dividend through `make_signed_t` whenever either operand is a signed integer, so an unsigned constant whose high bit is set divides as negative while its raw Field still compares positive. On a negative range the un-negated arm was accidentally correct for this shape, so adding the missing negation alone would turn a correct answer into a wrong one. A new `intDivConstDividendReinterpretsNegative` helper corrects the effective sign. * With a Decimal operand and no Float operand the division computes in the decimal's native width, truncating the divisor, so the quotient is periodic in the variable and not monotonic at all. Nothing is claimed for that combination, mirroring the rejection the sibling `variable / constant` branch already performs. A Decimal/Float pair routes through Float64, never truncates, and is exempt. * IPv4/IPv6 are substituted with UInt32/UInt128 and their Field cannot be compared with a numeric zero, so two existing comparisons against zero raised `BAD_TYPE_OF_FIELD` during key analysis on a valid query, in both operand roles. A numeric gate hoisted above the single-value fast path removes both; such a query now returns the correct rows without pruning. Pruning is lost for `const / variable` shapes with a Decimal operand and no Float operand (measured Granules 2/4 -> 4/4 and 2/4 -> 3/4, same rows returned). No committed reference changes. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review — 5 findings adjudicated (3 accepted, 2 declined with evidence)Before opening this PR I ran an independent cold code review plus a second-model review pass over ❌ Declined —
|
Pre-PR validation gate (click to expand)
Each of the four edits was mutation-tested individually (16 mutations, predictions written before Session id: cron:clickhouse-impl-slot-43:20260727-135900 |
|
cc @Ergus @Algunenano — could you review this? |
|
Workflow [PR], commit [ee7f2ac] Summary: ✅
AI ReviewSummaryThis PR fixes wrong monotonicity handling for Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code |
…riable-monotonicity
CI finish ledger - 3341c4dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
None of the three is caused by this PR, whose diff is On the stress red specifically: the tested build was The Session id: cron:our-pr-ci-monitor:20260728-053000 |
… path The `const / variable` monotonicity block rejects a `Decimal` operand based on the operand types, so it also covers a zero dividend and runs ahead of the `constant == 0` fast path. That ordering was untested, which made it look like an oversight: `0 / x` is constant 0 wherever it is defined, so the wrap/truncation argument appears not to apply. It does apply, because the truncation moves *where* the function is defined. With a `Decimal32` operand the divisor is truncated to `Int32`, so every multiple of `2^32` divides as zero and a key range that strictly excludes 0 can still contain a point where the quotient is undefined - which is exactly what the zero-constant guard assumes away. Letting the zero guard win claims monotonicity there, prunes the raising granule away, and returns `0` for a query that correctly raises `ILLEGAL_DIVISION`. Measured on an `Int64` key around `2^32`: with the current order the plan reads `Granules: 2/2` and the query raises, matching the `ENGINE = Memory` ground truth. With the two blocks swapped it reads `Granules: 0/2` and silently returns `0`. Adds two `EXPLAIN indexes = 1` rows (`c5iv`) covering `intDiv` and `divide`. They are asserted on the plan rather than on the error code because the stateless runner randomizes settings that can surface a different error first. Mutation-checked: with the blocks swapped exactly these two rows fail and nothing else; restoring the order rebuilds to a bit-identical Build ID. No production code changes.
…riable-monotonicity
CI finish ledger - 8f65cb8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
156 of 174 checks succeeded, 17 were skipped, and this was the only failure. The fix was absent from the tested build: Session id: cron:our-pr-ci-monitor:20260728-203000 |
CI finish ledger - 5a3cca9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not PR-caused. My diff is Session id: cron:our-pr-ci-monitor:20260729-023000 |
|
Fixing PR for the Root cause: #109339 added a Timeline: #109339 merged 2026-07-28 13:16 UTC, the master cascade began the same evening, #112381 reverted it 2026-07-29 01:39 UTC. Every failing build contained the introducing commit and lacked the revert. True-master runs since the revert are clean: 0 failures against 6804 passing rows across 23 distinct commits. #112382 re-lands the feature with No action is needed on this PR: its diff never touched PostgreSQL replication and did not cause this line. |
…riable-monotonicity Resolves one conflict in src/Functions/FunctionBinaryArithmetic.h, at the top of getMonotonicityForRange. Both sides append an independent early-return guard at the same insertion point and both return the same non-monotonic verdict, so the resolution keeps both: master's compound-type guard (from the merged ClickHouse#112339) first, in its original position, then this branch's numeric-operand guard for the `const / variable` arm. The two guards are orthogonal: the compound guard rejects Array/Tuple/Map key or result types, while this branch's guard rejects IPv4/IPv6 operands of a constant dividend. Neither subsumes the other and neither changes the other's outcome. Verified line-exact: the resolved file's change set against the merge base is the union of the two sides (+73/-10 == +51/-9 ours plus +22/-1 master), with no line added or removed beyond that union.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code |
|
Fixing PR for the |
|
Fixing PR for the That run's canary named I am claiming the route, not a reproduction of the abort itself: that fuzzer abort never reproduced locally and appears to need accumulated fuzzer session state. One caveat for whoever reads this ledger line later: STID 5182-684a pools more than one mechanism. A 26.6 hit on 2026-07-31 carries the same STID but its key is |
CI finish ledger - ccca54bCI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 157 success, 17 skipped, 0 failures.
Verified from the paginated check-runs API rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers. Session id: cron:our-pr-ci-monitor:20260803-163000 |
|
No, it accepts edits. |
|
Confirmed, and #112156 is otherwise unchanged (head On the part of #114984 that was not already on this branch: its only source delta over
The two |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes10 object files changed (+115.02 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units32 translation units recompiled, 450 s compile time in total, 32 of them have a recent master baseline. |
…riable-monotonicity
The test ran ~105s (median, 450 runs) in the public `amd_asan_ubsan` flaky
check and ~165s in the private one, where 3 of 50 runs crossed the 180s
per-test limit and blocked the sync:
Reason: Test runs too long (> 180s). Make it faster.
Attributing the cost from the failing job's `query_log.tsv` shows no hot
query - 79 oracle rows at ~500ms each, uniformly - and that fixture DDL
dominates: 26 `MergeTree` tables at 505ms per `CREATE`, 1000ms per `INSERT`
and 860ms per `DROP` (61s of the 126s of query time per run), because that
job stores parts on S3 with metadata in Keeper. Those 26 tables are exactly
the (type, range, granularity) matrix the probes need, so the cost cannot be
trimmed without dropping coverage. The 180s limit is per test file, so the
cases are split instead, one file per family:
* `04651_intdiv_const_variable_monotonicity` - cases 1-4, integer dividends
* `..._decimal_float` - cases 5 and 7, `Decimal` and `Float` operands
* `..._controls` - case 6, must-not-flip controls
* `..._ip` - case 9, non-numeric operands
Every file carries the case 8 pruning-liveness rows for its own fixtures and
keeps the shared case numbering. Only three fixtures are recreated across
files (`t_cv_neg`, `t_cv_span`, `t_cv_f64p`), so the total work grows by ~8%
while the largest file is ~50s in the private job.
No assertion changed: every statement is copied verbatim, the union of the
four references is byte-identical to the old one as a multiset, and running
the four files against a `master` build reproduces the old file's verdict for
all 73 rows it reached before aborting at case 9 - same 30 failing rows, no
value differs. Against the build from this pull request all four pass.
Report: https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/json.html?PR=66173&sha=9c1f92ddef5896da31ebb030e2ba24dd9f7eb500&name_0=PR
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CI finish ledger — 6e597b5Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260817-183000 |
|
🕵 Addressed the automated review: |
Master gained `getArithmeticField` (PRs ClickHouse#112156 / "Fix IP monotonicity for unbounded ranges"), which is the same value-level IPv4/IPv6 substitution this branch added as `substituteIPField`: both cast through DataTypeIPv4/IPv6 to UInt32/UInt128 rather than reinterpreting, because IPv6 stores its limbs byteswapped. Keeping both would leave two definitions of one notion, so the branch's copy is dropped and its three call sites now use master's helper. The residual this branch fixes is unaffected by master's new guards: those decline monotonicity only for `divide`/`intDiv`, so `plus`/`minus`/`multiply` with an IP-tagged constant still reach the Field-vs-zero comparison. Measured on master (b16561c) with `clickhouse local`, four shapes raise `Code: 169 BAD_TYPE_OF_FIELD` -- plus/minus/multiply with an IPv4 constant over a numeric key at index_granularity 1, and multiply at granularity 4 -- and all four return a value with this branch applied. The shipped test 04653 fails on master with that error at its first `oracle_plus_ip4_right_g1` row and passes here, both arms run against servers whose `buildId()` was asserted against the binary.
…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]>
Fix wrong intDiv/divide monotonicity for a constant dividend
Related: #106136
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes silently missing rows when a query filters on
intDiv(constant, key)ordivide(constant, key). Primary-key and partition analysis reports the wrong direction of monotonicity for a constant divided by a key column, so matching granules are pruned away and the query returns fewer rows with no error. Also fixesintDivwith an unsigned constant dividend whose high bit is set, stops claiming monotonicity when aDecimaloperand makes the division compute in the decimal's native width, and stops key analysis from raisingCannot compare DB::IPv4 with longfor a valid query that divides anIPv4/IPv6constant by a key column.Description
FunctionBinaryArithmetic::getMonotonicityForRangereports the direction ofc / xincorrectly inits
const / variablebranch, soKeyCondition::applyMonotonicFunctionsChainToRangeinverts thetransformed range exactly when it must not, the range matches no granule, and matching rows are
dropped with no error and exit code 0.
Reproduced at completely default settings (no
SETTINGSclause), 20000-rowInt32-keyed MergeTree:Root cause
For
f(x) = c / xon an interval excluding 0,d/dx (c/x) = -c/x², whose sign is-sign(c)forevery
x != 0— thex²denominator is positive on both sides of 0. So the direction is governedby
sign(c)alone and is the same on the negative and the positive branch; only the valuesdiffer. The code instead treated the two arms as needing opposite polarity, which is the intuition
that
1/x"flips" across the branches. It does not: it is monotone on each branch separately,which is exactly why the strict range-sign guards are there. The two arms are now one return with
a single
!is_constant_positive, and the strict guards are kept verbatim.Fixing only that is not sufficient, and on its own would be worse than the current code for one
shape. Three further defects live in the same branch:
Unsigned constant dividend.
intDivcasts the dividend throughmake_signed_twhenevereither operand is a signed integer (
DivisionUtils.h), so an unsigned constant whose high bit isset divides as negative —
intDiv(toUInt8(200), x)isintDiv(toInt8(-56), x)— while the rawFieldstill compares as positive. The boundary is2^(8 * width - 1)of the dividend's ownwidth (verified for 8/16/32/64/128/256-bit dividends; the divisor width is irrelevant). This is
reachable with no cast at all, because the literal
200isUInt8. On a negative range theun-negated arm is accidentally correct for this shape, so adding the missing
!alone would turna correct answer into a wrong one. A new
intDivConstDividendReinterpretsNegativehelpercorrects the effective sign; it deliberately does not reuse the existing
intDivConstReinterpretsNegative, whose width early-out has the opposite polarity here.Decimaloperand. With aDecimalon either operand and noFloatoperand, the divisioncomputes in the decimal's native width (
DecimalBinaryOperationcasts both operands toNativeResultTypeand substitutes the integral operation even fordivide). The divisor is thentruncated, so
intDiv(toDecimal32(1000, 0), x)is periodic inxwith period2^32and not evenmonotonic. Nothing is claimed for that combination, mirroring the rejection the sibling
variable / constantbranch already performs. ADecimal/Floatpair is exempt: it is convertedto
Float64before the operation, never truncates, and is itself a carrier of the directiondefect, so those shapes are fixed rather than rejected.
The rejection is deliberately keyed on the operand types and not on the constant's value, so it
also covers a zero dividend and therefore runs ahead of the
constant == 0fast path. Thatordering is load-bearing: the truncation moves where the quotient is defined, so a range that
strictly excludes 0 can still contain a point where the function is undefined, which is exactly
what the zero-constant guard assumes away. With
Decimal32the divisor truncates toInt32, sointDiv(toDecimal32(0, 0), key)over anInt64key range around2^32raisesILLEGAL_DIVISION; letting the zero guard win would claim monotonicity, prune the raising rowaway, and return a silent answer instead. Pinned by
c5iv.Non-numeric operand (pre-existing exception on a valid query).
IPv4/IPv6are substitutedwith
UInt32/UInt128, so their declared width does not describe the arithmetic, and their rawFieldcannot be compared with a numeric zero. Two existing comparisons against zero thereforeraise
Code: 169 BAD_TYPE_OF_FIELD "Cannot compare DB::IPv4 with long"during key analysis today:one in the single-value fast path (reached when a granule's min equals its max) and one in the
zero-constant guard (reached otherwise). Both roles are affected —
intDiv(toIPv4('192.168.0.1'), numeric_key)andintDiv(1, ipv4_key)— and one of them fireseven when the key range spans 0. A numeric gate hoisted above the fast path removes both; after it
each query returns the correct rows with no pruning. Placing the gate inside the
const / variableblock would cover only the second site, which the new test pins at twogranularities. Scope note: "both roles" here means the IP value as the dividend constant and as
the key column, both with the constant on the left. The mirror shape, an IP constant as the
divisor (
intDiv(numeric_key, toIPv4(...))), still raises the same exception, as doplus/minus/multiplywith anIPv4/IPv6operand. Both are pre-existing (measuredbyte-identical on
origin/master) and are tracked separately rather than widened into this PR,since a correct fix for them also has to touch the
multiplyarm and the shared fast path.Behaviour changes to be aware of
Two pre-existing key-analysis exceptions disappear. As above, a non-numeric operand now
reports non-monotonic instead of raising, so the query succeeds unpruned. This is a scope
extension beyond "fix the direction", included because those same comparisons against zero are
the mechanism being corrected and an exception on a valid query is a bug either way.
Pruning is lost for
Decimalshapes with noFloatoperand. Measured withEXPLAIN indexes = 1:Decimal32(0)key,intDiv(toInt32(-1000), a) = -25, positive rangeGranules: 2/4Granules: 4/4UInt64key,intDiv(toDecimal32(1000, 0), a) = 250Granules: 2/4Granules: 3/4Int64key,intDiv(toDecimal32(0, 0), a) = 5, range around2^32Granules: 0/2Granules: 2/2The first two queries return the same rows before and after — the index simply stops filtering.
The third is the zero-dividend case: it must stop pruning, because the pruned plan silently
returned
0for a query that correctly raisesILLEGAL_DIVISION. This mirrors the decisionalready shipped for the
variable / constantbranch, where the same truncation applies.Decimal/Floatpairs keep pruning and are additionally fixed. No committed reference in therepository changes.
Everything else keeps pruning. Strictly-positive ranges with a signed constant, both-unsigned
operands,
Floatdivisors, and unsigned key ranges crossing the divisor's own2^(8W-1)are allunaffected. That last group is worth naming: the values jump across the wrap while the order
is preserved, which satisfies the non-strict definition of
Monotonicity, so rejecting themwould delete pruning that is correct today. The new test pins them, with plan-level assertions.
Testing
04651_intdiv_const_variable_monotonicityand its three siblings..._decimal_float,..._controlsand..._ipcompare a keyed MergeTree against an identicalENGINE = Memorytableon the same data, so each of their 86 count rows prints
1when index-based pruning agrees withthe full-scan ground truth. The probes are split by family across four files, sharing one case
numbering, so that no single file outgrows the CI per-test time limit: the cost is fixture DDL for
the 26 tables of the (type, range, granularity) matrix, which cannot be trimmed without dropping
coverage. Together they cover both range signs for both functions and both constant signs,
unsigned dividends at several widths,
Decimalin either role plus theDecimal/Floatexemption,Float64/LowCardinality/Nullablekeys, ranges that span zero orhave zero as an endpoint, the unsigned wrap shapes, and the
IPv4/IPv6cases at twogranularities. Twelve further rows assert with
EXPLAIN indexes = 1that the surviving shapes stillprune (so the fix cannot silently degrade into "no pruning at all") and that the zero-dividend
Decimalshape stops pruning — 98 asserted rows in total.On a master-HEAD binary the tests fail: 34 rows print
0and..._ipaborts withCode: 169 BAD_TYPE_OF_FIELD. On this branch they pass, including 50/50 runs with randomizedsettings. Each of the four edits was mutation-tested individually — reverting the negation, the
sign correction, the
Decimalrejection, theFloatexemption, the numeric gate, the gate'shoisted position and its role restriction each make specific named rows fail.
index_granularitydecides whether the range handed togetMonotonicityForRangeis strictlynegative, strictly positive or spans zero, so it is pinned per DDL and the test carries
no-random-merge-tree-settingswith that reason stated inline in each of the four files.Workflow [PR]
Sync PR [sync-upstream/pr/112156]
Version info
26.8.1.1714(included in26.8and later)