Skip to content

Add regression tests for intDiv and divide key analysis with an IPv4 or IPv6 operand - #112388

Merged
nihalzp merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-intdiv-ip-key-monotonicity
Sep 8, 2026
Merged

nihalzp merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-intdiv-ip-key-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112156
Related: #112151

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Regression coverage for intDiv and divide key analysis with an IPv4 or IPv6 operand. This PR no longer changes any source file.

It started as a source fix, but the fix landed on master independently: #112156 shipped getArithmeticType and getArithmeticField, which model IPv4 as UInt32 and IPv6 as UInt128 and are applied in both the null-endpoint and the bounded arm. That is the same normalization this branch carried, so the conflicting hunk is resolved by taking master's version whole and only the test remains.

Master also declines monotonicity for a non-numeric constant divisor rather than computing it. The four rows that asserted Granules: 3/4 for an IP constant divisor are therefore dropped rather than re-expected or inverted, and the remaining assertions for that shape are stated as correctness only. Nothing here pins whether such a divisor prunes, so the open question on that behaviour is untouched.

What the test adds over 04651_intdiv_const_variable_monotonicity_ip: a LowCardinality(IPv4) and a Nullable(IPv4) key, a UInt128 key, an all-zero IP divisor asserted as ILLEGAL_DIVISION, and plus/minus/multiply controls. No test on master exercises an IP key together with a type wrapper.

Validated against a binary whose FunctionBinaryArithmetic.h is byte-identical to master: 40/40 rows pass, 12/12 with settings randomization and 8/8 self-parallel. On 26.7 the oracle rows read 0 where master reads 1, so they still fail without the fix.


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

groeneai and others added 5 commits July 28, 2026 14:18
…notonicity

`intDiv`/`divide` never see an `IPv4`/`IPv6` operand as itself:
`getReturnTypeImplStatic` substitutes `IPv4` with `UInt32` and `IPv6` with
`UInt128`, and `executeImpl` does the same on the columns. But
`FunctionBinaryArithmeticWithConstants::getMonotonicityForRange` reasoned about
the declared types and the raw endpoint/constant `Field`s, which produced two
user-visible bugs.

Silently missing rows: `WhichDataType::isUInt()` is false for `TypeIndex::IPv4`
and `IPv6`, so the signed-wrap guard `isUInt(arg_type) && isInt(divisor_type)`
never fired for an IP key and the arm fell through to an unconditional
"always monotonic". The arithmetic, however, is exactly the step function that
guard exists to reject: with a signed constant `ResultOfIntegerDivision` yields
a signed result of the dividend's width, so `DivideIntegralImpl::apply` takes
its `make_signed_t` branch and every dividend at or above 2^31 (`IPv4`) or
2^127 (`IPv6`) reinterprets as negative. Key analysis transformed the key range
under a false monotonicity claim, the transformed range matched no granule, and
matching rows were dropped with no error and a zero exit code.

Query failure: `is_arithmetic_v<IPv4>` is false and the accurate-comparison
visitors have no `IPv4`/`IPv6` arm, so comparing an IP-tagged `Field` against
zero throws `BAD_TYPE_OF_FIELD`. The first such comparison in this arm is the
divisor-zero check, so every `intDiv`/`divide` by an IP constant over a table
with a primary key failed during key analysis, whatever the key type.

Two static helpers normalize the declared types and the `Field` values before
the existing guards run; both are the identity for any non-IP input, so numeric
behaviour is unchanged. The value conversion goes through `castColumn`, the same
primitive the substitution in `executeImpl` uses, because `IPv6` is stored
big-endian and its cast to `UInt128` swaps the limbs and byte-swaps each: a raw
copy of the underlying value yields a different number for almost every address
and coincides only for ffff:...:ffff, which would have reintroduced the wrong
pruning while passing a test whose fixtures used that value.

The divisor constant is normalized once before the branches split, so all three
divisor-zero checks - the main arm, its null-endpoint twin, and the
equal-endpoints branch that returns before both - share one normalized value and
a future fourth check cannot forget it.

Correct pruning is preserved rather than disabled: an unsigned constant divisor
never reinterprets the dividend, and a signed-divisor range that stays on one
side of the wrap point is genuinely monotonic. Both are asserted with
`EXPLAIN indexes = 1` granule counts, not only with row counts, so a change that
quietly degrades the optimization fails the test.

The `const / variable` role and the `multiply` arm have the same class of defect
but different mechanisms and are handled separately.

Co-Authored-By: Claude Opus 5 <[email protected]>
…mization tag

The one-sided-range control asserted a granule count that the direct key bound
already produced on its own, so it would have stayed green under a design that
refused to prune signed-divisor IP ranges altogether. Give it a fixture whose two
lowest values quotient to zero, so the intDiv half removes a granule the bound
keeps, and assert both counts: the bound alone reads 3 of 5 granules and the
conjunction reads 2. A new mutation that forces the signed-wrap detector to reject
every range now reddens exactly that one row, which is the liveness proof.

Drop no-random-merge-tree-settings. Every assertion that depends on the granule
layout pins index_granularity in its own DDL, and an explicit per-DDL merge-tree
setting wins over the value the test harness injects, so the tag suppressed about
eighty-five unrelated randomizations for nothing.
Every EXPLAIN granule assertion in the test was keyed on IPv4, so a substituted IPv6 width that
was too narrow would move the wrap point from 2^127 down to 2^31 and could go unnoticed. Add the
IPv6 analogue of the existing one-sided pruning pair on a dedicated singleton-granule fixture,
asserting both the bound-only count and the conjunction count so the intDiv half is what removes
a granule.

Measured on the fix build: bound-only reads 3/5 and the conjunction reads 2/5, the two counts are
mutually distinguishing, and both are stable across optimize_use_implicit_projections. A mutation
that narrows the substituted IPv6 width to UInt32 reddens the new correctness row and the new
pruning row while leaving the bound-only row and the unbounded IPv6 rows green, because the
narrowed guard stops firing for a range that lies above 2^31 and still spans 2^127.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment text only. No behavioural change: no code line, assertion, fixture
value, granule count or reference row is touched.

The t6p comment in 04652 claimed that substituting a too-narrow IPv6 width
refuses monotonicity for every range and leaves the answers correct. Both
halves are wrong. Narrowing moves the wrap point from 2^127 down to 2^31,
and enumerating intDivRangeCrossesSignedWrap over the five granule ranges
shows the refusal count is 1 of 5 either way -- a different range is
refused, not more of them. The range straddling 2^31 is refused (pruning
lost), while the range above 2^31 that straddles the true 2^127 stops being
refused, so monotonicity is falsely claimed, intDiv inverts the endpoints
and rows are silently dropped. Both the correctness row and the pruning row
react, not just the pruning row.

The null-endpoint comment in FunctionBinaryArithmetic.h claimed only one
endpoint can be null at that point. The enclosing guard is a disjunction and
the equal-endpoints check comes later, so both endpoints can be null there,
and KeyCondition.cpp reaches that state directly with two default-constructed
Fields. Behaviour is unaffected -- substituteIPField is the identity for a
Null Field and the guard already models a null endpoint as unbounded -- so
this is a documentation fix.
The test asserted the preserved-pruning half of the contract only for an
IPv4/IPv6 key: every EXPLAIN indexes = 1 row used a numeric divisor, and
every IP-divisor row was a result-equality row. A conservative reject for
an IP constant divisor leaves those counts correct, merely unpruned, so
none of them could react and an implementation refusing every IP divisor
would have passed the whole file. That is the design this fix chose
against, so it needs an assertion.

Add four granule-count rows over the existing singleton-granularity
fixture, covering intDiv and divide by both an IPv4 and an IPv6 constant.
Each reads 3/4: the lowest granule maps strictly negative and cannot
satisfy the predicate, while a conservative reject would read 4/4. Also
add the missing divide-by-IPv6 correctness row, which had no coverage in
either direction.

Fix a one-word contradiction in the IPv6 width comment: it said "the only
assertion that reacts" three lines above "Both rows below react".

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Five review rounds, each with an independent cold reviewer and a separate second-model gate pass
over the resulting code: 27 findings adjudicated, 16 agreed, 3 disagreed, 8 dropped after
verification. The final round's gate returned zero findings. Each disagreement is backed by a
measurement or a code citation, not by an argument.

finding verdict
❌ The EXPLAIN indexes = 1 assertion for the one-sided IPv4 range was vacuous: on the original fixture the direct bound alone already selected the asserted granule count, so the intDiv half of the conjunction contributed nothing and the row would still have passed under a design that refused to prune signed-divisor IP ranges at all. AGREE, fixed. Dedicated 5-value fixture where the bound alone reads Granules: 3/5 and the conjunction reads 2/5, both asserted; the two counts are mutually distinguishing (neither query's output contains the other's number). A mutation forcing the wrap detector to always reject reddens exactly the pruning rows and leaves the bound-only and correctness rows green.
❌ No assertion could fail if the IPv6 substitution returned a too-narrow width: all granule assertions were IPv4-keyed, and the IPv6 fixtures used a divisor below both wrap points. AGREE, fixed. IPv6 analogue of the pruning pair added, plus a mutation narrowing the substituted IPv6 width.
❌ Nothing asserted that pruning survives for an IP constant divisor, the half of the change that fixes the query failure. Those rows compare row counts or an error code, and a conservative reject leaves every one of them correct and merely unpruned, so an implementation that refused monotonicity for every IP divisor would have passed the whole file. AGREE, fixed. Four EXPLAIN indexes = 1 granule assertions added for intDiv and divide with IPv4 and IPv6 constant divisors, plus the missing divide-by-IPv6 oracle row, plus a mutation that performs exactly that conservative reject and must redden those four rows and nothing else. Verified first that no existing mutation covered the gap: reverting the type substitution leaves the divisor verdict monotonic, and the two mutations that reintroduce the exception abort the whole file rather than pinning anything specific.
❌ The comment describing that IPv6 width mutation was wrong in three ways: it claimed one row reacts, that monotonicity is then refused for every range, and that the answers stay correct. AGREE, fixed. Enumerating the wrap detector over the five granule ranges under both wrap points shows narrowing does not refuse more ranges (1 of 5 either way) but a different one: a range straddling 2^31 becomes refused (pruning lost) while a range above 2^31 that straddles the true 2^127 stops being refused, so monotonicity is falsely claimed, intDiv inverts the endpoints, and rows are dropped. Measured: two rows react, one of them a correctness row. The comment now states the two-directional failure, and the assertions turn out stronger than it claimed rather than weaker.
⚠️ Array/Tuple keys whose elements are IPv4/IPv6 still receive a false monotonicity verdict. AGREE on the mechanism, DISAGREE on scope. The shapes are pre-existing and untouched here (this diff adds no Array/Tuple/Map handling, and the two helpers are top-level TypeIndex/Field::Types tests, so a compound key takes byte-identical control flow before and after). The suggested remedy is already implemented at a strictly more general layer by #112339, which refuses monotonicity for Array/Tuple/Map at the top of this same function and therefore covers an IP-element container exactly as it covers a numeric one. Adding a second rejection on the same line would duplicate a published fix and deepen the textual conflict measured between the two branches. The boundary is stated in the description.
⚠️ intDiv(constant, ip_key) still raises BAD_TYPE_OF_FIELD after this change, and the description did not say so. AGREE on the measurement, DISAGREE that it belongs in this diff. Reproduced on both binaries: that shape dies in the equal-endpoints divisor-zero check, whose dividend comparison is the sibling statement of the one this PR normalizes. It is owned by #112156, whose const / variable gate sits earlier in this same function and returns before the comparison is reached (isNumber is false for TypeIndex::IPv4/IPv6), and whose test carries the exact shape. Folding that gate in here would stack two PRs on one hunk. Now disclosed in the description with the owning PR.
⚠️ The description's merge-order paragraph was wrong: it named one conflicting PR. AGREE, corrected. git merge-tree --write-tree against each sibling shows three conflicts (#112151, #112156, #112339) and one clean merge (#112231). Re-measured against current master every round since, including this one: unchanged.
⚠️ The description exceeded the reviewer-facing length budget, and its title ran to 107 characters. AGREE, condensed. Retitled to 67 characters; the investigation detail, alternatives considered and validation matrices are kept out of the description.
💡 The no-random-merge-tree-settings tag was not load-bearing. AGREE, dropped. The explicit per-DDL SETTINGS index_granularity already wins over the runner's injected randomization, so the tag only suppressed unrelated randomizations. Verified by 100 runs with randomization enabled across two rounds, five forced adversarial merge-tree draws with a positive control proving the flag reaches the client, and three index_granularity_bytes values all yielding the same mark count because both settings are a maximum and the row cap binds first; corroborated by in-tree tests that assert exact granule counts with no tag.
💡 A comment claimed only one endpoint can be null in the null-endpoint branch. AGREE, corrected. The branch guard is a disjunction and the equal-endpoints check comes later, so both endpoints can be null, and KeyCondition calls this function that way. Behaviour is unaffected: the value normalization is the identity for a null Field, and the wrap detector already models a null endpoint as an unbounded side.
💡 The changelog entry opened in the past tense. AGREE, applied. docs/changelog_entry_guidelines.md prescribes the present tense and uses this exact substitution as its worked example.
💡 Four comment-wording nits (a function name written with parentheses; the hoisted divisor value deserved one clause explaining why it is deliberately a null Field for non-division functions; the IPv6-width comment still said "the only assertion" one line above correctly saying two react; the test preamble describes one oracle form where the file uses three). AGREE. The first three are applied. The last is recorded rather than applied: it is an over-general sentence in a test preamble that affects no assertion, and the rows it describes are independently shown live.
💡 The test file number is shared with a sibling branch. DISAGREE, not a defect. check_gaps_in_tests_numbers collects numbers into a set and reports only gaps of 100 or more, never collisions, and the number is absent from master, so no file is overwritten.

One claim was withdrawn during review rather than fixed. An earlier round's prescribed mutation
placed the conservative-reject counterfactual inside a single division arm; applied verbatim it
aborts the server with Inconsistent KeyCondition behavior instead of moving a verdict, because
the same expression is answered by three arms and rejecting in one leaves the other two claiming
monotonicity. That is a self-inconsistent mutant, strictly weaker than intended, and it never
reaches the rows it was meant to pin. Re-expressed at the point where the fix itself normalizes,
so all three arms reject coherently, it produces the required signature: exactly the four
constant-divisor pruning rows move, no answer changes.

Test liveness was verified independently rather than assumed, by running the file against a
master build: it exits with the same BAD_TYPE_OF_FIELD this change fixes after nine
assertions have already printed a mismatch, and passes 44 of 44 with the fix. Both
serverError expectations discriminate too, reporting the type-comparison failure before the
change and division by zero after it.

Noted and not blocking: the one remaining raw-Field-against-zero comparison in this function
belongs to the multiply arm, which fails by a different mechanism and is tracked separately.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -n --path=$(mktemp -d) --queries-file tests/queries/0_stateless/04652_intdiv_ip_key_monotonicity.sql < /dev/null exits RC=169 on master: the first nine assertions print 0 (keyed count differs from the ENGINE = Memory oracle, i.e. rows silently dropped) and then the file aborts with Code: 169 ... Cannot compare DB::IPv4 with long. (BAD_TYPE_OF_FIELD). No randomization, no timing, no settings dependency.
b Root cause explained? Yes. getReturnTypeImplStatic substitutes IPv4 with UInt32 and IPv6 with UInt128, but FunctionBinaryArithmeticWithConstants::getMonotonicityForRange reasons about the declared types and the raw Fields. (1) WhichDataType::isUInt() is false for TypeIndex::IPv4/IPv6, so the signed-wrap guard never fires for an IP key and the arm falls through to an unconditional "always monotonic", while with a signed constant ResultOfIntegerDivision produces a signed result of the dividend's width and DivideIntegralImpl::apply takes its make_signed_t branch, so every dividend >= 2^31 / >= 2^127 reinterprets as negative; the range is transformed under a false claim, matches no granule, and rows are dropped silently. (2) is_arithmetic_v<IPv4> is false and FieldAccurateComparison.cpp has no IP arm, so the divisor-zero comparison on an IP-tagged Field throws BAD_TYPE_OF_FIELD during key analysis.
c Fix matches root cause? Yes. It restores the type/value correspondence at the point the model is formed, inside the owning function, reusing castColumn, the same primitive the substitution in executeImpl performs. No widened bound, no no-random-* band-aid, no defensive check at the symptom. Notably it does not fix correctness by disabling the optimization: rejecting IP dividends outright was rejected because it deletes genuinely-monotonic pruning, and the test pins that pruning survives.
d Test intent preserved / new tests added? New stateless test 04652_intdiv_ip_key_monotonicity with 44 assertions (keyed MergeTree vs ENGINE = Memory oracle, plus EXPLAIN indexes = 1 granule-count liveness rows covering both an IP key and an IP constant divisor). No existing test was modified, weakened or removed; a 528-test in-area sweep moved no reference file. The test carries no no-random-* tag: every assertion that depends on index_granularity pins it per DDL, which wins over the harness's injected randomization, measured across 50 randomized runs plus four forced adversarial merge-tree draws.
e Both directions demonstrated? Yes. master: 9 mismatching rows then Code 169 (RC=169). Fix build (Build ID bddde5c101e9b8fa60b4fd2cb2492ea2df600812, verified against readelf and against the server's buildId()): all 44 rows pass, byte-identical to .reference, and 50/50 randomized plus 50/50 non-randomized runs pass. Every part of the change is mutation-tested and reddens only its own rows: reverting the type normalization brings the wrong-results rows back; reverting the value normalization makes the guard fire and then throw; reverting the equal-endpoints normalization reddens only the single-point row; replacing castColumn with a raw bit copy reddens only the IPv6 rows; forcing the signed-wrap detector to reject every range reddens only the two IP-key pruning-liveness rows; narrowing the substituted IPv6 width reddens only the two IPv6 one-sided rows, which is what proves the width itself is pinned; and refusing to model an IP constant divisor at all (the conservative-reject design this fix chose against) reddens only the four * const prunes rows and moves no answer, which is what proves the IP-divisor half of the pruning claim is pinned too.
f Fix is general across code paths? Yes. Both variable / constant branches (non-null and null endpoint) and the equal-endpoints divisor-zero check are fixed; divide shares the arm and is covered; intDivRangeCrossesSignedWrap and intDivConstReinterpretsNegative need no change (their widths are already right for IP and these are their only call sites); the Decimal rejection is unaffected. The two remaining Field-vs-zero sites are deliberately other changes' scope and verified so by grep: the const / variable direction (covered by #112156) and the multiply arm (different mechanism, tracked separately). Carrier set is closed: of Date, Date32, DateTime, Enum8, UUID, FixedString, Bool, only Bool besides the IP types type-checks with intDiv, and Bool is already UInt8 with its own visitor arm.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Both widths (IPv4 at 2^31, IPv6 at 2^127); both signs of the signed constant; = and range predicates; one-sided ranges, with the bound-only and conjunction granule counts both asserted so the intDiv half is shown to prune; Int8 and Int32 divisors; LowCardinality(IPv4) and Nullable(IPv4) keys with both a correctness row and a pruning-liveness row each; IPv6 boundary values ::1, 1::, ::ffff chosen because their raw-bit and cast readings differ by many orders of magnitude, so a future byte-order-blind conversion fails loudly; an all-zero IP divisor asserted to be recognized as zero (reaches execution and reports ILLEGAL_DIVISION instead of failing key analysis); and numeric non-regression twins on UInt32/UInt128/Int32 keys with byte-identical values.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to declare. No setting, default, serialization format, or protocol change, so no SettingsChangesHistory.cpp entry and no experimental gate. The only user-visible change is that previously-dropped rows are returned and previously-failing queries succeed.
i Invariants and contracts preserved? Yes. Both helpers are the identity for every non-IP input, so no numeric verdict can change (pinned by the numeric rows and by the 528-test sweep). The divisor constant is normalized once before the branches split; for non-division functions it stays a Null Field whose only unconditional read takes accurateEquals's Null-vs-non-Null fast path and is then consumed only under the divide/intDiv test, so plus/minus/multiply verdicts are unchanged. No new failure mode on the key-analysis path: for these two conversions castColumn is total: IPv6 -> UInt128 is a fixed two-limb std::byteswap loop with no parsing, no range check and no error path, and IPv4 is a StrongTypedef<UInt32> widening. A guard that starts firing can only reduce pruning, never create new wrong results, which is why the controls assert granule counts and not merely row counts.

Session id: cron:clickhouse-impl-slot-41:20260729-014800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @rschu1ze - could you review this? intDiv/divide substitute an IPv4/IPv6 operand with UInt32/UInt128, but getMonotonicityForRange reasoned about the declared type and the raw Field, so the signed-wrap guard never fired for an IP key (rows silently dropped across 2^31/2^127) and comparing an IP-tagged divisor against zero threw BAD_TYPE_OF_FIELD. The fix normalizes both before the existing guards run, and the test asserts via EXPLAIN indexes = 1 that correct pruning is preserved rather than disabled.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e216cd9]

Summary: ✅


AI Review

Summary

This PR has been reduced to a tests-only addition for intDiv / divide key analysis with IPv4 / IPv6 operands. The remaining coverage is mostly solid, but the new LowCardinality(IPv4) / Nullable(IPv4) rows do not actually exercise the wrapped-IP monotonicity path they are meant to protect, so the PR still misses the one behavior it now claims to add beyond the existing 04651_* coverage.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04652_intdiv_ip_key_monotonicity.sql:90] The wrapper-specific coverage is ineffective. Both wrapped MergeTree fixtures use index_granularity = 1, so every mark is a single-point interval and getMonotonicityForRange returns from its equal-endpoints shortcut before the wrapped-IP normalization logic runs. The accompanying pruning rows use an unsigned divisor, so they also miss the signed-wrap branch. A regression that stops unwrapping LowCardinality / Nullable around an IP key would still pass these rows.
    Suggested fix: add at least one wrapped fixture with a non-singleton range that crosses the signed wrap or reuse the one-sided ip_mono_t4p shape under LowCardinality / Nullable.
Final Verdict

⚠️ Changes requested. The PR’s remaining value is wrapper coverage, and that coverage does not currently reach the code path that was buggy.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f46d1ea

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 monotonicity canary at MergeTreeDataSelectExecutor.cpp:2457. The canary line is (intDiv(column 0, 18446744073709551615) in [-2, -2]) on a fuzzed Nullable(Int32) key: toUInt64('340282366920938463463374607431768211455') truncates to UInt64 max, i.e. an effective divisor of -1 at Int32 width. Not the IP-substitution mechanism this diff changes #112151 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit Code: 202 TOO_MANY_SIMULTANEOUS_QUERIES under parallel replicas; reproducible 3/3 on rerun, not caused by this diff #112385 (mine, open)

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

Resolve the one conflict in src/Functions/FunctionBinaryArithmetic.h.

Master's merged ClickHouse#112339 inserted a compound-type early return at the top of
getMonotonicityForRange, at the same place this branch inserts the normalized
right_constant. The two additions are orthogonal, so both are kept: the
compound guard runs first, so a compound type returns before the constant is
normalized, and substituteIPType / substituteIPField are unaffected.

Verified the merged file adds and removes exactly the same 55 and 10 lines
against master as this branch did against the merge base, so the resolution
introduces no behaviour of its own. 04652_intdiv_ip_key_monotonicity fails on
master (9 disagreeing rows, then BAD_TYPE_OF_FIELD) and passes here;
04652_compound_key_monotonicity still passes, so master's guard is intact.
@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.70% +0.20%

Changed lines: Changed C/C++ lines covered: 47/48 (97.92%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d8ccdd4

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

@nihalzp nihalzp self-assigned this Aug 3, 2026

const bool is_div_function = name_view == "divide" || name_view == "intDiv";

// Normalize the constant divisor once, before the branches split, so that every divisor-zero

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai Cut the length of the code comments in half. Do not reference other places in the code.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 320766a.

Comment blocks in this region go from 49 lines to 20, none longer than 2 lines, and every
see <symbol> pointer is gone. I trimmed the whole diff rather than only the block you
flagged, including the neighbouring Decimal and signed-wrap comments and the SQL test, which
was describing C++ internals. The reasoning that was in the comments is now in the commit
message.

The source change is comment-only. The test change is not: it also drops the
ignore_drop_queries_probability = 0 pins that @ alexey-milovidov asked me to remove. Since
that exposes the test to leftover tables in a stress run, I made it independent of prior state
instead of re-pinning: tables are prefixed ip_mono_ (the old t4 is created by 15 other
stateless tests, and stress shares one database across tests in half its threads), and setup
uses CREATE OR REPLACE TABLE, which discards a retained table's rows.

04652 passes 44/44, still fails on master without the fix, and now also passes with a foreign
t4 and stale own-named tables pre-created.

Per review: cut the comment length in half in the monotonicity code and stop pointing at
other places in the code. Comment blocks in the touched region go from 49 lines to 20, all
blocks are at most 2 lines, and every `see <symbol>` pointer is gone. The reasoning those
pointers carried is here instead:

- The constant divisor is normalized once before the branches split so that both divisor-zero
  checks (the null-endpoint arm and the equal-endpoints arm) compare the value the division
  actually uses. For a non-division function name it stays a `Null` `Field`;
  `FieldVisitorAccurateEquals` returns false whenever exactly one side is `Null`, so it never
  compares equal to zero, and the resulting boolean is read only under `is_div_function`.
- `intDiv`/`divide` by a Decimal constant goes through
  `DecimalBinaryOperation`, which feeds both operands into
  `DivideIntegralImpl<NativeResultType, NativeResultType>` after casting the dividend into the
  decimal's native signed width and pre-multiplying it by the scale. The wrap boundary
  therefore depends on the decimal width and scale rather than on the dividend width, which is
  why monotonicity is not claimed. A Float divisor computes through floating point and stays
  monotonic.
- `intDiv(unsigned, signed-integer-const)` reinterprets the dividend through a signed cast in
  `DivideIntegralImpl`, which is what `intDivRangeCrossesSignedWrap` models. An unbounded range
  over an unsigned domain always contains the discontinuity, so it is never always-monotonic.
- The mirror case is `intDivConstReinterpretsNegative`: an unsigned constant divisor with its
  high bit set is cast to a negative divisor, so the function decreases even though the raw
  constant looks positive.
- `substituteIPField` must cast rather than copy the underlying bits because `IPv6` is stored
  big-endian and `convertFromIPv6ToUInt128` swaps the limbs and byte-swaps each, so a
  `toUnderType` bit copy would yield a different number. Reusing the cast the substitution
  itself performs keeps the two in step.

Also removes the `ignore_drop_queries_probability = 0` pins from the test, as requested
separately, and trims the SQL comments, which described C++ internals.

No behaviour change: the source diff is comment-only. 04652 still passes 44/44 with the fix
and still fails without it (9 zeros, then `Code: 169 Cannot compare DB::IPv4 with long`).
… probability

Removing the `ignore_drop_queries_probability = 0` pins exposes the test to retained tables
in a stress run, where an ignored `DROP TABLE` keeps a disk-backed table and truncates a
memory-backed one. Two changes make the test immune rather than re-pinning the setting:

- Prefix every table with `ip_mono_`. The old names collided with other tests: `t4` is
  created by 15 other stateless tests and `m4` by one, and stress runs share one database
  across all tests in half of its threads, so a foreign leftover could feed this test's
  oracle. No other test in the suite or on master uses the `ip_mono_` prefix.
- Use `CREATE OR REPLACE TABLE` instead of `CREATE TABLE IF NOT EXISTS`, which discards the
  rows of a retained table of either engine, so setup no longer depends on prior state. This
  also makes the leading `DROP TABLE IF EXISTS` block redundant; the trailing cleanup stays,
  because `clickhouse-test` checks for leftover tables.

Verified with three runs of the test: passes 44/44 with the fix; still fails on pristine
master (9 zeros, then `Code: 169 Cannot compare DB::IPv4 with long`); and passes with a
foreign `t4` and own-named tables holding wrong rows pre-created, which the previous revision
failed.

Also corrects the preamble, which claimed every row compares MergeTree against Memory while
the file also asserts granule counts and two expected errors.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 320766a

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_msan) / Logical error: Bad cast from ColumnNothing to ColumnVector<char8_t> (STID: 1499-2747) logical error, pre-existing on master #113609 (mine, open)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found deadlock, pre-existing on master #113692 (mine, open)
Sync - CH Inc sync (private, not actionable)

STID 1499-2747 is the Nothing-element array comparison logical error, which is a trunk bug
unrelated to this diff (src/Functions/FunctionBinaryArithmetic.h plus its own test
04652_intdiv_ip_key_monotonicity, which passed). Build (arm_release) / Post Hooks reports a
failed row while that check's own conclusion is success - bookkeeping noise, not ledgered.

Session id: cron:our-pr-ci-monitor:20260810-193000

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

Copy link
Copy Markdown
Collaborator Author

I re-measured this PR against current master (ee7f2ace467d, "Fix IP constant divisor monotonicity") and most of it has already landed.

The correctness half is fixed on master. #112156 shipped getArithmeticType/getArithmeticField and applies them in both the null-endpoint and the bounded arm, which is the same normalization this PR does. Running this PR's own test file against a master binary, 40 of its 44 rows already pass, including every oracle row and the one-sided shapes:

IP key, signed constant divisor master 26.7
ipv4 / ipv6, two-sided range crossing the wrap 1 0
ipv4 / ipv6, one-sided (null-endpoint arm) 1 0

1 means key analysis agrees with an ENGINE = Memory oracle. 26.7 is the pre-fix control, which also throws Code: 169 BAD_TYPE_OF_FIELD on the IP-divisor rows, so the probe does discriminate.

What is left is 4 pruning-quality rows, all for a numeric key with an IP constant divisor:

b intdiv ipv4 const prunes     master: Granules 4/4     this PR: 3/4
b intdiv ipv6 const prunes
b divide ipv4 const prunes
b divide ipv6 const prunes

Master declines monotonicity for a non-numeric divisor; this PR models IPv4/IPv6 as UInt32/UInt128 and computes it exactly, so those queries prune. Neither behaviour gives wrong results, so this is a pruning improvement, not a bug fix.

@alexey-milovidov you added that decline, so rather than push a merge that replaces it: is the exact computation wanted here, or should the conservative decline stand?

If it stands, I would still like to keep the test coverage that 04651_intdiv_const_variable_monotonicity_ip does not have: LowCardinality(IPv4) and Nullable(IPv4) keys, a UInt128 key, the all-zero IP divisor asserted as ILLEGAL_DIVISION, and plus/minus/multiply controls. All of those already pass on master, so I can reduce this PR to tests only.

@nihalzp

nihalzp commented Aug 30, 2026

Copy link
Copy Markdown
Member

@groeneai Fix conflicts.

The monotonicity fix this PR carried has landed on master independently:
9b89056 ships getArithmeticType and getArithmeticField, which model IPv4 as
UInt32 and IPv6 as UInt128 exactly as substituteIPType and substituteIPField did,
and applies them in both the null-endpoint and the bounded arm. Keeping this
branch's copy would restate merged code, so the conflicting hunk is resolved by
taking master's version whole.

Master also declines monotonicity for a non-numeric constant divisor rather than
computing it. That decision is deliberate and belongs to its author, so the four
rows asserting Granules: 3/4 for an IP constant divisor are dropped instead of
being re-expected or inverted: pinning either value would pre-empt a design
question that is still open on this PR. Those assertions are now stated as
correctness only, so nothing in the file claims that shape prunes.

What remains is coverage the 04651 family does not have: a LowCardinality(IPv4)
and a Nullable(IPv4) key, a UInt128 key, an all-zero IP divisor asserted as
ILLEGAL_DIVISION, and plus/minus/multiply controls. No master test exercises an
IP key together with a type wrapper.

Validated against a binary whose FunctionBinaryArithmetic.h is byte-identical to
master: 40/40 rows pass, 12/12 with settings randomization and 8/8 self-parallel.
On 26.7 the oracle rows read 0 where master reads 1, so they still redden without
the fix.
@groeneai groeneai changed the title Fix key analysis for intDiv and divide with an IPv4 or IPv6 operand Add regression tests for intDiv and divide key analysis with an IPv4 or IPv6 operand Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in ec0c864; the PR is MERGEABLE again.

The only conflicting file was src/Functions/FunctionBinaryArithmetic.h, and I resolved it by taking master's version whole, because the fix this PR carried has already landed there. #112156 shipped getArithmeticType and getArithmeticField, which model IPv4 as UInt32 and IPv6 as UInt128, and applies them in both the null-endpoint and the bounded arm. Keeping my side of that hunk would have restated merged code and removed the conservative IP-divisor decline that came with it.

That leaves this as a tests-only PR, so I retitled it and moved the changelog category off Bug Fix. The pr-bugfix label is stale as a result; I have not touched labels.

The test still covers what 04651_intdiv_const_variable_monotonicity_ip does not: a LowCardinality(IPv4) and a Nullable(IPv4) key, a UInt128 key, an all-zero IP divisor asserted as ILLEGAL_DIVISION, and plus/minus/multiply controls. Validation is in the description.

One behaviour is deliberately not pinned: master declines monotonicity for a non-numeric constant divisor instead of computing it, so the four rows that asserted Granules: 3/4 for an IP constant divisor are dropped rather than inverted. That is a separate open question on this PR and nothing here decides it.

@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 58854ec

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_msan) / Logical error: Unexpected return type from globalIn (STID 3262-3243) flaky trunk defect (GROUPING SETS plus globalIn partial fold); 11 unrelated PRs and 0 master runs in 30d #116980 (external, open)

Session id: cron:our-pr-ci-monitor:20260831-030000

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-ci labels Sep 8, 2026

-- (C) A wrapped IP key must behave exactly like a bare one, for correctness and for pruning.
SET allow_suspicious_low_cardinality_types = 1;
CREATE OR REPLACE TABLE ip_mono_t4lc (a LowCardinality(IPv4)) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These LowCardinality(IPv4) / Nullable(IPv4) rows are meant to be the remaining coverage this PR adds over 04651_*, but both wrapped MergeTree fixtures use index_granularity = 1. That makes every mark a single-point interval, so getMonotonicityForRange returns from the equal-endpoints fast path at src/Functions/FunctionBinaryArithmetic.h:3873 before the recursiveRemoveLowCardinality / removeNullable + getArithmeticType / getArithmeticField logic that actually handles wrapped IP keys in the variable / constant branch runs.

The companion pruning probes do not rescue this: they use an unsigned divisor, so they never hit the signed-wrap path either. As written, a regression that stops unwrapping LowCardinality / Nullable around an IP key would still pass all four wrapper rows, so the only new behavior this tests-only PR claims to add is not actually pinned.

Please make at least one wrapped fixture use a non-singleton range that reaches the signed-divisor branch (for example a wrapped version of the ip_mono_t4 or ip_mono_t4p shape) so the wrapper coverage exercises the same path as the original bug.

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.

I measured this before answering, and the claim does not hold on either the mechanism or the consequence.

I instrumented getMonotonicityForRange on e216cd9a496e (a print at the accurateEquals(left_point, right_point) return, and one at the entry of the variable / constant branch), and separately made that branch stop unwrapping: arg_type/divisor_type taken as left.type/right.type instead of removeNullable(recursiveRemoveLowCardinality(...)), which is the regression your last paragraph describes, at the call sites you cite. Debug build, --no-random-settings --no-random-merge-tree-settings.

Unmutated, per wrapper row, equal-endpoints returns / variable / constant entries: c lc signed 1/5, c nullable signed 1/4, c lc unsigned prunes 0/6, c nullable unsigned prunes 0/5. The branch is entered 4 to 6 times per query, so index_granularity = 1 is not preempting it.

Under the no-unwrap mutation the test fails, on exactly one row:

-c nullable signed	1
+c nullable signed	0

That is one of the four wrapper rows, so the regression is pinned. The same test is OK on the unmutated binary.

The proposed non-singleton range does not change this. Repeating the matrix at index_granularity = 4 instead of 1: Nullable(IPv4) signed goes 1 to 0 under the mutation at both granularities, and the LowCardinality(IPv4) rows stay 1 at both.

Where the claim does land, and it is worth naming: the two LowCardinality rows do not react to that mutation at either granularity, and no fixture can make them, because the wrapper is already gone when the function is entered. Instrumented left.type for the LowCardinality(IPv4) table is IPv4, and the branch runs with arg_type=IPv4 arith=UInt32 divisor=Int8, the same path the bare IPv4 rows take. So those two rows redden for an IP-width regression and give end-to-end coverage of a LowCardinality(IPv4) key, but they are not a pin on recursiveRemoveLowCardinality, and the PR does not claim they are.

Leaving the fixtures as they are.

@nihalzp
nihalzp added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 42c0978 Sep 8, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-testing Test content only (no production code). labels Nov 22, 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 comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog 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.

6 participants