From e28f38731cea5f5a3258920cbc6b59a48f9e39e6 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
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

