From 5e26d954cb27bf98b64d920fce5b253f7786a8e5 Mon Sep 17 00:00:00 2001 From: xgbtxy <115146404+xgbtxy@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:49:26 +0800 Subject: [PATCH] optimizer: avoid intermediate overflow in sumRange arithmetic series sumRange folded sum(m..n), sum(m..n, pred), and reduce(m..n, # + #acc) with count * (m + n) / 2 in signed int. When m + n or count * (m + n) overflows before dividing by 2, the high carry bit is lost and the folded constant diverges from unoptimized evaluation (for example, sum(4611686018427387903..4611686018427387904) returned -1 instead of math.MaxInt64, and even single-element sum(4611686018427387904..4611686018427387904) returned -4611686018427387904). Divide the even factor by 2 using unsigned differences before multiplying so the folded result matches two's-complement runtime addition across all m <= n. --- optimizer/sum_range.go | 20 +++++++--- optimizer/sum_range_test.go | 80 +++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 5 deletions(-) diff --git a/optimizer/sum_range.go b/optimizer/sum_range.go index 92f6e1dac..142bb9106 100644 --- a/optimizer/sum_range.go +++ b/optimizer/sum_range.go @@ -17,9 +17,7 @@ func (*sumRange) Visit(node *Node) { m := from.Value n := to.Value if n >= m { - count := n - m + 1 - // Use the arithmetic series formula: (n - m + 1) * (m + n) / 2 - sum := count * (m + n) / 2 + sum, count := rangeSum(m, n) if len(sumBuiltin.Arguments) == 1 { // sum(m..n) @@ -47,8 +45,7 @@ func (*sumRange) Visit(node *Node) { m := from.Value n := to.Value if n >= m { - // Use the arithmetic series formula: (n - m + 1) * (m + n) / 2 - sum := (n - m + 1) * (m + n) / 2 + sum, _ := rangeSum(m, n) // Check for optional initialValue (3rd argument) if len(reduceBuiltin.Arguments) == 3 { @@ -67,6 +64,19 @@ func (*sumRange) Visit(node *Node) { } } +// rangeSum computes the sum of integers in [m, n] (for n >= m) and the element +// count in two's complement int arithmetic without overflowing before dividing by 2. +func rangeSum(m, n int) (int, int) { + diff := uint(n) - uint(m) + count := diff + 1 + if diff&1 == 1 { + halfCount := (diff >> 1) + 1 + return int(halfCount * (uint(m) + uint(n))), int(count) + } + halfSum := uint(m) + (diff >> 1) + return int(count * halfSum), int(count) +} + // isPointerPlusAcc checks if the node represents `# + #acc` pattern func isPointerPlusAcc(node Node) bool { predicate, ok := node.(*PredicateNode) diff --git a/optimizer/sum_range_test.go b/optimizer/sum_range_test.go index 87185b227..210285841 100644 --- a/optimizer/sum_range_test.go +++ b/optimizer/sum_range_test.go @@ -1,6 +1,8 @@ package optimizer_test import ( + "fmt" + "math" "testing" "github.com/expr-lang/expr" @@ -246,6 +248,84 @@ func TestOptimize_reduce_range_reversed_errors(t *testing.T) { require.Error(t, err, "reduce on empty range should error") } +func TestOptimize_sum_range_overflow(t *testing.T) { + halfMax := math.MaxInt/2 + 1 + thirdMax := math.MaxInt / 3 + + tests := []struct { + name string + code string + want int + }{ + { + name: "single element m+n overflows int", + code: fmt.Sprintf("sum(%d..%d)", halfMax, halfMax), + want: halfMax, + }, + { + name: "two elements summing to MaxInt", + code: fmt.Sprintf("sum(%d..%d)", halfMax-1, halfMax), + want: math.MaxInt, + }, + { + name: "two negative elements summing to -MaxInt", + code: fmt.Sprintf("sum(%d..%d)", -halfMax, -halfMax+1), + want: -math.MaxInt, + }, + { + name: "three elements count*(m+n) overflows int", + code: fmt.Sprintf("sum(%d..%d)", thirdMax-1, thirdMax+1), + want: 3 * thirdMax, + }, + { + name: "two elements wrapping int sum matches unoptimized", + code: fmt.Sprintf("sum(%d..%d)", halfMax, halfMax+1), + want: halfMax + (halfMax + 1), + }, + { + name: "sum with predicate on large range", + code: fmt.Sprintf("sum(%d..%d, # - 1)", halfMax-1, halfMax), + want: math.MaxInt - 2, + }, + { + name: "reduce sum without initial value", + code: fmt.Sprintf("reduce(%d..%d, # + #acc)", halfMax-1, halfMax), + want: math.MaxInt, + }, + { + name: "reduce sum with initial value", + code: fmt.Sprintf("reduce(%d..%d, # + #acc, -1)", halfMax-1, halfMax), + want: math.MaxInt - 1, + }, + { + name: "negative odd-length range", + code: "sum(-5..-3)", + want: -12, + }, + { + name: "zero-crossing even-length range", + code: "sum(-5..6)", + want: 6, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + optimized, err := expr.Compile(tt.code) + require.NoError(t, err) + got, err := expr.Run(optimized, nil) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + + unoptimized, err := expr.Compile(tt.code, expr.Optimize(false)) + require.NoError(t, err) + wantUnopt, err := expr.Run(unoptimized, nil) + require.NoError(t, err) + assert.Equal(t, wantUnopt, got) + }) + } +} + func BenchmarkSumRange_Optimized(b *testing.B) { program, err := expr.Compile(`sum(1..100)`) require.NoError(b, err)