From ad32fb431a1ee07d89d0283b7ad7442e66d8bc0e Mon Sep 17 00:00:00 2001
From: Josh Hurst <joshhurst77@gmail.com>
Date: Fri, 27 Nov 2026 19:01:25 -0500
Subject: [PATCH] Accumulate short numeric inputs directly for sum and avg

Use the space reserved for sum of squares for inline positive and
negative digit buffers when computing only a sum. Allocate ordinary
buffers on the first resize. Keep the existing carry, reset, final
and serialization paths, including for states that track sumX2.
---
 src/backend/utils/adt/numeric.c          | 104 ++++++++++++++++++++---
 src/test/regress/expected/aggregates.out |  13 +++
 src/test/regress/expected/numeric.out    |  61 +++++++++++++
 src/test/regress/sql/aggregates.sql      |   9 ++
 src/test/regress/sql/numeric.sql         |  18 ++++
 5 files changed, 191 insertions(+), 14 deletions(-)

diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index ff2c7d6..5fc5c49 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -385,6 +385,7 @@ typedef struct NumericSumAccum
 	int			dscale;
 	int			num_uncarried;
 	bool		have_carry_space;
+	bool		digits_inline;	/* buffers are part of the aggregate state */
 	int32	   *pos_digits;
 	int32	   *neg_digits;
 } NumericSumAccum;
@@ -608,12 +609,10 @@ static void accum_sum_final(NumericSumAccum *accum, NumericVar *result);
 static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src);
 static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2);
 
-#if DEC_DIGITS == 4
-
 /*
  * Unpacked representation of an inline (uncompressed, non-external)
  * NUMERIC_SHORT datum.  Long, special (NaN/Inf), and TOASTed values return
- * false from numeric_is_small() and fall back to the general paths.
+ * false from numeric_short_fits() and fall back to the general paths.
  */
 typedef struct UnpackedNumeric
 {
@@ -641,11 +640,12 @@ unpacked_digit(const UnpackedNumeric *u, int i)
 }
 
 /*
- * Test the varlena size before reading the numeric header.  In particular,
- * VARSIZE_SHORT is zero for an external pointer.
+ * Test the varlena size before reading the numeric header.  For an external
+ * pointer VARSIZE_SHORT is zero, so the unsigned payload length exceeds
+ * either caller's limit.
  */
 static inline bool
-numeric_is_small(Datum d)
+numeric_short_fits(Datum d, Size max_payload)
 {
 	const char *p = DatumGetPointer(d);
 	const char *body;
@@ -665,13 +665,21 @@ numeric_is_small(Datum d)
 	else
 		return false;
 
-	if (len > sizeof(hdr) + 4 * sizeof(NumericDigit))
+	if (len > max_payload)
 		return false;
 	memcpy(&hdr, body, sizeof(hdr));
 	return (hdr & NUMERIC_SIGN_MASK) == NUMERIC_SHORT;
 }
 
-/* Decode a datum already checked by numeric_is_small(). */
+#if DEC_DIGITS == 4
+static inline bool
+numeric_is_small(Datum d)
+{
+	return numeric_short_fits(d, sizeof(uint16) + 4 * sizeof(NumericDigit));
+}
+#endif
+
+/* Decode a datum already checked by numeric_short_fits(). */
 static inline void
 unpack_numeric_short(Datum d, UnpackedNumeric *u)
 {
@@ -692,8 +700,6 @@ unpack_numeric_short(Datum d, UnpackedNumeric *u)
 	u->digits_ptr = body + sizeof(uint16);
 }
 
-#endif							/* DEC_DIGITS == 4 */
-
 /* ----------------------------------------------------------------------
  *
  * Input-, output- and rounding-functions
@@ -5073,13 +5079,25 @@ numeric_pg_lsn(PG_FUNCTION_ARGS)
  * ----------------------------------------------------------------------
  */
 
+/* Room for both signs in the space otherwise used by sumX2. */
+#define NUMERIC_SUM_INLINE_DIGITS \
+	(sizeof(NumericSumAccum) / (2 * sizeof(int32)))
+
 typedef struct NumericAggState
 {
 	bool		calcSumX2;		/* if true, calculate sumX2 */
 	MemoryContext agg_context;	/* context we're calculating in */
 	int64		N;				/* count of processed numbers */
 	NumericSumAccum sumX;		/* sum of processed numbers */
-	NumericSumAccum sumX2;		/* sum of squares of processed numbers */
+	union
+	{
+		NumericSumAccum sumX2;	/* sum of squares of processed numbers */
+		struct
+		{
+			int32		pos[NUMERIC_SUM_INLINE_DIGITS];
+			int32		neg[NUMERIC_SUM_INLINE_DIGITS];
+		}			small;
+	};
 	int			maxScale;		/* maximum scale seen so far */
 	int64		maxScaleCount;	/* number of values seen with maximum scale */
 	/* These counts are *not* included in N!  Use NA_TOTAL_COUNT() as needed */
@@ -5395,6 +5413,60 @@ numeric_combine(PG_FUNCTION_ARGS)
 	PG_RETURN_POINTER(state1);
 }
 
+/*
+ * Add a short datum directly to existing digit buffers if neither a carry
+ * nor a resize is needed.  For a new group, use the otherwise idle sumX2
+ * storage for both signs.  The regular accumulator takes over on growth.
+ */
+static bool
+accum_short_sum(NumericAggState *state, Datum value)
+{
+	NumericSumAccum *accum = &state->sumX;
+	UnpackedNumeric u;
+	int			offset;
+	int32	   *digits;
+
+	Assert(!state->calcSumX2);
+	if (!numeric_short_fits(value, MaxAllocSize))
+		return false;
+	unpack_numeric_short(value, &u);
+
+	if (accum->pos_digits == NULL)
+	{
+		if (u.ndigits >= (int) NUMERIC_SUM_INLINE_DIGITS)
+			return false;
+
+		/* The state is zeroed.  Reserve one leading digit for carry. */
+		accum->weight = u.weight + 1;
+		accum->ndigits = NUMERIC_SUM_INLINE_DIGITS;
+		accum->pos_digits = state->small.pos;
+		accum->neg_digits = state->small.neg;
+		accum->digits_inline = true;
+		accum->have_carry_space = true;
+	}
+
+	offset = accum->weight - u.weight;
+	if (offset <= 0 || offset + u.ndigits > accum->ndigits ||
+		!accum->have_carry_space || accum->num_uncarried == NBASE - 1)
+		return false;
+
+	digits = u.sign == NUMERIC_POS ? accum->pos_digits : accum->neg_digits;
+	for (int i = 0; i < u.ndigits; i++)
+		digits[offset + i] += unpacked_digit(&u, i);
+
+	accum->num_uncarried++;
+	accum->dscale = Max(accum->dscale, u.dscale);
+	state->N++;
+	if (u.dscale > state->maxScale)
+	{
+		state->maxScale = u.dscale;
+		state->maxScaleCount = 1;
+	}
+	else if (u.dscale == state->maxScale)
+		state->maxScaleCount++;
+	return true;
+}
+
 /*
  * Generic transition function for numeric aggregates that don't require sumX2.
  */
@@ -5409,7 +5481,7 @@ numeric_avg_accum(PG_FUNCTION_ARGS)
 	if (state == NULL)
 		state = makeNumericAggState(fcinfo, false);
 
-	if (!PG_ARGISNULL(1))
+	if (!PG_ARGISNULL(1) && !accum_short_sum(state, PG_GETARG_DATUM(1)))
 		do_numeric_accum(state, PG_GETARG_NUMERIC(1));
 
 	PG_RETURN_POINTER(state);
@@ -12447,11 +12519,15 @@ accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
 		{
 			memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
 				   old_ndigits * sizeof(int32));
-			pfree(accum->pos_digits);
 
 			memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
 				   old_ndigits * sizeof(int32));
-			pfree(accum->neg_digits);
+			if (!accum->digits_inline)
+			{
+				pfree(accum->pos_digits);
+				pfree(accum->neg_digits);
+			}
+			accum->digits_inline = false;
 		}
 
 		accum->pos_digits = new_pos_digits;
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 275263c..7af2752 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -3853,6 +3853,19 @@ FROM (SELECT * FROM tenk1
  8333541.588539713493 | 4999.5000000000000000
 (1 row)
 
+-- Combine partial sums for both signs and a sum wider than the inline buffer.
+SELECT sum(x) = 199980000 AS pos, sum(-x) = -199980000 AS neg,
+       avg(x) = 4999.5 AS mean,
+       sum(x * 1e24 + 0.0001) = 199980000000000000000000000000004 AS wide
+FROM (SELECT unique1::numeric AS x FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1) s;
+ pos | neg | mean | wide 
+-----+-----+------+------
+ t   | t   | t    | t
+(1 row)
+
 ROLLBACK;
 -- test coverage for dense_rank
 SELECT dense_rank(x) WITHIN GROUP (ORDER BY x) FROM (VALUES (1),(1),(2),(2),(3),(3)) v(x) GROUP BY (x) ORDER BY 1;
diff --git a/src/test/regress/expected/numeric.out b/src/test/regress/expected/numeric.out
index 7427920..f0e52d1 100644
--- a/src/test/regress/expected/numeric.out
+++ b/src/test/regress/expected/numeric.out
@@ -4019,3 +4019,64 @@ FROM num_toast_arith;
 (1 row)
 
 DROP TABLE num_toast_arith;
+-- Accumulate both signs, then widen to the left and to the right.
+SELECT sum(x), avg(x) FROM (VALUES
+  (-1.25::numeric), (2.50), (-1.2500), (0.00000), (NULL)) v(x);
+   sum   |          avg           
+---------+------------------------
+ 0.00000 | 0.00000000000000000000
+(1 row)
+
+SELECT sum(x) FROM (VALUES (1e-20::numeric), (1e20), (-1e20)) v(x);
+          sum           
+------------------------
+ 0.00000000000000000001
+(1 row)
+
+SELECT sum(x) = 1e-96 FROM (VALUES (0::numeric), (1e-96), (1e60),
+                                (-1e60)) v(x);
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT avg(x) FROM (VALUES (NULL::numeric), (NULL::numeric)) v(x);
+ avg 
+-----
+    
+(1 row)
+
+SELECT sum(x) FROM (VALUES (1::numeric), ('NaN'), ('Infinity')) v(x);
+ sum 
+-----
+ NaN
+(1 row)
+
+SELECT avg(x) FROM (VALUES (1::numeric), ('-Infinity')) v(x);
+    avg    
+-----------
+ -Infinity
+(1 row)
+
+SELECT sum(x) FROM (VALUES (1::numeric), ('-Infinity'), ('Infinity')) v(x);
+ sum 
+-----
+ NaN
+(1 row)
+
+-- Remove the last non-null input, then reuse and widen the buffers.
+SELECT id, sum(v) OVER w, avg(v) OVER w
+FROM (VALUES (1, 10.50::numeric), (2, NULL), (3, NULL),
+             (4, 5.25), (5, -2.25), (6, 100000000000000000000.01)) t(id, v)
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
+ORDER BY id;
+ id |           sum           |           avg           
+----+-------------------------+-------------------------
+  1 |                   10.50 |     10.5000000000000000
+  2 |                   10.50 |     10.5000000000000000
+  3 |                         |                        
+  4 |                    5.25 |      5.2500000000000000
+  5 |                    3.00 |      1.5000000000000000
+  6 | 99999999999999999997.76 | 49999999999999999998.88
+(6 rows)
+
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 2bbb766..4b15cbd 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -1692,6 +1692,15 @@ FROM (SELECT * FROM tenk1
       UNION ALL SELECT * FROM tenk1
       UNION ALL SELECT * FROM tenk1) u;
 
+-- Combine partial sums for both signs and a sum wider than the inline buffer.
+SELECT sum(x) = 199980000 AS pos, sum(-x) = -199980000 AS neg,
+       avg(x) = 4999.5 AS mean,
+       sum(x * 1e24 + 0.0001) = 199980000000000000000000000000004 AS wide
+FROM (SELECT unique1::numeric AS x FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1
+      UNION ALL SELECT unique1 FROM tenk1) s;
+
 ROLLBACK;
 
 -- test coverage for dense_rank
diff --git a/src/test/regress/sql/numeric.sql b/src/test/regress/sql/numeric.sql
index 19b0420..73e3663 100644
--- a/src/test/regress/sql/numeric.sql
+++ b/src/test/regress/sql/numeric.sql
@@ -1625,3 +1625,21 @@ SELECT pg_column_compression(c) IS NOT NULL AS compressed,
        (e + s) - e AS delta, (s - c) + c AS diff, 2 * e = c AS product
 FROM num_toast_arith;
 DROP TABLE num_toast_arith;
+
+-- Accumulate both signs, then widen to the left and to the right.
+SELECT sum(x), avg(x) FROM (VALUES
+  (-1.25::numeric), (2.50), (-1.2500), (0.00000), (NULL)) v(x);
+SELECT sum(x) FROM (VALUES (1e-20::numeric), (1e20), (-1e20)) v(x);
+SELECT sum(x) = 1e-96 FROM (VALUES (0::numeric), (1e-96), (1e60),
+                                (-1e60)) v(x);
+SELECT avg(x) FROM (VALUES (NULL::numeric), (NULL::numeric)) v(x);
+SELECT sum(x) FROM (VALUES (1::numeric), ('NaN'), ('Infinity')) v(x);
+SELECT avg(x) FROM (VALUES (1::numeric), ('-Infinity')) v(x);
+SELECT sum(x) FROM (VALUES (1::numeric), ('-Infinity'), ('Infinity')) v(x);
+
+-- Remove the last non-null input, then reuse and widen the buffers.
+SELECT id, sum(v) OVER w, avg(v) OVER w
+FROM (VALUES (1, 10.50::numeric), (2, NULL), (3, NULL),
+             (4, 5.25), (5, -2.25), (6, 100000000000000000000.01)) t(id, v)
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
+ORDER BY id;
-- 
2.54.0 (Apple Git-157)

