pgsql: Detect overflows in various numerical aggregate transfns

From: David Rowley <drowley(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Detect overflows in various numerical aggregate transfns
Date: 2026-10-28 00:25:43
Message-ID: E1xLrU7-000000013Vb-0era@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Detect overflows in various numerical aggregate transfns

Here we add overflow checks to guard against overflowing the int8 sum of
all inputs for sum(int2), sum(int4), avg(int2) and avg(int4). Such an
overflow is very unlikely for the int2 versions, but somewhat possible
to hit for the int4 versions when given billions of large enough inputs.
Since our code and machines are getting faster, and with the advent of
things like columnar table AMs, it's getting more likely that such an
overflow could occur in a real use case.

No guards have been added to the average count. That would require 2^63
input rows, which is not possible to achieve in a single instance of
PostgreSQL, given other limitations such as 64-bit LSNs.

Fixing this only in master as we can probably get away with that today
due to this still being unlikely for users to ever hit.

Author: Andrei Lepikhov <lepihov(at)gmail(dot)com>
Reviewed-by: David Rowley <dgrowleyml(at)gmail(dot)com>
Reviewed-by: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Reviewed-by: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
Discussion: https://postgr.es/m/1ddc2a6f-4b26-43d9-9f3b-5b5db98a486d@gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/903ce587e665af18ef1af24b4632e5ed4bf78edc

Modified Files
--------------
src/backend/utils/adt/numeric.c | 38 +++++++++++++++++++++++++++++++++-----
1 file changed, 33 insertions(+), 5 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Michael Paquier 2026-10-28 05:24:17 pgsql: Fix stale pg_index flags in the relcache for TOAST indexes
Previous Message Michael Paquier 2026-10-27 23:46:27 pgsql: Avoid torn copy of the control file in base backups