From c8e124f6c6d209e39072e6c2859c476bce8c082e Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sun, 11 May 2025 13:32:17 -0400
Subject: [PATCH v1 08/11] Fix some extremely broken code from 525392d57.

This uselessly makes two copies of the plan tree during
BuildCachedPlan; there should be only one, and it should be
in the stmt_context not plan_context.   Also, UpdateCachedPlan
has a fragile and undocumented assumption that the length of
the stmt_list can't change.  (The XXX comments in that function
have a very strong whiff of code that wasn't really ready to
commit, but this is enough fixing to silence Valgrind's complaints
about leaked data in the plan_context.)

Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/285483.1746756246@sss.pgh.pa.us
---
 src/backend/utils/cache/plancache.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)

diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index 9bcbc4c3e97..53e3255ad7f 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -1114,17 +1114,18 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
 											 ALLOCSET_START_SMALL_SIZES);
 		MemoryContextCopyAndSetIdentifier(plan_context, plansource->query_string);
 
-		stmt_context = AllocSetContextCreate(CurrentMemoryContext,
+		stmt_context = AllocSetContextCreate(plan_context,
 											 "CachedPlan PlannedStmts",
 											 ALLOCSET_START_SMALL_SIZES);
 		MemoryContextCopyAndSetIdentifier(stmt_context, plansource->query_string);
-		MemoryContextSetParent(stmt_context, plan_context);
 
+		/*
+		 * Copy plans into the stmt_context.
+		 */
 		MemoryContextSwitchTo(stmt_context);
 		plist = copyObject(plist);
 
 		MemoryContextSwitchTo(plan_context);
-		plist = list_copy(plist);
 	}
 	else
 		plan_context = CurrentMemoryContext;
@@ -1207,8 +1208,6 @@ UpdateCachedPlan(CachedPlanSource *plansource, int query_index,
 {
 	List	   *query_list = plansource->query_list,
 			   *plan_list;
-	ListCell   *l1,
-			   *l2;
 	CachedPlan *plan = plansource->gplan;
 	MemoryContext oldcxt;
 
@@ -1260,12 +1259,7 @@ UpdateCachedPlan(CachedPlanSource *plansource, int query_index,
 
 	MemoryContextReset(plan->stmt_context);
 	oldcxt = MemoryContextSwitchTo(plan->stmt_context);
-	forboth(l1, plan_list, l2, plan->stmt_list)
-	{
-		PlannedStmt *plannedstmt = lfirst(l1);
-
-		lfirst(l2) = copyObject(plannedstmt);
-	}
+	plan->stmt_list = copyObject(plan_list);
 	MemoryContextSwitchTo(oldcxt);
 
 	/*
-- 
2.43.5

