From 9c38bc9ceb3b7189b0eccb51545ceedd79f7d51c Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 10 Nov 2026 11:44:38 -0500
Subject: [PATCH v1 08/10] STAR2: Free temporary allocations in
 build_joinrel_restrictlist

build_joinrel_restrictlist() is called for every pair of input relations
considered for a join.  The list of clauses derived from equivalence
classes, returned by generate_join_implied_equalities(), was appended to
the result using list_concat(), which copies the cells, so the list
itself was leaked.  The same applies to the union of input relids,
used only while collecting the clauses from the joininfo lists.

Free both.  On a 14-way star join with two-column join keys this
reduces planner memory by ~18%.

Reproducer: reproducers/21-free-restrictlist-temporaries.sql
---
 .../21-free-restrictlist-temporaries.sql      | 92 +++++++++++++++++++
 src/backend/optimizer/util/relnode.c          | 16 ++--
 2 files changed, 102 insertions(+), 6 deletions(-)
 create mode 100644 reproducers/21-free-restrictlist-temporaries.sql

diff --git a/reproducers/21-free-restrictlist-temporaries.sql b/reproducers/21-free-restrictlist-temporaries.sql
new file mode 100644
index 00000000000..912a57943b5
--- /dev/null
+++ b/reproducers/21-free-restrictlist-temporaries.sql
@@ -0,0 +1,92 @@
+-- Reproducer for commit "Free temporary allocations in build_joinrel_restrictlist"
+--
+-- build_joinrel_restrictlist() runs for every pair of input relations
+-- considered for a join.  It concatenates the clauses derived from
+-- EquivalenceClasses into the result, but never frees the list returned by
+-- generate_join_implied_equalities(), which list_concat() copies.  Nor does
+-- it free the union of the input relids it computes.  This frees both.
+--
+-- Query: 14-way star join (fact table + 13 dimensions), two-column keys.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/21-free-restrictlist-temporaries.sql
+--
+-- The tables are created in schema repro_21, 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   28385      33409
+--   this commit     23393      25217   (-17.6% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_21 CASCADE;
+CREATE SCHEMA repro_21;
+SET search_path = repro_21;
+
+-- Star schema: fact table f (10000 rows) referencing 13 dimension tables
+-- d1 .. d13 (1000 rows each) through a two-column key, with an index on the
+-- key of each dimension.
+DO $$
+BEGIN
+    FOR i IN 1..13 LOOP
+        EXECUTE format('CREATE TABLE d%s (k1 int, k2 int, val int)', i);
+        EXECUTE format('INSERT INTO d%s SELECT g, g, g FROM generate_series(1, 1000) g', i);
+        EXECUTE format('CREATE INDEX ON d%s (k1, k2)', i);
+    END LOOP;
+
+    EXECUTE 'CREATE TABLE f (id int, ' ||
+        (SELECT string_agg(format('d%s_1 int, d%s_2 int', i, i), ', ')
+           FROM generate_series(1, 13) i) || ')';
+    EXECUTE 'INSERT INTO f SELECT g, ' ||
+        (SELECT string_agg('g % 1000 + 1, g % 1000 + 1', ', ')
+           FROM generate_series(1, 13) i) ||
+        ' FROM generate_series(1, 10000) g';
+END
+$$;
+ANALYZE f, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13;
+
+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 f, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13
+ WHERE f.d1_1 = d1.k1 AND f.d1_2 = d1.k2
+   AND f.d2_1 = d2.k1 AND f.d2_2 = d2.k2
+   AND f.d3_1 = d3.k1 AND f.d3_2 = d3.k2
+   AND f.d4_1 = d4.k1 AND f.d4_2 = d4.k2
+   AND f.d5_1 = d5.k1 AND f.d5_2 = d5.k2
+   AND f.d6_1 = d6.k1 AND f.d6_2 = d6.k2
+   AND f.d7_1 = d7.k1 AND f.d7_2 = d7.k2
+   AND f.d8_1 = d8.k1 AND f.d8_2 = d8.k2
+   AND f.d9_1 = d9.k1 AND f.d9_2 = d9.k2
+   AND f.d10_1 = d10.k1 AND f.d10_2 = d10.k2
+   AND f.d11_1 = d11.k1 AND f.d11_2 = d11.k2
+   AND f.d12_1 = d12.k1 AND f.d12_2 = d12.k2
+   AND f.d13_1 = d13.k1 AND f.d13_2 = d13.k2
+$q$);
diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c
index 90a687c32da..b6179992453 100644
--- a/src/backend/optimizer/util/relnode.c
+++ b/src/backend/optimizer/util/relnode.c
@@ -1504,6 +1504,7 @@ build_joinrel_restrictlist(PlannerInfo *root,
 						   SpecialJoinInfo *sjinfo)
 {
 	List	   *result;
+	List	   *eclauses;
 	Relids		both_input_relids;
 
 	both_input_relids = bms_union(outer_rel->relids, inner_rel->relids);
@@ -1523,16 +1524,19 @@ build_joinrel_restrictlist(PlannerInfo *root,
 	 * redundant with the clauses in the joininfo lists, so don't bother
 	 * checking.
 	 */
-	result = list_concat(result,
-						 generate_join_implied_equalities(root,
-														  joinrel->relids,
-														  outer_rel->relids,
-														  inner_rel,
-														  sjinfo));
+	eclauses = generate_join_implied_equalities(root,
+												joinrel->relids,
+												outer_rel->relids,
+												inner_rel,
+												sjinfo);
+	result = list_concat(result, eclauses);
+	list_free(eclauses);
 
 	/* We should not have accepted multiple clones of the same clause */
 	Assert(no_duplicate_clause_serials(result));
 
+	bms_free(both_input_relids);
+
 	return result;
 }
 
-- 
2.56.1

