Skip to content

IndexOutOfRangeException in PgNumeric.Builder.ToDecimal() when reading many numeric rows (sync path, 8.0.9) #6509

Description

@wumian1360

Describe the bug

After upgrading to 8.0.9, we encounter a sporadic IndexOutOfRangeException in PgNumeric.Builder.ToDecimal() when synchronously reading a large number of rows containing numeric columns via NpgsqlDataReader.GetValue().

We are aware that #6383 / PR #6385 fixed a similar ArraySegment boundary issue in NumericConverters.ReadAsync (the BigInteger async path) for 8.0.9. However, the synchronous decimal read path through PgNumeric.Builder.ToDecimal() appears to have the same class of bug that was not addressed in 8.0.9.

Environment

  • Npgsql version: 8.0.9 (confirmed via Assembly.GetName().Version = 8.0.9.0)
  • .NET version: .NET Framework 4.8
  • PostgreSQL version: Greenplum 6.x (PostgreSQL 9.4 compatible)
  • Operating system: Windows Server 2019

Exception details

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.ThrowHelper.ThrowIndexOutOfRangeException()
   at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal(Int16 scale, Int16 weight, UInt16 sign, Span`1 digits)
   at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal()
   at Npgsql.Internal.Converters.DecimalNumericConverter`1.ConvertTo(Builder& numeric)
   at Npgsql.Internal.Converters.DecimalNumericConverter`1.ReadCore(PgReader reader)
   at Npgsql.Internal.PgBufferedConverter`1.Read(PgReader reader)
   at Npgsql.Internal.PgBufferedConverter`1.ReadAsObject(Boolean async, PgReader reader, CancellationToken cancellationToken)
   at Npgsql.Internal.PgConverter.ReadAsObject(PgReader reader)
   at Npgsql.NpgsqlDataReader.GetValue(Int32 ordinal)

Key observation: the call goes through PgBufferedConverter<T>.Read (sync), not ReadAsync. The exception source is System.Memory (Span<T> indexer), not Npgsql's own array access.

Steps to reproduce

The issue is sporadic and depends on internal buffer reuse patterns. It occurs more frequently with:

  • Large result sets (thousands of rows)
  • numeric columns with varying precision
  • Aggregation functions (SUM, AVG) that produce numeric results with different digit counts

Minimal reproduction pattern:

using var conn = new NpgsqlConnection(connStr);
conn.Open();

// Read many rows with numeric values - triggers buffer reuse in PgReader
using var cmd = new NpgsqlCommand(
    "SELECT 1234567890.123456::numeric AS val FROM generate_series(1, 8000)", conn);

using var reader = cmd.ExecuteReader();
while (reader.Read())
{
    // Sporadic IndexOutOfRangeException here
    var value = reader.GetValue(0);  // sync path → PgNumeric.Builder.ToDecimal()
}

Analysis

Comparing v8.0.8...v8.0.9, the fix in NumericConverters.cs (line 219) corrected the ArraySegment boundary in the async BigInteger read path:

// NumericConverters.cs ReadAsync method (line 219)
// Before: for (var i = digits.Offset; i < array.Length; i++)
// After:  for (var i = digits.Offset; i < digits.Offset + digits.Count; i++)

However, PgNumeric.Builder.ToDecimal(Int16 scale, Int16 weight, UInt16 sign, Span<short> digits) in PgNumeric.cs — which is the sync decimal path — was not modified in 8.0.9. The Span<short> digits parameter appears to receive incorrect bounds when the PgReader's internal buffer is reused across many rows, causing the Span indexer to throw IndexOutOfRangeException from System.Memory.

This is the same root cause as #4313 and #6383 — ArraySegment/Span boundary not properly scoped after buffer reuse — but manifesting in a different code path.

Related issues

Expected behavior

NpgsqlDataReader.GetValue() should return a decimal value without throwing IndexOutOfRangeException, regardless of result set size.

Actual behavior

Sporadic IndexOutOfRangeException in PgNumeric.Builder.ToDecimal() when reading large result sets with numeric columns via the synchronous GetValue() path.

Possible fix

The fix from PR #6117 (merged to main / 10.0.0) likely addresses this. Could the relevant PgNumeric.cs changes be backported to the 8.0.x branch?

Activity

  1. NinoFloris commented on Mar 19, 2026

    @NinoFloris
    Member

    I don't have access to .NET Framework and I am unable to reproduce this locally on 8.0.9 on .NET 10 (I let it run for over 10 minutes while typing this reply). If you trace the relevant code there are no array bounds to fix in the sync path leading up to PgNumeric, as everything uses enumerators. The other fixes you linked are either for the pre 8.x type conversion stack, or for BigInteger, not decimal.

    Could you please test whether your reproduction fails on e.g. .NET 10?

    To explain why, take a look at the method in the stack trace that caused the exception, ToDecimal (this is the code that runs on 8.0.9): https://github.com/npgsql/npgsql/blob/hotfix/8.0.10/src/Npgsql/Internal/Converters/Primitive/PgNumeric.cs#L335

    We take a span of digits as an argument, we get the length directly from this span on line 340, after which we only access its indexer in two places (line 363 and 369). Both of these accesses are bounded by the self reported length that was stored earlier in digitCount.

    Unless something in the actual codegen by .NET Framework is wrong it is not possible for digits to produce an out of bounds exception with this code.

    There are three other array access (all into UIntPowers10) which could produce a similar error, though those would happen deterministically based on the decimal input.

    Please try to reproduce your issue on .NET 10, this tells us whether we're looking at a .NET Framework problem. If you can also post the line numbers for the stack trace we can rule out the UIntPowers10 accesses.

  2. wumian1360 commented on Mar 20, 2026

    @wumian1360
    Author

    Thank you for the detailed analysis. We've completed extensive testing and found the actual root cause — it's a deterministic code logic bug in PgNumeric.Builder.ToDecimal, not a .NET Framework "slow span" issue.

    Root Cause: PgNumeric.cs Line 370-374

    The bug is in the digitCount == MaxDecimalNumericDigits (== 8) branch:

    // PgNumeric.cs v8.0.9, line 370-374
    if (digitCount == MaxDecimalNumericDigits) // digitCount == 8
    {
        var scaleDifference = (weight + 1 - digitCount) * 4 + scale;
        var pow = UIntPowers10[-scaleDifference]; // BUG: when scaleDifference > 0, index is NEGATIVE!
        // ...
    }

    When scaleDifference > 0, the array index -scaleDifference becomes negative, causing IndexOutOfRangeException.

    Trigger Condition

    The bug triggers when ALL of the following are true:

    • ndigits == 8 (PostgreSQL numeric base-10000 digit array length = 8, meaning 13-16 decimal integer digits)
    • scaleDifference > 0, i.e., scale > (7 - weight) * 4
    • For weight=3 (13-16 digit integers): scale > 16 triggers the bug

    Minimal Reproduction (100% deterministic)

    SELECT 1234567890123456.66666666666666700000::numeric

    This value has:

    • 16 integer digits → weight=3, ndigits=8 (base-10000 digits)
    • dscale=20 (20 decimal places)
    • scaleDifference = (3+1-8)*4 + 20 = -16 + 20 = 4
    • UIntPowers10[-4] → IndexOutOfRangeException

    Confirmed on Both .NET Framework 4.8 AND .NET 10

    This is NOT a .NET Framework "slow span" issue. We verified the bug triggers on both platforms:

    Platform Test Result
    .NET Framework 4.8 (CLR 4.0.30319.42000) SELECT 1234567890123456.66666666666666700000::numeric ❌ IndexOutOfRangeException at PgNumeric.cs:373
    .NET 10.0.2 Same SQL ❌ IndexOutOfRangeException
    .NET Framework 4.8 13-digit integer + dscale=20 ❌ IndexOutOfRangeException at PgNumeric.cs:373
    .NET 10.0.2 Same SQL ❌ IndexOutOfRangeException
    .NET Framework 4.8 12-digit integer + dscale=20 (ndigits=7) ✅ Pass
    .NET 10.0.2 Same SQL ✅ Pass

    Stack Trace (with source-built PDB, .NET Framework 4.8)

    System.IndexOutOfRangeException: Index was outside the bounds of the array.
       at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal(Int16 scale, Int16 weight, UInt16 sign, Span`1 digits)
         in d:\project\OpenSource\npgsql\src\Npgsql\Internal\Converters\Primitive\PgNumeric.cs:line 373
       at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal()
         in d:\...\PgNumeric.cs:line 275
       at Npgsql.Internal.Converters.DecimalNumericConverter`1.ConvertTo(Builder& numeric)
         in d:\...\NumericConverters.cs:line 179
       ...
    

    Why Npgsql 2.2.3 Doesn't Have This Bug

    We upgraded from Npgsql 2.2.3, which never exhibited this issue. After examining the v2.2.3 source code, the reason is clear: 2.2.3 uses text protocol for numeric, while 8.0.9 uses binary protocol.

    In 2.2.3, the numeric type is registered with no binary converter (NpgsqlTypesHelper.cs):

    // v2.2.3 — no text converter, no binary converter for numeric
    yield return new NpgsqlBackendTypeInfo(0, "numeric", NpgsqlDbType.Numeric, 
        DbType.Decimal, typeof(Decimal), null);  // both converter params are null

    When both converters are null, ConvertBackendTextToNative falls back to a generic path (NpgsqlTypeInfoBackend.cs):

    // v2.2.3 fallback — simple string-to-decimal conversion
    return Convert.ChangeType(
        BackendEncoding.UTF8Encoding.GetString(BackendData), 
        Type,  // typeof(Decimal)
        CultureInfo.InvariantCulture);

    So the 2.2.3 conversion flow is:

    PostgreSQL → text "1234567890123456.66666666666666700000" → decimal.Parse() → decimal ✅
    

    While 8.0.9 uses binary protocol:

    PostgreSQL → binary [ndigits, weight, sign, dscale, digits[]] → PgNumeric.Builder.ToDecimal() → 💥
    

    decimal.Parse simply treats the value as a plain decimal string. It knows nothing about base-10000 digits, weight, or scaleDifference — so there's no array indexing to go wrong. If the value exceeds decimal's 28-29 significant digit precision, it silently truncates trailing digits rather than throwing IndexOutOfRangeException.

    The bug was introduced when Npgsql switched to binary protocol parsing with the hand-rolled PgNumeric.ToDecimal arithmetic, which has the negative-index flaw in the digitCount == 8 branch.

    Suggested Fix

    The scaleDifference calculation in the digitCount == MaxDecimalNumericDigits branch needs to handle the case where scaleDifference > 0. A possible fix:

    if (digitCount == MaxDecimalNumericDigits)
    {
        var scaleDifference = (weight + 1 - digitCount) * 4 + scale;
        if (scaleDifference < 0)  // Only access UIntPowers10 when index is valid
        {
            var pow = UIntPowers10[-scaleDifference];
            // existing logic...
        }
        else
        {
            // Handle scaleDifference >= 0 case (truncate or throw meaningful error)
        }
    }
  3. self-assigned this
    on Mar 23, 2026
  4. added theissue type on Mar 23, 2026
  5. added this to the 10.0.3 milestone on Mar 23, 2026
  6. vonzshik commented on Mar 23, 2026

    @vonzshik
    Contributor

    Hmm, this number doesn't actually fit into .NET decimal. .NET decimal supports up to 28-29 digits, while postgresql sends us a 31 digits decimal. I guess we probably should throw instead of rounding up the number?

  7. wumian1360 commented on Mar 24, 2026

    @wumian1360
    Author

    Hmm, this number doesn't actually fit into .NET decimal. .NET decimal supports up to 28-29 digits, while postgresql sends us a 31 digits decimal. I guess we probably should throw instead of rounding up the number?

    I'd strongly prefer truncation (rounding to fit decimal precision) over throwing. Here's why:

    1. Npgsql 2.2.3 already handled this gracefully via truncation

    In v2.2.3, numeric was read via text protocol → decimal.Parse(), which silently truncates to 28-29 significant digits. This worked perfectly for years. The current IndexOutOfRangeException is a regression from that behavior — switching to "throw explicitly" would still be a regression, just a different one.

    v2.2.3: "1234567890123456.66666666666666700000" → decimal.Parse() → truncated decimal ✅
    v8.0.9: binary [ndigits=8, dscale=20] → PgNumeric.ToDecimal() → IndexOutOfRangeException 💥
    

    2. Other database drivers truncate, not throw

    • ADO.NET SqlClient (SQL Server): decimal.Parse() truncates silently
    • Npgsql 2.x: decimal.Parse() truncates silently
    • psycopg2 (Python): Python's Decimal has arbitrary precision, no issue
    • JDBC (Java): BigDecimal has arbitrary precision, no issue

    For .NET specifically, truncation is the established convention when the source precision exceeds decimal's capacity.

    3. Suggested behavior

    if (digitCount == MaxDecimalNumericDigits && scaleDifference > 0)
    {
        // Total digits exceed decimal's 28-29 digit precision.
        // Truncate least-significant decimal digits to fit, matching decimal.Parse() behavior.
        // This preserves backward compatibility with Npgsql 2.x text protocol path.
    }

    If you still want to surface this to users, perhaps a configurable option would be ideal:

    • Default: truncate (backward compatible, matches v2.x behavior)
    • Opt-in: throw OverflowException with a clear message like "PostgreSQL numeric value exceeds System.Decimal precision (28-29 digits). Use round() in SQL or read as double/BigInteger."

    This way, users who need strict precision validation can opt in, while existing production systems continue working.

  8. roji commented on Mar 24, 2026

    @roji
    Member

    @wumian1360 see #6125; we have generally not believed that truncating, rounding, or any other imprecise reading is a good idea to do by default. Npgsql already throws for other scenarios where a PostgreSQL decimal value cannot be 100% faithfully read into a .NET decimal. However, we do agree that an opt into truncating makes sense (that's #6125).

    Npgsql 2.2.3 is an absolutely ancient version, and its text-based transfer and parsing was non-ideal in many cases; I don't think it's appropriate to use it as inspiration or as an argument for anything. SqlClient is also a different database driver - with quite a few problematic behaviors - and I wouldn't think Npgsql should necessarily do something just because SqlClient does.

    For .NET specifically, truncation is the established convention when the source precision exceeds decimal's capacity.

    I'm not too sure what this refers to exactly (beyond Npgsql 2.2.3 and SqlClient which you mentioned above). Where else in .NET do you see that "truncation is the established convention?

  9. wumian1360 commented on Mar 25, 2026

    @wumian1360
    Author

    Thank you for the detailed response and for pointing to #6125.

    We fully agree with the approach: throw by default, opt-in to truncation via #6125. That gives users the choice, which is exactly what we need.

    Regarding the "established convention" claim — you're right to push back on that. My wording was imprecise. What I should have said is: in our specific upgrade scenario (from 2.x text protocol to 8.x binary protocol), the previous behavior happened to truncate silently, and our production SQL relied on that implicitly. That's not a universal .NET convention — it's just the behavior we were accustomed to. I appreciate the correction.

    Is there a target release version for #6125? That would help us plan our upgrade timeline.

  10. RobertGiesecke commented on Mar 25, 2026

    @RobertGiesecke

    Oracle has 38 digits for their number type.

    When you use more than what System.Decimal supports, they throw. Not throwing would be kinda sloppy, IMO. Because you silently change the value.

    They provide a struct that you can use with full precision: OracleNumber.

    I think something similar would be a good solution.
    Or support for ExtendedNumerics.BigDecimal which could add headaches for AOT…

  11. roji commented on Mar 25, 2026

    @roji
    Member

    Yeah, we discussed this internally and agreed to maintain the current throwing behavior by default, but add an opt-in for truncating (#6125). We'll hopefully do this for 11, but no promises.

    Re having a custom type, there has been lots of discussion around that, and the tl;dr is that for such a type to actually be useful, it would have to e.g. implement arithmetic and other number behavior; we simply can't take on the maintenance of a full arbitrary-length math type - as part of a database driver; however, Npgsql's type system is fully extensible, and anyone can write a plugin to allow reading PG numeric as any type out there from some 3rd-party package.

    Note that ExtendedNumerics.BigDecimal is indeed arbitrary precision (which is great), but is a floating point type, so not a good fit for PG numeric, which isn't floating point.

  12. wumian1360 commented on Apr 2, 2026

    @wumian1360
    Author

    Thank you for the clear answer and for confirming the plan for #6125. Throwing by default + opt-in truncation sounds like a solid approach — looking forward to seeing it in v11.

    Thanks again for the thorough discussion and the quick responses.

  13. changed the issue type fromtoon May 8, 2026
  14. modified the milestones: 10.0.3, 10.0.4 on May 27, 2026
  15. brianlagunas commented on Aug 10, 2026

    @brianlagunas

    Still repros on 10.0.3 (latest), .NET 10, PG 16. The UIntPowers10[-scaleDifference] line is unchanged on main as of bfafb61, so whatever landed in 10.0.0 didn't cover this path.

    I confirmed the trigger by reading the binary header out of numeric_send rather than inferring it. It needs ndigits == 8 exactly and scaleDifference > 0. The literal in the OP comes across as ndigits=8, weight=3, dscale=20, which gives index -4. A value with ndigits=11 hits the digitCount > MaxDecimalNumericDigits guard at L301 and throws OverflowException as intended, so the ndigits==8 branch looks like it's just missing the overflow check the other paths get.

    Probably worth knowing: you don't need a crafted literal for this. Ordinary aggregate arithmetic produces these values, since select_div_scale floors the result scale at the operands' scale and an AVG over near-zero values already carries a large one.

    SELECT (AVG(cur) - AVG(prior)) * 1.0 / NULLIF(AVG(prior), 0)
    FROM (VALUES (1234567.89::numeric(18,4), 0.0001::numeric(18,4)),
                 (999999.9999::numeric(18,4), -0.0075::numeric(18,4)),
                 (42::numeric(18,4), 0.0075::numeric(18,4))) t(cur, prior);
    -- 22346098898.0000000002234609889900000  (ndigits=8, weight=2, dscale=25, index -5)

    Every input there is a plain numeric(18,4). We hit it on a percent-change calculation where the prior period's average happened to land near zero.

    Separately, and possibly more of a problem than which exception gets thrown: there's no reader path for these values at all. GetFieldValue<double> and <float> both route through PgNumeric.Builder.ToDecimal, so they fail identically (including on the ndigits=11 value, where it's a clean OverflowException). BigInteger rejects anything with a fractional part, and string isn't supported for numeric without a ::text cast in the query. The value above is about 2.2e10 and sits well inside double's range.

    Is routing the double conversion through the decimal builder deliberate? Asking because the truncation trade-off in #6125 doesn't seem to apply the same way when the caller has explicitly asked for an approximate type.

  16. bartoszkalinowski-gs commented on Nov 5, 2026

    @bartoszkalinowski-gs

    Adding a data point to this one that I think changes what the fix needs to be: the crash is not limited to values that don't fit in System.Decimal. Plain, representable values (26-28 significant digits) hit it too, so making this branch throw OverflowException would still reject valid values.

    Environment: Npgsql 10.0.3 (the indexing line is unchanged on main at e87d421), .NET 10.0, PostgreSQL 17.7 (postgres:17.7-alpine). The line is PgNumeric.cs#L333 on main and at v10.0.3:

    if (digitCount == MaxDecimalNumericDigits)
    {
        // On the max group we adjust the base based on the scale difference, to prevent overflow for valid values.
        var pow = UIntPowers10[-scaleDifference];

    Repro

    // dotnet new console; dotnet add package Npgsql --version 10.0.3
    using Npgsql;
    
    await using var conn = new NpgsqlConnection("Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres");
    await conn.OpenAsync();
    
    await using var cmd = new NpgsqlCommand("SELECT '1000000000000.0000000000001'::numeric(36,18)", conn);
    await using var reader = await cmd.ExecuteReaderAsync();
    await reader.ReadAsync();
    Console.WriteLine(reader.GetDecimal(0));

    The same happens when the value comes from a numeric(36,18) column, e.g. CREATE TEMP TABLE probe(v numeric(36,18)); INSERT INTO probe VALUES (1000000000000.0000000000001); SELECT v FROM probe.

    Expected: 1000000000000.0000000000001. It has 26 significant digits; the same value read from numeric(36,16) returns 1000000000000.0000000000001000. (The scale of the result may be lower than the column's 18, since a decimal can't hold 13 integer digits plus 18 fractional digits.)

    Actual:

    Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
       at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal(Int16 scale, Int16 weight, UInt16 sign, Span`1 digits)
       at Npgsql.Internal.Converters.PgNumeric.Builder.ToDecimal()
       at Npgsql.Internal.Converters.DecimalNumericConverter`1.ConvertTo(Builder& numeric)
       at Npgsql.Internal.Converters.DecimalNumericConverter`1.ReadCore(PgReader reader)
       at Npgsql.Internal.PgBufferedConverter`1.Read(PgReader reader)
       at Npgsql.NpgsqlDataReader.GetFieldValueCore[T](Int32 ordinal)
       at Npgsql.NpgsqlDataReader.GetDecimal(Int32 ordinal)
    

    Which values

    I read the binary header with numeric_send(...) (ndigits, weight, dscale) and computed scaleDifference = (weight + 1 - ndigits) * 4 + dscale, as ToDecimal does:

    value type ndigits weight dscale scaleDifference GetDecimal
    1000000000000.0000000000001 numeric(36,18) 8 3 18 2 IndexOutOfRangeException
    100000000000000000.000000001 numeric(36,18) 8 4 18 6 IndexOutOfRangeException (27 digits, fits)
    999999999999999999.9999999999 numeric(36,18) 8 4 18 6 IndexOutOfRangeException (28 digits, fits)
    1000000000000.0000000000001 numeric(36,17) 8 3 17 1 IndexOutOfRangeException
    1234567890123456.66666666666666700000 numeric 8 3 20 4 IndexOutOfRangeException (the literal from the original report; 31 digits, doesn't fit)
    9999999999999999.9999999999999999 numeric(36,18) 8 3 18 2 IndexOutOfRangeException (32 digits, doesn't fit; OverflowException expected)
    1000000000000.0000000000001 numeric(36,16) 8 3 16 0 1000000000000.0000000000001000
    1000000000000.0000000000001 numeric 8 3 13 -3 1000000000000.0000000000001
    100000000000.0000000000001 numeric(36,18) 7 2 18 2 100000000000.00000000000010000

    Analysis

    ToDecimal has a branch for exactly MaxDecimalNumericDigits (8) groups. It computes pow = UIntPowers10[-scaleDifference], so it assumes scaleDifference <= 0, i.e. the last group reaches past dscale and its trailing digits have to be divided away. scaleDifference is positive when Postgres has stripped trailing zero groups and dscale extends past the last stored group, which is what happens when a numeric(p, s) column or cast pads the scale: the stored value ends at group 8, but dscale says there are more fractional digits. The index is then negative.

    The condition is:

    • exactly 8 base-10000 groups after trailing zero groups are stripped, and
    • scaleDifference > 0, i.e. dscale > 4 * (7 - weight). For 13-16 integer digits (weight = 3) that is dscale >= 17; for 17-20 integer digits (weight = 4) it is dscale >= 13.

    With 7 groups or fewer the generic path handles scaleDifference > 0 (scaleFactor *= UIntPowers10[scaleChunk]), and with 9 or more groups the digitCount > MaxDecimalNumericDigits guard throws a clean OverflowException. Only the 8-group branch is missing the scaleDifference > 0 case.

    So a bounds/overflow check there is not enough. The representable cases (the first, second, third and fourth rows) need to return the value, with the trailing zeros that Postgres omitted not counting towards decimal's 96-bit mantissa. Only values that really need more than 28-29 digits should get an OverflowException.

  17. modified the milestones: 10.0.4, 10.0.5 on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions