SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
Вложения:
Hi, Playing around with variants of parallel aggregation on massive inputs, I found that sum(int4) silently wraps around on overflow. It looks like a rare case, but looking around I found that almost all the aggregates have defensive checks, except the int2 and int4 ones. The overflow itself is not the big problem. The aggregate is inconsistent with itself: the combine function of sum(int2)/sum(int4) is int8pl(), which always throws an overflow error. So the same overflow is either an error or a silently wrong answer, depending on where in the plan it happens. This is definitely not a field bug, and the int8 accumulator was a deliberate choice, not an oversight. A quick overview shows the following: 1. bec98a31c55 used Numeric accumulators for integer sum/avg specifically "to avoid overflow at the cost of being a little slower". 2. 5f7c2bdb537 then replaced that with int8 "for speed reasons", on the judgement that "INT8 seems large enough to avoid overflow in practical situations". 3. 4d6ad31 improved the performance of overflow checks on hot paths. 4. 22b0ccd65d2 treated the absence of such a check for the money type as a bug and back-patched it. Can it actually be a problem in production? Tables with a row count around 10^10-10^11 are quite possible (especially partitioned ones, which are my primary interest), so with average integer values around 10^8, this could show up in some corner cases, though probably not often. The attached patch checks with pg_add_s64_overflow() and reports overflow the way int8pl() does, in int2_sum(), int4_sum(), int2_avg_accum(), int4_avg_accum() and int4_avg_combine(). The last three modify the transition value in place, so the patch computes the new sum first and updates count and sum together. Otherwise an error partway through would leave the caller with a state whose count and sum disagree. Benchmarking with a direct call to the routine (see the examples in the regression tests) shows an overhead of about 0.07% on my Intel MacBook, which is close to nothing. Patch attached -- happy to hear if I'm missing something. -- regards, Andrei Lepikhov, pgEdge
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On Wed, Sep 02, 2026 at 08:01:56AM +0200, Andrei Lepikhov wrote: > In my mind, we should pay for CPU cycles only in practical cases. So, if this > case deserves an overflow check, it should be an assertion that consumes no > resources in production. All the patterns you are showing imply direct function calls, which don't really seem worth bothering about. Are any of these overflow cases reachable using operators with dedicated casts? I would count as OK even cases where the sum functions are used in a custom aggregate, say with a SFUNC set to one of the paths you are pointing at. -- Michael
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On 02/09/2026 09:37, Michael Paquier wrote: > On Wed, Sep 02, 2026 at 08:01:56AM +0200, Andrei Lepikhov wrote: >> In my mind, we should pay for CPU cycles only in practical cases. So, if this >> case deserves an overflow check, it should be an assertion that consumes no >> resources in production. > > All the patterns you are showing imply direct function calls, which > don't really seem worth bothering about. Are any of these overflow > cases reachable using operators with dedicated casts? I would count > as OK even cases where the sum functions are used in a custom > aggregate, say with a SFUNC set to one of the paths you are pointing > at. I use direct calls mainly to make regression tests run faster. The first case arose during benchmarking built-in SUM(int4) with various parallelising methods [1] (bare research topic) at scale. This may not be a big issue right now, but as databases get larger, it could become one. I think it's more likely to happen first in the microcurrency space, where the base unit is a cent instead of a dollar, especially with very large partitioned tables. [1] https://www.pgedge.com/blog/do-global-hash-tables-strike-back-in-postgresql -- regards, Andrei Lepikhov, pgEdge
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On Fri, 4 Sept 2026 at 16:59, Michael Paquier wrote: > Any thoughts or comments from others? I think if we don't add overflow error checking for sum(int2) and sum(int4) today, we'll need to do it at some point in the future. I suspect we've only gotten away with it for this long, not because nobody aggregates 4+ billion rows, but because the values being aggregated are unlikely to be large enough to cause the overflow. Since Andrei has demonstrated that it's possible to hit that limit with a non-parallel query in less than 5 minutes, albeit that is passing INT_MAX (the most extreme case), it might be worth adding the checks. I was surprised that it only took 5 mins to do 4 billion rows, especially with generate_series. It's probably just a matter of time before someone discovers this with a real-world case out in the wild. If there's a measurable performance regression from adding the overflow checks, does the attached buy enough of it back? I couldn't really measure much of a performance difference from it on my Zen2 machine, so I didn't try with the overflow patch. The patch adds PG_RETURN_INPUT(n) to avoid some of the branching in int4_sum() so that it immediately returns the aggstate when the value being aggregated is null. With my compiler, it cut int4_sum from 18 down to 16 instructions. David
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On 04/09/2026 10:55, David Rowley wrote: > On Fri, 4 Sept 2026 at 16:59, Michael Paquier wrote: >> Any thoughts or comments from others? > The patch adds PG_RETURN_INPUT(n) to avoid some of the branching in > int4_sum() so that it immediately returns the aggstate when the value > being aggregated is null. With my compiler, it cut int4_sum from 18 > down to 16 instructions. Thanks for your attention. I adopted your changes. Although I don't see any overhead beyond noise, it seems better to optimise than to keep it as is. Also, tests were rewritten - instead of a direct call, I have used the initcond trick. -- regards, Andrei Lepikhov, pgEdge
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On Fri, Sep 04, 2026 at 08:55:07PM +1200, David Rowley wrote: > Since Andrei has demonstrated that it's possible to hit that limit > with a non-parallel query in less than 5 minutes, albeit that is > passing INT_MAX (the most extreme case), it might be worth adding the > checks. I was surprised that it only took 5 mins to do 4 billion rows, > especially with generate_series. It's probably just a matter of time > before someone discovers this with a real-world case out in the wild. I guess so.. > If there's a measurable performance regression from adding the > overflow checks, does the attached buy enough of it back? I couldn't > really measure much of a performance difference from it on my Zen2 > machine, so I didn't try with the overflow patch. > > The patch adds PG_RETURN_INPUT(n) to avoid some of the branching in > int4_sum() so that it immediately returns the aggstate when the value > being aggregated is null. With my compiler, it cut int4_sum from 18 > down to 16 instructions. FWIW, I've always been a fan of your compiler magic tricks like this one. Even if you did not measure much of a performance difference at runtime, less instructions overall across gcc and clang sounds like a better deal to me anyway? It sounds like the sort of improvements that could be done independently of what is being discussed here. -- Michael
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Mon, 7 Sept 2026 at 23:52, Andrei Lepikhov wrote: > > On 07/09/2026 10:25, Andrei Lepikhov wrote: > > Removed. Adding a regression test alongside a bug fix is just my default habit, > > so I followed it here without thinking it through - happy to drop them. > It looks like I mistakenly sent the old version as v2. Here is the actual > version (v3) of the patch. I was thinking that this might only be worth fixing on master. I'd say it's increasingly likely as we make the software faster and computers get faster, plus more efficient tableAMs, will result in overflows being more likely in the future. That might mean it's inevitable that we will need to fix it at some point. The concern I have with backpatching is around the new PG_RETURN_INPUT() macro. That existing in backbranches but not all minor versions of the given release could lead to any extension that opts to use the macro not compiling on older minor versions that don't have the macro defined. Any other ideas? David
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
On Thu, 15 Oct 2026 at 23:51, David Rowley wrote: > I was thinking that this might only be worth fixing on master. I'd say > it's increasingly likely as we make the software faster and computers > get faster, plus more efficient tableAMs, will result in overflows > being more likely in the future. That might mean it's inevitable that > we will need to fix it at some point. > > The concern I have with backpatching is around the new > PG_RETURN_INPUT() macro. That existing in backbranches but not all > minor versions of the given release could lead to any extension that > opts to use the macro not compiling on older minor versions that don't > have the macro defined. I've split Andrei's v3 into two patches. 0001 is the new macro to return the input, and 0002 is Andrei's overflow checks. I ended up renaming the PG_RETURN_INPUT() to PG_RETURN_ARG() as I thought it better combined the existing names of PG_GETARG_* and PG_RETURN_*. I agree with what Andres mentioned about changing things so we don't support calling transition functions directly, as that would allow getting rid of various AggCheckCallContext checks that don't need to fetch an actual context. The best way I've thought to do that requires a new pg_proc column. "procallable", or by using prokind with something like PROKIND_INTERNAL. I don't really like the idea of doing this by forcing ourselves into having internal states for these byval aggregates as a way to block calling due to the INTERNAL parameter. That means having to palloc memory for the state that we don't currently have to do for these aggregates. Looking at the history of int4_sum(), you can see that when we used to have USE_FLOAT8_BYVAL, we used to palloc memory for that state for non-USE_FLOAT8_BYVAL builds and pass by value for USE_FLOAT8_BYVAL builds. It's easy to assume we did the pass-by-value to avoid the palloc. 0001 also gets rid of a stale comment in int8_sum that is left over from getting rid of USE_FLOAT8_BYVAL. David
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 21 Oct 2026 at 12:14, David Rowley wrote: > I've split Andrei's v3 into two patches. 0001 is the new macro to > return the input, and 0002 is Andrei's overflow checks. I ended up > renaming the PG_RETURN_INPUT() to PG_RETURN_ARG() as I thought it > better combined the existing names of PG_GETARG_* and PG_RETURN_*. I've pushed both of these patches now. Before I pushed 0002, I was playing around with queries to see how quickly I could hit an overflow. The best I came up with was 4.4 seconds on a Zen2 64-core machine. create table t (a int, v int); insert into t select s,2147483647 from generate_series(1,65536)s; vacuum freeze analyze t; alter table t set (parallel_workers=64); alter system set max_parallel_workers=100; alter system set max_worker_processes=100; select pg_reload_conf(); -- restart set max_parallel_workers_per_gather = 64; set min_parallel_table_scan_size = 0; select sum(t.v),count(*) from t, generate_Series(1,65537); ERROR: bigint out of range Time: 4404.796 ms (00:04.405) That did overflow prior to the patch as the combine function (int8pl) does already have overflow checking. So whether you got the overflow or not could have depended on chance, depending on how work was distributed between parallel workers. I didn't think that was great, so I was more in favour of adding these checks after seeing that. David
Re: SUM(int2)/SUM(int4) do not detect overflow of the int8 accumulator
От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
On 21/10/2026 01:14, David Rowley wrote: > I agree with what Andres mentioned about changing things so we don't > support calling transition functions directly, as that would allow > getting rid of various AggCheckCallContext checks that don't need to > fetch an actual context. The best way I've thought to do that requires > a new pg_proc column. "procallable", or by using prokind with > something like PROKIND_INTERNAL. I don't really like the idea of doing > this by forcing ourselves into having internal states for these byval > aggregates as a way to block calling due to the INTERNAL parameter. > That means having to palloc memory for the state that we don't > currently have to do for these aggregates. Looking at the history of > int4_sum(), you can see that when we used to have USE_FLOAT8_BYVAL, we > used to palloc memory for that state for non-USE_FLOAT8_BYVAL builds > and pass by value for USE_FLOAT8_BYVAL builds. It's easy to assume we > did the pass-by-value to avoid the palloc. I think a column like 'procallable' is the best approach. My only concern is how broadly useful it would be. The use cases I can see: 1. Transition and combine functions could rely on being called only by the aggregate machinery, so the defensive code could go away. The per-row gain is minor, but the simplification is real (maybe not so minor for by-val states). 2. No more bug reports caused by SQL calls feeding transition functions with various flavours of garbage, like the int2_avg_accum_inv case upthread. 3. No mandatory serial/deserial functions and no palloc for states that are naturally by-value. 4. More generally, it decouples 'callable from SQL' from the type system; today that can only be expressed through pseudo-types. 5. It has the potential to be later extended to other support functions, e.g. opclass support like btint4cmp, if a type's author wants to hide them. 6. Extensions could define functions with limited exposure to the users. Great simplification for me personally (suppose that needs a CREATE FUNCTION clause and other stuff). 7. \df could filter such functions out by default. Having written that, I recalled a similar issue while writing prosupport functions: I need to remember that someone might add my prosupport to something else I originally planned. It is an unrelated discussion, of course, but maybe we need a more general mechanism than a boolean. Imagine a mask of allowed call contexts, declared in SQL similar to Oracle’s ACCESSIBLE BY clause: CREATE FUNCTION ... CALLABLE FROM (sql, aggregate) The core would check it at binding time (parser for plain SQL calls, CREATE AGGREGATE/TRIGGER/OPERATOR CLASS etc. for the rest), and a function whose mask excludes 'sql' could drop its defensive checks entirely. -- regards, Andrei Lepikhov, pgEdge