From 491d6a5626be5e27946777a5ac11ddb6face0058 Mon Sep 17 00:00:00 2001 From: Tynan Couture-Rashid Date: Thu, 3 Dec 2026 16:34:25 +0000 Subject: [PATCH v1 1/2] Fix per-call memory leak in InitMaterializedSRF() When the caller doesn't pass MAT_SRF_USE_EXPECTED_DESC, InitMaterializedSRF() resolves the result type with get_call_result_type() while the per-query context is current. For functions with OUT parameters this reaches build_function_result_tupdesc_d(), whose scratch allocations (the deconstructed proargnames array, the output type and name arrays, and the name strings) are never freed. ExecMakeTableFunctionResult() frees the returned descriptor, but the scratch memory stays until the query ends. A set-returning function called once per outer row, for example from a correlated subquery, therefore leaks on every call. jsonb_each() leaks about 300 bytes per call, and functions with more output columns leak more: pg_stat_get_activity() leaks about 1.4 kB. A query making 2 million calls grows by about 600 MB, and work_mem doesn't limit it. Resolve the type in the caller's context, which the executor resets between calls, and copy only the finished descriptor into the per-query context. CreateTupleDescCopyConstr() is used so the copy keeps everything get_call_result_type() returned. This is a regression from 9e98583898c, which added the helper in 15. Before it, callers such as each_worker_jsonb() resolved the type in the caller's context and copied the descriptor into the per-query context, as this does. Back-patch to 15. --- src/backend/utils/fmgr/funcapi.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/backend/utils/fmgr/funcapi.c b/src/backend/utils/fmgr/funcapi.c index 5cc6c52..7f87503 100644 --- a/src/backend/utils/fmgr/funcapi.c +++ b/src/backend/utils/fmgr/funcapi.c @@ -105,8 +105,19 @@ InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags) stored_tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc); else { - if (get_call_result_type(fcinfo, NULL, &stored_tupdesc) != TYPEFUNC_COMPOSITE) + TupleDesc result_tupdesc; + + /* + * Resolve the result type in the caller's context, which the executor + * resets between calls, and keep only a copy of the finished + * descriptor; the lookup's scratch allocations would otherwise leak + * into the per-query context on every call. + */ + MemoryContextSwitchTo(old_context); + if (get_call_result_type(fcinfo, NULL, &result_tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); + MemoryContextSwitchTo(per_query_ctx); + stored_tupdesc = CreateTupleDescCopyConstr(result_tupdesc); } /* If requested, bless the tuple descriptor */ -- 2.47.3