From ab2d6a1bdc17d8b06955acc2c0ae73ecf7dd8f2f Mon Sep 17 00:00:00 2001 From: Dilip Kumar Date: Wed, 20 Aug 2025 13:09:06 +0000 Subject: [PATCH v2] Fix: Release cached plan and clear function cache on error This commit fixes a bug where a SQL function's cached plan was not being properly released on error. The function cache stores a reference to a saved plan and its associated resource owner. However, when an error occurs, the resource owner is released as part of transaction abort, but the function cache still holds a dangling pointer to the resource owner. This leads to an error on the next execution, as the system tries to access a freed resource owner to release the plan. To resolve this, this patch ensures that on error, the cached plan is explicitly released and the reference is cleared from the SQL function cache. This prevents the resource leak and ensures a safe state for subsequent function calls. Reported by: Alexander Lakhin Author: Dilip Kumar and Kirill Reshke --- src/backend/executor/functions.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c index 359aafea681..d3de5b1ea6e 100644 --- a/src/backend/executor/functions.c +++ b/src/backend/executor/functions.c @@ -1913,6 +1913,13 @@ sql_exec_error_callback(void *arg) internalerrquery(fcache->func->src); } + /* On error, release CachedPlan if we have one */ + if (fcache->cplan) + { + ReleaseCachedPlan(fcache->cplan, fcache->cowner); + fcache->cplan = NULL; + } + /* * If we failed while executing an identifiable query within the function, * report that. Otherwise say it was "during startup". -- 2.51.0.rc1.167.g924127e9c0-goog