Repository navigation
Do not hoist a constant out of an aggregate when it truncates into a Decimal - #117779
alexey-milovidov merged 11 commits into
Conversation
…`Decimal` Arithmetic with a `Decimal` operand computes in the decimal's own native signed width (`Int32` for every `Decimal32`), into which the other operand is materialised by a `static_cast`, so `Decimal32 * 9223372036854775807` multiplies by `-1`. `optimize_arithmetic_operations_in_aggregate_functions` decided the `min`/`max` swap from the untruncated literal, which has the opposite sign, and returned `min` greater than `max`. Hoisting also moves the multiplication into the wider result type of the aggregate, where the constant survives, so even without a swap the rewritten query computed a different value than the one written. The analyzer pass now declines the rewrite for a `Decimal` argument whose integer constant does not fit the decimal's native width, the same condition `decimalDivConstDivisorTruncates` uses for the arithmetic monotonicity analysis. The old analyzer works on an AST without types, so it declines for every integer literal outside `Int32`, the narrowest of those widths. Closes: #117265
|
Workflow [PR], commit [cbdf854] Summary: ✅
AI ReviewSummaryThe PR broadens the fix from "large literal truncates into Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit cbdf854.
Changed lines: Changed C/C++ lines covered: 28/72 (38.89%) · Uncovered code |
|
The fix looks correct and boundary-exact for the reported shape (integer constant against a CREATE TABLE t (a Int64) ENGINE = Memory;
INSERT INTO t VALUES (4294967298), (5);
SELECT min(a * toDecimal32(1, 0)), max(a * toDecimal32(1, 0)), avg(a * toDecimal32(1, 0)) FROM t;
-- 5, 2, 2147483651.5 (min > max)
SELECT min(a * toDecimal32(1, 0)), max(a * toDecimal32(1, 0)), avg(a * toDecimal32(1, 0)) FROM t
SETTINGS optimize_arithmetic_operations_in_aggregate_functions = 0;
-- 2, 5, 3.5
One more condition in |
Build profile diff (arm_release)Commit See the job log for details. |
…metic-decimal-truncation-117265
…e tests
The guard was one-sided: it declined only for a `Decimal` argument with an
integer constant. The query tree folds `toDecimal32(1, 0)` into a
`ConstantNode`, so `min(a * toDecimal32(1, 0))` over an `Int64` column still
reached the rewrite, and because the multiplication computes in the decimal's
native `Int32` the expression stops being order-preserving above `2^31 - 1`:
over `{4294967298, 5}` the hoisted form returned `min = 5`, `max = 2`,
`avg = 2147483651.5` instead of `2`, `5`, `3.5`.
`operandTruncatesIntoDecimalWidth` now screens both operand orders: a `Decimal`
argument with an integer constant its native width cannot represent, and an
integer argument wider than the native width of a `Decimal` constant (an
unsigned argument of the same width already overflows the signed native width).
Both tests set `optimize_arithmetic_operations_in_aggregate_functions`
explicitly - the CI settings randomizer turned it off and the `EXPLAIN`
assertions failed with `sum` instead of `multiply`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 @zlareb1 thank you - confirmed and fixed. The screen is symmetric now: it also declines when the constant is the Also fixed the red on the PR's own tests: the CI settings randomizer sets |
…metic-decimal-truncation-117265
…me `Decimal` width invariant `RewriteSumFunctionWithSumAndCountPass` (and its old-analyzer twin `RewriteSumFunctionWithSumAndCountVisitor`) run under the same `optimize_arithmetic_operations_in_aggregate_functions` setting and hoist the literal out of `sum(column + literal)` into `sum(column) + literal * count(column)`. For a `Decimal32` column, `a + 4294967296` adds `0` to every row because the literal is `static_cast` into the decimal's native `Int32` width, while the rewritten form adds the full literal, so `sum(a + 4294967296)` returned 42949673005 instead of 45. The guard `operandTruncatesIntoDecimalWidth` moves out of `AggregateFunctionsArithmeticOperationsPass.cpp` into `src/DataTypes/DecimalNativeWidthTruncation.h` and is applied by all three rewrites, screening both operand orders. The test is renumbered to `05227` and gains the `sum(a +/- literal)` cases together with `EXPLAIN QUERY TREE` probes for the guarded and the still-hoisted shapes. The old-analyzer test `05066` is dropped: `enable_analyzer = 0` is rejected since 26.9, so it can no longer run. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…metic-decimal-truncation-117265
…of an aggregate at all
Screening only the width truncation of the other operand was not enough. Arithmetic with a
`Decimal` operand also checks every row for overflow of the decimal's native width, and
`divide` drops the fractional digits beyond the scale on every row, so it does not distribute
over `sum`, `min`, `max` and `avg` even when the constant fits the native width:
`sum(a + 1200000000)` over a `Decimal32(0)` row `999999999` throws `DECIMAL_OVERFLOW`, but
`sum(a) + 1200000000 * count(a)` does not; `sum(a / 2)` over `{1, 1}` is `0`, but `sum(a) / 2` is `1`.
Both analyzer passes (`AggregateFunctionsArithmeticOperationsPass`,
`RewriteSumFunctionWithSumAndCountPass`) now decline whenever an operand is a `Decimal`, which
subsumes the truncation screen, so the `operandTruncatesIntoDecimalWidth` helper is removed.
The old AST path of the multiply/divide rewrite does not know the types of expressions, so it
now fires only when the non-constant operand is a source column whose type is known not to be
`Decimal`; the old `sum(column +/- literal)` rewrite declines `Decimal` columns and literals.
`02932_analyzer_rewrite_sum_column_and_constant` pinned the rewritten query tree for a
`Decimal32` column; its reference is updated.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117779&sha=48feb796fe66c3f579190345291a925e98213738&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 ( |
|
Investigated. I'll send the |
|
Fixing PR: #122522. It also handles the |
When a test outlives its timeout, the `proc.wait` in `run_single_test`
raises `TimeoutExpired` and leaves `returncode` unset, and
`process_result_impl` then kills the test's process group. If the test
finishes in between, its leader has exited but nothing has reaped it yet,
and macOS hides such a process (xnu-12377.1.9): `proc_exit` sets
`P_REF_DEAD` ("will not be visible via proc_find", bsd/kern/kern_exit.c),
so `getpgid` returns ESRCH (bsd/kern/kern_prot.c), and `killpg1` skips
`SZOMB` members of a process group and returns EPERM to a POSIX caller when
it found no other member (bsd/kern/kern_sig.c). Linux still reports the
pgid of such a process and signals a group of them without an error.
So on `Fast test (arm_darwin)` a test that exits at its deadline was
reported as `Test internal error` instead of `Timeout!`, and its group was
not killed: `ProcessLookupError` from `os.getpgid(proc.pid)` in
`process_result_impl` (05055_strict_resize_associated_output, ClickHouse#117779), and
`PermissionError` from `os.killpg(pgid, signal.SIGTSTP)` and from
`os.killpg(pgid, signal.SIGTERM)` in `kill_process_group`
(01674_executable_dictionary_implicit_key and 01474_executable_dictionary,
ClickHouse#89945).
Pass `proc.pid` as the process group id. The test is started with
`start_new_session=True`, so its leader is a session leader whose pgid is
its pid and cannot change, and the pid stays taken until the leader is
reaped. This also lets the kill reach members that outlived an exited
leader.
Let `kill_process_group` ignore EPERM like ESRCH for every signal it
sends, not only for SIGKILL: the runner's children run under its uid, which
XNU always lets it signal, so EPERM there means that no member is left to
signal. The SIGKILL-only handler that already did this for the same macOS
behaviour is folded into the common one.
The new test loads the runner as a module, answers `getpgid` and `killpg`
the way macOS does for such a group, and checks that the test is reported
as a timeout with its group signalled, with and without
`--capture-client-stacktrace`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#117779 the pass returns before the empty-state check whenever either operand is a Decimal, so a Decimal constant or a Decimal aggregate result type can no longer reach constantKeepsZeroAtZero or hoistOverEmptyState. The three plan assertions that expected a Decimal hoist are removed; the decline itself is covered by 05227_aggregate_arithmetic_decimal_truncation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… hoist ClickHouse#117779 declines every Decimal operand, so these rows no longer exercise a kept hoist; 05227_aggregate_arithmetic_decimal_truncation covers the decline. Co-Authored-By: Claude Opus 5.5 <[email protected]>
AggregateFunctionsArithmeticOperationsPass rewrites `min|max(x <op> c)` into `min|max(x) <op> c`, swapping min and max for a negative multiplier or divisor and for `c - x`. The rewrite is valid only if the operation is monotone (or antitone) in the order min and max use, and if it commutes with the default value of the aggregate. Both hold for a number, neither for an Array or a Tuple: min and max compare those lexicographically, and an element-wise operation does not preserve that order. Negation reverses the order of the elements but not of the lengths, so `[]` and a prefix stay the least; truncating `Decimal` division, or the constant cast into the native width of a decimal element, creates ties in the leading elements that change which row wins. Over no rows the hoisted operation runs on the default value (`[]`, `(0)`), and `[] + [1]` throws SIZES_OF_ARRAYS_DONT_MATCH. For a Variant operand the hoisted `max(Variant)` is rejected with ILLEGAL_TYPE_OF_ARGUMENT. ClickHouse#117779 added a decline for a `Decimal` operand, but it inspects only the top-level type, so `Array(Decimal)` and `Tuple(Decimal)` still pass, and the `Array(Int64)` case involves no `Decimal` at all. On 26.8.2.7, `min(arr * -1), max(arr * -1)` over `[]`, `[0]`, `[0, 1]` returns `[0,-1]` and `[]`. Extend that loop: also decline when either operand, after LowCardinality and Nullable, is an Array, a Tuple, a Map or a Variant, named explicitly (the rule of FunctionBinaryArithmetic::isCompoundForMonotonicity, plus Variant). IDataType::haveSubtypes() is not used because it is false for `Tuple()`. Checking the constant side too declines `min(number * (2, 3))` and `min(number * tuple())`, which threw BAD_TYPE_OF_FIELD. Scalar operands are hoisted as before. The sibling RewriteSumFunctionWithSumAndCountPass accepts only numeric columns and literals, and sum and avg reject compound arguments. Closes ClickHouse#122647 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Arithmetic with a
Decimaloperand computes in the decimal's own native signed width (Int32for everyDecimal32), into which the other operand is materialised by astatic_cast, soDecimal32 * 9223372036854775807multiplies by-1.optimize_arithmetic_operations_in_aggregate_functions(on by default) decided themin/maxswap from the untruncated literal, which has the opposite sign:More generally, arithmetic with a
Decimaloperand does not distribute oversum,min,maxandavgat all: besides the truncation of the other operand, it checks every row for overflow of the native width, anddividedrops the fractional digits beyond the scale on every row. The hoisted operation runs once, on the aggregate, in its wider result type. Fora Decimal32(0),sum(a / 2)over{1, 1}is0butsum(a) / 2is1, andsum(a + 1200000000)over a row999999999throwsDECIMAL_OVERFLOWbutsum(a) + 1200000000 * count(a)returns2199999999.The analyzer passes now decline the rewrite whenever an operand is a
Decimal(either operand order, somin(a * toDecimal32(1, 0))over anInt64column is left alone too). That coversAggregateFunctionsArithmeticOperationsPass(sum/min/max/avgofmultiply/divide/plus/minuswith a constant) and the siblingsum(column +/- literal)->sum(column) +/- literal * count(column)rewrite (RewriteSumFunctionWithSumAndCountPass), which had the same defect (sum(a + 4294967296)over aDecimal32column returned 42949673005 instead of 45). The old AST path does not know the types of expressions, so it hoists only when the non-constant operand is a source column whose type is known not to beDecimal, and itssum(column +/- literal)twin declinesDecimalcolumns and literals. Non-Decimalarithmetic is hoisted as before - the test asserts that withEXPLAIN QUERY TREE.02932_analyzer_rewrite_sum_column_and_constantpinned the rewritten query tree for aDecimal32column; its reference is updated.Closes: #117265
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed wrong results of
sum,min,maxandavgover arithmetic with aDecimaloperand and a constant (for examplemingreater thanmax, a changedsumof a division, or a missingDECIMAL_OVERFLOW):optimize_arithmetic_operations_in_aggregate_functionsno longer moves such arithmetic out of the aggregate.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117779]
Version info
26.10.1.838-master(included in26.10and later)