Hi,

Over the past couple months I've been working on various improvements to
join planning (starjoins, join hardness, ...). Back in June I've been
looking into feasibility of increasing join_collapse_limit [1], but it
turned out that's not really feasible for two reasons.

First, the exponential complexity is still there (and won't go away),
and having faster CPUs can't really help with that meaningfuly. Maybe we
could increase it from 8 to 10, but after that the exponential growth wins.

Second, planning can eat mind-boggling amounts of memory, and faster
CPUs can't really help with that. And by mind-boggling I mean a join
with 16 tables can eat 32GB of RAM (yes, it's an adversarial query, but
that's exactly why we have join_collapse_limit limit set so low).

At that point I mostly abandoned the effort to reduce memory usage, as
it was clear it won't get us to significant increases of the
join_collapse_limit anyway. And I started experimenting with modern join
planning algorithms (which are mostly alternatives to GEQO, i.e.
heuristics and not exhaustive algorithms).

But then I realized the memory consumption matters even for those
algorithms, because they work with much larger joins. They save the CPU
time, and limit the number of explored join orders, but they can still
generate a lot of different paths etc. So I revived the patches shared
in the June thread [1] and expanded it a "little" bit.

The total patch series has ~45 patches, reducing memory consumption by
up to ~90% for certain "adversarial" join queries. But most of the
savings (~80%) really comes from only ~10 patches, so I'm going to post
those. The rest is either negligible or a bit too experimental. I may
submit them later, not sure.

I'll split the patches into three separate threads - the whole series
would be too unwieldy. And there really are three separate types of
improvements (by topic / complexity).

In this thread I'm sharing patches that simply free "working" copies of
items (like list of clauses), private in a function. Our custom is to
just leave them around, and MemoryContext will eventually cleanup the
allocations. But with exponential number of long lists that's not really
working well. So this frees such allocations in a couple places.

There's 10 patches, each with a reproducer included. But really, there
are just 3 query shapes - EXISTS, STAR2 and ECCHAIN - targeted by the
patches (there's some overlap of the benefits, ofc). And the reproducers
are effectively the same for "same shape" patches.

- v1-0001-STAR2-Free-mergejoin-clause-and-pathkey-lists-of-.patch
- v1-0002-STAR2-Avoid-leaking-temporary-lists-during-join-p.patch
- v1-0003-EXISTS-Free-temporary-lists-in-estimate_num_group.patch
- v1-0004-STAR2-Free-member-lists-in-generate_join_implied_.patch
- v1-0005-EXISTS-Free-GroupVarInfos-in-estimate_num_groups.patch
- v1-0006-STAR2-Free-hashclause-lists-of-rejected-hashjoin-.patch
- v1-0007-EXISTS-Free-the-attribute-set-built-by-examine_si.patch
- v1-0008-STAR2-Free-temporary-allocations-in-build_joinrel.patch
- v1-0009-ECCHAIN-Free-outerkeys-and-merge_pathkeys-in-sort.patch
- v1-0010-EXISTS-Free-temporary-lists-in-get_joinrel_paramp.patch

The effect of the patches (on a 14-table join) looks like this (the
numbers are memory usage in kB):

               ECCHAIN        EXIST         STAR2
  -----------------------------------------------
  master        106561       264979        190919
  0001           81341       242900        126278
  0002           68407       229137         76356
  0003           61207       192653         76330
  0004           56158       180489         59685
  0005           53998       169543         59670
  0006           49670       166023         51351
  0007           48213       158721         51333
  0008           45096       156033         45509
  0009           40722       156033         45509
  0010           40722       151873         45509

So that's ~50-60% reduction. It helps a bit with planning time too, but
that wasn't the aim here (except for not getting slower).

Earlier I said the patches are merely freeing local "private" copies of
lists, and that's true for 8 out of the 10 patches. But there are two
patches that do something a little bit different:

- v1-0001-STAR2-Free-mergejoin-clause-and-pathkey-lists-of-.patch
- v1-0006-STAR2-Free-hashclause-lists-of-rejected-hashjoin-.patch

These patches are freeing lists from *rejected paths* (mergejoin and
hashjoin). The patches do that in add_path() but that seems a bit dirty.
It relies on the fact that the path can't be reference by anything, and
while I think that's true, maybe it isn't? There might be a better way
to do this - e.g. by making add_path() to return false when the new path
gets rejected. And do the freeing in the caller. But it seems to work
well enought to demonstrate the benefits.


regards

[1]
https://www.postgresql.org/message-id/[email protected]

-- 
Tomas Vondra
From e28f38731cea5f5a3258920cbc6b59a48f9e39e6 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 9 Jun 2026 00:17:33 +0200
Subject: [PATCH v1 01/10] STAR2: Free mergejoin clause and pathkey lists of
 rejected paths

Most mergejoin paths built during the join search are rejected by
add_path(), but their lists of mergeclauses and pathkeys were never
freed.  Make create_mergejoin_path() copy the lists so that each
MergePath owns them, and free them when add_path() or
add_partial_path() rejects a new MergePath of the rel being added to.
Also free the temporary lists in add_paths_to_joinrel(),
sort_inner_and_outer() and generate_mergejoin_paths().

Don't free the lists of paths displaced from the pathlist, or of paths
of other rels, because they may be shared with a copy of the path.
postgres_fdw's GetExistingLocalJoinPath() makes a shallow copy of a
join path in the joinrel's pathlist for EPQ rechecks, and createplan.c
builds the EPQ plan from the copy even after the original path has been
displaced.  And create_ordered_paths() passes paths that are still in
the pathlist of its input rel to add_path() for the ordered rel.
Freeing those lists would make planning FOR UPDATE queries with foreign
joins fail or crash.

On a 14-way star join with two-column keys, planning memory goes from
110801 kB to 52625 kB (-53%).

Reproducers: reproducers/05-mergejoin-path-lists.sql for the memory,
reproducers/05-epq-join-path-lists.sql for the EPQ paths
---
 reproducers/05-epq-join-path-lists.sql  | 158 ++++++++++++++++++++++++
 reproducers/05-mergejoin-path-lists.sql |  95 ++++++++++++++
 src/backend/optimizer/path/joinpath.c   |  18 ++-
 src/backend/optimizer/util/pathnode.c   |  75 +++++++++--
 4 files changed, 337 insertions(+), 9 deletions(-)
 create mode 100644 reproducers/05-epq-join-path-lists.sql
 create mode 100644 reproducers/05-mergejoin-path-lists.sql

diff --git a/reproducers/05-epq-join-path-lists.sql b/reproducers/05-epq-join-path-lists.sql
new file mode 100644
index 00000000000..7db1c11f70a
--- /dev/null
+++ b/reproducers/05-epq-join-path-lists.sql
@@ -0,0 +1,158 @@
+-- Reproducer for commit "Free mergejoin clause and pathkey lists of rejected paths"
+--
+-- The commit frees the clause and pathkey lists of a MergePath only when
+-- add_path() or add_partial_path() rejects a new path of the rel it is
+-- adding to: not when it displaces an old path from the pathlist, and not
+-- for paths of other rels.  This shows why.
+--
+-- postgres_fdw gets the local join path for EPQ rechecks of a pushed-down
+-- join from GetExistingLocalJoinPath(), which returns a shallow copy of a
+-- path in the joinrel's pathlist, sharing those lists.  If add_path() freed
+-- them when it discards the original path, the copy would be left pointing
+-- to freed memory, and building the EPQ plan from it would fail.  Part 1
+-- is a path displaced from the joinrel's pathlist.  Part 2 is a path
+-- borrowed from another rel: create_ordered_paths() passes an already
+-- sorted path of the joinrel to add_path() for the ordered rel, which
+-- rejects it.
+--
+-- Run it on a build of this commit:
+--
+--   psql -X -f reproducers/05-epq-join-path-lists.sql
+--
+-- It requires a superuser and the postgres_fdw extension.  It creates a
+-- postgres_fdw server repro_05_epq_loopback, connecting back to the current
+-- database through the first unix_socket_directories entry, and its
+-- tables in schema repro_05_epq.  Both are dropped and recreated on each run.
+--
+-- Results:
+--
+--   build                              part 1      part 2
+--   parent commit                      plan        plan
+--   freeing the lists of all           ERROR (1)   server crash (SIGSEGV)
+--     discarded paths
+--     - with assertions                TRAP (2)    TRAP (2), if run on its own
+--   this commit without the            plan        server crash; TRAP (2)
+--     parent_rel check                             with assertions
+--   this commit, with and              plan        plan
+--     without assertions
+--
+--   (1) ERROR:  outer pathkeys do not match mergeclauses
+--   (2) TRAP: failed Assert("ptr == NULL || nodeTag(ptr) == type"),
+--       File: "nodes.h", Line: 175
+--
+-- Keeping the lists of displaced paths costs a little memory.  Planning
+-- memory in kB with the queries of reproducers 04 and 05, when the lists of
+-- all discarded paths are freed and with this commit, measured on builds
+-- without assertions (meson buildtype=debugoptimized); the plans are the
+-- same on both builds:
+--
+--                                    used                    allocated
+--                             all paths  this commit     all paths  this commit
+--   04, correlated semijoin      158435  159302 (+0.5%)     164129  164129
+--   05, star join                 50897   52625 (+3.4%)      57985   57985
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SERVER IF EXISTS repro_05_epq_loopback CASCADE;
+DROP SCHEMA IF EXISTS repro_05_epq CASCADE;
+CREATE SCHEMA repro_05_epq;
+SET search_path = repro_05_epq;
+
+CREATE EXTENSION IF NOT EXISTS postgres_fdw;
+
+DO $$
+BEGIN
+    EXECUTE format('CREATE SERVER repro_05_epq_loopback FOREIGN DATA WRAPPER postgres_fdw
+                    OPTIONS (dbname %L, host %L, port %L)',
+                   current_database(),
+                   trim(split_part(current_setting('unix_socket_directories'), ',', 1)),
+                   current_setting('port'));
+END
+$$;
+CREATE USER MAPPING FOR CURRENT_USER SERVER repro_05_epq_loopback;
+
+-- Part 1: displaced path.  FOR UPDATE makes postgres_fdw build an EPQ path
+-- for the foreign join ft1 FULL JOIN ft2, a copy of the Merge Full Join
+-- path.  That path is then displaced from the joinrel's pathlist, so its
+-- lists must not be freed.
+CREATE TABLE t1 (a int, b int);
+CREATE TABLE t2 (a int, b int);
+CREATE TABLE loc (a int);
+INSERT INTO t1 SELECT i, i FROM generate_series(1, 1000) i;
+INSERT INTO t2 SELECT i, i FROM generate_series(1, 1000) i;
+INSERT INTO loc VALUES (50);
+ANALYZE t1, t2, loc;
+
+CREATE FOREIGN TABLE ft1 (a int, b int) SERVER repro_05_epq_loopback
+    OPTIONS (schema_name 'repro_05_epq', table_name 't1',
+             use_remote_estimate 'true');
+CREATE FOREIGN TABLE ft2 (a int, b int) SERVER repro_05_epq_loopback
+    OPTIONS (schema_name 'repro_05_epq', table_name 't2',
+             use_remote_estimate 'true');
+
+-- Part 2: borrowed path.  ORDER BY uses a btree opfamily that postgres_fdw
+-- does not ship, so there is no sorted foreign join path, and the Merge
+-- Join path, which is sorted by "<<<", stays in the joinrel's pathlist.
+-- It is also the source of the EPQ path's copy.  create_ordered_paths()
+-- passes it to add_path() for the ordered rel, where a Sort on top of the
+-- cheaper Foreign Scan beats it, so add_path() rejects it.  It is not a
+-- path of the ordered rel, so its lists must not be freed either.
+CREATE OPERATOR <<< (LEFTARG = int4, RIGHTARG = int4, FUNCTION = int4lt);
+CREATE OPERATOR FAMILY my_int4_ops USING btree;
+CREATE OPERATOR CLASS my_int4_ops FOR TYPE int4 USING btree FAMILY my_int4_ops AS
+    OPERATOR 1 <<<, OPERATOR 2 <=, OPERATOR 3 =, OPERATOR 4 >=, OPERATOR 5 >,
+    FUNCTION 1 btint4cmp(int4, int4);
+
+CREATE TABLE t3 (a int, b int);
+CREATE TABLE t4 (a int, b int);
+INSERT INTO t3 SELECT i, i FROM generate_series(1, 100) i;
+INSERT INTO t4 SELECT i, i FROM generate_series(1, 100) i;
+ANALYZE t3, t4;
+
+CREATE FOREIGN TABLE ft3 (a int, b int) SERVER repro_05_epq_loopback
+    OPTIONS (schema_name 'repro_05_epq', table_name 't3');
+CREATE FOREIGN TABLE ft4 (a int, b int) SERVER repro_05_epq_loopback
+    OPTIONS (schema_name 'repro_05_epq', table_name 't4');
+ANALYZE ft3, ft4;
+
+-- keep going if the first query fails
+\set ON_ERROR_STOP off
+
+-- Part 1.  This commit:
+--
+--   LockRows
+--     ->  Nested Loop
+--           ->  Seq Scan on loc
+--                 Filter: (a = 50)
+--           ->  Foreign Scan
+--                 Relations: (ft1) FULL JOIN (ft2)
+--                 ->  Merge Full Join
+--                       Merge Cond: (ft1.a = ft2.a)
+--                       ->  Foreign Scan on ft1
+--                       ->  Materialize
+--                             ->  Foreign Scan on ft2
+EXPLAIN (COSTS OFF)
+SELECT * FROM loc, (ft1 FULL JOIN ft2 ON ft1.a = ft2.a)
+ WHERE loc.a = 50 FOR UPDATE OF loc;
+
+-- Part 2.  This commit:
+--
+--   LockRows
+--     ->  Sort
+--           Sort Key: ft3.a USING <<<
+--           ->  Foreign Scan
+--                 Relations: (ft3) INNER JOIN (ft4)
+--                 ->  Merge Join
+--                       Merge Cond: (ft3.a = ft4.a)
+--                       ->  Sort
+--                             Sort Key: ft3.a USING <<<
+--                             ->  Foreign Scan on ft3
+--                       ->  Sort
+--                             Sort Key: ft4.a USING <<<
+--                             ->  Foreign Scan on ft4
+SET enable_hashjoin = off;
+SET enable_nestloop = off;
+
+EXPLAIN (COSTS OFF)
+SELECT ft3.a FROM ft3 JOIN ft4 ON ft3.a = ft4.a
+ ORDER BY ft3.a USING <<< FOR UPDATE;
diff --git a/reproducers/05-mergejoin-path-lists.sql b/reproducers/05-mergejoin-path-lists.sql
new file mode 100644
index 00000000000..a4018a22796
--- /dev/null
+++ b/reproducers/05-mergejoin-path-lists.sql
@@ -0,0 +1,95 @@
+-- Reproducer for commit "Free mergejoin clause and pathkey lists of rejected paths"
+--
+-- Each candidate mergejoin path carries lists of mergeclauses and of outer,
+-- inner and output pathkeys, and most candidates are rejected by add_path().
+-- The commit makes MergePaths own copies of these lists and frees them when
+-- add_path()/add_partial_path() rejects a new MergePath of the rel being
+-- added to, and frees some temporary lists in add_paths_to_joinrel(),
+-- sort_inner_and_outer() and generate_mergejoin_paths().  The lists of
+-- paths displaced from the pathlist are not freed, because postgres_fdw may
+-- have copied such a path (see reproducers/05-epq-join-path-lists.sql).
+--
+-- 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/05-mergejoin-path-lists.sql
+--
+-- The tables are created in schema repro_05, 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  110801     115329
+--   this commit     52625      57985   (-52.5% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_05 CASCADE;
+CREATE SCHEMA repro_05;
+SET search_path = repro_05;
+
+-- 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/joinpath.c b/src/backend/optimizer/path/joinpath.c
index beb2856dd21..cface0aeadc 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -408,6 +408,8 @@ add_paths_to_joinrel(PlannerInfo *root,
 	if (set_join_pathlist_hook)
 		set_join_pathlist_hook(root, joinrel, outerrel, innerrel,
 							   save_jointype, &extra);
+
+	list_free(extra.mergeclause_list);
 }
 
 /*
@@ -1677,7 +1679,7 @@ sort_inner_and_outer(PlannerInfo *root,
 							  list_delete_nth_cell(list_copy(all_pathkeys),
 												   foreach_current_index(l)));
 		else
-			outerkeys = all_pathkeys;	/* no work at first one... */
+			outerkeys = list_copy(all_pathkeys);	/* no work at first one... */
 
 		/* Sort the mergeclauses into the corresponding ordering */
 		cur_mergeclauses =
@@ -1731,7 +1733,15 @@ sort_inner_and_outer(PlannerInfo *root,
 									   innerkeys,
 									   jointype,
 									   extra);
+
+		list_free(cur_mergeclauses);
+		list_free(innerkeys);
+
+		if ((outerkeys != merge_pathkeys) && (innerkeys != merge_pathkeys))
+			list_free(outerkeys);
 	}
+
+	list_free(all_pathkeys);
 }
 
 /*
@@ -1792,7 +1802,10 @@ generate_mergejoin_paths(PlannerInfo *root,
 	}
 	if (useallclauses &&
 		list_length(mergeclauses) != list_length(extra->mergeclause_list))
+	{
+		list_free(mergeclauses);
 		return;
+	}
 
 	/* Compute the required ordering of the inner path */
 	innersortkeys = make_inner_pathkeys_for_merge(root,
@@ -1963,6 +1976,9 @@ generate_mergejoin_paths(PlannerInfo *root,
 		if (useallclauses)
 			break;
 	}
+
+	list_free(innersortkeys);
+	list_free(mergeclauses);
 }
 
 /*
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index 5f28174a5fa..b45ac47de7f 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -439,7 +439,9 @@ set_cheapest(RelOptInfo *parent_rel)
  *	  memory consumption.  We dare not try to free the substructure of a Path,
  *	  since much of it may be shared with other Paths or the query tree itself;
  *	  but just recycling discarded Path nodes is a very useful savings in
- *	  a large join tree.
+ *	  a large join tree.  The one exception is a rejected new merge join path
+ *	  of this rel, whose clause and pathkey lists are private to it, so we
+ *	  free those too.
  *
  *	  As noted in optimizer/README, deleting a previously-accepted Path is
  *	  safe because we know that Paths of this rel cannot yet be referenced
@@ -633,7 +635,12 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
 		{
 			parent_rel->pathlist = foreach_delete_current(parent_rel->pathlist,
 														  p1);
-			/* Delete the old path, if it's safe; see header comment */
+
+			/*
+			 * Delete the old path, if it's safe; see header comment.  Unlike
+			 * for a rejected new path (see below), we must not free the lists
+			 * of a join path here, because it may have been copied.
+			 */
 			if (!IsA(old_path, IndexPath) &&
 				old_path->parent == parent_rel)
 				pfree(old_path);
@@ -667,6 +674,38 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
 	}
 	else
 	{
+		/*
+		 * Free the lists of a rejected merge join path.  They belong to the
+		 * path alone: create_mergejoin_path() makes copies of them, and
+		 * nothing can have seen a path that never made it into the pathlist.
+		 *
+		 * We don't do this for old paths removed from the pathlist above.
+		 * While a path is in the pathlist, other code may make a shallow copy
+		 * of it, which shares these lists.  In particular, postgres_fdw's
+		 * postgresGetForeignJoinPaths() calls GetExistingLocalJoinPath() to
+		 * get a local join path for EPQ rechecks of a pushed-down join.  That
+		 * is a flat copy of a path from the joinrel's pathlist, and
+		 * createplan.c builds the EPQ plan from the copy, lists included,
+		 * even if the original path has been removed in the meantime.
+		 *
+		 * For the same reason, leave the lists of other rels' paths alone.
+		 * Some callers pass us a path that is still in its own rel's
+		 * pathlist; for example, create_ordered_paths() adds input paths that
+		 * are already sorted.
+		 */
+		if (new_path->parent == parent_rel)
+		{
+			if (IsA(new_path, MergePath))
+			{
+				MergePath  *mjpath = (MergePath *) new_path;
+
+				list_free(mjpath->path_mergeclauses);
+				list_free(mjpath->innersortkeys);
+				list_free(mjpath->outersortkeys);
+				list_free(mjpath->jpath.path.pathkeys);
+			}
+		}
+
 		/* Reject and recycle the new path, if it's safe */
 		if (!IsA(new_path, IndexPath) &&
 			new_path->parent == parent_rel)
@@ -882,7 +921,11 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 		{
 			parent_rel->partial_pathlist =
 				foreach_delete_current(parent_rel->partial_pathlist, p1);
-			/* Delete the old path, if it's safe; see header comment */
+
+			/*
+			 * Delete the old path, if it's safe; see header comment.  As in
+			 * add_path, don't free the lists of a join path here.
+			 */
 			if (old_path->parent == parent_rel)
 				pfree(old_path);
 		}
@@ -915,9 +958,25 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 	}
 	else
 	{
-		/* Reject and recycle the new path, if it's safe */
+		/*
+		 * Reject and recycle the new path, if it's safe; see header comment.
+		 * As in add_path, free the lists of a merge join path too; see the
+		 * comments there.
+		 */
 		if (new_path->parent == parent_rel)
+		{
+			if (IsA(new_path, MergePath))
+			{
+				MergePath  *mjpath = (MergePath *) new_path;
+
+				list_free(mjpath->path_mergeclauses);
+				list_free(mjpath->innersortkeys);
+				list_free(mjpath->outersortkeys);
+				list_free(mjpath->jpath.path.pathkeys);
+			}
+
 			pfree(new_path);
+		}
 	}
 }
 
@@ -2509,15 +2568,15 @@ create_mergejoin_path(PlannerInfo *root,
 		outer_path->parallel_safe && inner_path->parallel_safe;
 	/* This is a foolish way to estimate parallel_workers, but for now... */
 	pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
-	pathnode->jpath.path.pathkeys = pathkeys;
+	pathnode->jpath.path.pathkeys = list_copy(pathkeys);
 	pathnode->jpath.jointype = jointype;
 	pathnode->jpath.inner_unique = extra->inner_unique;
 	pathnode->jpath.outerjoinpath = outer_path;
 	pathnode->jpath.innerjoinpath = inner_path;
 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
-	pathnode->path_mergeclauses = mergeclauses;
-	pathnode->outersortkeys = outersortkeys;
-	pathnode->innersortkeys = innersortkeys;
+	pathnode->path_mergeclauses = list_copy(mergeclauses);
+	pathnode->outersortkeys = list_copy(outersortkeys);
+	pathnode->innersortkeys = list_copy(innersortkeys);
 	pathnode->outer_presorted_keys = outer_presorted_keys;
 	/* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
 	/* pathnode->materialize_inner will be set by final_cost_mergejoin */
-- 
2.56.1

From eef6c342a62a1334d3f6f16c166f55e19afc2600 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
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 <[email protected]>
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

From 46c92da45c95bda5d37a2842ec845922b76d6564 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 9 Jun 2026 00:19:46 +0200
Subject: [PATCH v1 03/10] EXISTS: Free temporary lists in estimate_num_groups

Free the per-relation varinfo list once the relation is processed, and
the list of varinfos at the end of each iteration.  During join
planning, estimate_num_groups() is called for every nestloop with a
Memoize inner path (from cost_memoize_rescan), so the leaks add up
with many parameterized paths.

On a correlated semijoin against a 13-way join, planning memory goes
from 212009 kB to 179172 kB (-15%).

Reproducer: reproducers/04-estimate-num-groups-lists.sql
---
 reproducers/04-estimate-num-groups-lists.sql | 106 +++++++++++++++++++
 src/backend/utils/adt/selfuncs.c             |   9 ++
 2 files changed, 115 insertions(+)
 create mode 100644 reproducers/04-estimate-num-groups-lists.sql

diff --git a/reproducers/04-estimate-num-groups-lists.sql b/reproducers/04-estimate-num-groups-lists.sql
new file mode 100644
index 00000000000..9cd5e88b131
--- /dev/null
+++ b/reproducers/04-estimate-num-groups-lists.sql
@@ -0,0 +1,106 @@
+-- Reproducer for commit "Free temporary lists in estimate_num_groups"
+--
+-- estimate_num_groups() leaked its per-relation and remaining-vars lists in
+-- each iteration.  During join planning it is called for every nestloop with
+-- a Memoize inner path (from cost_memoize_rescan), so the query needs many
+-- parameterized inner paths that can be memoized: a correlated semijoin with
+-- indexes on all join columns.  All of the reduction comes from Memoize
+-- costing; with enable_memoize = off the planning memory is the same before
+-- and after, give or take 1 kB.
+--
+-- 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/04-estimate-num-groups-lists.sql
+--
+-- The tables are created in schema repro_04, 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  212009     213281
+--   this commit    179172     180513   (-15.5% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_04 CASCADE;
+CREATE SCHEMA repro_04;
+SET search_path = repro_04;
+
+-- 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 5ee377595bd..b696901b649 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -3916,7 +3916,10 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 		if (varshere == NIL)
 		{
 			if (contain_volatile_functions(groupexpr))
+			{
+				list_free(varinfos);
 				return input_rows;
+			}
 			continue;
 		}
 
@@ -4034,6 +4037,7 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 				}
 
 				/* we're done with this relation */
+				list_free(relvarinfos);
 				relvarinfos = NIL;
 			}
 		}
@@ -4120,6 +4124,9 @@ estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows,
 			numdistinct *= reldistinct;
 		}
 
+		list_free(varinfos);
+		list_free_deep(relvarinfos);
+
 		varinfos = newvarinfos;
 	} while (varinfos != NIL);
 
@@ -4135,6 +4142,8 @@ 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

From 74e1fec73fd0b30a90d1688a027fa26ab3ffbeda Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 9 Jun 2026 01:35:31 +0200
Subject: [PATCH v1 04/10] STAR2: Free member lists in
 generate_join_implied_equalities_normal

The outer_members, inner_members and new_members lists are built for
every EC and join pair, and were never freed.  Free them before
returning, including the ec_broken failure paths.

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

Reproducer: reproducers/03-join-implied-equalities-normal-lists.sql
---
 ...3-join-implied-equalities-normal-lists.sql | 91 +++++++++++++++++++
 src/backend/optimizer/path/equivclass.c       | 12 +++
 2 files changed, 103 insertions(+)
 create mode 100644 reproducers/03-join-implied-equalities-normal-lists.sql

diff --git a/reproducers/03-join-implied-equalities-normal-lists.sql b/reproducers/03-join-implied-equalities-normal-lists.sql
new file mode 100644
index 00000000000..c72182dcc62
--- /dev/null
+++ b/reproducers/03-join-implied-equalities-normal-lists.sql
@@ -0,0 +1,91 @@
+-- Reproducer for commit "Free member lists in generate_join_implied_equalities_normal"
+--
+-- generate_join_implied_equalities_normal() sorts the members of an
+-- EquivalenceClass into outer, inner and new members using three temporary
+-- lists, for every EC and every join pair, and leaked all of them.  Like 01,
+-- this grows with the number of ECs linking the joined relations.
+--
+-- 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/03-join-implied-equalities-normal-lists.sql
+--
+-- The tables are created in schema repro_03, 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  125805     131713
+--   this commit    110825     115329   (-11.9% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_03 CASCADE;
+CREATE SCHEMA repro_03;
+SET search_path = repro_03;
+
+-- 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 481cc23dcf2..e91a5d99fc1 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -1826,6 +1826,10 @@ generate_join_implied_equalities_normal(PlannerInfo *root,
 		{
 			/* failed... */
 			ec->ec_broken = true;
+			list_free(result);
+			list_free(new_members);
+			list_free(inner_members);
+			list_free(outer_members);
 			return NIL;
 		}
 
@@ -1875,6 +1879,10 @@ generate_join_implied_equalities_normal(PlannerInfo *root,
 				{
 					/* failed... */
 					ec->ec_broken = true;
+					list_free(result);
+					list_free(new_members);
+					list_free(inner_members);
+					list_free(outer_members);
 					return NIL;
 				}
 				/* do NOT set parent_ec, this qual is not redundant! */
@@ -1888,6 +1896,10 @@ generate_join_implied_equalities_normal(PlannerInfo *root,
 		}
 	}
 
+	list_free(new_members);
+	list_free(inner_members);
+	list_free(outer_members);
+
 	return result;
 }
 
-- 
2.56.1

From 06145f076780a82dc981b206e935887d13f1635a Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
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

From 8398ac07437f0382d5295c9879438eb714038398 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 9 Jun 2026 00:19:24 +0200
Subject: [PATCH v1 06/10] STAR2: Free hashclause lists of rejected hashjoin
 paths

Same as commit "Free mergejoin clause and pathkey lists of rejected
paths", for the hashclauses of HashPaths: make create_hashjoin_path()
copy the list, free it when add_path() or add_partial_path() rejects a
new HashPath of the rel being added to, and free the temporary list in
hash_inner_and_outer().  As there, the lists of displaced paths and of
other rels' paths are not freed, because they may be shared with
postgres_fdw's copy of the path.

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

Reproducer: reproducers/06-hashjoin-path-lists.sql
---
 reproducers/06-hashjoin-path-lists.sql | 90 ++++++++++++++++++++++++++
 src/backend/optimizer/path/joinpath.c  |  5 ++
 src/backend/optimizer/util/pathnode.c  | 31 ++++++---
 3 files changed, 117 insertions(+), 9 deletions(-)
 create mode 100644 reproducers/06-hashjoin-path-lists.sql

diff --git a/reproducers/06-hashjoin-path-lists.sql b/reproducers/06-hashjoin-path-lists.sql
new file mode 100644
index 00000000000..06dfdd4cb53
--- /dev/null
+++ b/reproducers/06-hashjoin-path-lists.sql
@@ -0,0 +1,90 @@
+-- Reproducer for commit "Free hashclause lists of rejected hashjoin paths"
+--
+-- Like 05, but for the hashclauses list of HashPaths, and the temporary
+-- hashclauses list in hash_inner_and_outer().  As in 05, only the lists of
+-- rejected new paths of the rel being added to are freed.
+--
+-- 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/06-hashjoin-path-lists.sql
+--
+-- The tables are created in schema repro_06, 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   52625      57985
+--   this commit     45138      49793   (-14.2% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_06 CASCADE;
+CREATE SCHEMA repro_06;
+SET search_path = repro_06;
+
+-- 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/joinpath.c b/src/backend/optimizer/path/joinpath.c
index cface0aeadc..5a4c7587eb1 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -2436,7 +2436,10 @@ hash_inner_and_outer(PlannerInfo *root,
 		 */
 		if (PATH_PARAM_BY_REL(cheapest_total_outer, innerrel) ||
 			PATH_PARAM_BY_REL(cheapest_total_inner, outerrel))
+		{
+			list_free(hashclauses);
 			return;
+		}
 
 		/*
 		 * Consider the cheapest startup outer together with the cheapest
@@ -2558,6 +2561,8 @@ hash_inner_and_outer(PlannerInfo *root,
 										  false /* parallel_hash */ );
 		}
 	}
+
+	list_free(hashclauses);
 }
 
 /*
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index b45ac47de7f..a70eacd5fde 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -439,9 +439,9 @@ set_cheapest(RelOptInfo *parent_rel)
  *	  memory consumption.  We dare not try to free the substructure of a Path,
  *	  since much of it may be shared with other Paths or the query tree itself;
  *	  but just recycling discarded Path nodes is a very useful savings in
- *	  a large join tree.  The one exception is a rejected new merge join path
- *	  of this rel, whose clause and pathkey lists are private to it, so we
- *	  free those too.
+ *	  a large join tree.  The one exception is a rejected new merge or hash
+ *	  join path of this rel, whose clause and pathkey lists are private to it,
+ *	  so we free those too.
  *
  *	  As noted in optimizer/README, deleting a previously-accepted Path is
  *	  safe because we know that Paths of this rel cannot yet be referenced
@@ -675,9 +675,10 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
 	else
 	{
 		/*
-		 * Free the lists of a rejected merge join path.  They belong to the
-		 * path alone: create_mergejoin_path() makes copies of them, and
-		 * nothing can have seen a path that never made it into the pathlist.
+		 * Free the lists of a rejected merge or hash join path.  They belong
+		 * to the path alone: create_mergejoin_path() and
+		 * create_hashjoin_path() make copies of them, and nothing can have
+		 * seen a path that never made it into the pathlist.
 		 *
 		 * We don't do this for old paths removed from the pathlist above.
 		 * While a path is in the pathlist, other code may make a shallow copy
@@ -704,6 +705,12 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
 				list_free(mjpath->outersortkeys);
 				list_free(mjpath->jpath.path.pathkeys);
 			}
+			else if (IsA(new_path, HashPath))
+			{
+				HashPath   *hjpath = (HashPath *) new_path;
+
+				list_free(hjpath->path_hashclauses);
+			}
 		}
 
 		/* Reject and recycle the new path, if it's safe */
@@ -960,8 +967,8 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 	{
 		/*
 		 * Reject and recycle the new path, if it's safe; see header comment.
-		 * As in add_path, free the lists of a merge join path too; see the
-		 * comments there.
+		 * As in add_path, free the lists of a merge or hash join path too;
+		 * see the comments there.
 		 */
 		if (new_path->parent == parent_rel)
 		{
@@ -974,6 +981,12 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 				list_free(mjpath->outersortkeys);
 				list_free(mjpath->jpath.path.pathkeys);
 			}
+			else if (IsA(new_path, HashPath))
+			{
+				HashPath   *hjpath = (HashPath *) new_path;
+
+				list_free(hjpath->path_hashclauses);
+			}
 
 			pfree(new_path);
 		}
@@ -2652,7 +2665,7 @@ create_hashjoin_path(PlannerInfo *root,
 	pathnode->jpath.outerjoinpath = outer_path;
 	pathnode->jpath.innerjoinpath = inner_path;
 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
-	pathnode->path_hashclauses = hashclauses;
+	pathnode->path_hashclauses = list_copy(hashclauses);
 	/* final_cost_hashjoin will fill in pathnode->num_batches */
 
 	final_cost_hashjoin(root, pathnode, workspace, extra);
-- 
2.56.1

From 08b280f1a7e36c9952d859f024b198c0ea99c6c0 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 10 Nov 2026 11:39:53 -0500
Subject: [PATCH v1 07/10] EXISTS: Free the attribute set built by
 examine_simple_variable

examine_simple_variable() builds a single-member Bitmapset to pass to
all_rows_selectable(), and never frees it.  That happens for every
examine_variable() call on a column with statistics, including the calls
estimate_num_groups() makes for every Memoize path considered.  Free the
set after the call.

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

Reproducer: reproducers/17-free-acl-check-attnos.sql
---
 reproducers/17-free-acl-check-attnos.sql | 104 +++++++++++++++++++++++
 src/backend/utils/adt/selfuncs.c         |   9 +-
 2 files changed, 110 insertions(+), 3 deletions(-)
 create mode 100644 reproducers/17-free-acl-check-attnos.sql

diff --git a/reproducers/17-free-acl-check-attnos.sql b/reproducers/17-free-acl-check-attnos.sql
new file mode 100644
index 00000000000..a16e1ec0e86
--- /dev/null
+++ b/reproducers/17-free-acl-check-attnos.sql
@@ -0,0 +1,104 @@
+-- Reproducer for commit "Free the attribute set built by examine_simple_variable"
+--
+-- examine_simple_variable() builds a single-member Bitmapset to pass to
+-- all_rows_selectable(), and never frees it.  That happens for every
+-- examine_variable() call on a column with statistics, including the ones
+-- estimate_num_groups() makes for every Memoize path considered
+-- (cost_memoize_rescan).  This frees the set after the call.
+--
+-- 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/17-free-acl-check-attnos.sql
+--
+-- The tables are created in schema repro_17, 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   26178      33057
+--   this commit     20702      24865   (-20.9% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_17 CASCADE;
+CREATE SCHEMA repro_17;
+SET search_path = repro_17;
+
+-- 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 3446c4947fc..60e0d8dea03 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -6094,6 +6094,8 @@ examine_simple_variable(PlannerInfo *root, Var *var,
 
 		if (HeapTupleIsValid(vardata->statsTuple))
 		{
+			Bitmapset  *varattnos;
+
 			/*
 			 * Test if user has permission to read all rows from this column.
 			 *
@@ -6105,9 +6107,10 @@ examine_simple_variable(PlannerInfo *root, Var *var,
 			 * user doesn't have permission to see --- see
 			 * statistic_proc_security_check().
 			 */
-			vardata->acl_ok =
-				all_rows_selectable(root, var->varno,
-									bms_make_singleton(var->varattno - FirstLowInvalidHeapAttributeNumber));
+			varattnos = bms_make_singleton(var->varattno -
+										   FirstLowInvalidHeapAttributeNumber);
+			vardata->acl_ok = all_rows_selectable(root, var->varno, varattnos);
+			bms_free(varattnos);
 		}
 		else
 		{
-- 
2.56.1

From 9c38bc9ceb3b7189b0eccb51545ceedd79f7d51c Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
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

From 9fc7160fa0bf299e5a5d4c255d39c98344ab81d4 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 10 Nov 2026 12:04:36 -0500
Subject: [PATCH v1 09/10] ECCHAIN: Free outerkeys and merge_pathkeys in
 sort_inner_and_outer

sort_inner_and_outer() freed the outer sort keys only when the list was
not also used as the join's output pathkeys, and it never freed the
output pathkeys.  But create_mergejoin_path() copies all the lists it is
given, so neither list is referenced by the new path.  build_join_pathkeys()
returns the outer sort keys unchanged when all of them are useful for the
join rel, which is the case whenever the merge key is shared with
relations outside the join, e.g. when many tables are joined on the same
column.  So the list was leaked for most join pairs of such queries.

Free the output pathkeys when they are a separate list, and always free
the outer sort keys.

When joining 10 tables on the same column, planning memory goes from
8558 kB to 4621 kB (-46%).

Reproducer: reproducers/27-free-sort-inner-outer-keys.sql
---
 reproducers/27-free-sort-inner-outer-keys.sql | 81 +++++++++++++++++++
 src/backend/optimizer/path/joinpath.c         |  6 +-
 2 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 reproducers/27-free-sort-inner-outer-keys.sql

diff --git a/reproducers/27-free-sort-inner-outer-keys.sql b/reproducers/27-free-sort-inner-outer-keys.sql
new file mode 100644
index 00000000000..387839a00c8
--- /dev/null
+++ b/reproducers/27-free-sort-inner-outer-keys.sql
@@ -0,0 +1,81 @@
+-- Reproducer for commit "Free outerkeys and merge_pathkeys in sort_inner_and_outer"
+--
+-- sort_inner_and_outer() freed the outer sort keys only when the list was
+-- not also used as the join's output pathkeys, and never freed the output
+-- pathkeys.  But create_mergejoin_path() copies all the lists it gets, so
+-- neither list is referenced by the path.  build_join_pathkeys() returns
+-- the outer sort keys unchanged when they are all useful for the join rel,
+-- which is the case whenever the merge key is shared with relations
+-- outside the join, e.g. when many tables are joined on the same column.
+--
+-- Query: 10 tables joined on the same column, so all the join clauses
+-- belong to a single equivalence class.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/27-free-sort-inner-outer-keys.sql
+--
+-- The tables are created in schema repro_27, 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    8558      16448
+--   this commit      4621       8256   (-46.0% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_27 CASCADE;
+CREATE SCHEMA repro_27;
+SET search_path = repro_27;
+
+-- Ten tables t1 .. t10 (1000 rows each), with an index on column a.
+DO $$
+BEGIN
+    FOR i IN 1..10 LOOP
+        EXECUTE format('CREATE TABLE t%s (a int, b int)', i);
+        EXECUTE format('INSERT INTO t%s SELECT g, g FROM generate_series(1, 1000) g', i);
+        EXECUTE format('CREATE INDEX ON t%s (a)', i);
+    END LOOP;
+END
+$$;
+ANALYZE t1, t2, t3, t4, t5, t6, t7, t8, t9, t10;
+
+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 t1
+  JOIN t2 ON t1.a = t2.a
+  JOIN t3 ON t2.a = t3.a
+  JOIN t4 ON t3.a = t4.a
+  JOIN t5 ON t4.a = t5.a
+  JOIN t6 ON t5.a = t6.a
+  JOIN t7 ON t6.a = t7.a
+  JOIN t8 ON t7.a = t8.a
+  JOIN t9 ON t8.a = t9.a
+  JOIN t10 ON t9.a = t10.a
+$q$);
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index 5a4c7587eb1..0b610beb475 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -1737,8 +1737,10 @@ sort_inner_and_outer(PlannerInfo *root,
 		list_free(cur_mergeclauses);
 		list_free(innerkeys);
 
-		if ((outerkeys != merge_pathkeys) && (innerkeys != merge_pathkeys))
-			list_free(outerkeys);
+		/* build_join_pathkeys() may have returned outerkeys itself */
+		if (merge_pathkeys != outerkeys)
+			list_free(merge_pathkeys);
+		list_free(outerkeys);
 	}
 
 	list_free(all_pathkeys);
-- 
2.56.1

From 21ec7ea636055c5fb7ce7ad8a6cf6eaddfb4be48 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 9 Jun 2026 00:11:47 +0200
Subject: [PATCH v1 10/10] EXISTS: Free temporary lists in
 get_joinrel_parampathinfo

get_joinrel_parampathinfo() is called for every parameterized join
path, and leaked the lists of EC-derived join clauses and dropped ECs.
Free them, and also the per-EC sublists in
generate_join_implied_equalities_for_ecs().

This only affects queries with parameterized join paths.  On a
correlated semijoin against a 13-way join, planning memory goes from
226700 kB to 222956 kB (-1.7%).

Reproducer: reproducers/02-joinrel-parampathinfo-lists.sql
---
 .../02-joinrel-parampathinfo-lists.sql        | 106 ++++++++++++++++++
 src/backend/optimizer/path/equivclass.c       |   1 +
 src/backend/optimizer/util/relnode.c          |   5 +
 3 files changed, 112 insertions(+)
 create mode 100644 reproducers/02-joinrel-parampathinfo-lists.sql

diff --git a/reproducers/02-joinrel-parampathinfo-lists.sql b/reproducers/02-joinrel-parampathinfo-lists.sql
new file mode 100644
index 00000000000..b6cad886f42
--- /dev/null
+++ b/reproducers/02-joinrel-parampathinfo-lists.sql
@@ -0,0 +1,106 @@
+-- Reproducer for commit "Free temporary lists in get_joinrel_parampathinfo"
+--
+-- get_joinrel_parampathinfo() runs for every parameterized join path, and
+-- leaked the lists of EC-derived clauses and dropped ECs it builds.  The
+-- commit also frees the per-EC sublists in
+-- generate_join_implied_equalities_for_ecs().  This only matters for queries
+-- producing parameterized join paths (outer joins, semijoins, lateral
+-- references), so the reproducer uses a correlated semijoin.  With plain
+-- inner joins (e.g. the star join from 01) there is no difference.
+--
+-- 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/02-joinrel-parampathinfo-lists.sql
+--
+-- The tables are created in schema repro_02, 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  226700     229665
+--   this commit    222956     229665   (-1.7% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_02 CASCADE;
+CREATE SCHEMA repro_02;
+SET search_path = repro_02;
+
+-- 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/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index e91a5d99fc1..ca2e4b78dd4 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -1713,6 +1713,7 @@ generate_join_implied_equalities_for_ecs(PlannerInfo *root,
 															  inner_rel);
 
 		result = list_concat(result, sublist);
+		list_free(sublist);
 	}
 
 	return result;
diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c
index b6179992453..728574ccd50 100644
--- a/src/backend/optimizer/util/relnode.c
+++ b/src/backend/optimizer/util/relnode.c
@@ -2014,6 +2014,8 @@ get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel,
 		pclauses = lappend(pclauses, rinfo);
 	}
 
+	list_free(eclauses);
+
 	/*
 	 * EquivalenceClasses are harder to deal with than we could wish, because
 	 * of the fact that a given EC can generate different clauses depending on
@@ -2077,6 +2079,9 @@ get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel,
 				continue;		/* drop if already accepted */
 			pclauses = lappend(pclauses, rinfo);
 		}
+
+		list_free(dropped_ecs);
+		list_free(eclauses);
 	}
 
 	/*
-- 
2.56.1

Reply via email to