Repository navigation
Description
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)
numericcolumns with varying precision- Aggregation functions (
SUM,AVG) that producenumericresults 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
IndexOutOfRangeExceptionin theNumericHandler#4313 -IndexOutOfRangeExceptionin theNumericHandler(original report, closed)- NpgsqlBinaryExporter function throws exception when reading BigInteger. #6383 - Reading numerics as
BigIntegerthrowsIndexOutOfRangeException(fixed in 8.0.9, but only asyncBigIntegerpath) - PR Fix reading numerics as BigInteger #6385 - Fix reading numerics as BigInteger (the 8.0.9 fix)
- PR Fixes #6107 missed should buffer in biginteger numeric converter #6117 - Broader fix merged to
main(10.0.0)
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
NinoFloris commentedon Mar 19, 2026
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
UIntPowers10accesses.wumian1360 commentedon Mar 20, 2026
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.csLine 370-374The bug is in the
digitCount == MaxDecimalNumericDigits(== 8) branch:When
scaleDifference > 0, the array index-scaleDifferencebecomes negative, causingIndexOutOfRangeException.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) * 4weight=3(13-16 digit integers):scale > 16triggers the bugMinimal Reproduction (100% deterministic)
This value has:
weight=3,ndigits=8(base-10000 digits)dscale=20(20 decimal places)scaleDifference = (3+1-8)*4 + 20 = -16 + 20 = 4UIntPowers10[-4]→ IndexOutOfRangeExceptionConfirmed 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:
SELECT 1234567890123456.66666666666666700000::numericStack Trace (with source-built PDB, .NET Framework 4.8)
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
numerictype is registered with no binary converter (NpgsqlTypesHelper.cs):When both converters are null,
ConvertBackendTextToNativefalls back to a generic path (NpgsqlTypeInfoBackend.cs):So the 2.2.3 conversion flow is:
While 8.0.9 uses binary protocol:
decimal.Parsesimply 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 exceedsdecimal's 28-29 significant digit precision, it silently truncates trailing digits rather than throwingIndexOutOfRangeException.The bug was introduced when Npgsql switched to binary protocol parsing with the hand-rolled
PgNumeric.ToDecimalarithmetic, which has the negative-index flaw in thedigitCount == 8branch.Suggested Fix
The
scaleDifferencecalculation in thedigitCount == MaxDecimalNumericDigitsbranch needs to handle the case wherescaleDifference > 0. A possible fix:vonzshik commentedon Mar 23, 2026
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?
wumian1360 commentedon Mar 24, 2026
I'd strongly prefer truncation (rounding to fit
decimalprecision) over throwing. Here's why:1. Npgsql 2.2.3 already handled this gracefully via truncation
In v2.2.3,
numericwas read via text protocol →decimal.Parse(), which silently truncates to 28-29 significant digits. This worked perfectly for years. The currentIndexOutOfRangeExceptionis a regression from that behavior — switching to "throw explicitly" would still be a regression, just a different one.2. Other database drivers truncate, not throw
decimal.Parse()truncates silentlydecimal.Parse()truncates silentlyDecimalhas arbitrary precision, no issueBigDecimalhas arbitrary precision, no issueFor .NET specifically, truncation is the established convention when the source precision exceeds
decimal's capacity.3. Suggested behavior
If you still want to surface this to users, perhaps a configurable option would be ideal:
OverflowExceptionwith a clear message like "PostgreSQL numeric value exceeds System.Decimal precision (28-29 digits). Useround()in SQL or read asdouble/BigInteger."This way, users who need strict precision validation can opt in, while existing production systems continue working.
roji commentedon Mar 24, 2026
@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.
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?
wumian1360 commentedon Mar 25, 2026
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.
RobertGiesecke commentedon Mar 25, 2026
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…
roji commentedon Mar 25, 2026
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.
wumian1360 commentedon Apr 2, 2026
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.
brianlagunas commentedon Aug 10, 2026
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_sendrather than inferring it. It needsndigits == 8exactly andscaleDifference > 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 thedigitCount > MaxDecimalNumericDigitsguard 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_scalefloors the result scale at the operands' scale and an AVG over near-zero values already carries a large one.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 throughPgNumeric.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::textcast 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.
bartoszkalinowski-gs commentedon Nov 5, 2026
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 throwOverflowExceptionwould still reject valid values.Environment: Npgsql 10.0.3 (the indexing line is unchanged on
mainat e87d421), .NET 10.0, PostgreSQL 17.7 (postgres:17.7-alpine). The line isPgNumeric.cs#L333onmainand at v10.0.3:Repro
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 fromnumeric(36,16)returns1000000000000.0000000000001000. (The scale of the result may be lower than the column's 18, since adecimalcan't hold 13 integer digits plus 18 fractional digits.)Actual:
Which values
I read the binary header with
numeric_send(...)(ndigits,weight,dscale) and computedscaleDifference = (weight + 1 - ndigits) * 4 + dscale, asToDecimaldoes:GetDecimal1000000000000.0000000000001numeric(36,18)100000000000000000.000000001numeric(36,18)999999999999999999.9999999999numeric(36,18)1000000000000.0000000000001numeric(36,17)1234567890123456.66666666666666700000numeric9999999999999999.9999999999999999numeric(36,18)OverflowExceptionexpected)1000000000000.0000000000001numeric(36,16)1000000000000.00000000000010001000000000000.0000000000001numeric1000000000000.0000000000001100000000000.0000000000001numeric(36,18)100000000000.00000000000010000Analysis
ToDecimalhas a branch for exactlyMaxDecimalNumericDigits(8) groups. It computespow = UIntPowers10[-scaleDifference], so it assumesscaleDifference <= 0, i.e. the last group reaches pastdscaleand its trailing digits have to be divided away.scaleDifferenceis positive when Postgres has stripped trailing zero groups anddscaleextends past the last stored group, which is what happens when anumeric(p, s)column or cast pads the scale: the stored value ends at group 8, butdscalesays there are more fractional digits. The index is then negative.The condition is:
scaleDifference > 0, i.e.dscale > 4 * (7 - weight). For 13-16 integer digits (weight = 3) that isdscale >= 17; for 17-20 integer digits (weight = 4) it isdscale >= 13.With 7 groups or fewer the generic path handles
scaleDifference > 0(scaleFactor *= UIntPowers10[scaleChunk]), and with 9 or more groups thedigitCount > MaxDecimalNumericDigitsguard throws a cleanOverflowException. Only the 8-group branch is missing thescaleDifference > 0case.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 anOverflowException.