From 06145f076780a82dc981b206e935887d13f1635a Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 10 Nov 2026 11:39:06 -0500
Subject: [PATCH v1 05/10] EXISTS: Free GroupVarInfos in estimate_num_groups

estimate_num_groups() never frees the GroupVarInfo it allocates for each
grouping variable, and it runs for every Memoize path considered
(cost_memoize_rescan).  Free the GroupVarInfos of each relation after
processing it, and the ones add_unique_group_var() discards.

The list_free_deep(relvarinfos) meant to free them was a no-op, because
relvarinfos is always NIL at that point, and so was the final
list_free(varinfos).  Remove both.

On a correlated semijoin against a 13-way join, planning memory goes
from 35299 kB to 26178 kB (-25.8%).

Reproducer: reproducers/16-free-group-var-infos.sql
---
 reproducers/16-free-group-var-infos.sql | 108 ++++++++++++++++++++++++
 src/backend/utils/adt/selfuncs.c        |  18 +++-
 2 files changed, 122 insertions(+), 4 deletions(-)
 create mode 100644 reproducers/16-free-group-var-infos.sql

diff --git a/reproducers/16-free-group-var-infos.sql b/reproducers/16-free-group-var-infos.sql
new file mode 100644
index 00000000000..e1de4715f84
--- /dev/null
+++ b/reproducers/16-free-group-var-infos.sql
@@ -0,0 +1,108 @@
+-- Reproducer for commit "Free GroupVarInfos in estimate_num_groups"
+--
+-- estimate_num_groups() allocates a GroupVarInfo for each grouping variable,
+-- but never frees them.  It runs for every Memoize path considered
+-- (cost_memoize_rescan), so they add up.  This frees the GroupVarInfos of
+-- each relation once the relation has been processed, and the ones
+-- add_unique_group_var() discards.
+--
+-- The list_free_deep(relvarinfos) meant to free them was a no-op, because
+-- relvarinfos is always NIL at that point, and so was the final
+-- list_free(varinfos).  Both are removed.
+--
+-- Query: semijoin of a table against a 13-way join (14 relations),
+-- correlated with the outer query.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/16-free-group-var-infos.sql
+--
+-- The tables are created in schema repro_16, which is dropped and
+-- recreated on each run.  plan_md5 is a hash of the plan, to show the
+-- plan is the same on both builds.
+--
+-- Planning memory in kB, measured on builds without assertions
+-- (meson buildtype=debugoptimized):
+--
+--                    used  allocated
+--   parent commit   35299      41249
+--   this commit     26178      33057   (-25.8% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_16 CASCADE;
+CREATE SCHEMA repro_16;
+SET search_path = repro_16;
+
+-- Outer table a, and a semijoin against b joined to 12 dimension tables,
+-- correlated with the outer query on b.x = a.x.  All tables have 1000 rows
+-- and an index on every column, so the semijoin's inner side gets
+-- parameterized join paths (parameterized by a) for every subset of
+-- relations containing b.
+CREATE TABLE a (x int, y int);
+INSERT INTO a SELECT g, g FROM generate_series(1, 1000) g;
+CREATE INDEX ON a (x);
+CREATE INDEX ON a (y);
+
+DO $$
+BEGIN
+    EXECUTE 'CREATE TABLE b (x int, ' ||
+        (SELECT string_agg(format('c%s int', i), ', ')
+           FROM generate_series(1, 12) i) || ')';
+    EXECUTE 'INSERT INTO b SELECT g, ' ||
+        (SELECT string_agg('g', ', ') FROM generate_series(1, 12) i) ||
+        ' FROM generate_series(1, 1000) g';
+    EXECUTE 'CREATE INDEX ON b (x)';
+
+    FOR i IN 1..12 LOOP
+        EXECUTE format('CREATE INDEX ON b (c%s)', i);
+        EXECUTE format('CREATE TABLE d%s (k int, v int)', i);
+        EXECUTE format('INSERT INTO d%s SELECT g, g FROM generate_series(1, 1000) g', i);
+        EXECUTE format('CREATE INDEX ON d%s (k)', i);
+        EXECUTE format('CREATE INDEX ON d%s (v)', i);
+    END LOOP;
+END
+$$;
+ANALYZE a, b, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12;
+
+SET join_collapse_limit = 16;
+SET from_collapse_limit = 16;
+SET geqo = off;
+
+-- Plan the query and return the planning memory reported by EXPLAIN (MEMORY),
+-- along with a hash of the plan (to check the plan did not change).
+CREATE FUNCTION pg_temp.planning_memory(query text,
+                                        OUT memory_used_kb bigint,
+                                        OUT memory_allocated_kb bigint,
+                                        OUT plan_md5 text)
+LANGUAGE plpgsql AS $fn$
+DECLARE
+    plan json;
+BEGIN
+    EXECUTE 'EXPLAIN (MEMORY, COSTS OFF, FORMAT JSON) ' || query INTO plan;
+    memory_used_kb := (plan->0->'Planning'->>'Memory Used')::bigint;
+    memory_allocated_kb := (plan->0->'Planning'->>'Memory Allocated')::bigint;
+    plan_md5 := md5((plan->0->'Plan')::text);
+END
+$fn$;
+
+SELECT * FROM pg_temp.planning_memory($q$
+SELECT *
+  FROM a
+ WHERE EXISTS (SELECT 1
+                 FROM b
+                 JOIN d1 ON b.c1 = d1.k
+                 JOIN d2 ON b.c2 = d2.k
+                 JOIN d3 ON b.c3 = d3.k
+                 JOIN d4 ON b.c4 = d4.k
+                 JOIN d5 ON b.c5 = d5.k
+                 JOIN d6 ON b.c6 = d6.k
+                 JOIN d7 ON b.c7 = d7.k
+                 JOIN d8 ON b.c8 = d8.k
+                 JOIN d9 ON b.c9 = d9.k
+                 JOIN d10 ON b.c10 = d10.k
+                 JOIN d11 ON b.c11 = d11.k
+                 JOIN d12 ON b.c12 = d12.k
+                WHERE b.x = a.x)
+$q$);
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index b696901b649..3446c4947fc 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -3714,6 +3714,7 @@ add_unique_group_var(PlannerInfo *root, List *varinfos,
 			{
 				/* Delete the older item */
 				varinfos = foreach_delete_current(varinfos, lc);
+				pfree(varinfo);
 			}
 		}
 	}
@@ -3917,7 +3918,7 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 		{
 			if (contain_volatile_functions(groupexpr))
 			{
-				list_free(varinfos);
+				list_free_deep(varinfos);
 				return input_rows;
 			}
 			continue;
@@ -4124,8 +4125,19 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 			numdistinct *= reldistinct;
 		}
 
+		/*
+		 * We're done with the GroupVarInfos of this rel; the others are in
+		 * newvarinfos.  (estimate_multivariate_ndistinct may have replaced
+		 * relvarinfos, so use varinfos to find them.)
+		 */
+		foreach(l, varinfos)
+		{
+			GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
+
+			if (varinfo2->rel == rel)
+				pfree(varinfo2);
+		}
 		list_free(varinfos);
-		list_free_deep(relvarinfos);
 
 		varinfos = newvarinfos;
 	} while (varinfos != NIL);
@@ -4142,8 +4154,6 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 	if (numdistinct < 1.0)
 		numdistinct = 1.0;
 
-	list_free(varinfos);
-
 	return numdistinct;
 }
 
-- 
2.56.1

