Repository navigation
Conversation
…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]>
Internal second-model reviewFive review rounds, each with an independent cold reviewer and a separate second-model gate pass
One claim was withdrawn during review rather than fixed. An earlier round's prescribed mutation Test liveness was verified independently rather than assumed, by running the file against a Noted and not blocking: the one remaining raw- |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260729-014800 |
|
cc @antaljanosbenjamin @rschu1ze - could you review this? |
|
Workflow [PR], commit [e216cd9] Summary: ✅ AI ReviewSummaryThis PR has been reduced to a tests-only addition for Findings
Final Verdict |
CI finish ledger — f46d1eaEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 47/48 (97.92%) · Uncovered code |
CI finish ledger - d8ccdd4CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 157 success, 17 skipped, 0 failures.
Verified from the paginated check-runs API rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers. Session id: cron:our-pr-ci-monitor:20260803-163000 |
|
|
||
| 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 |
There was a problem hiding this comment.
@groeneai Cut the length of the code comments in half. Do not reference other places in the code.
There was a problem hiding this comment.
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.
CI finish ledger - 320766aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
STID 1499-2747 is the Session id: cron:our-pr-ci-monitor:20260810-193000 |
|
I re-measured this PR against current master ( The correctness half is fixed on master. #112156 shipped
1 means key analysis agrees with an What is left is 4 pruning-quality rows, all for a numeric key with an IP constant divisor: Master declines monotonicity for a non-numeric divisor; this PR models @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 |
|
@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.
|
Fixed in ec0c864; the PR is The only conflicting file was That leaves this as a tests-only PR, so I retitled it and moved the changelog category off Bug Fix. The The test still covers what 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 |
CI finish ledger - 58854ecEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260831-030000 |
|
|
||
| -- (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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Related: #112156
Related: #112151
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Regression coverage for
intDivanddividekey analysis with anIPv4orIPv6operand. This PR no longer changes any source file.It started as a source fix, but the fix landed on master independently: #112156 shipped
getArithmeticTypeandgetArithmeticField, which modelIPv4asUInt32andIPv6asUInt128and 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/4for 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: aLowCardinality(IPv4)and aNullable(IPv4)key, aUInt128key, an all-zero IP divisor asserted asILLEGAL_DIVISION, andplus/minus/multiplycontrols. No test on master exercises an IP key together with a type wrapper.Validated against a binary whose
FunctionBinaryArithmetic.his byte-identical to master: 40/40 rows pass, 12/12 with settings randomization and 8/8 self-parallel. On 26.7 the oracle rows read0where master reads1, so they still fail without the fix.Workflow [PR]
Sync PR [sync-upstream/pr/112388]