Fix Portal snapshot tracking to handle subtransactions properly.
authorTom Lane <tgl@sss.pgh.pa.us>
Fri, 1 Oct 2021 15:10:12 +0000 (11:10 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Fri, 1 Oct 2021 15:10:12 +0000 (11:10 -0400)
commit7b5d4c29ed0262e537026cb3a85161d6cf98abcc
treec22377b3b39ed1955ac6b663d84d2c04a14b82ca
parent2d44dee0281a1abf0dcb1548c910fae067f1d34d
Fix Portal snapshot tracking to handle subtransactions properly.

Commit 84f5c2908 forgot to consider the possibility that
EnsurePortalSnapshotExists could run inside a subtransaction with
lifespan shorter than the Portal's.  In that case, the new active
snapshot would be popped at the end of the subtransaction, leaving
a dangling pointer in the Portal, with mayhem ensuing.

To fix, make sure the ActiveSnapshot stack entry is marked with
the same subtransaction nesting level as the associated Portal.
It's certainly safe to do so since we won't be here at all unless
the stack is empty; hence we can't create an out-of-order stack.

Let's also apply this logic in the case where PortalRunUtility
sets portalSnapshot, just to be sure that path can't cause similar
problems.  It's slightly less clear that that path can't create
an out-of-order stack, so add an assertion guarding it.

Report and patch by Bertrand Drouvot (with kibitzing by me).
Back-patch to v11, like the previous commit.

Discussion: https://postgr.es/m/ff82b8c5-77f4-3fe7-6028-fcf3303e82dd@amazon.com
src/backend/access/transam/xact.c
src/backend/tcop/pquery.c
src/backend/utils/mmgr/portalmem.c
src/backend/utils/time/snapmgr.c
src/include/utils/portal.h
src/include/utils/snapmgr.h
src/pl/plpgsql/src/expected/plpgsql_transaction.out
src/pl/plpgsql/src/sql/plpgsql_transaction.sql