This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 4a4017c6 fix(arrow/decimal): correct rescaling results and report cast 
errors (#1513)
4a4017c6 is described below

commit 4a4017c635d04bfe8f372be0610a7f818f8e5d86
Author: Harrison Crosse <[email protected]>
AuthorDate: Tue Nov 10 17:08:48 2026 -0500

    fix(arrow/decimal): correct rescaling results and report cast errors (#1513)
    
    ### Rationale for this change
    
    Decimal rescaling can panic or return wrong values, and safe compute
    casts can discard the error text.
    
    ### What changes are included in this PR?
    
    `decimal128.Num.Rescale` checks scale differences and overflow, returns
    zero for zero, and reports `rescale data loss` instead of panicking.
    
    `Decimal32.Rescale` and `Decimal64.Rescale` use exact multipliers and
    signed bounds checks. `Decimal64.ReduceScaleBy` computes its divisor in
    `int64`.
    
    The four decimal cast kernels report the `Rescale` error instead of
    formatting their previous error output.
    `TestListScalarHashSupportsChildArraysWithoutScalars` drops its
    `decimal32` and `decimal64` rows because both types now have scalars.
    
    ### Are these changes tested?
    
    `TestRescale` in `decimal128`, `TestBasicDecimal128`,
    `TestDecimalRescale` and `TestDecimalReduceScale` cover panics and wrong
    results. `TestDecimal128ToInt` covers safe integer casts.
    `TestDecimal128ToDecimal128`, `TestDecimal128ToDecimal256`,
    `TestDecimal256ToDecimal128` and `TestDecimal256ToDecimal256` check cast
    error text.
    
    The regression cases panic, return wrong values or report incorrect
    errors on main. The reproduction now prints the expected output.
    
    With Go 1.26.10, `go test -tags assert,test ./arrow/...` with
    `arrow-testing` and `parquet-testing` checked out, focused `-race -tags
    assert,test` runs, vet, lint and the Release Audit Tool passed.
    
    ### Are there any user-facing changes?
    
    Yes. Rescaling returns correct values or errors, and safe cast errors
    retain their cause. There is no API change.
    
    Closes https://github.com/apache/arrow-go/issues/1511.
---
 arrow/compute/cast_test.go                     | 30 +++++++++++
 arrow/compute/internal/kernels/numeric_cast.go |  8 +--
 arrow/decimal/decimal.go                       | 74 ++++++++------------------
 arrow/decimal/decimal_test.go                  | 57 ++++++++++++++++++++
 arrow/decimal128/decimal128.go                 | 25 +++++----
 arrow/decimal128/decimal128_test.go            | 31 +++++++++++
 arrow/scalar/scalar_test.go                    | 21 ++------
 7 files changed, 160 insertions(+), 86 deletions(-)

diff --git a/arrow/compute/cast_test.go b/arrow/compute/cast_test.go
index d49aac73..57d9bff3 100644
--- a/arrow/compute/cast_test.go
+++ b/arrow/compute/cast_test.go
@@ -863,6 +863,16 @@ func (c *CastSuite) TestDecimal128ToInt() {
                opts.AllowIntOverflow = true
                opts.AllowDecimalTruncate = true
                c.checkCastArr(negScale, arrow.PrimitiveTypes.Int64, 
`[1234567890000, -120000]`, *opts)
+
+               pastTable := array.NewDecimal128Builder(c.mem, 
&arrow.Decimal128Type{Precision: 1, Scale: -39})
+               defer pastTable.Release()
+               pastTable.Append(decimal128.FromI64(1))
+               pastTableArr := pastTable.NewArray()
+               defer pastTableArr.Release()
+
+               opts.AllowDecimalTruncate = false
+               _, err = compute.CastArray(context.Background(), pastTableArr, 
opts)
+               c.EqualError(err, "invalid: rescale data loss")
        })
 
        c.Run("int64 bounds inclusive", func() {
@@ -1118,6 +1128,8 @@ func (c *CastSuite) TestDecimal128ToDecimal128() {
                opts.AllowDecimalTruncate = false
                opts.ToType = dP28S0.DataType()
                checkCastFails(c.T(), dP38S10, opts)
+               _, err := compute.CastArray(context.Background(), dP38S10, 
&opts)
+               c.EqualError(err, "invalid: rescale data loss")
                checkCast(c.T(), dP28S0, dP38S10RoundTripped, opts)
        })
 
@@ -1141,6 +1153,18 @@ func (c *CastSuite) TestDecimal128ToDecimal128() {
                        checkCastFails(c.T(), d42, opts)
                }
        })
+
+       c.Run("rescale overflow", func() {
+               d20, _, _ := array.FromJSON(c.mem, 
&arrow.Decimal128Type{Precision: 2, Scale: 0},
+                       strings.NewReader(`["12", null]`))
+               defer d20.Release()
+
+               opts.AllowDecimalTruncate = false
+               opts.ToType = &arrow.Decimal128Type{Precision: 38, Scale: 38}
+               checkCastFails(c.T(), d20, opts)
+               _, err := compute.CastArray(context.Background(), d20, &opts)
+               c.EqualError(err, "invalid: rescale data loss")
+       })
 }
 
 func (c *CastSuite) TestDecimal256ToDecimal256() {
@@ -1202,6 +1226,8 @@ func (c *CastSuite) TestDecimal256ToDecimal256() {
                opts.AllowDecimalTruncate = false
                opts.ToType = dP28S0.DataType()
                checkCastFails(c.T(), dP38S10, opts)
+               _, err := compute.CastArray(context.Background(), dP38S10, 
&opts)
+               c.EqualError(err, "invalid: rescale data loss")
                checkCast(c.T(), dP28S0, dP38S10RoundTripped, opts)
        })
 
@@ -1291,6 +1317,8 @@ func (c *CastSuite) TestDecimal128ToDecimal256() {
                opts.AllowDecimalTruncate = false
                opts.ToType = d256P28S0.DataType()
                checkCastFails(c.T(), d128P38S10, opts)
+               _, err := compute.CastArray(context.Background(), d128P38S10, 
&opts)
+               c.EqualError(err, "invalid: rescale data loss")
                checkCast(c.T(), d128P28S0, d256P38S10RoundTripped, opts)
        })
 
@@ -1378,6 +1406,8 @@ func (c *CastSuite) TestDecimal256ToDecimal128() {
                opts.AllowDecimalTruncate = false
                opts.ToType = d128P28S0.DataType()
                checkCastFails(c.T(), d256P52S10, opts)
+               _, err := compute.CastArray(context.Background(), d256P52S10, 
&opts)
+               c.EqualError(err, "invalid: rescale data loss")
                checkCast(c.T(), d256P42S0, d128P38S10RoundTripped, opts)
        })
 
diff --git a/arrow/compute/internal/kernels/numeric_cast.go 
b/arrow/compute/internal/kernels/numeric_cast.go
index 9ce451c7..c8fed2a5 100644
--- a/arrow/compute/internal/kernels/numeric_cast.go
+++ b/arrow/compute/internal/kernels/numeric_cast.go
@@ -312,7 +312,7 @@ func safeRescaleDecimal256Out(inputType arrow.Type, 
outScale, outPrecision, inSc
                return ScalarUnaryNotNull(func(_ *exec.KernelCtx, val 
decimal128.Num, err *error) decimal256.Num {
                        out, e := 
decimal256.FromDecimal128(val).Rescale(inScale, outScale)
                        if e != nil {
-                               *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, 
*err)
+                               *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, e)
                                return decimal256.Num{}
                        }
 
@@ -327,7 +327,7 @@ func safeRescaleDecimal256Out(inputType arrow.Type, 
outScale, outPrecision, inSc
        return ScalarUnaryNotNull(func(_ *exec.KernelCtx, val decimal256.Num, 
err *error) decimal256.Num {
                out, e := val.Rescale(inScale, outScale)
                if e != nil {
-                       *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, *err)
+                       *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, e)
                        return decimal256.Num{}
                }
 
@@ -345,7 +345,7 @@ func safeRescaleDecimal128Out(inputType arrow.Type, 
outScale, outPrecision, inSc
                return ScalarUnaryNotNull(func(_ *exec.KernelCtx, val 
decimal128.Num, err *error) decimal128.Num {
                        out, e := val.Rescale(inScale, outScale)
                        if e != nil {
-                               *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, 
*err)
+                               *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, e)
                                return decimal128.Num{}
                        }
 
@@ -360,7 +360,7 @@ func safeRescaleDecimal128Out(inputType arrow.Type, 
outScale, outPrecision, inSc
        return ScalarUnaryNotNull(func(_ *exec.KernelCtx, val decimal256.Num, 
err *error) decimal128.Num {
                out, e := val.Rescale(inScale, outScale)
                if e != nil {
-                       *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, *err)
+                       *err = fmt.Errorf("%w: %s", arrow.ErrInvalid, e)
                        return decimal128.Num{}
                }
 
diff --git a/arrow/decimal/decimal.go b/arrow/decimal/decimal.go
index f62ea5a9..ea748966 100644
--- a/arrow/decimal/decimal.go
+++ b/arrow/decimal/decimal.go
@@ -21,7 +21,6 @@ import (
        "fmt"
        "math"
        "math/big"
-       "math/bits"
        "strconv"
        "strings"
        "unsafe"
@@ -402,7 +401,7 @@ func reduceScale[T interface {
                return n
        }
 
-       divisor := T(intPow(10, reduce))
+       divisor := T(intPow(10, int64(reduce)))
        if !round {
                return n / divisor
        }
@@ -434,65 +433,34 @@ func (n Decimal64) ReduceScaleBy(reduce int32, round 
bool) Decimal64 {
        return reduceScale(n, reduce, round)
 }
 
-//lint:ignore U1000 function is being used, staticcheck seems to not follow 
generics
-func (n Decimal32) rescaleWouldCauseDataLoss(deltaScale int32, multiplier 
Decimal32) (out Decimal32, loss bool) {
-       if deltaScale < 0 {
-               debug.Assert(multiplier != 0, "multiplier must not be zero")
-               quo, remainder := bits.Div32(0, uint32(n), uint32(multiplier))
-               return Decimal32(quo), remainder != 0
-       }
-
-       overflow, result := bits.Mul32(uint32(n), uint32(multiplier))
-       if overflow != 0 {
-               return Decimal32(result), true
-       }
-
-       out = Decimal32(result)
-       return out, out < n
-}
-
-//lint:ignore U1000 function is being used, staticcheck seems to not follow 
generics
-func (n Decimal64) rescaleWouldCauseDataLoss(deltaScale int32, multiplier 
Decimal64) (out Decimal64, loss bool) {
-       if deltaScale < 0 {
-               debug.Assert(multiplier != 0, "multiplier must not be zero")
-               quo, remainder := bits.Div64(0, uint64(n), uint64(multiplier))
-               return Decimal64(quo), remainder != 0
+func rescale[T Decimal32 | Decimal64](n T, originalScale, newScale int32) (T, 
error) {
+       if originalScale == newScale || n == 0 {
+               return n, nil
        }
 
-       overflow, result := bits.Mul64(uint64(n), uint64(multiplier))
-       if overflow != 0 {
-               return Decimal64(result), true
+       deltaScale := int64(newScale) - int64(originalScale)
+       absDeltaScale := deltaScale
+       if absDeltaScale < 0 {
+               absDeltaScale = -absDeltaScale
        }
-
-       out = Decimal64(result)
-       return out, out < n
-}
-
-func rescale[T interface {
-       Decimal32 | Decimal64
-       rescaleWouldCauseDataLoss(int32, T) (T, bool)
-       Sign() int
-}](n T, originalScale, newScale int32) (out T, err error) {
-       if originalScale == newScale {
-               return n, nil
+       // Scaling any nonzero value by 10^(MaxPrecision+1) or more overflows 
or drops every digit.
+       if absDeltaScale > int64(MaxPrecision[T]()) {
+               return 0, errors.New("rescale data loss")
        }
 
-       deltaScale := newScale - originalScale
-       absDeltaScale := int32(math.Abs(float64(deltaScale)))
-
-       sign := n.Sign()
-       if n < 0 {
-               n = -n
+       multiplier := T(intPow(10, absDeltaScale))
+       if deltaScale < 0 {
+               if n%multiplier != 0 {
+                       return 0, errors.New("rescale data loss")
+               }
+               return n / multiplier, nil
        }
 
-       multiplier := T(intPow(10, absDeltaScale))
-       var wouldHaveLoss bool
-       out, wouldHaveLoss = n.rescaleWouldCauseDataLoss(deltaScale, multiplier)
-       if wouldHaveLoss {
-               err = errors.New("rescale data loss")
+       maxValue := T(int64(math.MaxInt64) >> (64 - 8*unsafe.Sizeof(n)))
+       if n > maxValue/multiplier || n < (-maxValue-1)/multiplier {
+               return 0, errors.New("rescale data loss")
        }
-       out *= T(sign)
-       return
+       return n * multiplier, nil
 }
 
 func (n Decimal32) Rescale(originalScale, newScale int32) (out Decimal32, err 
error) {
diff --git a/arrow/decimal/decimal_test.go b/arrow/decimal/decimal_test.go
index 8793d4fc..f65d8a20 100644
--- a/arrow/decimal/decimal_test.go
+++ b/arrow/decimal/decimal_test.go
@@ -460,6 +460,61 @@ func TestDecimalRescale(t *testing.T) {
        // A value that genuinely overflows Decimal64 still reports data loss.
        _, err = decimal.Decimal64(5_000_000_000_000_000_000).Rescale(0, 1)
        assert.ErrorContains(t, err, "rescale data loss")
+
+       for _, tc := range []struct {
+               bits               int
+               n                  int64
+               oldScale, newScale int32
+               want               int64
+               wantErr            bool
+       }{
+               {64, 1, 0, 10, 10_000_000_000, false},
+               {64, -1, 0, 18, -1_000_000_000_000_000_000, false},
+               {64, 10_000_000_000, 10, 0, 1, false},
+               {64, -1_000_000_000_000_000_000, 18, 0, -1, false},
+               {32, 2, 0, 9, 2_000_000_000, false},
+               {32, -3, 0, 9, 0, true},
+               {64, -9, 0, 18, -9_000_000_000_000_000_000, false},
+               {64, 10, 0, 18, 0, true},
+               {32, 214748364, 0, 1, 2147483640, false},
+               {32, 214748365, 0, 1, 0, true},
+               {64, -922337203685477580, 0, 1, -9223372036854775800, false},
+               {64, -922337203685477581, 0, 1, 0, true},
+               {32, 1, 0, 10, 0, true},
+               {64, -1, 19, 0, 0, true},
+               {32, 1410065408, 10, 0, 0, true},
+               {32, 0, 32, 0, 0, false},
+               {64, 0, math.MinInt32, math.MaxInt32, 0, false},
+               {32, math.MinInt32, 5, 5, math.MinInt32, false},
+               {32, math.MinInt32, 1, 0, 0, true},
+               {64, math.MinInt64, 0, 1, 0, true},
+               {32, 10, math.MinInt32, math.MaxInt32, 0, true},
+               {64, 10, math.MaxInt32, math.MinInt32, 0, true},
+               {32, 1, -1, math.MaxInt32, 0, true},
+               {32, 111, math.MaxInt32 - 2, math.MaxInt32, 11100, false},
+               {64, 11100, math.MinInt32 + 2, math.MinInt32, 111, false},
+               {64, -555, 2, 1, 0, true},
+       } {
+               t.Run(fmt.Sprintf("decimal%d_%d_%d_%d", tc.bits, tc.n, 
tc.oldScale, tc.newScale), func(t *testing.T) {
+                       var got int64
+                       var err error
+                       if tc.bits == 32 {
+                               var out decimal.Decimal32
+                               out, err = 
decimal.Decimal32(tc.n).Rescale(tc.oldScale, tc.newScale)
+                               got = int64(out)
+                       } else {
+                               var out decimal.Decimal64
+                               out, err = 
decimal.Decimal64(tc.n).Rescale(tc.oldScale, tc.newScale)
+                               got = int64(out)
+                       }
+                       if tc.wantErr {
+                               assert.EqualError(t, err, "rescale data loss")
+                               return
+                       }
+                       require.NoError(t, err)
+                       assert.Equal(t, tc.want, got)
+               })
+       }
 }
 
 func TestDecimalIncreaseScale(t *testing.T) {
@@ -500,6 +555,8 @@ func TestDecimalReduceScale(t *testing.T) {
                assert.Equal(t, decimal.Decimal64(tt.expected).Negate(),
                        
decimal.Decimal64(tt.value).Negate().ReduceScaleBy(tt.scale, tt.round), 
"decimal64")
        }
+
+       assert.Equal(t, decimal.Decimal64(1), 
decimal.Decimal64(10_000_000_000).ReduceScaleBy(10, false))
 }
 
 func TestDecimalBasics(t *testing.T) {
diff --git a/arrow/decimal128/decimal128.go b/arrow/decimal128/decimal128.go
index 2febecea..b061f1e8 100644
--- a/arrow/decimal128/decimal128.go
+++ b/arrow/decimal128/decimal128.go
@@ -480,7 +480,7 @@ func (n Num) ReduceScaleBy(reduce int32, round bool) Num {
        return FromBigInt(result)
 }
 
-func (n Num) rescaleWouldCauseDataLoss(deltaScale int32, multiplier Num) (out 
Num, loss bool) {
+func (n Num) rescaleWouldCauseDataLoss(deltaScale int64, multiplier Num) (out 
Num, loss bool) {
        var (
                value, result, remainder *big.Int
        )
@@ -492,14 +492,10 @@ func (n Num) rescaleWouldCauseDataLoss(deltaScale int32, 
multiplier Num) (out Nu
        }
 
        result = (&big.Int{}).Mul(value, multiplier.BigInt())
-       out = FromBigInt(result)
-       cmp := result.Cmp(value)
-       if n.Sign() < 0 {
-               loss = cmp == 1
-       } else {
-               loss = cmp == -1
+       if result.BitLen() > 127 {
+               return Num{}, true
        }
-       return
+       return FromBigInt(result), false
 }
 
 // Rescale returns a new decimal128.Num with the value updated assuming
@@ -507,12 +503,19 @@ func (n Num) rescaleWouldCauseDataLoss(deltaScale int32, 
multiplier Num) (out Nu
 // to newScale. If rescaling this way would cause data loss, an error is
 // returned instead.
 func (n Num) Rescale(originalScale, newScale int32) (out Num, err error) {
-       if originalScale == newScale {
+       if originalScale == newScale || n == (Num{}) {
                return n, nil
        }
 
-       deltaScale := newScale - originalScale
-       absDeltaScale := int32(math.Abs(float64(deltaScale)))
+       deltaScale := int64(newScale) - int64(originalScale)
+       absDeltaScale := deltaScale
+       if absDeltaScale < 0 {
+               absDeltaScale = -absDeltaScale
+       }
+       // Scaling any nonzero value by 10^39 or more overflows or drops every 
digit.
+       if absDeltaScale >= int64(len(scaleMultipliers)) {
+               return Num{}, errors.New("rescale data loss")
+       }
 
        multiplier := scaleMultipliers[absDeltaScale]
        var wouldHaveLoss bool
diff --git a/arrow/decimal128/decimal128_test.go 
b/arrow/decimal128/decimal128_test.go
index 95da30ae..cafa8d7a 100644
--- a/arrow/decimal128/decimal128_test.go
+++ b/arrow/decimal128/decimal128_test.go
@@ -207,6 +207,37 @@ func TestDiv(t *testing.T) {
        }
 }
 
+func TestRescale(t *testing.T) {
+       oneE38 := decimal128.FromBigInt(new(big.Int).Exp(big.NewInt(10), 
big.NewInt(38), nil))
+       for _, tc := range []struct {
+               n                  int64
+               original, newScale int32
+               want               decimal128.Num
+               wantErr            bool
+       }{
+               {111, 0, 2, decimal128.FromI64(11100), false},
+               {-11100, 2, 0, decimal128.FromI64(-111), false},
+               {555, 2, 1, decimal128.Num{}, true},
+               {1, 0, 38, oneE38, false},
+               {-2, 0, 38, decimal128.Num{}, true},
+               {0, -9, 38, decimal128.Num{}, false},
+               {0, 38, -9, decimal128.Num{}, false},
+               {12, 0, 39, decimal128.Num{}, true},
+               {-12, 39, 0, decimal128.Num{}, true},
+               {10, math.MinInt32, math.MaxInt32, decimal128.Num{}, true},
+       } {
+               t.Run(fmt.Sprintf("%d_%d_%d", tc.n, tc.original, tc.newScale), 
func(t *testing.T) {
+                       got, err := 
decimal128.FromI64(tc.n).Rescale(tc.original, tc.newScale)
+                       if tc.wantErr {
+                               assert.EqualError(t, err, "rescale data loss")
+                               return
+                       }
+                       require.NoError(t, err)
+                       assert.Equal(t, tc.want, got)
+               })
+       }
+}
+
 func TestPow(t *testing.T) {
        for _, tc := range []struct {
                n    decimal128.Num
diff --git a/arrow/scalar/scalar_test.go b/arrow/scalar/scalar_test.go
index bb51c6d8..609f4569 100644
--- a/arrow/scalar/scalar_test.go
+++ b/arrow/scalar/scalar_test.go
@@ -147,6 +147,9 @@ func TestBasicDecimal128(t *testing.T) {
        assert.False(t, null.IsValid())
 
        assert.False(t, scalar.Equals(pi, pi2))
+
+       _, err := pi.CastTo(&arrow.Decimal128Type{Precision: 38, Scale: 38})
+       assert.EqualError(t, err, "rescale data loss")
 }
 
 func TestBasicDecimal256(t *testing.T) {
@@ -1430,24 +1433,6 @@ func 
TestListScalarHashSupportsChildArraysWithoutScalars(t *testing.T) {
                name      string
                newValues func() arrow.Array
        }{
-               {
-                       name: "decimal32",
-                       newValues: func() arrow.Array {
-                               b := 
array.NewDecimal32Builder(memory.DefaultAllocator, 
&arrow.Decimal32Type{Precision: 6, Scale: 2})
-                               defer b.Release()
-                               b.AppendValues([]decimal.Decimal32{123, 456}, 
nil)
-                               return b.NewDecimalArray()
-                       },
-               },
-               {
-                       name: "decimal64",
-                       newValues: func() arrow.Array {
-                               b := 
array.NewDecimal64Builder(memory.DefaultAllocator, 
&arrow.Decimal64Type{Precision: 12, Scale: 2})
-                               defer b.Release()
-                               b.AppendValues([]decimal.Decimal64{123, 456}, 
nil)
-                               return b.NewDecimalArray()
-                       },
-               },
                {
                        name: "list view",
                        newValues: func() arrow.Array {

Reply via email to