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