Two bugs around ALTER TYPE

Поиск
Список
Период
Сортировка
Искать

Two bugs around ALTER TYPE

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Вложения:
Hi,

Users reported a bug involving ALTER TYPE/TABLE and set-returning PL/pgSQL
functions, so I took a stab at fixing them.


Bug 1: ALTER TYPE/TABLE ADD COLUMN does not invalidate cached SETOF plans

When a PL/pgSQL function executes RETURN QUERY against a SETOF function
returning a named composite type, the SPI plan for that inner query is
cached.  If ALTER TYPE ... ADD ATTRIBUTE (or ALTER TABLE ... ADD COLUMN
when the table's rowtype is the return type) is executed afterward, the
cached plan is not marked stale and the next call raises:
  ERROR: structure of query does not match function result type
  DETAIL: Number of returned columns (3) does not match expected column
  count (2).

Reproduction (single session):

  CREATE TYPE planinv_ct AS (a int, b int);
  CREATE TABLE planinv_tbl (a int, b int);
  INSERT INTO planinv_tbl VALUES (1, 2);
  CREATE FUNCTION planinv_srf() RETURNS SETOF planinv_ct
    LANGUAGE sql STABLE SECURITY DEFINER AS $$
      SELECT * FROM planinv_tbl $$;
  CREATE FUNCTION planinv_caller() RETURNS SETOF planinv_ct
    LANGUAGE plpgsql AS $$
  BEGIN
    RETURN QUERY SELECT r.* FROM planinv_srf() r;
  END; $$;
  SELECT * FROM planinv_caller();   -- warms up plan cache
  ALTER TYPE planinv_ct ADD ATTRIBUTE c int;
  ALTER TABLE planinv_tbl ADD COLUMN c int DEFAULT 99;
  SELECT * FROM planinv_caller();   -- ERROR without fix, (1,2,99) with fix

Root cause:

When a plan is finalised, setrefs.c records OIDs of referenced relations
in glob->relationOids so that relcache invalidations can mark it stale.
For RTE_FUNCTION nodes only the function OID is tracked. If the
function's declared return type is a named composite, ALTER TYPE (or
ALTER TABLE for table rowtypes) updates pg_class for that composite
without touching the function OID, so the cached plan never sees the
invalidation.

Note: SECURITY DEFINER is required in the reproducer to prevent the
planner from inlining planinv_srf() into the caller; the bug affects any
non-inlined SETOF function returning a named composite type.

Fix:

Add a helper add_function_rte_relation_deps() in setrefs.c that, for
each RTE_FUNCTION node, resolves the typrelid of the function's return
type via typeOrDomainTypeRelid() and appends it to glob->relationOids.
Call it from add_rte_to_flat_rtable(), flatten_rtes_walker(), and
extract_query_dependencies_walker(). ALTER TYPE/TABLE then triggers
relcache invalidation and seems to force a re-plan.

Bug 2: Concurrent ALTER TYPE/TABLE mid-execution causes mismatch in PL/pgSQL

I was looking for workarounds and proposed the user to add something
that would invalidate plan when they alter a type:
CREATE OR REPLACE FUNCTION planinv_srf()

Users replied that they already do it, and it does not help.

Together we found out that a race window exists inside a single PL/pgSQL call.
The function enters with a 2-column tuple descriptor;
a concurrent transaction commits ALTER TYPE ADD ATTRIBUTE plus CREATE OR
REPLACE FUNCTION while RETURN QUERY is still running. The inner SRF
is replanned with 3 columns, but the tstoreReceiver was already set up
for 2, giving the same error mid-execution.

The race requires precise timing and is reproduced reliably only with
injection points (TAP test included in the patch series).  In brief:
  Session A: SELECT * FROM planinv_caller();  -- suspended just before
                                              -- RETURN QUERY executes
  Session B: BEGIN;
             ALTER TYPE planinv_ct ADD ATTRIBUTE c int;
             CREATE OR REPLACE FUNCTION planinv_srf() ... 3 columns ...
             COMMIT;
  Session A resumes: ERROR

The same race exists with ALTER TABLE when the return type is a table
rowtype that is not itself scanned by the function body.  When the
function does scan the same table it returns, ALTER TABLE is naturally
blocked by the AccessShareLock already held by the scan; but for
standalone composite types there is no such automatic protection.

Root cause:

plpgsql_estate_setup() captures the return type descriptor with no lock
preventing ALTER TYPE from modifying the composite type's pg_class row
between estate setup and the RETURN QUERY re-plan.  Within a single SQL
statement the row shape should be stable, analogous to snapshot
semantics for catalog changes.

Fix:

In plpgsql_estate_setup(), when the function is a SETOF returning a
named composite type (retisset && retistuple), resolve typrelid via
typeOrDomainTypeRelid() and call LockRelationOid(typrelid,
AccessShareLock).  The lock is released at transaction end.
This mirrors how table scans acquire AccessShareLock to pin the schema
for statement duration.  ALTER TYPE/TABLE requires AccessExclusiveLock
on the same relid, so it blocks behind the in-progress call.

Thanks to Victor Popov for reporting and adapting single-session test case
for the race condition.


Regards, Andrey Borodin.

Re: Two bugs around ALTER TYPE

От:
surya poondla <suryapoondla4@gmail.com>
Дата:

Hi Andrey,

Thanks for the patch series. I was able to reproduce both bugs on master at HEAD and verified each fix end-to-end:

A couple of points:
Bug 1: "Number of returned columns (2) does not match expected column count (3) on the second call.
With 0002 patch, it returns the new 3-column shape as expected.

Bug 2 (with only 0004 patch): Session A returns (1,2), DDL commits after, next call returns (1,2,99). Mechanism works as designed.

  
I also confirmed why glob->relationOids is the right channel rather than glob->invalItems via record_plan_type_dependency(): ALTER TYPE ADD ATTRIBUTE
on a composite goes through ALTER TABLE on typrelid and modifies pg_class/pg_attribute but not the composite's pg_type row, so no TYPEOID syscache invalidation fires
(CacheInvalidateHeapTuple in AlterDomainAddConstraint). relcache-on-typrelid is the only channel that actually delivers, which is what the patch hooks into.

A few comments:
1. 0003 patch alone leaves a permanently-failing TAP test (its expected 1|2|99 is only producible by 0004's lock forcing the DDL to
wait). Maybe equash 0003 patch into 0004 patch.

2. alter_table.sql comment says the fix records typrelid in "the plan's invalItems"; it actually goes into glob->relationOids
different list, different callback (PlanCacheRelCallback vs PlanCacheObjectCallback). 

3. TAP test in 0004 captures $ddl_pid via pg_backend_pid() (lines 68-69) but never uses it.
Either we can drop, or use it to assert the DDL session is genuinely waiting on the typrelid in pg_locks
(granted=false on AccessExclusiveLock). The latter would directly verify the lock instead of just observing the symptom.


Regards,
Surya Poondla

Re: Two bugs around ALTER TYPE

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Andrey,

You can create a commitfest entry and we can take it from there.

Regards,
Surya Poondla

Re: Two bugs around ALTER TYPE

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Вложения:


> On 21 Jul 2026, at 02:24, surya poondla  wrote:
> 
> You can create a commitfest entry and we can take it from there.

Thanks for the review!

Commitfest item exists [0].

I did not squash test with a fix so anyone can easily check that test verifies
the problem. Other review notes are addressed in v2.

Also, I did not bump number in 012_plpgsql_composite_replan_race.pl. It might be
changed before the commit anyway.

Thanks!


Best regards, Andrey Borodin.

[0] https://commitfest.postgresql.org/patch/6903/

Re: Two bugs around ALTER TYPE

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Hi hackers,

Thank you for the substantial work on tuple descriptors and attribute
versioning in the new release.

Unfortunately, both bugs reported in this thread still reproduce on
new minors.

It would be great to move these fixes forward.

Thank you!


Best regards, Andrey Borodin.



Re: Two bugs around ALTER TYPE

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Andrey,

Thanks for working on these fixes. 0002 fixes the cached plan issue you
reported after ALTER TYPE changes a composite return type. I also
tested adding and dropping attributes and changing attribute types.

However, 0004 still leaves a window before the function acquires its
lock. A cursor can save the old result descriptor at DECLARE, then
enter the function after another session has changed the type.
This fails on both master at 2e0fe6d5ace and the full v2 series:

CREATE TYPE planinv_ct AS (a int, b int);
CREATE TABLE planinv_tbl (a int, b int);
INSERT INTO planinv_tbl VALUES (1, 2);
CREATE FUNCTION planinv_caller() RETURNS SETOF planinv_ct
LANGUAGE plpgsql AS $$
BEGIN
  RETURN QUERY SELECT * FROM planinv_tbl;
END;
$$;

-- Session 1:
BEGIN;
DECLARE c CURSOR FOR SELECT * FROM planinv_caller();

-- Session 2: completes without waiting for session 1.
BEGIN;
ALTER TYPE planinv_ct ADD ATTRIBUTE c int;
ALTER TABLE planinv_tbl ADD COLUMN c int DEFAULT 99;
COMMIT;

-- Session 1:
FETCH ALL FROM c;
ERROR:  structure of query does not match function result type
DETAIL:  Number of returned columns (3) does not match expected
column count (2).
ROLLBACK;

The error occurs because ExecInitFunctionScan() copies the two-column
descriptor during DECLARE.
At FETCH, ExecMakeTableFunctionResult() passes it as rsi->expectedDesc.
Only then does plpgsql_estate_setup() acquire the new lock.
exec_init_tuple_store() still uses that old descriptor, while RETURN
QUERY reads three columns. The lock needs to protect the caller's
descriptor setup too. Acquiring it at PL/pgSQL function entry is
too late.

I chose init_sexpr() because both SRF call paths reach it before
copying the result descriptor. The attached patch, on top of v2,
moves the lock there. It covers SETOF functions returning named
composites or domains over them. The lock still lasts until
transaction end, but now protects DECLARE before the first FETCH too.

I also considered these places for the lock:

1. ExecInitFunctionScan() covers FROM f(), but not SELECT f().
   The latter would need a separate lock in ExecInitFunctionResultSet().
2. get_expr_result_type() is also used by the parser and planner.
   Adding a lock there would affect more than SRF execution.

So I settled on init_sexpr().

I extended rowtypes-alter.spec, reusing its type, table and cursor
steps. The four added schedules cover both call forms, a domain, and
reuse of a cached SPI plan. All four fail on v2 and pass with the patch.
Core regression, isolation, and your TAP test passed.

I also synchronized alter_table.out with the comments changed by
0005; that mismatch was the only core regression failure on v2.

Regards,
Rui

Re: Two bugs around ALTER TYPE

От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,

On 2026-11-10 16:32:14 +0500, Andrey Borodin wrote:
> Thank you for the substantial work on tuple descriptors and attribute
> versioning in the new release.
> 
> Unfortunately, both bugs reported in this thread still reproduce on
> new minors.

Yea, since they weren't really security relevant, it didn't seem necessary to
go through the security process for them.  They're also only partial fixes to
the problems they're trying to address, so we can't rely on them as a hard
barrier.



> From 36451d306ea25e97b431c9496744813bdaca9859 Mon Sep 17 00:00:00 2001
> From: Andrey Borodin 
> Date: Tue, 7 Apr 2026 15:28:06 +0500
> Subject: [PATCH v2 2/5] Track RTE_FUNCTION composite rowtype dependencies
> 
> Record typrelid dependencies for named composite outputs of RTE_FUNCTION
> nodes, so relcache invalidation from ALTER TYPE marks cached plans stale.
> 
> This keeps prepared and SPI plans in sync with composite rowshape changes.
> ---
>  doc/src/sgml/ref/alter_type.sgml     |  9 +++++++
>  src/backend/optimizer/plan/setrefs.c | 36 ++++++++++++++++++++++++++++
>  2 files changed, 45 insertions(+)
> 
> diff --git a/doc/src/sgml/ref/alter_type.sgml b/doc/src/sgml/ref/alter_type.sgml
> index 025a3ee48f5..72b046afd98 100644
> --- a/doc/src/sgml/ref/alter_type.sgml
> +++ b/doc/src/sgml/ref/alter_type.sgml
> @@ -242,6 +242,15 @@ ALTER TYPE name SET (      and/or alter the type of several attributes in a single command.
>    
>  
> +  
> +   Changing a composite type's attributes also invalidates cached plans for
> +   queries that scan SETOF functions returning that
> +   composite type (including through a domain over the composite), even when
> +   no CREATE OR REPLACE FUNCTION is run.  This matches the
> +   relcache invalidation already sent for the composite type's cataloged
> +   rowtype.
> +  

That doesn't feel like the kind of detail we normally have in the docs.


> +/*
> + * Record relcache dependencies for RTE_FUNCTION entries whose declared result
> + * is a named composite type (or a domain over one).  ALTER TYPE {ADD | DROP |
> + * ALTER} ATTRIBUTE updates the composite type's pg_class row without changing
> + * OIDs of dependent functions, so plans must be rebuilt when the composite
> + * rowtype changes.  (Compare extract_query_dependencies_walker, which must
> + * stay in sync.)
> + */
> +static void
> +add_function_rte_relation_deps(PlannerGlobal *glob, const RangeTblEntry *rte)
> +{
> +	ListCell   *lc;
> +
> +	Assert(rte->rtekind == RTE_FUNCTION);
> +
> +	foreach(lc, rte->functions)
> +	{
> +		RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
> +		Oid			typid;
> +		Oid			typrelid;
> +
> +		typid = exprType(rtfunc->funcexpr);
> +		typrelid = typeOrDomainTypeRelid(typid);
> +		if (OidIsValid(typrelid))
> +			glob->relationOids = lappend_oid(glob->relationOids, typrelid);
> +	}
> +}

Does this actually work right for things like arrays of named composite types?

Also, I'm pretty sure this won't reliably work for things like nested
composite types were only the inner type is changed.



Seems like this should have tests documenting cases in which we now do inval?
There should be plenty non-race paths?



> From 9557e372fcf7822afa4ef64dec498ceaeaefefb8 Mon Sep 17 00:00:00 2001
> From: Andrey Borodin 
> Date: Tue, 14 Apr 2026 14:29:14 +0500
> Subject: [PATCH v2 3/5] Add TAP test for plpgsql RETURN QUERY DDL race
> 
> Add an injection-point TAP reproducer for concurrent ALTER TYPE +
> CREATE OR REPLACE FUNCTION during an in-progress RETURN QUERY call.
> 

> ---
>  src/pl/plpgsql/src/pl_exec.c                  |  6 ++
>  src/test/modules/test_misc/meson.build        |  1 +
>  .../t/012_plpgsql_composite_replan_race.pl    | 96 +++++++++++++++++++

Adding dedicated tap tests for stuff like this does not scale. Each of them
does an initdb (or copies a cluster). That's a fair bit of IO.


I think this doesn't even need an injection point, it's probably quite easy to
repro with just an advisory lock acquisition? Then make it an isolation
test...


> From f298c979b11983851177cce465cce54772278cc7 Mon Sep 17 00:00:00 2001
> From: Andrey Borodin 
> Date: Tue, 14 Apr 2026 14:29:21 +0500
> Subject: [PATCH v2 4/5] Lock SETOF composite return type during plpgsql
>  execution
> 
> For SETOF PL/pgSQL functions returning named composite tuples, acquire
> AccessShareLock on the return type's typrelid at function entry.
> 
> This keeps rowshape stable for the whole execution under concurrent
> ALTER TYPE and avoids mid-statement mismatch errors.

I really doubt this makes sense. There's a lot of places that are affected by
concurrent rowtype changes. Why would we want to specifically fix this one
with locking?

Greetings,

Andres


FAQ