Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: Andrei Lepikhov <lepihov(at)gmail(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>, Andres Freund <andres(at)anarazel(dot)de>, Nathan Bossart <nathandbossart(at)gmail(dot)com>
Subject: Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
Date: 2026-09-02 05:42:49
Message-ID: E22D6E36-292A-4F3F-A53C-DC6936AB5744@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

> On Sep 1, 2026, at 16:22, Andrei Lepikhov <lepihov(at)gmail(dot)com> wrote:
>
> On 01/09/2026 09:35, Chao Li wrote:
>> If newval is negative, the minus operation may also overflow.
> I don't think that's the case. An inverted function removes values that were
> already included in the aggregate, which usually brings the total closer to zero
> instead of pushing it toward the boundary. From what I see, this means there's
> no risk of integer overflow.
>
> --
> regards, Andrei Lepikhov,
> pgEdge

I agree that this may not happen during normal aggregate execution, but int2_avg_accum_inv() is also directly callable as a SQL function. For example:
```
evantest=# select int2_avg_accum_inv('{1,9223372036854775807}'::int8[], -1::int2);
int2_avg_accum_inv
--------------------------
{0,-9223372036854775808}
(1 row)
```

It’s showing an overflow for a caller-supplied state. I wouldn’t submit a dedicated patch for this case, but I just thought that, since this patch adds overflow checks to the neighboring transition functions, perhaps it would be worth handling this one at the same time. But, anyway, that’s not a strong comment, it’s up to you.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Andrei Lepikhov 2026-09-02 06:01:56 Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
Previous Message Hayato Kuroda (Fujitsu) 2026-09-02 05:42:05 RE: 035_standby_logical_decoding might fail due to FATAL message lost inside libpq