Proposal to make temporary change of memory context a bit safer

From: Antonin Houska <ah(at)cybertec(dot)at>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Proposal to make temporary change of memory context a bit safer
Date: 2025-01-28 10:30:56
Message-ID: 5532.1738060256@antos
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

When dealing with a tricky bug in an extension [1] last week, I found out that
one should not rely on a PG core functions to leave CurrentMemoryContext
always unchanged. While the change of memory context makes sense for functions
involved in error handling or transaction control, it's less obvious in other
cases.

In particular, I realized that DecodingContextFindStartpoint() can switch to
TopTransactionContext, but it only does so in special cases (i.e. when dealing
with catalog cache invalidations), so it's not trivial to detect this behavior
during testing.

I think that the risk of problems like this would be smaller if we had a macro
that both calls MemoryContextSwitchTo() and checks if the context has not
changed. For example

DO_IN_MEMORY_CONTEXT(myContext)
{
...
}

which expands to

{
MemoryContext oldcontext = MemoryContextSwitchTo(myContext);

...

if (CurrentMemoryContext != myContext)
ereport(ERROR, ...);
MemoryContextSwitchTo(oldcontext);
}

Is this worth a patch? (I don't mean that macro like this should automatically
replace all the existing uses of MemoryContextSwitchTo() across the tree.)

[1] https://www.postgresql.org/about/news/pg_squeeze-18-released-3005/

--
Antonin Houska
Web: https://www.cybertec-postgresql.com

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Eisentraut 2025-01-28 10:31:48 Re: NOT ENFORCED constraint feature
Previous Message Ashutosh Bapat 2025-01-28 10:26:45 Re: SQL Property Graph Queries (SQL/PGQ)