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 78af17d3 fix(arrow/decimal): reject infinite decimal strings and bound 
extreme exponents (#1514)
78af17d3 is described below

commit 78af17d3b7c4d337694b12abe3a4c13cf10b462d
Author: Harrison Crosse <[email protected]>
AuthorDate: Tue Nov 10 17:35:43 2026 -0500

    fix(arrow/decimal): reject infinite decimal strings and bound extreme 
exponents (#1514)
    
    ### Rationale for this change
    
    `decimal128.FromString` and `decimal256.FromString` panic on infinities
    and huge exponents. Short strings representing huge or tiny values can
    allocate hundreds of megabytes, including in `Decimal32` and `Decimal64`
    at some scales.
    
    ### What changes are included in this PR?
    
    Parsing now rejects infinite parsed or scaled values and checks
    magnitude before converting to `big.Int`, including at negative scales
    in all four widths. It skips rounding when the scaled magnitude is below
    one quarter and already rounds to zero. Accepted values and range error
    messages are unchanged.
    
    ### Are these changes tested?
    
    `TestFromString` covers infinity and exponent panics in `decimal128` and
    `decimal256`, plus allocation limits for tiny values in all four widths.
    These cases panic or exceed the allocation limits on main. `TestBitLen`
    and boundary rows preserve existing range behavior.
    
    Some guards only limit memory use for huge values. Tests pass without
    them. I measured their memory use separately.
    
    With Go 1.26.10, `go 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. Parsing avoids these panics and excessive allocations. There is no
    API change.
    
    Closes https://github.com/apache/arrow-go/issues/1512.
---
 arrow/decimal/decimal.go            | 14 +++++++++---
 arrow/decimal/decimal_test.go       | 31 +++++++++++++++++++++++++-
 arrow/decimal128/decimal128.go      | 22 ++++++++++++++++---
 arrow/decimal128/decimal128_test.go | 44 +++++++++++++++++++++++++++++++++++++
 arrow/decimal256/decimal256.go      | 22 ++++++++++++++++---
 arrow/decimal256/decimal256_test.go | 44 +++++++++++++++++++++++++++++++++++++
 6 files changed, 167 insertions(+), 10 deletions(-)

diff --git a/arrow/decimal/decimal.go b/arrow/decimal/decimal.go
index ea748966..a51b8563 100644
--- a/arrow/decimal/decimal.go
+++ b/arrow/decimal/decimal.go
@@ -189,11 +189,13 @@ func decimalFromString[T interface {
        }
 
        if scale < 0 {
-               var tmp big.Int
-               val, _ := out.Int(&tmp)
-               if val.BitLen() > int(nbits) {
+               // Check the magnitude before converting, which would allocate 
as many
+               // bits as the value has.
+               if out.MantExp(nil) > int(nbits) {
                        return n, fmt.Errorf("bitlen too large for decimal%d", 
nbits)
                }
+               var tmp big.Int
+               val, _ := out.Int(&tmp)
 
                // |val| < 2^64 < 10^20, so a larger divisor gives the same 
quotient.
                div := new(big.Int).Exp(big.NewInt(10), 
big.NewInt(min(-int64(scale), 20)), nil)
@@ -210,6 +212,12 @@ func decimalFromString[T interface {
                if out.IsInf() || out.MantExp(nil) > int(nbits) {
                        return n, fmt.Errorf("bitlen too large for decimal%d", 
nbits)
                }
+               // A magnitude below 1/4 rounds to zero. Clearing it skips the
+               // rounding below, which allocates in proportion to the gap 
between
+               // the value's exponent and 0.5's.
+               if out.MantExp(nil) < -1 {
+                       out.SetInt64(0)
+               }
                if out.Signbit() {
                        out.Sub(out, pt5)
                } else {
diff --git a/arrow/decimal/decimal_test.go b/arrow/decimal/decimal_test.go
index f65d8a20..663105eb 100644
--- a/arrow/decimal/decimal_test.go
+++ b/arrow/decimal/decimal_test.go
@@ -20,6 +20,7 @@ import (
        "fmt"
        "math"
        "math/big"
+       "runtime"
        "strconv"
        "testing"
 
@@ -300,6 +301,14 @@ func TestFromString(t *testing.T) {
                {"2112.33", 211233, 2},
                {"-2112.33", -211233, 2},
                {"12E2", 12, -2},
+               {"0", 0, 0},
+               {"0.24", 0, 0},
+               {"0.5", 1, 0},
+               {"-0.5", -1, 0},
+               {"0.51", 1, 0},
+               {"-0.51", -1, 0},
+               {"0.0051", 1, 2},
+               {"-0.0051", -1, 2},
        }
 
        for _, tt := range tests {
@@ -329,8 +338,15 @@ func TestFromString(t *testing.T) {
                _, err := decimal.Decimal32FromString(s, 9, 0)
                assert.Error(t, err, s)
        }
-       _, err := decimal.Decimal64FromString("9223372036854775808", 18, 0)
+       n32, err := decimal.Decimal32FromString("4294967295", 9, -1)
+       require.NoError(t, err)
+       assert.Equal(t, decimal.Decimal32(429496729), n32)
+       _, err = decimal.Decimal32FromString("4294967296", 9, -1)
+       assert.ErrorContains(t, err, "bitlen too large for decimal32")
+       _, err = decimal.Decimal64FromString("9223372036854775808", 18, 0)
        assert.Error(t, err)
+       _, err = decimal.Decimal64FromString("18446744073709551616", 18, -1)
+       assert.ErrorContains(t, err, "bitlen too large for decimal64")
 
        for _, tc := range []struct {
                s     string
@@ -338,6 +354,7 @@ func TestFromString(t *testing.T) {
                want  decimal.Decimal64
        }{
                {"9223372036854775808", -1, 922337203685477580},
+               {"18446744073709551615", -2, 184467440737095516},
                {"10000000000000000000", -19, 1},
                {"18000000000000000000", -20, 0},
                {"1", math.MinInt32, 0},
@@ -373,6 +390,18 @@ func TestFromString(t *testing.T) {
                assert.Equal(t, decimal.Decimal32(tc.want), n32, tc.s)
                assert.Equal(t, decimal.Decimal64(tc.want), n64, tc.s)
        }
+
+       var before, after runtime.MemStats
+       runtime.ReadMemStats(&before)
+       tiny32, err := decimal.Decimal32FromString("-1e-20000000", 9, 0)
+       require.NoError(t, err)
+       tiny64, err := decimal.Decimal64FromString("-1e-20000000", 18, 0)
+       runtime.ReadMemStats(&after)
+       require.NoError(t, err)
+       assert.Equal(t, decimal.Decimal32(0), tiny32)
+       assert.Equal(t, decimal.Decimal64(0), tiny64)
+       // Rounding these values directly would allocate about 33 MB.
+       assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(1<<20))
 }
 
 func TestCmp(t *testing.T) {
diff --git a/arrow/decimal128/decimal128.go b/arrow/decimal128/decimal128.go
index b061f1e8..41c59313 100644
--- a/arrow/decimal128/decimal128.go
+++ b/arrow/decimal128/decimal128.go
@@ -274,13 +274,18 @@ func FromString(v string, prec, scale int32) (n Num, err 
error) {
        if err != nil {
                return
        }
+       if out.IsInf() {
+               return Num{}, fmt.Errorf("cannot convert %s to decimal128", v)
+       }
 
        if scale < 0 {
-               var tmp big.Int
-               val, _ := out.Int(&tmp)
-               if val.BitLen() > 127 {
+               // Check the magnitude before converting, which would allocate 
as many
+               // bits as the value has.
+               if out.MantExp(nil) > 127 {
                        return Num{}, errors.New("bitlen too large for 
decimal128")
                }
+               var tmp big.Int
+               val, _ := out.Int(&tmp)
                n = FromBigInt(val)
                n, _ = n.Div(scaleMultipliers[-scale])
        } else {
@@ -290,6 +295,17 @@ func FromString(v string, prec, scale int32) (n Num, err 
error) {
                // we're positive we'll add 0.5.
                p := (&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())
                out.SetPrec(precInBits).Mul(out, p)
+               // Reject before rounding and converting, which would allocate 
as many
+               // bits as the value has.
+               if out.IsInf() || out.MantExp(nil) > 128 {
+                       return Num{}, errors.New("bitlen too large for 
decimal128")
+               }
+               // A magnitude below 1/4 rounds to zero. Clearing it skips the
+               // rounding below, which allocates in proportion to the gap 
between
+               // the value's exponent and 0.5's.
+               if out.MantExp(nil) < -1 {
+                       out.SetInt64(0)
+               }
                if out.Signbit() {
                        out.Sub(out, pt5)
                } else {
diff --git a/arrow/decimal128/decimal128_test.go 
b/arrow/decimal128/decimal128_test.go
index cafa8d7a..781fb9cf 100644
--- a/arrow/decimal128/decimal128_test.go
+++ b/arrow/decimal128/decimal128_test.go
@@ -20,6 +20,7 @@ import (
        "fmt"
        "math"
        "math/big"
+       "runtime"
        "testing"
 
        "github.com/apache/arrow-go/v18/arrow/decimal128"
@@ -703,6 +704,14 @@ func TestFromString(t *testing.T) {
                {"2112.33", 211233, 2},
                {"-2112.33", -211233, 2},
                {"12E2", 12, -2},
+               {"0", 0, 0},
+               {"0.24", 0, 0},
+               {"0.5", 1, 0},
+               {"-0.5", -1, 0},
+               {"0.51", 1, 0},
+               {"-0.51", -1, 0},
+               {"0.0051", 1, 2},
+               {"-0.0051", -1, 2},
        }
 
        for _, tt := range tests {
@@ -714,6 +723,33 @@ func TestFromString(t *testing.T) {
                        assert.Equal(t, ex, n)
                })
        }
+
+       for _, s := range []string{"Inf", "+Inf", "-inf", "1e1000000000", 
"-1e1000000000"} {
+               for _, scale := range []int32{2, -2} {
+                       _, err := decimal128.FromString(s, 37, scale)
+                       assert.ErrorContains(t, err, "cannot convert", "%s at 
scale %d", s, scale)
+               }
+       }
+
+       for _, tc := range []struct {
+               s     string
+               scale int32
+       }{
+               {"1e646456990", 38},
+               {"-1e600000000", -2},
+       } {
+               _, err := decimal128.FromString(tc.s, 37, tc.scale)
+               assert.ErrorContains(t, err, "bitlen too large for decimal128", 
"%s at scale %d", tc.s, tc.scale)
+       }
+
+       var before, after runtime.MemStats
+       runtime.ReadMemStats(&before)
+       tiny, err := decimal128.FromString("-1e-20000000", 37, 0)
+       runtime.ReadMemStats(&after)
+       require.NoError(t, err)
+       assert.Equal(t, decimal128.Num{}, tiny)
+       // Rounding this value directly would allocate about 16 MB.
+       assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(1<<20))
 }
 
 func TestInvalidNonNegScaleFromString(t *testing.T) {
@@ -740,6 +776,14 @@ func TestBitLen(t *testing.T) {
        assert.ErrorContains(t, err, "bitlen too large for decimal128")
        _, err = decimal128.FromString(b.String(), decimal128.MaxPrecision, -1)
        assert.ErrorContains(t, err, "bitlen too large for decimal128")
+
+       limit := new(big.Int).Lsh(big.NewInt(1), 127)
+       _, err = decimal128.FromString(limit.String(), decimal128.MaxPrecision, 
-1)
+       assert.ErrorContains(t, err, "bitlen too large for decimal128")
+       limit.Sub(limit, big.NewInt(1))
+       got, err := decimal128.FromString(limit.String(), 
decimal128.MaxPrecision, -1)
+       require.NoError(t, err)
+       assert.Equal(t, limit.Quo(limit, big.NewInt(10)).String(), 
got.BigInt().String())
 }
 
 func TestFromStringDecimal128b(t *testing.T) {
diff --git a/arrow/decimal256/decimal256.go b/arrow/decimal256/decimal256.go
index cbc28c8d..9bf4c16f 100644
--- a/arrow/decimal256/decimal256.go
+++ b/arrow/decimal256/decimal256.go
@@ -154,18 +154,34 @@ func FromString(v string, prec, scale int32) (n Num, err 
error) {
        if err != nil {
                return
        }
+       if out.IsInf() {
+               return Num{}, fmt.Errorf("cannot convert %s to decimal256", v)
+       }
 
        if scale < 0 {
-               var tmp big.Int
-               val, _ := out.Int(&tmp)
-               if val.BitLen() > 255 {
+               // Check the magnitude before converting, which would allocate 
as many
+               // bits as the value has.
+               if out.MantExp(nil) > 255 {
                        return Num{}, errors.New("bitlen too large for 
decimal256")
                }
+               var tmp big.Int
+               val, _ := out.Int(&tmp)
                n = FromBigInt(val)
 
                n, _ = n.Div(scaleMultipliers[-scale])
        } else {
                out.Mul(out, 
(&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())).SetPrec(precInBits)
+               // Reject before rounding and converting, which would allocate 
as many
+               // bits as the value has.
+               if out.IsInf() || out.MantExp(nil) > 256 {
+                       return Num{}, errors.New("bitlen too large for 
decimal256")
+               }
+               // A magnitude below 1/4 rounds to zero. Clearing it skips the
+               // rounding below, which allocates in proportion to the gap 
between
+               // the value's exponent and 0.5's.
+               if out.MantExp(nil) < -1 {
+                       out.SetInt64(0)
+               }
                // Since we're going to truncate this to get an integer, we 
need to round
                // the value instead because of edge cases so that we match how 
other implementations
                // (e.g. C++) handles Decimal values. So if we're negative 
we'll subtract 0.5 and if
diff --git a/arrow/decimal256/decimal256_test.go 
b/arrow/decimal256/decimal256_test.go
index 2143ff58..68f9a7f5 100644
--- a/arrow/decimal256/decimal256_test.go
+++ b/arrow/decimal256/decimal256_test.go
@@ -20,6 +20,7 @@ import (
        "fmt"
        "math"
        "math/big"
+       "runtime"
        "strings"
        "testing"
 
@@ -612,6 +613,14 @@ func TestFromString(t *testing.T) {
                {"2112.33", 211233, 2},
                {"-2112.33", -211233, 2},
                {"12E2", 12, -2},
+               {"0", 0, 0},
+               {"0.24", 0, 0},
+               {"0.5", 1, 0},
+               {"-0.5", -1, 0},
+               {"0.51", 1, 0},
+               {"-0.51", -1, 0},
+               {"0.0051", 1, 2},
+               {"-0.0051", -1, 2},
        }
 
        for _, tt := range tests {
@@ -623,6 +632,33 @@ func TestFromString(t *testing.T) {
                        assert.Equal(t, ex, n)
                })
        }
+
+       for _, s := range []string{"Inf", "+Inf", "-inf", "1e1000000000", 
"-1e1000000000"} {
+               for _, scale := range []int32{2, -2} {
+                       _, err := decimal256.FromString(s, 35, scale)
+                       assert.ErrorContains(t, err, "cannot convert", "%s at 
scale %d", s, scale)
+               }
+       }
+
+       for _, tc := range []struct {
+               s     string
+               scale int32
+       }{
+               {"1e646456990", 76},
+               {"-1e600000000", -2},
+       } {
+               _, err := decimal256.FromString(tc.s, 35, tc.scale)
+               assert.ErrorContains(t, err, "bitlen too large for decimal256", 
"%s at scale %d", tc.s, tc.scale)
+       }
+
+       var before, after runtime.MemStats
+       runtime.ReadMemStats(&before)
+       tiny, err := decimal256.FromString("-1e-20000000", 37, 0)
+       runtime.ReadMemStats(&after)
+       require.NoError(t, err)
+       assert.Equal(t, decimal256.Num{}, tiny)
+       // Rounding this value directly would allocate about 16 MB.
+       assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(1<<20))
 }
 
 // Test issues from GH-38395
@@ -698,4 +734,12 @@ func TestBitLen(t *testing.T) {
        assert.ErrorContains(t, err, "bitlen too large for decimal256")
        _, err = decimal256.FromString(b.String(), decimal256.MaxPrecision, -1)
        assert.ErrorContains(t, err, "bitlen too large for decimal256")
+
+       limit := new(big.Int).Lsh(big.NewInt(1), 255)
+       _, err = decimal256.FromString(limit.String(), decimal256.MaxPrecision, 
-1)
+       assert.ErrorContains(t, err, "bitlen too large for decimal256")
+       limit.Sub(limit, big.NewInt(1))
+       got, err := decimal256.FromString(limit.String(), 
decimal256.MaxPrecision, -1)
+       require.NoError(t, err)
+       assert.Equal(t, limit.Quo(limit, big.NewInt(10)).String(), 
got.BigInt().String())
 }

Reply via email to