Skip to content

Fix wrong intDiv/divide monotonicity for a constant dividend - #112156

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-intdiv-const-variable-monotonicity
Aug 19, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-intdiv-const-variable-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Fix wrong intDiv/divide monotonicity for a constant dividend

Related: #106136

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 silently missing rows when a query filters on intDiv(constant, key) or divide(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 fixes intDiv with an unsigned constant dividend whose high bit is set, stops claiming monotonicity when a Decimal operand makes the division compute in the decimal's native width, and stops key analysis from raising Cannot compare DB::IPv4 with long for a valid query that divides an IPv4/IPv6 constant by a key column.

Description

FunctionBinaryArithmetic::getMonotonicityForRange reports the direction of c / x incorrectly in
its const / variable branch, so KeyCondition::applyMonotonicFunctionsChainToRange inverts the
transformed 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 SETTINGS clause), 20000-row Int32-keyed MergeTree:

SELECT count() FROM t WHERE intDiv(toInt32(-1000000), a) >= 11;
-- keyed MergeTree: 0     ENGINE = Memory oracle: 10909

Root cause

For f(x) = c / x on an interval excluding 0, d/dx (c/x) = -c/x², whose sign is -sign(c) for
every x != 0 — the x² denominator is positive on both sides of 0. So the direction is governed
by sign(c) alone and is the same on the negative and the positive branch; only the values
differ. 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. intDiv casts the dividend through make_signed_t whenever
    either operand is a signed integer (DivisionUtils.h), so an unsigned constant whose high bit is
    set divides as negative — intDiv(toUInt8(200), x) is intDiv(toInt8(-56), x) — while the raw
    Field still compares as positive. The boundary is 2^(8 * width - 1) of the dividend's own
    width (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 200 is UInt8. On a negative range the
    un-negated arm is accidentally correct for this shape, so adding the missing ! alone would turn
    a correct answer into a wrong one. A new intDivConstDividendReinterpretsNegative helper
    corrects the effective sign; it deliberately does not reuse the existing
    intDivConstReinterpretsNegative, whose width early-out has the opposite polarity here.

  • Decimal operand. With a Decimal on either operand and no Float operand, the division
    computes in the decimal's native width (DecimalBinaryOperation casts both operands to
    NativeResultType and substitutes the integral operation even for divide). The divisor is then
    truncated, so intDiv(toDecimal32(1000, 0), x) is periodic in x with period 2^32 and not even
    monotonic. Nothing is claimed for that combination, mirroring the rejection the sibling
    variable / constant branch already performs. A Decimal/Float pair is exempt: it is converted
    to Float64 before the operation, never truncates, and is itself a carrier of the direction
    defect, 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 == 0 fast path. That
    ordering 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 Decimal32 the divisor truncates to Int32, so
    intDiv(toDecimal32(0, 0), key) over an Int64 key range around 2^32 raises
    ILLEGAL_DIVISION; letting the zero guard win would claim monotonicity, prune the raising row
    away, and return a silent answer instead. Pinned by c5iv.

  • Non-numeric operand (pre-existing exception on a valid query). IPv4/IPv6 are substituted
    with UInt32/UInt128, so their declared width does not describe the arithmetic, and their raw
    Field cannot be compared with a numeric zero. Two existing comparisons against zero therefore
    raise 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) and intDiv(1, ipv4_key) — and one of them fires
    even 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 / variable block would cover only the second site, which the new test pins at two
    granularities. 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 do
    plus/minus/multiply with an IPv4/IPv6 operand. Both are pre-existing (measured
    byte-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 multiply arm 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 Decimal shapes with no Float operand. Measured with
    EXPLAIN indexes = 1:

    shape before after
    Decimal32(0) key, intDiv(toInt32(-1000), a) = -25, positive range Granules: 2/4 Granules: 4/4
    UInt64 key, intDiv(toDecimal32(1000, 0), a) = 250 Granules: 2/4 Granules: 3/4
    Int64 key, intDiv(toDecimal32(0, 0), a) = 5, range around 2^32 Granules: 0/2 Granules: 2/2

    The 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 0 for a query that correctly raises ILLEGAL_DIVISION. This mirrors the decision
    already shipped for the variable / constant branch, where the same truncation applies.
    Decimal/Float pairs keep pruning and are additionally fixed. No committed reference in the
    repository changes.

  • Everything else keeps pruning. Strictly-positive ranges with a signed constant, both-unsigned
    operands, Float divisors, and unsigned key ranges crossing the divisor's own 2^(8W-1) are all
    unaffected. 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 them
    would delete pruning that is correct today. The new test pins them, with plan-level assertions.

Testing

04651_intdiv_const_variable_monotonicity and its three siblings ..._decimal_float,
..._controls and ..._ip compare a keyed MergeTree against an identical ENGINE = Memory table
on the same data, so each of their 86 count rows prints 1 when index-based pruning agrees with
the 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, Decimal in either role plus the
Decimal/Float exemption, Float64/LowCardinality/Nullable keys, ranges that span zero or
have zero as an endpoint, the unsigned wrap shapes, and the IPv4/IPv6 cases at two
granularities. Twelve further rows assert with EXPLAIN indexes = 1 that the surviving shapes still
prune (so the fix cannot silently degrade into "no pruning at all") and that the zero-dividend
Decimal shape stops pruning — 98 asserted rows in total.

On a master-HEAD binary the tests fail: 34 rows print 0 and ..._ip aborts with
Code: 169 BAD_TYPE_OF_FIELD. On this branch they pass, including 50/50 runs with randomized
settings. Each of the four edits was mutation-tested individually — reverting the negation, the
sign correction, the Decimal rejection, the Float exemption, the numeric gate, the gate's
hoisted position and its role restriction each make specific named rows fail.

index_granularity decides whether the range handed to getMonotonicityForRange is strictly
negative, strictly positive or spans zero, so it is pinned per DDL and the test carries
no-random-merge-tree-settings with that reason stated inline in each of the four files.


Workflow [PR]
Sync PR [sync-upstream/pr/112156]

Version info

  • Merged into: 26.8.1.1714 (included in 26.8 and later)

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
the diff, and adjudicated every finding. Nothing here changes the shipped source: the three
accepted findings were all about this description's own wording and counts, and the two declined
ones are recorded below with the measurements that settle them.

❌ Declined — intDiv(IPv4/IPv6 key, signed constant) is falsely always-monotonic

The mechanism is real and I am not disputing it: IPv4 executes as UInt32 (IPv6 as
UInt128), so with a signed integer constant divisor DivideIntegralImpl casts through
make_signed_t and every key value at or above 2^31 (respectively 2^127) reinterprets as
negative — exactly the step function intDivRangeCrossesSignedWrap exists to reject. That guard
is keyed on isUInt(arg_type), which is false for the declared IPv4/IPv6 type, so it
never fires and the arm claims always-monotonic.

It is declined here for four reasons, not because it is wrong:

  • It is not in this diff. The finding concerns the variable / constant arm; this PR edits
    only the const / variable arm. Extracting the variable / constant arm from origin/master
    and from this branch and diffing gives 46 lines each with zero differences, and both cited
    helpers are byte-identical (intDivRangeCrossesSignedWrap, intDivConstReinterpretsNegative).
    The only line in this diff matching those symbols is a comment cross-reference.
  • It is not newly reachable. The numeric gate this PR adds is guarded by "constant is the
    left operand"; the reported shape has the constant on the right, so the gate is skipped and
    master reaches the identical return with identical arguments.
  • It is outside this PR's stated scope. The changelog entry scopes the IPv4/IPv6 work to
    removing the two pre-existing Code: 169 BAD_TYPE_OF_FIELD throws that fire during key
    analysis on a valid query; it does not claim the variable / constant role's direction or wrap
    handling is corrected.
  • The suggested remedy would regress behaviour this PR pins. DivideIntegralImpl casts
    through make_signed_t only when either operand is signed, so an IP key with an unsigned
    divisor (the bare literal 10 is UInt8) never reinterprets and its pruning is correct today
    — which this PR asserts explicitly, including a plan-level Granules: 1/4 check. A blanket
    "reject IP dividends" would fail those assertions and delete correct pruning. The real fix
    needs the signed/unsigned-divisor split plus a test matrix over both IP widths.

The guard in question came from #107586, and #112151 is already open against these same lines
(it conflicts with this branch textually while merging cleanly into master), so folding a third
change in here would stack unreviewed edits on one hunk. I have filed it separately with the
mechanism, the measured reproduction to re-verify, the scope boundary above, both candidate fix
directions and the merge-order note, and I will link the fixing PR here when it opens.

❌ Declined — case-8 plan assertions could be voided by projection rewriting

My own review raised this: the ten EXPLAIN indexes = 1 pruning-liveness rows are written over
SELECT count(), which is the shape optimizeUseAggregateProjections rewrites into a
ReadFromPreparedSource — and if the ReadFromMergeTree step disappears, so does the
Granules: line the rows grep for, leaving them to evaluate to 0 silently. Both
optimize_use_projections and optimize_use_implicit_projections are randomized and neither is
pinned.

Refuted by tracing it through: these tables declare no projections, so no real candidate exists;
the implicit min-max candidate additionally requires the filter to be computable from the
projection's keys, and with no PARTITION BY the projection has no keys, so resolution fails for
an intDiv(constant, key) filter; that failure is what routes to the trivial-count path, and
there the ReadFromMergeTree step survives as long as any parent parts remain — which it always
does here, because exact ranges are suppressed outright for a relaxed condition, and pushing a
constant through a monotonic function chain is exactly what marks the condition relaxed. So the
Granules: line is present however those settings are drawn. The 50-run randomized run agrees
(50/50, no result diffs); a silent 0 would have surfaced as a reference diff. Pinning the two
settings would still be cheap insurance and is what two sibling tests do, so it is noted, but the
path is closed here.

⚠️ Accepted — the description's row counts were wrong

Counting the committed files instead of trusting the prose: 82 rows compare the keyed read
against the ENGINE = Memory oracle and 10 assert on EXPLAIN indexes = 1, for 92 asserted rows
in total. This description previously said "92 rows" for the oracle comparison and "eight further
rows" for the plan checks (it was eight before two liveness rows were added while
mutation-testing). Corrected above.

💡 Accepted — changelog tense, PR title length

The changelog entry had one past-tense sentence between two present-tense ones; the entry
guidelines ask for present tense throughout, so it now reads "reports / are pruned / returns".
The title was 88 characters and is now 60. Both re-validated against the CI body checks.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, at completely default settings (no SETTINGS clause). A 20000-row Int32-keyed MergeTree with intDiv(toInt32(-1000000), a) >= 11 returns 0 rows against an ENGINE = Memory oracle's 10909. Reduced form: Int32 key -40,-30,-20,-10, where all 8 predicates of intDiv/divide × both constant signs drop every matching row. Each of the four defects has its own on-demand repro; none is timing- or rate-dependent.
b Root cause explained? Yes. getMonotonicityForRange's const / variable branch reported the wrong is_positive, so KeyCondition::applyMonotonicFunctionsChainToRange inverted the transformed range exactly when it must not, the range matched no granule, and rows were dropped silently with exit code 0. For c / x on an interval excluding 0, d/dx (c/x) = -c/x² has sign -sign(c) for every x != 0 — the x² denominator is positive on both sides of 0 — so the direction is the same on both branches and only the values differ; the code negated the flag in the positive-range arm only. Three companion defects share the branch: intDiv casts its dividend through make_signed_t, so an unsigned constant with its high bit set divides as negative while its raw Field compares positive; a Decimal operand with no Float operand moves the arithmetic into the decimal's native width, truncating the divisor so the quotient is periodic and not monotonic at all; and IPv4/IPv6 operands make two pre-existing comparisons against a numeric zero raise Code: 169 BAD_TYPE_OF_FIELD during key analysis on a valid query.
c Fix matches root cause? Yes. The fix is at the branch that owns the direction claim, not at any of its five deciding consumers — a per-consumer patch would be the band-aid shape rejected in #88544 / #98783 / #107319. No widened bounds, no no-random-* blanket on an existing test, no reduced dataset, no defensive check masking an upstream bug. Note that the reported "add the missing !" alone would be worse than the current code: for an unsigned dividend with its high bit set on a negative range the un-negated arm is accidentally correct, so the sign correction is required for the negation to be safe.
d Test intent preserved / new tests added? Yes. No existing test was modified, weakened, re-recorded or re-tagged, and no committed reference in the repository changes. The source fix ships with a new regression test, 04651_intdiv_const_variable_monotonicity (92 asserted rows: 82 comparing a keyed MergeTree against an identical ENGINE = Memory table, so each prints 1 when pruning agrees with the full-scan ground truth, plus 10 EXPLAIN indexes = 1 pruning-liveness rows).
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Fixed build e481c2229c7a3b40…; master-HEAD oracle is the debug snapshot of this PR's own base commit, Build ID 9ebd11fe9bc8d547…. On master-HEAD the new test prints 0 for 28 rows and then aborts with Code: 169 BAD_TYPE_OF_FIELD; on this branch it passes, including 50/50 runs with randomized settings and grep -c "result differs" = 0. Every repro file was run on both binaries with the identical command.
f Fix is general across code paths? Yes. The branch is shared by intDiv and divide (name_view == "divide" || name_view == "intDiv") and both are asserted in every case. The sibling variable / constant arm is a disjoint else if and is deliberately untouched — its existing Decimal rejection is the precedent this fix mirrors. The null-endpoint branch was checked and has no const / variable arm at all (it tests right.column only), so it already returns non-monotonic. The changed code is a function template shared by every MergeTree family member, so no separate Replicated/Shared change is owed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, asserted in the test: Int8/Int32/Int64/UInt8/UInt32/UInt64/Float64/Decimal32/Decimal64 keys; Nullable and LowCardinality wrappers; unsigned constants at the 2^7 and 2^63 boundaries and just below them (the boundary is 2^(8·width − 1) of the dividend's own width — verified for 8/16/32/64/128/256-bit dividends, divisor width irrelevant); both range signs; ranges spanning zero and ranges with zero as either endpoint; the unsigned-divisor wrap boundary; IPv4/IPv6 in both operand roles at two granularities; and the bare-literal form intDiv(200, a), which is reachable with no cast because 200 is UInt8.
h Backward compatible? (maintainer-approved exception only) Yes — no setting is added or changed, so no SettingsChangesHistory.cpp entry is owed, and no serialization format is touched. Two user-visible behaviour changes are disclosed in the PR body: two pre-existing key-analysis exceptions stop being raised (a valid query starts succeeding, a strict improvement), and index 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, with the same rows returned in both cases. That matches the decision already shipped for the sibling branch. Decimal/Float pairs keep pruning and are additionally fixed.
i Invariants and contracts preserved? Yes. The Monotonicity contract is now honoured rather than violated, which is the point of the change. is_always_monotonic stays false because the full input domain contains 0, and is_strict keeps its existing divide-only value, which is correct since intDiv collapses distinct divisors onto one quotient while divide does not. The strict accurateLess range guards are kept verbatim, so 0 and any range spanning it still fall through to non-monotonic — pinned by a mutation that relaxes them to accurateLessOrEqual. All three new early returns use {false, true, false, false}, the established "claim nothing" value already used elsewhere in the same function; none allocates, throws, or touches shared state, and no lock or error path is involved.

Each of the four edits was mutation-tested individually (16 mutations, predictions written before
building): reverting the negation, the sign correction, the Decimal rejection, the Float
exemption, the numeric gate, the gate's hoisted position and its role restriction each make
specific named rows of the new test fail. After the matrix the source restored to its exact md5 and
the rebuild returned the Build ID bit-identically.

Session id: cron:clickhouse-impl-slot-43:20260727-135900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @Algunenano — could you review this? FunctionBinaryArithmetic::getMonotonicityForRange reported the wrong direction for its const / variable branch (d/dx (c/x) = -c/x² has sign -sign(c) on both sides of 0, so the two range arms need the same polarity, not opposite ones), which made key analysis invert the transformed range and silently drop matching rows at default settings; it also corrects the effective sign for an unsigned constant dividend whose high bit is set, stops claiming monotonicity when a Decimal operand moves the division into the decimal's native width, and removes two pre-existing BAD_TYPE_OF_FIELD throws for IPv4/IPv6 operands.

@yariks5s yariks5s self-assigned this Jul 27, 2026
@PedroTadim PedroTadim 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 [ee7f2ac]

Summary: ✅


AI Review

Summary

This PR fixes wrong monotonicity handling for intDiv and divide with a constant dividend in src/Functions/FunctionBinaryArithmetic.h, adds the related Decimal and IP guards, and ships focused stateless regressions for the previously reported silent row-loss and BAD_TYPE_OF_FIELD cases. I re-checked the current head against every prior inline thread and did not find any remaining correctness, coverage, or PR-metadata issues.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3341c4d

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) wide-cast key comparison: the aborting query is SELECT count() FROM t_nofinal WHERE (g = toUInt256(2)) AND (r = 1) under viewExplain, i.e. the toUInt256-on-narrow-PK shape fixing PR #109023 (mine, merged 2026-07-27T20:50:49Z) - merged master @ b952cf8 to pick it up
Stateless tests (amd_tsan, s3 storage, parallel, 1/3) / 04615_client_progress_table_toggle_config expect-script timeout (rc 1); the runner's own diagnosis reports Runs: 7, Failed: 0 on re-run with identical randomized settings, so not reproducible a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Integration tests (arm_binary, distributed plan, 2/4) / test_system_stop.py::test_stopped_table_releases_hash_ring_slot + ::test_refresh_survives_unready_dependencies server SIGABRT (libcxx hardening) in ObjectStorageQueueSource::FileIterator::next; the second test is collateral, failing at its own first query with Code: 210 Connection reset by peer against the already-dead server fixing PR #108977 (mine, open, approved)
CH Inc sync - CH Inc sync (private, not actionable)

None of the three is caused by this PR, whose diff is src/Functions/FunctionBinaryArithmetic.h plus one new stateless test.

On the stress red specifically: the tested build was ac94f7d67e14 (Merge 3341c4d754d2 into d93a2e3466c6), and src/Storages/MergeTree/KeyCondition.cpp in that tree has zero occurrences of the mapping.functions.empty() guard #109023 added, so the failure happened without the fix present. The fix landed on master as 1f4a77b8b9c3 after this branch's base, so I merged master to pick it up; CI is re-running on the new head.

The 04615 and test_system_stop reds are pre-existing: 04615 has 12 hits across 12 unrelated PRs and 0 master in 30 days, and the s3_queue pair has 56 hits across 27 unrelated PRs plus 2 master runs, confined to the single arm_binary, distributed plan, 2/4 shard (1592 OK against 22 FAIL on that shard for the crasher).

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.
@groeneai

groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8f65cb8

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, distributed plan, 1/4) / test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming flaky (REFRESH-while-stopped cycle released its pool permit before draining the queued backlog, so wait_dst_count(table, 6) saw 1 row) #111480 (mine, merged 2026-07-28T14:22:51Z) - merged master @ 5a3cca96b3e33477bbe1a2db803c99597febb68d to pick it up
Sync - CH Inc sync (private, not actionable)

156 of 174 checks succeeded, 17 were skipped, and this was the only failure.

The fix was absent from the tested build: driveLoopUntilMessage (the helper #111480 adds to
src/Storages/RabbitMQ/RabbitMQSource.cpp) has 5 occurrences on current master and 0 in the
tree at 8f65cb89d625. The failing shard also ran 11:50-13:02Z, i.e. before #111480 merged at
14:22Z, so the failure happened without the fix rather than with it. CI is re-running on the
merge commit.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5a3cca9

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Inconsistent KeyCondition behavior (STID 5182-684a) debug-only canary abort at MergeTreeDataSelectExecutor.cpp:2457; the fuzzed carrier is an Array(IPv4) key, and #109023 (merged) is already present in the tested tree, so it is a different mechanism (a non-injective element-wise map over a compound key breaks lexicographic order) a fix task is created (investigating at full effort - fixing-PR link to follow here)
Integration tests (amd_tsan, 1/6) / 46 x test_postgresql_replica_database_engine/test_3.py::* ONE server-death event, not 46 failures: every row is Code: 210 Connection refused raised in the autouse setup_teardown fixture a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit deterministic under parallel replicas (Failed 3 out of 3 reruns) #112385 (mine, open)
Sync - CH Inc sync (private, not actionable)

Not PR-caused. My diff is src/Functions/FunctionBinaryArithmetic.h plus one stateless test; it
contains no reference to KeyCondition.cpp, MergeTreeDataSelectExecutor.cpp, the PostgreSQL
replication code, or 01666. Fast test, Style check and all 15 built Build (*) nodes are green.

Session id: cron:our-pr-ci-monitor:20260729-023000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_postgresql_replica_database_engine Connection-refused cascade dispositioned to a fix task on this PR's CI finish ledger: #112381 (merged), with the re-land #112382.

Root cause: #109339 added a materialized_tables traversal to DatabaseMaterializedPostgreSQL::getTablesIterator. The asynchronous-metrics thread reaches that iterator (ServerAsynchronousMetrics.cpp:447, and this database reports isExternal() == false so it is not skipped) while stopReplication clears the same map holding only handler_mutex, never tables_mutex. That is a heap-use-after-free on the stored wrappers, it killed the server, and every remaining test in the module then failed inside the autouse setup_teardown fixture with Code: 210 Connection refused. One server death per job, not N independent flaky tests.

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 tables_mutex taken on all materialized_tables touch points, including the swap-and-destroy-outside-the-lock form in stopReplication.

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.
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04615_client_progress_table_toggle_config line on this PR's CI finish ledger: #112160 (external, merged 2026-07-28).

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Inconsistent KeyCondition behavior compound-key carrier (STID 5182-684a) on this PR's CI finish ledger: #112339 (merged 2026-07-29).

That run's canary named (intDiv(column 0, -2147483649) in [1048577, 1048577]) on t_cv_ipv__fuzz_7, whose key is Array(IPv4). Arithmetic over a compound value is element-wise while the comparison of the whole value is lexicographic, so a non-injective element map (this divisor collapses every IPv4 in the fixture) lets a later element decide the order and the range stops being exactly continuous. #112339 stops getMonotonicityForRange from returning a verdict at all when the varying argument or the result is Array/Tuple/Map, which removes that route: re-measured on master, the Array(IPv4) + intDiv shape now reports Granules: 2/2 (no pruning) and agrees with a Memory oracle (2 vs 2, 3 vs 3 for IN, 4 vs 4 for the collapsing divisor above).

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 ORDER BY tuple(g, r DESC) over two scalar UInt32 columns with no intDiv, which is a different shape and not covered by #112339. Worth reading Participating conditions: from the server log before attributing a future 684a row here.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ccca54b

CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 157 success, 17 skipped, 0 failures. Finish Workflow completed successfully, and no check reported a failed test.

Check / test Reason Owner / fixing PR
(none) no failing check on this commit not applicable

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

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #114984 because the fork branch now rejects maintainer pushes. The new PR preserves the original work, credits @groeneai, and addresses the unresolved signed-divisor IPv4/IPv6 key monotonicity review.

@alexey-milovidov

Copy link
Copy Markdown
Member

No, it accepts edits.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and #112156 is otherwise unchanged (head ccca54bc), so there is nothing to recreate here.

On the part of #114984 that was not already on this branch: its only source delta over ccca54bc is getArithmeticType plus its use in the variable / constant signed-wrap guard. That defect is already carried by #112388 (open), which is a superset of it:

  • it substitutes the IP Field as well as the type (substituteIPField via castColumn), so IP-tagged endpoints and constants are compared as UInt32/UInt128 instead of raising BAD_TYPE_OF_FIELD;
  • it applies the substitution in the null-endpoint arm too, not only the general arm;
  • it covers divide alongside intDiv, and adds LowCardinality/Nullable/UInt32/UInt128/Int32 controls plus granule-count assertions.

The two c9iv wrap cases from your test file assert the same boundary that #112388's a ipv4 neg gt/a ipv6 neg lt rows already cover against a Memory oracle. So closing #114984 loses no coverage, and I do not think anything needs moving between the two PRs. Say the word if you would rather have that guard land here instead of in #112388.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ee7f2ace4 with master adae6c4db (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.04 MiB 699.02 MiB -3.01 MiB (-0.43%)

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 sizes

10 object files changed (+115.02 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/intDiv.cpp.o 15.34 MiB 15.44 MiB +105.79 KiB (+0.67%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

32 translation units recompiled, 450 s compile time in total, 32 of them have a recent master baseline.

Job report

alexey-milovidov and others added 5 commits August 16, 2026 06:26
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6e597b5

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
Build (llvm_coverage_build) · Stateless tests (arm_binary, parallel and sequential) · Stateless tests (amd_binary / amd_debug / amd_msan, flaky check) · Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, 1/3) · Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) infra — all 8 died in GitHub's Set up job step before checkout: ##[error]Failed to download archive 'https://codeload.github.com/actions/checkout/tar.gz/d234...' after 3 attempts (429/502/503). No test ran a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Timeout harness — xdist.dsession.Interrupted: session-timeout: 7200.0 sec exceeded at 95% with every executed test PASSED; the graceful session-timeout is treated as core-blocking, so one overrun reds the shard #114956 (ours, open)
Finish Workflow / Post Hooks (new_tests_check.py) consequence, not an independent defect — with Build (llvm_coverage_build) killed above, all four Bugfix validation jobs were DROPPED for want of a binary, so the hook correctly reported that no per-arch job validated the bug same owner as the Set up job row above

Session id: cron:our-pr-ci-monitor:20260817-183000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the automated review: intDiv and divide now decline monotonicity before comparing an IP-typed constant divisor with numeric zero. Added IPv4 divisor regression cases for both functions and merged current master (commit ee7f2ac).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 19, 2026
Merged via the queue into ClickHouse:master with commit caccecd Aug 19, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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.
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]>
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-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants