Skip to content

Do not hoist a constant out of an aggregate when it truncates into a Decimal - #117779

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-aggregate-arithmetic-decimal-truncation-117265
Sep 27, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-aggregate-arithmetic-decimal-truncation-117265

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

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 (on by default) decided the min/max swap from the untruncated literal, which has the opposite sign:

CREATE TABLE t (a Decimal(5,4)) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT toDecimal32(number, 4) FROM numbers(10);

SELECT min(a * 9223372036854775807), max(a * 9223372036854775807), sum(a * 4294967296) FROM t;
-- 0, -9, 193273528320   (min greater than max)
-- -9, 0, 0 with optimize_arithmetic_operations_in_aggregate_functions = 0

More generally, arithmetic with a Decimal operand does not distribute over sum, min, max and avg at all: besides the truncation of the other operand, it checks every row for overflow of the native width, and divide drops the fractional digits beyond the scale on every row. The hoisted operation runs once, on the aggregate, in its wider result type. For a Decimal32(0), sum(a / 2) over {1, 1} is 0 but sum(a) / 2 is 1, and sum(a + 1200000000) over a row 999999999 throws DECIMAL_OVERFLOW but sum(a) + 1200000000 * count(a) returns 2199999999.

The analyzer passes now decline the rewrite whenever an operand is a Decimal (either operand order, so min(a * toDecimal32(1, 0)) over an Int64 column is left alone too). That covers AggregateFunctionsArithmeticOperationsPass (sum/min/max/avg of multiply/divide/plus/minus with a constant) and the sibling sum(column +/- literal) -> sum(column) +/- literal * count(column) rewrite (RewriteSumFunctionWithSumAndCountPass), which had the same defect (sum(a + 4294967296) over a Decimal32 column 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 be Decimal, and its sum(column +/- literal) twin declines Decimal columns and literals. Non-Decimal arithmetic is hoisted as before - the test asserts that with EXPLAIN QUERY TREE. 02932_analyzer_rewrite_sum_column_and_constant pinned the rewritten query tree for a Decimal32 column; its reference is updated.

Closes: #117265

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 to CHANGELOG.md):

Fixed wrong results of sum, min, max and avg over arithmetic with a Decimal operand and a constant (for example min greater than max, a changed sum of a division, or a missing DECIMAL_OVERFLOW): optimize_arithmetic_operations_in_aggregate_functions no longer moves such arithmetic out of the aggregate.

🤖 Generated with Claude Code


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

Version info

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

…`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
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cbdf854]

Summary: ✅


AI Review

Summary

The PR broadens the fix from "large literal truncates into Decimal" to the full invariant that arithmetic with any Decimal operand must not be hoisted out of sum/min/max/avg. I checked the current merged code, the full diff, and the prior review threads; the current implementation now blocks the rewrite in both the query-tree passes and the earlier AST optimizer, and the new stateless coverage exercises the reported truncation, overflow, mirrored-operand, and per-row division cases. I did not find a remaining actionable issue in the current patch.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit cbdf854.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 28/72 (38.89%) · 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 2, 2026
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

The fix looks correct and boundary-exact for the reported shape (integer constant against a Decimal column), and the legacy-analyzer screen in ArithmeticOperationsInAgrFuncOptimize.cpp covers that leg too. But the screen's precondition is one-sided, and the mirrored shape still rewrites: a Decimal constant against a wider integer column. constantTruncatesIntoDecimalWidth requires isDecimal(argument_type) and an integer constant, so with min(a * toDecimal32(1, 0)) over an Int64 column both checks are false, the hoist fires, and because the multiplication computes in the decimal's native width (Int32 for Decimal32), the hoisted and unhoisted forms diverge — at pure defaults on the current analyzer:

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

sum escapes only incidentally, through the pre-existing result-type-equality guard (Decimal(38, 0) vs Decimal(9, 0)); min/max/avg type-match and rewrite. The old analyzer is clean by accident — ArithmeticOperationsInAgrFuncOptimize only matches ASTLiteral, and a Decimal constant reaches the pass only as a constant-folded node, so only the new-analyzer pass needs the extra condition. The per-row truncation itself is #117237 and out of scope here, but the rewrite makes the observable result depend on the optimization and manufactures min greater than max, which is the same class this PR closes.

One more condition in constantTruncatesIntoDecimalWidth would close it: also decline when the constant is a Decimal and the argument's integer width exceeds the decimal's native width — or, equivalently, key the screen on the computed width of the binary operation rather than on which side the constant is.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit cbdf8546680f49fd7b4a755856b62370f6c612a1 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 12:39
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you - confirmed and fixed. The screen is symmetric now: it also declines when the constant is the Decimal and the argument is an integer type wider than the decimal's native signed width (Int64 × Decimal32, and UInt32 × Decimal32 too, since the native width is signed). Your reproducer now returns 2, 5, 3.5 with the optimization both on and off, and it is committed as a regression in 05065_aggregate_arithmetic_decimal_truncation alongside a positive control that the hoist still fires for min(toInt16(a) * toDecimal32(1, 0)).

Also fixed the red on the PR's own tests: the CI settings randomizer sets optimize_arithmetic_operations_in_aggregate_functions to 0, which made the EXPLAIN assertions print sum instead of multiply; both tests now set it explicitly.

alexey-milovidov and others added 2 commits September 17, 2026 18:41
…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]>
alexey-milovidov and others added 2 commits September 27, 2026 07:05
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (05055_strict_resize_associated_output on Fast test (arm_darwin): ProcessLookupError: [Errno 3] No such process from os.getpgid(proc.pid) in process_result_impl of tests/clickhouse-test, a harness race after the test process has already exited) and provide a fix in a separate PR. If the fix is already in progress, link it here. The other red, order_by_read_in_order #1 in Performance Comparison (arm_release, master_head, 2/6), is tracked in #121456.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. 05055_strict_resize_associated_output ran past the --timeout 60 of Fast test (61.2 s reported; its 5379 passing arm_darwin runs in CIDB have p50 21.7 s and max 55.3 s), and its bash leader exited after proc.wait() gave up but before process_result_impl ran. os.getpgid(proc.pid) on that unreaped zombie still returns its pgid on Linux (checked), but returns ESRCH on macOS: XNU marks an exiting process dead so that proc_find no longer finds it (kern_exit.c), and getpgid returns ESRCH when proc_find fails (kern_prot.c). The ProcessLookupError then escaped as Test internal error, skipping the group kill and the client stack trace capture; with the harness fixed, this run would have been reported as a plain timeout.

I'll send the tests/clickhouse-test fix in a separate PR and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR: #122522. It also handles the EPERM that killpg returns on macOS when every process left in the group has exited but is not reaped yet.

@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.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into master with commit cb1b645 Sep 27, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-aggregate-arithmetic-decimal-truncation-117265 branch September 27, 2026 21:15
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
LyJacky pushed a commit to LyJacky/ClickHouse that referenced this pull request Sep 28, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 1, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 1, 2026
… 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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 10, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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

4 participants