Repository navigation
Compute the remainder in a signed type when either modulo operand is signed - #119616
alexey-milovidov merged 4 commits into
Conversation
`modulo` took the remainder in the operand types, so the usual arithmetic conversions made it unsigned once the unsigned operand was at least as wide as the signed one and a negative operand wrapped first. `DivideIntegralImpl` already casts to signed, which is why `intDiv` disagreed with `modulo` on the same operands; `ModuloImpl` and the common-type choice that prunes its wide mixed-pair kernels now follow the same rule.
|
Workflow [PR], commit [eab7853] Summary: ✅
AI ReviewSummaryThis PR fixes mixed signed/unsigned remainder semantics for Findings❌ Blockers
Final VerdictChanges requested: the arithmetic fix itself looks good, but the unchanged LLVM Coverage ReportMeasured on commit eab7853.
Changed lines: Changed C/C++ lines covered: 38/45 (84.44%) · Uncovered code |
…gned cast The first version of this fix cast operands to a signed type sized by nextSize, mirroring DivideIntegralImpl. That still overflows whenever an unsigned operand's own value exceeds the signed maximum of the width chosen for it, which a quotient tolerates (its own comment calls this "less harmful") but a remainder does not, since the wrapped value IS the result. `modulo(toUInt16(37528), toInt32(167682982))` returned -28008 under the first fix; `modulo(toInt64(-9e18), toUInt64(1e19))` regressed an input the ORIGINAL code answered right by an unrelated pair of wraps cancelling out, caught only because a boundary-value matrix (not small operands) was run through the actual test runner. Working in unsigned magnitudes removes the class entirely: casting any value, signed or unsigned, to an unsigned type at least as wide as its own is exact for every input including the minimal signed number, and unsigned subtraction recovers that number's true magnitude without overflow. `|a| mod |b|` in the wider of the two operands' widths cannot overflow either, and the dividend's sign is applied last. Four existing tests had pinned the previous, unsigned-computed remainder as "the quirk to preserve" for exactly the mixed-sign pairs this fixes; their references now hold the value this algorithm - and independently, plain C truncating-division arithmetic - agrees is correct.
…o Int256
CI's own review skill found two things this branch had missed. First, casting the
computed magnitude to Result and then negating it is itself unsafe whenever that
magnitude equals |Result::min()|, reachable whenever Result is no wider than the
type the magnitude was computed in - modulo(toInt64(-9223372036854775808),
toUInt64(18446744073709551615)) hit exactly that and UBSan traps on it, though the
value it produced happened to be right. Negating in Result's own unsigned type
instead avoids any signed negation at all.
Second, the wide-mixed-pair pruning in FunctionBinaryArithmetic.h mapped an unsigned
128-bit operand to same-width Int128 before this file's ModuloImpl ever runs, so a
UInt128 value above Int128::max was corrupted by the SQL CAST itself -
modulo(toUInt128('170141183460469231731687303715884105729'), toInt8(-7)) returned
255 instead of 3. Int256 exists and holds the full UInt128 range, so this widens up
to it specifically for this pruning rather than reusing NumberTraits::nextSize, which
is capped at 8 bytes for its other, unrelated callers.
Re-verified against both binaries with an all-string vectorized matrix (avoiding an
arrayJoin tuple's own Float64 type inference on values above Int64::max, which had
made an earlier such check silently wrong): every case my PR touches that used to be
wrong is now correct or unchanged, and nothing that was already correct regressed.
The residual gap - a UInt256 value above Int256::max mixed with a signed operand,
where there is no 512-bit type left to widen into - was already wrong before this PR
and stays wrong, disclosed in the PR description.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/modulo.cpp.o |
17.16 MiB | 16.83 MiB | -337.94 KiB (-1.92%) |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/moduloOrNull.cpp.o |
8.15 MiB | 8.30 MiB | +151.28 KiB (+1.81%) |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/moduloOrZero.cpp.o |
3.89 MiB | 3.92 MiB | +30.80 KiB (+0.77%) |
716 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
33 translation units recompiled, 423 s compile time in total, 33 of them have a recent master baseline.
…s fix moduloLegacy computes on-disk MergeTree partition IDs (KeyDescription.cpp rewrites every modulo() in a PARTITION BY expression to it), so it must keep the historical, sometimes unsigned-computed C++ % behaviour rather than the corrected signed remainder - inheriting the fix silently changed partition IDs for existing tables (moduloLegacy(-1, 10) moved 5 -> -1). Gave it its own apply() reproducing the pristine pre-fix computation. The wide-mixed-pair pruning in FunctionBinaryArithmetic.h shared one CommonType rule between modulo and moduloLegacy; split it so moduloLegacy prunes via the plain wider-of-the-original-types rule (matching its own raw-%% semantics) instead of ModuloImpl's safe-signed-widening rule. Also stop pruning modulo/moduloOrNull for a UInt256 operand, which has no wider signed type to widen into and would otherwise be silently reinterpreted as negative before %% ever runs; the direct kernel needs no such cast. Co-Authored-By: Claude Sonnet 5 <[email protected]>
| static constexpr bool compilable = false; /// moduloLegacy is only used in partition key expression | ||
| #endif | ||
|
|
||
| /// `moduloToModuloLegacyRecursive` (`KeyDescription.cpp`) silently rewrites every `modulo` in a |
There was a problem hiding this comment.
Keeping moduloLegacy for partition-ID stability is not enough here, because the MergeTree pruning path still rewrites query-side modulo(...) predicates to moduloLegacy(...) when it tries to match them to the adjusted partition key (MergeTreePartition::adjustPartitionKey, KeyCondition::canConstantBeWrappedByDeterministicFunctions, and canSetValuesBeWrappedByDeterministicFunctions).
After this PR the two functions diverge on mixed-sign inputs. For a table defined as PARTITION BY (c0 % toUInt32(10)), inserting c0 = -1 still stores the row in partition 5, but SELECT * FROM t WHERE modulo(c0, toUInt32(10)) = -1 should now match that row. The pruning code rewrites the predicate to moduloLegacy(c0, toUInt32(10)) = -1, decides partition 5 cannot match, and skips the only part that contains the row. The same issue exists for IN (...) because canSetValuesBeWrappedByDeterministicFunctions does the same rewrite.
I think this needs a storage-layer change in the same PR: either version/gate PARTITION BY modulo(...) so tables that declare modulo actually store the new semantics, or stop using the modulo -> moduloLegacy rewrite for pruning when the two are no longer equivalent. A focused MergeTree regression test with WHERE modulo(...) = -1 on a mixed-sign modulo partition key would make this visible.
…n-canonical master 0bbfed8 ("Compute the remainder in a signed type when either operand is signed", ClickHouse#119616) landed between this branch's two CI runs and makes `number % -1` evaluate to 0 for every row: the remainder is now taken in a signed type, so the Int8 -1 no longer reaches the operation as 255 through the UInt8 result type. The report's own condition then selects the else branch for all 150 rows, the projection is a non-NULL constant, and the query answers 1 1 where the reference recorded 2 2 on the older base. Fast test fails on exactly that line on fe88b9e, the merge of this branch with master c08d0d8; the same query answers 2 2 on 4da0600, a merge from before ClickHouse#119616. An all-zero null map also leaves the query vacuous: with no non-canonical byte in the map it can no longer tell a nullness-based reader from a byte-based one. `number % 3` keeps the bytes 0, 1 and 2 there, matching the rest of the file, and its value does not depend on the mixed-sign rule that changed, so the query reads the same on both sides of ClickHouse#119616. Measured on three arms: the unfixed 4da0600 returns 3 distinct rows against 2 from GROUP BY, the disagreement the report describes, while fe88b9e and this branch's own base both return 2 2. The test passes 50/50 on fe88b9e.
ReproducerSELECT modulo(toInt32(-1), toUInt32(10)); -- 5, expected -1
SELECT positiveModulo(toInt32(-1), toUInt32(10)); -- 5, expected 9
SELECT modulo(toInt32(-100000), toUInt32(100000)); -- 67296, expected 0
SELECT modulo(toUInt32(7), toInt32(-3)); -- 7, expected 1
SELECT moduloOrZero(toInt32(-1), toUInt32(10)); -- 5, expected -1Results:
Backport the fix to CC component owner: @alexey-milovidov @bharatnc Analysis metadata
Introducing change: not identified
|
…der unsigned type ClickHouse#119616 made the code-size pruning of mixed wide `modulo` / `moduloOrNull` pairs convert every unsigned operand to the next signed size (up to `Int256`), and stopped pruning pairs with a `UInt256` operand. Both are needed only when one of the operands is signed. For two unsigned operands `ModuloImpl` takes the plain remainder in the wider unsigned type, so the widening only adds cost: `UInt128 % UInt16` ran as `Int256 % Int256` (a 256-bit division per row), and `UInt256 % UInt64` lost the pruning. Use the wider of the two unsigned types again (the rule before ClickHouse#119616) when both operands are unsigned; pairs with a signed operand keep the ClickHouse#119616 rule. Results, result types and errors do not change. Release build without LTO, clickhouse-local, max_threads = 1, median of 14: - min_max_wide_integers ClickHouse#14, GROUP BY u128 % 1000: 0.365 s -> 0.114 s - wide_integer_division ClickHouse#19, modulo(UInt128, UInt16): 0.053 s -> 0.012 s - wide_integer_division ClickHouse#1, modulo(UInt256, UInt64): 0.067 s -> 0.035 s - controls modulo(Int128, UInt16), intDiv(UInt128, UInt16): unchanged These are the queries that became slower on master right after ClickHouse#119616; ClickHouse#14 was reported slower on ClickHouse#112950. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #119587
The problem
modulotook the remainder in the operand types, and the usual arithmetic conversions make thatunsigned as soon as the unsigned operand is at least as wide as the signed one, so a negative
operand wrapped to a large positive value first:
Beyond the report, the same cause breaks the mirror order and the wide integers:
Why a same-width signed cast is not the fix
DivideIntegralImpl::applycasts operands to a signed type when either is signed, and its owncomment names this bug class: "overflow may occur due to integer promotion. Example:
int8_t(-1) / uint64_t(2)". My first attempt mirrored that formoduloand it is not safe there:the comment accepts that overflow as "less harmful" for a quotient, whose magnitude usually stays
right even from a wrapped operand - a remainder's own magnitude is not exempt, since it IS the
value produced.
modulo(toUInt16(37528), toInt32(167682982))castUInt16(37528)toInt16first, overflowing to -28008; separately,
modulo(toInt64(-9e18), toUInt64(1e19))cast theUInt64divisor toInt64, overflowing it, and broke an input the original code had answeredcorrectly by an unrelated pair of wraps cancelling out.
The fix works in unsigned magnitudes instead, which cannot overflow at any width: casting any
value - signed or unsigned, including the minimal signed number - to an unsigned type at least as
wide as its own is exact; unsigned subtraction recovers the true magnitude without overflow
(
0u - (Unsigned)a == |a|, including|INT_MIN|).|a| mod |b|in the wider of the two operands'widths is then an ordinary unsigned remainder with nothing left to overflow; the dividend's sign
is applied last.
ModuloImpland the common-type choice pruning its 128/256-bit mixed-pairkernels (
FunctionBinaryArithmetic.h) both follow this rule, since the second had the same classof bug.
This fixes
modulo,moduloOrZero,moduloOrNullandpositiveModulotogether, since thelatter three delegate to
ModuloImpl.positiveModulo's ownif (res < 0)correction wasunreachable while the remainder came back unsigned-computed.
moduloLegacydoes not get this fix:KeyDescription::moduloToModuloLegacyRecursiverewrites every
moduloinside aPARTITION BYexpression tomoduloLegacy, andMergeTreePartition::adjustPartitionKeyruns that rewritten expression to compute on-diskpartition IDs on every insert. An earlier revision of this PR had
ModuloLegacyImplinheritthe new
ModuloImpl::apply, which silently changes those IDs for any existing table partitionedby a mixed-sign modulo expression (
moduloLegacy(toInt32(-1), toUInt32(10))moved from5to-1) - confirmed end-to-end: creating a table withPARTITION BY (c0 % toUInt32(10))andinserting
c0 = -1writes partition5on26.9.1.1190and partition-1with that revision.ModuloLegacyImplnow has its ownapply, reproducing the pre-this-PR computation verbatim, somoduloLegacy's behaviour - and every existing partition ID that depends on it - is unchanged bythis PR.
Evidence
144 operand-type combinations per function (6 widths x 6 widths x 4 signedness pairs, small
values) plus a second, boundary-focused matrix using values at and past each width's signed
maximum - the shape that broke the first attempt - checked against
26.9.1.1190and this branch:intDiv, untouched)modulo/moduloOrZero/moduloOrNull/positiveModulointDiv(control, never touched)intDivitselfmoduloLegacyFour existing tests had pinned the previous, unsigned-computed remainder as expected for exactly
the mixed-sign pairs this fixes (one literally commented "unsigned wrap quirks... preserved");
their references now hold the value this algorithm, and plain C truncating division, agree is correct.
The wide mixed-pair kernels are pruned via a common type rather than instantiated directly (to
control binary size); that common-type choice needed the same fix
ModuloImplitself did, plusone more: a
UInt256operand has no wider signed type to widen into, somodulo/moduloOrNullnow skip pruning for it and use the direct
ModuloImpl<UInt256, ...>kernel instead, which needsno such cast -
modulo(toUInt256('...2^255...'), toInt8(-7))now returns the correct1ratherthan reinterpreting the dividend as negative first.
moduloLegacyshares this pruning branch butneeded its own, unmodified common-type rule (the plain wider-of-the-original-types one) to keep
matching its own frozen semantics at every width, including
UInt256.Changelog category (leave one):
Changelog entry:
modulo,positiveModulo,moduloOrZeroandmoduloOrNullreturned wrong results when oneoperand was a signed integer and the other an unsigned integer at least as wide, because the
remainder was computed in unsigned arithmetic and a negative operand wrapped first. For example
positiveModulo(toInt32(-1), toUInt32(10))returned 5 instead of 9, andmodulo(toInt32(-100000), toUInt32(100000))returned 67296 instead of 0. The remainder is nowcomputed from unsigned magnitudes whenever either operand is signed, consistently with
intDivon the same operands.
moduloLegacy(used internally forMergeTreepartition-key backwardcompatibility) is unaffected.
Workflow [PR]
Sync PR [sync-upstream/pr/119616]
Version info
26.9.1.1346(included in26.9and later)