From eef6c342a62a1334d3f6f16c166f55e19afc2600 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 9 Jun 2026 00:06:00 +0200
Subject: [PATCH v1 02/10] STAR2: Avoid leaking temporary lists during join
 planning

generate_join_implied_equalities() leaked the per-EC sublist after
appending it to the result, and find_mergeclauses_for_outer_pathkeys()
built a temporary list of matching clauses for every pathkey.  Both run
for every join pair considered, so with many relations and ECs the
waste adds up.  Free the sublist, and append the matching clauses to
the result list directly.

On a 14-way star join with two-column keys, planning memory goes from
170735 kB to 125805 kB (-26%).

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reproducer: reproducers/01-join-clause-lists.sql
---
 reproducers/01-join-clause-lists.sql    | 94 +++++++++++++++++++++++++
 src/backend/optimizer/path/equivclass.c |  3 +-
 src/backend/optimizer/path/pathkeys.c   | 15 ++--
 3 files changed, 102 insertions(+), 10 deletions(-)
 create mode 100644 reproducers/01-join-clause-lists.sql

diff --git a/reproducers/01-join-clause-lists.sql b/reproducers/01-join-clause-lists.sql
new file mode 100644
index 00000000000..e36d73e3398
--- /dev/null
+++ b/reproducers/01-join-clause-lists.sql
@@ -0,0 +1,94 @@
+-- Reproducer for commit "Avoid leaking temporary lists during join planning"
+--
+-- generate_join_implied_equalities() runs for every pair of relations the
+-- join search considers, and leaked the per-EC list of clauses after
+-- concatenating it to the result.  find_mergeclauses_for_outer_pathkeys()
+-- built a temporary list for every pathkey, which leaked the same way.  Both
+-- grow with the number of EquivalenceClasses linking the two sides of a join,
+-- so a star join with two-column keys (two ECs per dimension) shows the effect
+-- well.
+--
+-- 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/01-join-clause-lists.sql
+--
+-- The tables are created in schema repro_01, 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  170735     172673
+--   this commit    125805     131713   (-26.3% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_01 CASCADE;
+CREATE SCHEMA repro_01;
+SET search_path = repro_01;
+
+-- 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/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 248386a6298..481cc23dcf2 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -1606,7 +1606,7 @@ generate_join_implied_equalities(PlannerInfo *root,
 	while ((i = bms_next_member(matching_ecs, i)) >= 0)
 	{
 		EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
-		List	   *sublist = NIL;
+		List	   *sublist;
 
 		/* ECs containing consts do not need any further enforcement */
 		if (ec->ec_has_const)
@@ -1636,6 +1636,7 @@ generate_join_implied_equalities(PlannerInfo *root,
 															  inner_rel);
 
 		result = list_concat(result, sublist);
+		list_free(sublist);
 	}
 
 	return result;
diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c
index 50651813a11..47fc08c5c1e 100644
--- a/src/backend/optimizer/path/pathkeys.c
+++ b/src/backend/optimizer/path/pathkeys.c
@@ -1568,7 +1568,7 @@ find_mergeclauses_for_outer_pathkeys(PlannerInfo *root,
 	{
 		PathKey    *pathkey = (PathKey *) lfirst(i);
 		EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
-		List	   *matched_restrictinfos = NIL;
+		bool		found_clauses = false;
 		ListCell   *j;
 
 		/*----------
@@ -1616,7 +1616,10 @@ find_mergeclauses_for_outer_pathkeys(PlannerInfo *root,
 			clause_ec = rinfo->outer_is_left ?
 				rinfo->left_ec : rinfo->right_ec;
 			if (clause_ec == pathkey_ec)
-				matched_restrictinfos = lappend(matched_restrictinfos, rinfo);
+			{
+				mergeclauses = lappend(mergeclauses, rinfo);
+				found_clauses = true;
+			}
 		}
 
 		/*
@@ -1624,14 +1627,8 @@ find_mergeclauses_for_outer_pathkeys(PlannerInfo *root,
 		 * sort-key positions in the pathkeys are useless.  (But we can still
 		 * mergejoin if we found at least one mergeclause.)
 		 */
-		if (matched_restrictinfos == NIL)
+		if (!found_clauses)
 			break;
-
-		/*
-		 * If we did find usable mergeclause(s) for this sort-key position,
-		 * add them to result list.
-		 */
-		mergeclauses = list_concat(mergeclauses, matched_restrictinfos);
 	}
 
 	return mergeclauses;
-- 
2.56.1

