pgsql: Don't use a tuplestore if we don't have to for SQL-language func

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Don't use a tuplestore if we don't have to for SQL-language func
Date: 2025-05-02 20:16:32
Message-ID: E1uAwoC-000fkH-27@gemulon.postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Don't use a tuplestore if we don't have to for SQL-language functions.

We only need a tuplestore if we're actually going to accumulate
multiple result tuples. Obviously then we don't need one for non-set-
returning functions; but even a SRF doesn't need one if we decide to
use "lazyEval" (one row at a time) mode. In these cases, it's
sufficient to use the junkfilter's result slot to hold the single row
that's due to be returned. We just need to "materialize" that slot
to ensure it holds onto the data past shutdown of the sub-executor.

The original intent of this patch was partially to save a few cycles
(by not putting tuples into a tuplestore only to pull them back out
immediately), but mostly to ensure that we don't use a tuplestore
in non-set-returning functions. That's because I had concerns
about whether a tuplestore is safe to keep across queries,
which was possible for functions invoked via long-lived FmgrInfos
such as those kept in the typcache. There are no cases where SRFs
are called that way, so getting rid of the tuplestore in non-SRFs
should make things safer.

However, it emerges that running fmgr_sql in a short-lived context
(as 595d1efed made it do) makes the existing coding unsafe anyway:
we can end up with a long-lived TupleTableSlot holding a freeable
reference to a short-lived tuple, resulting in a double-free crash.
Not trying to pull tuples out of the tuplestore using that slot
dodges the problem, so I'm going to commit this now rather than
invent a band-aid solution for v18.

Reported-by: Alexander Lakhin <exclusion(at)gmail(dot)com>
Author: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Discussion: https://postgr.es/m/2443532.1744919968@sss.pgh.pa.us
Discussion: https://postgr.es/m/9f975803-1a1c-4f21-b987-f572e110e860@gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/e83a8ae44729bfdd15d31101bd2c99be98cfc691

Modified Files
--------------
src/backend/executor/functions.c | 135 ++++++++++++++++++++++++---------------
1 file changed, 85 insertions(+), 50 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Tomas Vondra 2025-05-02 21:06:40 pgsql: Fix memory leak in _gin_parallel_merge
Previous Message Álvaro Herrera 2025-05-02 19:30:07 pgsql: Handle self-referencing FKs correctly in partitioned tables