Skip to content

Make by-constant intDiv throw on division of the minimal signed number by -1 - #113048

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-intdiv-const-min-minus-one
Aug 3, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-intdiv-const-min-minus-one

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Changelog category (leave one):

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

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

Fixed intDiv on a non-constant column with the constant divisor -1 silently wrapping the division of the minimal signed number (e.g. intDiv(-9223372036854775808, -1)) instead of throwing the ILLEGAL_DIVISION exception like the other execution paths do. The silent wrap could also produce wrong ORDER BY/DISTINCT results, because the read-in-order optimization correctly treats intDiv by a negative constant as monotonic, and the wrapped value violated the resulting sort order.

Description

The vectorized by-constant path of intDiv (DivideIntegralByConstantImpl::vectorConstant in src/Functions/intDiv.cpp) handles a constant divisor -1 by negating through the unsigned type, which silently wraps intDiv(-9223372036854775808, -1) to -9223372036854775808. The constant-folded and generic (both arguments non-constant) paths throw ILLEGAL_DIVISION ("Division of minimal signed number by minus one", see throwIfDivisionLeadsToFPE) for the same input:

SELECT intDiv(toInt64(-9223372036854775808), -1);              -- ILLEGAL_DIVISION
SELECT intDiv(materialize(toInt64(-9223372036854775808)), -1); -- was: -9223372036854775808, silently

The silent wrap is not only inconsistent, it produces wrong query results. The read-in-order optimization treats intDiv by a negative constant as monotonically decreasing (which is true for every representable quotient — exactly because the one non-representable case is supposed to throw), and plans an in-reverse-order read with optimize_distinct_in_order/optimize_read_in_order. The wrapped value then sits at the wrong end of a stream the plan assumes to be sorted:

  • in release builds, MergingSortedTransform merges the mis-sorted inputs into a mis-sorted output — wrong ORDER BY/DISTINCT results;
  • in debug builds, DistinctSortedStreamTransform aborts with the logical error Equal values are not contiguous within the range assumed to be sorted.

That is how a stress test found it, on the fuzzed query SELECT DISTINCT intDiv(x, -1) AS d FROM nl ORDER BY d ASC NULLS LAST LIMIT 0.5, 1 from 04545_negative_limit_distinct.sql, after fuzzer inserts had filled the table with duplicated parts including values next to the Int64 boundaries (reproduced locally with the CI binary: deterministic abort with the same stack).

The fix makes the by-constant -1 branch throw the same ILLEGAL_DIVISION exception when the dividend contains the minimal signed number, keeping the loop itself branch-free (a flag accumulated over the block, checked once after). intDivOrZero is unaffected (it has no by-constant specialization and keeps returning 0).

The reference of 01772_intdiv_minus_one_ubsan pinned the silent wrap (its second output row was the wrapped -9223372036854775808), so it is updated to expect the exception, keeping the by-constant negation loop covered on the rest of the range. The new test 04691_intdiv_by_minus_one_minimal_signed covers the consistency across execution paths and the in-order DISTINCT scenario.

Note: modulo has a mirrored inconsistency (modulo(materialize(min), -1) returns 0 while the constant-folded path throws), but modulo is not part of the monotonicity optimization and 0 is the mathematically correct remainder, so it is left out of this fix.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…ber by -1

The vectorized by-constant path of `intDiv` (`DivideIntegralByConstantImpl::vectorConstant`)
silently wrapped `intDiv(-9223372036854775808, -1)` to `-9223372036854775808`, while the
constant-folded and generic (both arguments non-constant) paths throw the `ILLEGAL_DIVISION`
exception for the same input.

Besides the inconsistency, the silent wrap produced wrong query results: the read-in-order
optimization treats `intDiv` by a negative constant as monotonically decreasing, and the
wrapped value ends up out of order in a stream the plan assumes to be sorted. In release
builds this leads to wrong `ORDER BY`/`DISTINCT` results; in debug builds it aborts with the
logical error 'Equal values are not contiguous within the range assumed to be sorted' in
`DistinctSortedStreamTransform`, which is how a stress test found it on a fuzzed query
`SELECT DISTINCT intDiv(x, -1) AS d FROM nl ORDER BY d ASC NULLS LAST LIMIT 0.5, 1` over a
table with duplicated parts including values around the `Int64` boundaries.

Update `01772_intdiv_minus_one_ubsan`, whose reference pinned the silent wrap, to expect the
exception (keeping the by-constant negation loop covered on the rest of the range), and add
`04691_intdiv_by_minus_one_minimal_signed` covering the consistency across paths and the
in-order DISTINCT scenario.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29

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

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1c5dd14]

Summary: ✅


AI Review

Summary

This PR fixes the by-constant intDiv specialization so intDiv(min_signed, -1) now throws the same ILLEGAL_DIVISION exception as the constant-folded and generic paths, which also removes the wrong-ordering bug that could surface through optimize_read_in_order/optimize_distinct_in_order. I reviewed the current diff, the touched implementation, the surrounding intDiv/monotonicity code, the prior PR discussion state, and the green CI surface, and I did not find a remaining correctness, safety, or test-coverage issue worth posting inline.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes, slowest function optimization changes (thinlto), compile time of recompiled translation units, symbol sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 685.32 MiB 682.33 MiB -2.99 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

3 object files changed (-40.18 MiB total), 0 added, 685 removed.

Object file Master PR Δ
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/ext/transport/chttp2/transport/cht… 960.56 KiB removed -960.56 KiB (-100.00%)
src/Common/ZooKeeper/CMakeFiles/clickhouse_common_zookeeper_no_log.dir/ZooKeeperImpl.cpp.o 804.97 KiB removed -804.97 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/server/server.cc.o 612.22 KiB removed -612.22 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/load_balancing/rls/rls.cc.o 611.36 KiB removed -611.36 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/client_channel/client_channel_filt… 548.04 KiB removed -548.04 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/client_channel/client_channel.cc.o 525.46 KiB removed -525.46 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/client_channel/retry_interceptor.c… 518.85 KiB removed -518.85 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/lib/channel/promise_based_filter.c… 482.91 KiB removed -482.91 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/load_balancing/grpclb/grpclb.cc.o 434.97 KiB removed -434.97 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/call/client_call.cc.o 433.89 KiB removed -433.89 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/call/server_call.cc.o 391.29 KiB removed -391.29 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc++_unsecure.dir/__/grpc/src/cpp/server/server_cc.cc.o 384.88 KiB removed -384.88 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/client_channel/retry_filter_legacy… 369.55 KiB removed -369.55 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/ext/transport/chttp2/transport/wri… 349.81 KiB removed -349.81 KiB (-100.00%)
contrib/google-cloud-cpp-cmake/CMakeFiles/google_cloud_cpp_grpc_utils.dir/__/google-cloud-cpp/googl… 346.93 KiB removed -346.93 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/ext/transport/inproc/legacy_inproc… 345.35 KiB removed -345.35 KiB (-100.00%)
contrib/google-cloud-cpp-cmake/CMakeFiles/google_cloud_cpp_longrunning_operations_protos.dir/google… 339.33 KiB removed -339.33 KiB (-100.00%)
contrib/google-cloud-cpp-cmake/CMakeFiles/google_cloud_cpp_iam_credentials_v1_iamcredentials_protos… 334.24 KiB removed -334.24 KiB (-100.00%)
contrib/google-protobuf-cmake/CMakeFiles/_libprotobuf-lite.dir/__/google-protobuf/src/google/protob… 316.58 KiB removed -316.58 KiB (-100.00%)
contrib/grpc-cmake/CMakeFiles/grpc_unsecure.dir/__/grpc/src/core/call/call_spine.cc.o 312.88 KiB removed -312.88 KiB (-100.00%)
Slowest function optimization changes (ThinLTO) ⚠️

Median per-function time ratio to the master baseline is ×1.16 (different machine and build flags); deltas below are relative to that ratio.

Binary Function Master PR Δ vs median
programs/clickhouse-keeper DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.11069338206770680048] new 17.8 s +17.8 s
programs/clickhouse DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.12487241783113815285] 8.7 s gone -10.1 s (-100%)
programs/clickhouse-keeper DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.12487241783113815285] 8.2 s gone -9.5 s (-100%)
programs/clickhouse DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.11069338206770680048] new 7.1 s +7.1 s
programs/clickhouse-keeper DB::registerFunctionConversion(DB::FunctionFactory&) 6.7 s 14.8 s +7.1 s (+91%)
programs/clickhouse-keeper _GLOBAL__sub_I_TargetLibraryInfo.cpp 5.8 s 11.8 s +5.1 s (+76%)
programs/clickhouse DB::Parquet::writeColumnChunkBody(DB::Parquet::ColumnChunkWriteState&, DB::Parquet::WriteOptions co… 5.4 s 3.4 s -2.9 s (-46%)
programs/clickhouse-keeper DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.54623650351436… new 2.6 s +2.6 s
programs/clickhouse DB::getSettingsChangesHistory()::$_0::operator()() const 4.5 s 2.7 s -2.6 s (-49%)
programs/clickhouse-keeper DB::registerFunctionVectorFunctions(DB::FunctionFactory&) 2.2 s 4.9 s +2.4 s (+97%)
programs/clickhouse DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.17566710545920… 2.0 s gone -2.3 s (-100%)
programs/clickhouse-keeper DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.56540966842… new 2.3 s +2.3 s
programs/clickhouse DB::attachSystemTablesServer(std::__1::shared_ptr<DB::Context const>, DB::IDatabase&, bool, bool) 4.6 s 3.1 s -2.3 s (-42%)
programs/clickhouse DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 3.6 s 2.0 s -2.2 s (-53%)
programs/clickhouse-keeper _GLOBAL__sub_I_sqid.cpp 1.7 s 4.2 s +2.1 s (+107%)
programs/clickhouse DB::DatabaseDataLakeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.9031… 1.8 s gone -2.1 s (-100%)
programs/clickhouse-keeper _ZN2DB18FunctionArrayIndexINS_16CountEqualActionENS_14NameCountEqualEE15executeIntegralIJDutjmDB8_s… 2.0 s 4.4 s +2.1 s (+91%)
programs/clickhouse DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.16712493492… 1.8 s gone -2.1 s (-100%)
programs/clickhouse-keeper DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.17566710545920… 1.8 s gone -2.0 s (-100%)
Compile time of recompiled translation units ⚠️

7 translation units recompiled, 37 s compile time in total, 6 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Functions/intDiv.cpp: 33.5 s
Symbol sizes ⚠️
Binary Symbol Master PR Δ
programs/clickhouse-keeper DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.12487241783113815285] 439.45 KiB removed -439.45 KiB (-100.00%)
programs/clickhouse-keeper DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.11069338206770680048] new 439.45 KiB +439.45 KiB
programs/clickhouse DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.11069338206770680048] new 439.45 KiB +439.45 KiB
programs/clickhouse DB::SettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.12487241783113815285] 439.45 KiB removed -439.45 KiB (-100.00%)
programs/clickhouse-keeper DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.17566710545920… 114.16 KiB removed -114.16 KiB (-100.00%)
programs/clickhouse DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.54623650351436… new 114.16 KiB +114.16 KiB
programs/clickhouse-keeper DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.54623650351436… new 114.16 KiB +114.16 KiB
programs/clickhouse DB::ServerSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.17566710545920… 114.16 KiB removed -114.16 KiB (-100.00%)
programs/clickhouse DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.16712493492… 102.51 KiB removed -102.51 KiB (-100.00%)
programs/clickhouse-keeper DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.56540966842… new 102.51 KiB +102.51 KiB
programs/clickhouse-keeper DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.16712493492… 102.51 KiB removed -102.51 KiB (-100.00%)
programs/clickhouse DB::MergeTreeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.56540966842… new 102.51 KiB +102.51 KiB
programs/clickhouse DB::DatabaseDataLakeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.1111… new 97.41 KiB +97.41 KiB
programs/clickhouse DB::DatabaseDataLakeSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.9031… 97.41 KiB removed -97.41 KiB (-100.00%)
programs/clickhouse DB::ObjectStorageQueueSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.14… new 92.15 KiB +92.15 KiB
programs/clickhouse DB::ObjectStorageQueueSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.10… 92.15 KiB removed -92.15 KiB (-100.00%)
programs/clickhouse DB::KafkaSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.872715978862839… new 89.47 KiB +89.47 KiB
programs/clickhouse DB::KafkaSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.176316896530569… 89.47 KiB removed -89.47 KiB (-100.00%)
programs/clickhouse DB::DataLakeStorageSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.41967… 88.38 KiB removed -88.38 KiB (-100.00%)
programs/clickhouse DB::DataLakeStorageSettingsTraits::Accessor::instance()::$_0::operator()() const [clone .llvm.13841… new 88.38 KiB +88.38 KiB

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Approved.

It might lead to a small performance degradation, but the code appears smart enough to do it mostly for free.

A small correction:

  • we documented the division of the most negative integer to -1 as an implementation-specific behavior, and the fact that the optimization makes the result inconsistent falls into the same category.

@alexey-milovidov alexey-milovidov self-assigned this Aug 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 3, 2026
Merged via the queue into master with commit 3c17dc7 Aug 3, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-intdiv-const-min-minus-one branch August 3, 2026 20:08
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 3, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 31, 2026
…rge constant divisor

intDiv and divide with a Decimal dividend compute in the decimal's own
native signed width (DecimalBinaryOperation::NativeResultType) and
materialise the constant divisor into that width with static_cast. For
Decimal(5, 4) that width is Int32, so intDiv(a, -9223372036854775807)
actually divides by 1 and increases.

getMonotonicityForRange derived the direction from the untruncated
literal and reported decreasing, and its only Decimal guard tested the
divisor, which is the wrong operand for this shape. Key analysis then
called Range::invert() on a range whose values never reversed, so
left > right. For a set atom MergeTreeSetIndex::checkInRange then gets
begin > end and hits its debug-only assertion, reported by the AST
fuzzer as STID 3252-3a4a. For a range atom there is no assertion at
all, so every matching granule is pruned away and the query silently
returns wrong results in release builds too: on Decimal(5, 4) data
holding 0..9, WHERE intDiv(a, -9223372036854775807) > 4 returned 0 rows
where 5 match.

Add one shared predicate, decimalDivConstDivisorTruncates, and call it
from both variable / constant branches of getMonotonicityForRange. The
second branch handles ranges with an infinite endpoint, which
forAnyHyperrectangle produces routinely, so a fix applied only to the
finite-endpoint branch leaves those exposed; a mutant that removes the
call from the infinite branch alone still reddens two of the new test
arms. The predicate is a round-trip test rather than a blanket
rejection, so intDiv(decimal_col, small_const) keeps its pruning, and
it is gated on an integer divisor because a Float divisor converts both
operands to Float64 and stays order preserving.

The defect does not depend on the literal's sign: a positive
9223372036854775807 casts to Int32 -1, so the function decreases while
the claim says it increases, and that fails the same way. Both
directions are covered by test arms, as are all the invariant carriers:
divide as well as intDiv, both checkInRange overloads, IN and NOT IN,
range atoms as well as set atoms, ascending and DESC keys, and the
wider Decimal widths where the same constant survives the cast.

This is the third defect of this family, after ClickHouse#107586 and ClickHouse#113048;
ClickHouse#112156 fixed the mirror case of a constant dividend.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants