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

