Skip to content

Add opt-in exact integer division - #124490

Merged
qoega merged 23 commits into
ClickHouse:masterfrom
qoega:codex/exact-integer-division
Oct 12, 2026
Merged

qoega merged 23 commits into
ClickHouse:masterfrom
qoega:codex/exact-integer-division

Conversation

@qoega

@qoega qoega commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Add the opt-in exact_division_for_integers setting so SQL that expects integer division can use / and divide without rewriting each expression to intDiv. The setting is disabled by default.

When enabled, two integer operands produce a quotient truncated toward zero. The result has the first operand's width and is signed if either operand is signed. All integer widths through 256 bits are supported, including mixed signed/unsigned operands. Division by zero and results outside the result type's range throw ILLEGAL_DIVISION; nullable inputs propagate NULL.

Division involving Decimal or floating-point operands and the explicit functions intDiv, divideDecimal, and divideOrNull retain their existing behavior. Compatible non-nullable integer pairs reuse intDiv and its constant-divisor kernels and monotonicity metadata. Other mixed-sign pairs, nullable inputs, and potentially throwing constant divisors use the checked internal __divideIntegers path. The resolved divideExact identity keeps exact division separate from floating-point expressions in stored keys and serialized plans while preserving the delegated kernels and monotonicity metadata. Aggregate optimization preserves per-row truncation and overflow checks. Kusto interval ratios and subsecond timestamp helpers explicitly retain floating-point division.

Division semantics are now fixed in newly submitted ASTs before they can enter table metadata, views, SQL function definitions, mutations, or distributed execution: the opt-in spelling becomes divideExact, while stored divide retains its historical behavior. Existing metadata and ATTACH, restore, and replicated DDL replays are not reinterpreted under the current setting. Automatic view column names are preserved, and VALUES expressions receive the same normalization.

The compatibility follow-up passed an incremental ARM64 build, all ten relevant functional regressions, and six randomized repetitions of the two new tests. Coverage includes key and partition expressions, primary-index reads, forced projections, defaults/materialized/alias columns, constraints, views, materialized views, SQL functions, ALTER, mutation expressions, and VALUES. Actual server restarts with the default switched to 1 and back to 0 preserved both integer and legacy fractional results, primary-index use, and inserts into new parts. This used the existing partial dev source tree; builds against the complete PR head remain a CI check.

Validated on the ARM64 dev VM with a RelWithDebInfo executable build with optional libraries disabled. All five new functional tests and nine existing compatibility tests passed, including stored division keys and distributed SQL/serialized-plan execution. An independent Python oracle passed all 144 integer type pairs across 55,959 vector rows, 4,320 constant/mixed cases, and 504 expected errors.

The review follow-up passed an incremental build on the existing ARM64 dev build: both added regressions, all five feature regressions, three existing Kusto/planner tests, and the same arithmetic oracle passed. The added tests cover Kusto with the setting both enabled and disabled, primary-key use, ordered reads, and short-circuit evaluation. Current-base build validation continues in CI.

LogsQL compatibility coverage checks multi-field avg with nullable integer fields and empty input in both setting modes, including its Nullable(Float64) result type. The existing translator already converts numeric fields through numericValueExpr to Float64, so no implementation change is needed for the reported average case. The current parser was compiled separately on dev, and its emitted SQL passed all six value/type cases; the full client/dialect regression is included for CI.

LogsQL math division and two-argument round now explicitly use a Float64 numerator, preserving fractional ratios, rounding, and non-finite default handling with the setting enabled. The reported truncation was reproduced with the compiled current parser before the fix. After the fix, all 18 value/type cases passed on dev, including nullable fields and aggregate ratios, and their combined output matched the new functional test reference. Full client/dialect execution is covered by the new CI regression.

The unrelated SQLite test cleanup failure in the S3 stress job is fixed separately in the linked CI PR and included here. Its existing reference, query fuzzing with ignored drops, and a server restart passed using this PR's ARM64 CI binary. Current master was merged normally; the feature diff was preserved.

Related: #124548

The legacy AST aggregate optimizer now restricts its integer-division guard using the known column type and literal type, preserving floating-point rewrites and the existing decimal guard. All 32 direct visitor cases passed after an incremental ARM64 build, and both the new floating-point SQL compatibility test and the existing integer-optimizer test passed. Current SQL already uses the analyzer (enable_analyzer=0 is obsolete and coerced to 1), so the SQL baseline also preserved these floating-point plans; the direct visitor checks validate the legacy code adjustment.

Safe unsigned constant divisors now reuse intDiv with signed dividends, including equal-width and wider constants, while constants outside the signed-cast range retain checked semantics. The previous binary reproduced INDEX_NOT_USED for Int64 / toUInt64(10); after an incremental ARM64 build, the new regression passed three randomized runs and six existing arithmetic/type/optimizer tests passed. The aggregate-plan test also pins optimize_syntax_fuse_functions; three randomized repetitions passed with fusion initially disabled. This validation used the existing partial dev build; current-base builds remain covered by CI.

Changelog category (leave one):

  • New Feature

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

Add the exact_division_for_integers setting, disabled by default, to make / and divide return integer quotients truncated toward zero when both operands are integers. Supports integer types through 256 bits and checks division by zero and result overflow. Division involving decimal or floating-point operands is unchanged.


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

Version info

  • Merged into: 26.10.1.2236-master (included in 26.10 and later)

Use checked integer arithmetic for integer operands of `/` and `divide` when enabled, including 128-bit and 256-bit types. Preserve the existing default behavior and division involving `Decimal` or floating-point operands.

Give exact division a distinct internal function identity so indexes and serialized plans distinguish it from floating-point division. Keep per-row truncation and overflow checks intact in aggregate rewrites.

Add functional coverage for integer type pairs, nullable columns, overflow, optimizer behavior, stored division keys, and distributed execution.
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6423cad]

Summary: ✅


AI Review

Summary

This PR adds the opt-in exact_division_for_integers setting by freezing newly submitted / and divide expressions to divideExact, then delegating compatible cases back to intDiv or legacy floating division at resolution time. Most of the earlier planner/dialect regressions now look addressed, but there is still one correctness hole in the AST normalization pass: nested query-local SETTINGS scopes carried outside ASTSelectQuery::settings() are not modeled, so some subqueries can still freeze division semantics from the outer context instead of their own clause.

Findings
❌ Blockers
  • [src/Interpreters/normalizeDivision.cpp:30] normalize only opens a new settings scope for ASTSelectQuery::settings(), but nested query-local settings can also arrive through other carriers such as ASTQueryWithOutput::settings_ast (for example a subquery that is an ASTSelectWithUnionQuery with trailing SETTINGS). executeQuery applies the top-level clause before calling normalizeDivision, so top-level INSERT ... SETTINGS ... SELECT is now fine, but a nested subquery like SELECT * FROM (SELECT 5 / 2 UNION ALL SELECT 7 / 2 SETTINGS exact_division_for_integers = 1) is still normalized under the outer context because the inner union node never flips exact. That violates the PR’s core contract that query-local exact-division semantics are fixed before execution/persistence. Suggested fix: teach normalize to mirror the full nested query-level settings carriers that InterpreterSetQuery::applySettingsFromQuery uses, not just ASTSelectQuery::settings().
Final Verdict

Changes requested: the remaining nested-SETTINGS scope hole in normalizeDivision should be fixed before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 7, 2026
Comment thread src/Functions/divide.cpp Resolved
Comment thread src/Functions/FunctionExactDivide.cpp Resolved
qoega added 2 commits October 7, 2026 23:58
Convert interval ticks and timestamp divisors explicitly to floating point so
`exact_division_for_integers` cannot truncate ratios or subsecond timestamps.
Use an unsigned scale argument for `toDateTime64`. Add regression coverage
for constants, columns, nulls, zero divisors, and both setting values.

Related: ClickHouse#124490
Retain constant-divisor kernels and monotonicity information where `intDiv`
operand casts preserve every input value. Keep nullable inputs, unsafe
mixed-sign pairs, and potentially throwing constant divisors on the checked
path to preserve null masking, range checks, and short-circuit execution.
Add primary-key, ordered-read, and short-circuit regressions.

Related: ClickHouse#124490
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 7, 2026
Comment thread src/Functions/divide.cpp Resolved
Check fractional results, nullable inputs, empty inputs, and result types
for multi-field `avg` with `exact_division_for_integers` disabled and enabled.
The existing `numericValueExpr` conversion keeps the average floating-point;
no change to the translator is needed.

Related: ClickHouse#124490
Comment thread src/Functions/divide.cpp Resolved
qoega added 3 commits October 8, 2026 01:51
Lower LogsQL `/` and two-argument `round` through a `Float64`
numerator so `exact_division_for_integers` cannot truncate ratios
or alter rounding and `default` behavior.

Cover constants, aggregate ratios, nullable fields, and non-finite
results with the setting enabled and disabled. The compiled current
parser passes all 18 value/type cases on the ARM64 development server.

Related: ClickHouse#124490
Disable DDL mutation for tables tied to the test's SQLite file and
force cleanup drops to execute. Keep the backing file if a drop fails,
while retaining query fuzzing.

Validated the existing reference, query fuzzing with randomly ignored
drops, and a server restart using the ARM64 CI binary.

Related: ClickHouse#124490
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124490&sha=556553a5d64f1b467909bcfa9b982188ca3c6cbb&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
Use the source column type and literal type when deciding whether to
hoist `divide` out of an aggregate. Preserve floating-point rewrites
while retaining integer truncation checks and the existing decimal guard.

Current SQL always uses the analyzer, so its floating-point plans were
already unchanged. Add SQL compatibility coverage and validate the
legacy visitor directly with floating, integer, nullable, low-cardinality,
and decimal operands.

Related: ClickHouse#124490 (comment)
Comment thread src/Functions/divide.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6423cad5d with master e830e6ecd (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 457f57469; 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 ⚠️

14 object files changed (+1.36 MiB total), 2 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionExactDivide.cpp.o new 1.19 MiB +1.19 MiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/divide.cpp.o 11.10 MiB 11.19 MiB +94.94 KiB (+0.84%)
src/CMakeFiles/dbms.dir/Interpreters/normalizeDivision.cpp.o new 44.76 KiB +44.76 KiB

719 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

18 translation units recompiled, 106 s compile time in total, 16 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +6.9 s (+8%) in total before that adjustment.

Translation units without a recent master baseline:

  • src/Functions/FunctionExactDivide.cpp: 7.1 s

Job report

qoega added 3 commits October 8, 2026 10:06
Pin `optimize_syntax_fuse_functions` so randomized settings cannot replace
`sumCount` with separate `sum` and `avg` in the expected plan.
The result values were already correct.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124490&sha=4947520ef07f502a1ae36c80f927439f628a4d6e&name_0=PR
Related: ClickHouse#124490
Reuse `intDiv` for signed dividends when an unsigned constant divisor
fits the signed type used by `DivideIntegralImpl`. Constants at or above
that type boundary remain on the checked magnitude path, as does zero.

Add primary-key and ordered-read coverage for same-width and wider
constants, signed-cast boundaries at all integer widths, and lazy zero
division. The old executable reproduces `INDEX_NOT_USED`; the new
regression passes after rebuilding.

Review: ClickHouse#124490 (comment)
@serxa serxa self-assigned this Oct 8, 2026

@serxa serxa left a comment

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.

Looks solid. The only thing I'm worried about is stored metadata. What if we change the meaning of / inside it? Looks like we can get in trouble.

Canonicalize opt-in division to `divideExact` when a new query is submitted,
leaving `divide` in existing metadata with its historical behavior. Skip
metadata and distributed DDL replays and normalize separately parsed `VALUES`
expressions. Preserve automatic view column names and the resolved function
identity used by keys, projections, and serialized plans.

Retain delegated integer kernels and monotonicity information, and prevent
aggregate rewrites from moving integer truncation across aggregation.

Add reload regressions for keys, partitions, columns, projections, views,
SQL functions, and mutations. Validate both default-setting directions with
real server restarts and randomized functional tests on the ARM64 dev VM.

Discussion: https://clickhouse-inc.slack.com/archives/C02F2LML5UG/p1791495863981149
Related: ClickHouse#124490
Comment thread src/Interpreters/normalizeDivision.cpp Resolved
qoega added 2 commits October 9, 2026 16:04
Apply `ASTSetQuery::default_settings` after explicit setting changes,
matching `InterpreterSetQuery`, before serializing division semantics.
Use the built-in default instead of inheriting the enclosing scope.

Cover nested resets for `/` and `divide`, sibling scope isolation,
explicit changes followed by resets, and persisted view definitions.

Review: ClickHouse#124490 (comment)
Concurrent flaky-check runs use separate databases but SQL UDF names are
server-wide. Move the UDF compatibility checks to a shell test with names
prefixed by `CLICKHOUSE_DATABASE`, and clean them up on exit. Keep the AST
and UDF coverage enabled for parallel execution.

Validated both tests for ten runs each across four workers on the dev VM.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124490&sha=b0791417c1bdee7d05c555839201a2ba18e4ef93&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
Related: ClickHouse#124490
Comment thread src/Interpreters/normalizeDivision.cpp Resolved
qoega added 2 commits October 9, 2026 19:29
Recognize `divideExact` as null-propagating when detecting legal outer
join reorderings. Its nullable operands propagate `NULL` for both exact
integer division and delegated floating-point division.

Add a functional regression comparing join plans and results with the
setting enabled and disabled. The exact-mode plan failed before the fix.

Review: ClickHouse#124490 (comment)
Pass the query context into `normalizeDivision` and copy it for nested
`SETTINGS` clauses. Apply clamped changes in order, including `profile`
and `compatibility`, and use `resetSettingsToDefaultValue` for resets.
Propagate the resulting scope only to its descendants before freezing
`divideExact` into the AST.

Cover profile overrides in both directions, assignment order, sibling
scope isolation, resets, and stored views after profile changes and reload.
The nested-profile regression failed before the fix. The dev build, 13
focused tests and six randomized concurrent test runs passed.

Related: ClickHouse#124490
return false;

ContextPtr scope_context;
if (const auto * select = ast.as<ASTSelectQuery>(); select && select->settings())

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.

normalize only re-scopes on ASTSelectQuery::settings() here, but query-local SETTINGS can also live on settings_ast (ASTSelectWithUnionQuery for UNION … SETTINGS, ASTQueryWithOutput for INSERT ... SETTINGS ... SELECT, UPDATE / DELETE / EXPLAIN, etc.), and CREATE ... SETTINGS query settings are hoisted out of storage->settings later by InterpreterSetQuery::applySettingsFromQuery.

Because executeQuery calls normalizeDivision before InterpreterSetQuery::applySettingsFromQuery, those settings never flip exact while / is being frozen. A concrete repro is:

INSERT INTO dst SETTINGS exact_division_for_integers = 1 SELECT 5 / 2;

The source SELECT is normalized under the session setting instead of the query-local one, so it keeps legacy divide and inserts 2.5 instead of 2. SELECT 5 / 2 UNION ALL SELECT 7 / 2 SETTINGS exact_division_for_integers = 1 has the same problem on the union node. I think this pass needs to model the same outer-setting sources that InterpreterSetQuery::applySettingsFromQuery applies before execution.

qoega added 2 commits October 11, 2026 04:51
Bring in the Parquet query-condition-cache fix and the replicated query-log test correction.

Related: ClickHouse#124991
Related: ClickHouse#124928
Related: ClickHouse#124490
Apply the finite non-zero divisor guard introduced on master to the stable division name. Moving division outside an aggregate can reverse signed-zero extrema or turn zero and empty sums into NaN.

Add a regression comparing optimizer-enabled results with disabled controls for signed zero, infinite divisors, and empty sums.

Related: ClickHouse#124490
@qoega

qoega commented Oct 11, 2026

Copy link
Copy Markdown
Member Author

@serxa added conversion for stored ast. all green again

Comment thread src/Functions/FunctionExactDivide.cpp Outdated

REGISTER_FUNCTION(ExactDivide)
{
factory.registerFunction<FunctionExactDivide>(FunctionDocumentation::INTERNAL_FUNCTION_DOCS);

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.

I think it might be worth to add a documentation entry for this function because it is now publically visible and will be persisted in metadata as well.

qoega added 2 commits October 11, 2026 21:52
Describe integer result types, checked errors, setting independence, and the stable name persisted in metadata. Add examples for integer, mixed-sign, and floating-point division.

Address review: ClickHouse#124490 (comment)
Preserve the new documentation while satisfying the category invariant for functions with a double-underscore prefix. The existing category regression passes after an incremental dev build.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124490&sha=0618babcf6fe1346d8d9a11ec3881c00cb1f3eda&name_0=PR&name_1=Fast%20test

Related: ClickHouse#124490
@qoega
qoega added this pull request to the merge queue Oct 12, 2026
Merged via the queue into ClickHouse:master with commit ff3515c Oct 12, 2026
173 checks passed
@qoega
qoega deleted the codex/exact-integer-division branch October 12, 2026 20:29
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
bacek pushed a commit to bacek/ClickHouse that referenced this pull request Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-feature Pull request with new product feature 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.

3 participants