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

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: Andrei Lepikhov <lepihov(at)gmail(dot)com>
Cc: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>, 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-04 04:58:55
Message-ID: appQD0uWUrspuP0F@paquier.xyz
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, Sep 03, 2026 at 09:48:31AM +0200, Andrei Lepikhov wrote:
> Two details make me think this deserves a fix rather than a documentation note:
>
> * For sum(int4) the answer depends on the plan. int4_sum has no overflow check,
> but the combine function is int8pl, which does. So the same query over the same
> data returns a wrapped negative number under a serial plan and can fail with
> "bigint out of range" under parallel aggregation.
>
> * avg(int4) is not even inconsistent - it is wrong either way. Both
> int4_avg_accum and int4_avg_combine add into state->sum unchecked, so no plan
> shape turns this into an error. The int2 variants behave the same.

It looks to me that you are making your point here, thanks. I can
fall behind that. Even if these functions are marked as internal, we
could still reach the overflows, and I don't find that cool, like you.

A custom aggregate could make the test cheaper and still available
without direct function calls, perhaps, for example with a sfunc =
int{2,4}_sum and an initcond at INT64_MIN/MAX?

Any thoughts or comments from others?
--
Michael

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Andrey Rachitskiy 2026-09-04 05:01:15 Re: Fix PGTYPESdate_fmt_asc overflow when a year does not fit "yyyy"
Previous Message Ayush Tiwari 2026-09-04 04:56:29 Re: Stabilize recovery conflict stats checks in 031_recovery_conflict.pl