paimon
paimon copied to clipboard
[core] Fix integer overflow in FieldSumAgg causing silent data corruption
Purpose
FieldSumAgg performs unchecked arithmetic for TINYINT, SMALLINT, INTEGER, and BIGINT types. When the accumulator overflows, the result silently wraps around (e.g., Byte.MAX_VALUE + 1 becomes -128), producing incorrect aggregation results without any error or warning. This is silent data corruption in the merge-tree SUM aggregation path.
The root cause differs by type:
- TINYINT/SMALLINT: Java promotes operands to
intfor arithmetic, then the(byte)or(short)cast silently truncates the overflow bits. - INTEGER/BIGINT: Standard
+and-wrap around atMAX_VALUE/MIN_VALUEper Java spec.
This fix adds overflow detection to all three affected methods (agg, retract, negative):
- For INTEGER and BIGINT: uses
Math.addExact/Math.subtractExact/Math.negateExact, which throwArithmeticExceptionon overflow. - For TINYINT and SMALLINT: uses range-checked helper methods that perform arithmetic in
intwidth and verify the result fits inbyte/shortrange before casting.
This is consistent with the overflow-protection pattern already used in DecimalUtils.add() and DecimalUtils.subtract() in the same codebase.
Tests
testFieldSumByteOverflow— TINYINT: verifies normal addition works, positive overflow throwsArithmeticException, negative overflow throws, and retract overflow throws.testFieldSumShortOverflow— SMALLINT: same coverage.testFieldSumIntOverflow— INTEGER: same coverage.testFieldSumLongOverflow— BIGINT: same coverage.
API and Format
No API or storage format changes.
Documentation
No new feature introduced.
Generative AI tooling
Generated-by: Claude Code 1.0.0