Repository navigation
Add opt-in exact integer division - #124490
Conversation
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.
|
Workflow [PR], commit [6423cad] Summary: ✅
AI ReviewSummaryThis PR adds the opt-in Findings❌ Blockers
Final VerdictChanges requested: the remaining nested- |
Add the required `26.10` settings-history entry with the default unchanged. This fixes the `settings_changes_history` style check. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124490&sha=d784c7bc84470c8807956541f04a6efa0baf029e&name_0=PR&name_1=Style%20check ClickHouse#124490
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
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
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)
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/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
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
left a comment
There was a problem hiding this comment.
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
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
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()) |
There was a problem hiding this comment.
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.
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
|
@serxa added conversion for stored ast. all green again |
|
|
||
| REGISTER_FUNCTION(ExactDivide) | ||
| { | ||
| factory.registerFunction<FunctionExactDivide>(FunctionDocumentation::INTERNAL_FUNCTION_DOCS); |
There was a problem hiding this comment.
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.
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
…integers` Update the setting registration, references, function documentation sources, and existing functional tests without changing division semantics. Related: ClickHouse#124490 Requested rename: https://github.com/ClickHouse/ClickHouse/pull/124490/changes#diff-d33ff1f4e22c61b4aed54d20df5b89677cbd182442ce4263dc94cf099076462eR4954
Add the opt-in
exact_division_for_integerssetting so SQL that expects integer division can use/anddividewithout rewriting each expression tointDiv. 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 propagateNULL.Division involving
Decimalor floating-point operands and the explicit functionsintDiv,divideDecimal, anddivideOrNullretain their existing behavior. Compatible non-nullable integer pairs reuseintDivand its constant-divisor kernels and monotonicity metadata. Other mixed-sign pairs, nullable inputs, and potentially throwing constant divisors use the checked internal__divideIntegerspath. The resolveddivideExactidentity 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 storeddivideretains its historical behavior. Existing metadata andATTACH, restore, and replicated DDL replays are not reinterpreted under the current setting. Automatic view column names are preserved, andVALUESexpressions 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, andVALUES. Actual server restarts with the default switched to1and back to0preserved 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
devVM with aRelWithDebInfoexecutable 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
devbuild: 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
avgwith nullable integer fields and empty input in both setting modes, including itsNullable(Float64)result type. The existing translator already converts numeric fields throughnumericValueExprtoFloat64, so no implementation change is needed for the reported average case. The current parser was compiled separately ondev, 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
roundnow explicitly use aFloat64numerator, preserving fractional ratios, rounding, and non-finitedefaulthandling 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 ondev, 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
masterwas 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=0is obsolete and coerced to1), 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
intDivwith signed dividends, including equal-width and wider constants, while constants outside the signed-cast range retain checked semantics. The previous binary reproducedINDEX_NOT_USEDforInt64 / 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 pinsoptimize_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add the
exact_division_for_integerssetting, disabled by default, to make/anddividereturn 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
26.10.1.2236-master(included in26.10and later)