Skip to content

Compute the remainder in a signed type when either modulo operand is signed - #119616

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
serhiy-bzhezytskyy:fix-modulo-mixed-sign
Sep 13, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
serhiy-bzhezytskyy:fix-modulo-mixed-sign

Conversation

@serhiy-bzhezytskyy

@serhiy-bzhezytskyy serhiy-bzhezytskyy commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #119587

The problem

modulo took the remainder in the operand types, and the usual arithmetic conversions make that
unsigned 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:

SELECT 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

Beyond the report, the same cause breaks the mirror order and the wide integers:

SELECT modulo(toUInt32(7), toInt32(-3));                    -- 7, expected 1
SELECT modulo(toInt128(-1), toUInt128(10));                 -- 5, expected -1
SELECT modulo(toInt64(-9223372036854775808), toUInt64(10)); -- 8, expected -8

Why a same-width signed cast is not the fix

DivideIntegralImpl::apply casts operands to a signed type when either is signed, and its own
comment names this bug class: "overflow may occur due to integer promotion. Example:
int8_t(-1) / uint64_t(2)"
. My first attempt mirrored that for modulo and 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)) cast UInt16(37528) to Int16
first, overflowing to -28008; separately, modulo(toInt64(-9e18), toUInt64(1e19)) cast the
UInt64 divisor to Int64, overflowing it, and broke an input the original code had answered
correctly 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. ModuloImpl and the common-type choice pruning its 128/256-bit mixed-pair
kernels (FunctionBinaryArithmetic.h) both follow this rule, since the second had the same class
of bug.

This fixes modulo, moduloOrZero, moduloOrNull and positiveModulo together, since the
latter three delegate to ModuloImpl. positiveModulo's own if (res < 0) correction was
unreachable while the remainder came back unsigned-computed.

moduloLegacy does not get this fix: KeyDescription::moduloToModuloLegacyRecursive
rewrites every modulo inside a PARTITION BY expression to moduloLegacy, and
MergeTreePartition::adjustPartitionKey runs that rewritten expression to compute on-disk
partition IDs on every insert. An earlier revision of this PR had ModuloLegacyImpl inherit
the new ModuloImpl::apply, which silently changes those IDs for any existing table partitioned
by a mixed-sign modulo expression (moduloLegacy(toInt32(-1), toUInt32(10)) moved from 5 to
-1) - confirmed end-to-end: creating a table with PARTITION BY (c0 % toUInt32(10)) and
inserting c0 = -1 writes partition 5 on 26.9.1.1190 and partition -1 with that revision.
ModuloLegacyImpl now has its own apply, reproducing the pre-this-PR computation verbatim, so
moduloLegacy's behaviour - and every existing partition ID that depends on it - is unchanged by
this 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.1190 and this branch:

function small-value matrix boundary matrix (excl. intDiv, untouched)
modulo / moduloOrZero / moduloOrNull / positiveModulo 34/144 wrong before, 0 after, 0 regressions 0/1810 mismatches
intDiv (control, never touched) 0/144 33/362, identical before and after - a pre-existing, unrelated limit of intDiv itself
moduloLegacy unchanged before/after (by design - see above) unchanged before/after

Four 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 ModuloImpl itself did, plus
one more: a UInt256 operand has no wider signed type to widen into, so modulo/moduloOrNull
now skip pruning for it and use the direct ModuloImpl<UInt256, ...> kernel instead, which needs
no such cast - modulo(toUInt256('...2^255...'), toInt8(-7)) now returns the correct 1 rather
than reinterpreting the dividend as negative first. moduloLegacy shares this pruning branch but
needed 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):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

modulo, positiveModulo, moduloOrZero and moduloOrNull returned wrong results when one
operand 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, and
modulo(toInt32(-100000), toUInt32(100000)) returned 67296 instead of 0. The remainder is now
computed from unsigned magnitudes whenever either operand is signed, consistently with intDiv
on the same operands. moduloLegacy (used internally for MergeTree partition-key backward
compatibility) is unaffected.


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

Version info

  • Merged into: 26.9.1.1346 (included in 26.9 and later)

`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.
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 12, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eab7853]

Summary: ✅


AI Review

Summary

This PR fixes mixed signed/unsigned remainder semantics for modulo, positiveModulo, moduloOrZero, and moduloOrNull, and correctly keeps moduloLegacy frozen for partition-key compatibility. I found one blocker: the storage layer still rewrites query-side modulo predicates to moduloLegacy during partition pruning, so the new function semantics can make SELECT skip the only partition that contains a matching row.

Findings

❌ Blockers

  • [src/Functions/DivisionUtils.h:321] modulo now differs from moduloLegacy on mixed-sign operands, but MergeTreePartition::adjustPartitionKey still stores PARTITION BY modulo(...) as moduloLegacy(...) and KeyCondition::canConstantBeWrappedByDeterministicFunctions / canSetValuesBeWrappedByDeterministicFunctions still rewrite query predicates the same way. A query like SELECT * FROM t WHERE modulo(c0, toUInt32(10)) = -1 on a table partitioned by c0 % toUInt32(10) can therefore prune the partition that contains c0 = -1 and return no rows.
  • Suggested fix: either version/gate partition-key semantics so tables that declare modulo store the new modulo result, or make partition pruning stop treating modulo and moduloLegacy as interchangeable once mixed-sign semantics diverge. Add a MergeTree regression test that proves a WHERE modulo(...) = -1 predicate still reads the correct partition.
Final Verdict

Changes requested: the arithmetic fix itself looks good, but the unchanged modulo -> moduloLegacy rewrite in MergeTree makes query pruning unsound for mixed-sign modulo partition keys.

LLVM Coverage Report

Measured on commit eab7853.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.70% 91.70% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 38/45 (84.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
…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.
Comment thread src/Functions/DivisionUtils.h Resolved
…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.
Comment thread src/Functions/DivisionUtils.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing eab78530a with master 68afe2720 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e2ca0b04e; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

23 object files changed (-154.00 KiB total), 0 added.

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.

Job report

…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

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.

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.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 11f0dc8 Sep 13, 2026
176 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 13, 2026
…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.
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SELECT 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 -1

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6, 26.3.

CC component owner: @alexey-milovidov @bharatnc

Analysis metadata

comp-regular-function · Severity P2 · Finding phase_d_pr119616

  • Verified against master build 8f68f32a0846 (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 1, 2026
…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]>
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... external Author is not a member of the ClickHouse organization 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.

modulo and positiveModulo compute in unsigned arithmetic for a signed dividend with an unsigned divisor, giving wrong results for negatives

4 participants