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.
7b5d4c29ed Fix Portal snapshot tracking to handle subtransactions properly.
src/backend/access/transam/xact.c | 1 +
src/backend/tcop/pquery.c | 27 +++++++++++++++------
src/backend/utils/mmgr/portalmem.c | 4 ++++
src/backend/utils/time/snapmgr.c | 17 ++++++++++++-
src/include/utils/portal.h | 2 ++
src/include/utils/snapmgr.h | 1 +
.../plpgsql/src/expected/plpgsql_transaction.out | 28 ++++++++++++++++++++++
src/pl/plpgsql/src/sql/plpgsql_transaction.sql | 21 ++++++++++++++++
8 files changed, 93 insertions(+), 8 deletions(-)