From 21679016e7c37cf0402b92054c4deee0672f7f35 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Wed, 2 Dec 2026 17:46:18 +0100
Subject: [PATCH v1 1/2] PWJ: Free unused Material and Memoize paths in
 consider_parallel_nestloop

consider_parallel_nestloop() builds a MaterialPath for the cheapest
inner path, and a MemoizePath with its own cache key lists for each
pair of outer partial path and parameterized inner path.  When the
partial nestloop path using them is rejected, nothing references them
any more, but they were never freed.  match_unsorted_outer() already
frees them for regular nestloop paths.

Make add_partial_path() return whether the new path was accepted, like
add_path() does, and have try_partial_nestloop_path() pass that on, so
that consider_parallel_nestloop() can free the rejected inner paths the
same way.  While at it, fix the add_path() header comment, which still
said it returns nothing.

This matters mostly for partitionwise joins, which plan each pair of
child relations separately.  With 6 hash-partitioned tables (8
partitions each) joined on the partition key, planning memory goes from
10249 kB to 6099 kB (-40.5%).  With 100 partitions each, it goes from
122872 kB to 76176 kB (-38.0%), and with 1000 partitions each, from
1940172 kB to 1477266 kB (-23.9%).
---
 .../29-free-parallel-nestloop-inner-100.sql   | 89 +++++++++++++++++
 .../29-free-parallel-nestloop-inner-1000.sql  | 96 +++++++++++++++++++
 .../29-free-parallel-nestloop-inner.sql       | 85 ++++++++++++++++
 src/backend/optimizer/path/joinpath.c         | 55 +++++++----
 src/backend/optimizer/util/pathnode.c         | 10 +-
 src/include/optimizer/pathnode.h              |  2 +-
 6 files changed, 313 insertions(+), 24 deletions(-)
 create mode 100644 reproducers/29-free-parallel-nestloop-inner-100.sql
 create mode 100644 reproducers/29-free-parallel-nestloop-inner-1000.sql
 create mode 100644 reproducers/29-free-parallel-nestloop-inner.sql

diff --git a/reproducers/29-free-parallel-nestloop-inner-100.sql b/reproducers/29-free-parallel-nestloop-inner-100.sql
new file mode 100644
index 00000000000..48b65a4ff59
--- /dev/null
+++ b/reproducers/29-free-parallel-nestloop-inner-100.sql
@@ -0,0 +1,89 @@
+-- Reproducer for commit "Free unused Material and Memoize paths in consider_parallel_nestloop"
+--
+-- consider_parallel_nestloop() builds a MaterialPath once for the cheapest
+-- inner path, and a MemoizePath (with its own cache key lists) for every
+-- pair of outer partial path and parameterized inner path.  When the
+-- resulting partial nestloop is rejected, these are never referenced and
+-- were leaked.  match_unsorted_outer() frees them already; do the same for
+-- partial paths, by making add_partial_path() and try_partial_nestloop_path()
+-- report whether the path was accepted.  This matters for partitionwise
+-- joins, which plan every child join pair separately.
+--
+-- Query: 6 hash-partitioned tables (100 partitions each) joined on the
+-- partition key, with enable_partitionwise_join = on.
+--
+-- This is a larger variant of 29-free-parallel-nestloop-inner.sql, which
+-- uses 8 partitions per table, to show how the savings scale with the
+-- number of partitions.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/29-free-parallel-nestloop-inner-100.sql
+--
+-- The tables are created in schema repro_29_100, 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  122872     123401
+--   this commit     76176      82441   (-38.0% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_29_100 CASCADE;
+CREATE SCHEMA repro_29_100;
+SET search_path = repro_29_100;
+
+-- Six tables p1 .. p6 (10000 rows each), hash-partitioned on column k into
+-- 100 partitions, with an index on k.
+DO $$
+BEGIN
+    FOR i IN 1..6 LOOP
+        EXECUTE format('CREATE TABLE p%s (k int, v int) PARTITION BY HASH (k)', i);
+        FOR j IN 0..99 LOOP
+            EXECUTE format('CREATE TABLE p%s_%s PARTITION OF p%s '
+                           'FOR VALUES WITH (MODULUS 100, REMAINDER %s)', i, j, i, j);
+        END LOOP;
+        EXECUTE format('INSERT INTO p%s SELECT g, g FROM generate_series(1, 10000) g', i);
+        EXECUTE format('CREATE INDEX ON p%s (k)', i);
+        EXECUTE format('ANALYZE p%s', i);
+    END LOOP;
+END
+$$;
+
+SET enable_partitionwise_join = on;
+
+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 p1
+  JOIN p2 ON p1.k = p2.k
+  JOIN p3 ON p2.k = p3.k
+  JOIN p4 ON p3.k = p4.k
+  JOIN p5 ON p4.k = p5.k
+  JOIN p6 ON p5.k = p6.k
+$q$);
diff --git a/reproducers/29-free-parallel-nestloop-inner-1000.sql b/reproducers/29-free-parallel-nestloop-inner-1000.sql
new file mode 100644
index 00000000000..ef6ee349df5
--- /dev/null
+++ b/reproducers/29-free-parallel-nestloop-inner-1000.sql
@@ -0,0 +1,96 @@
+-- Reproducer for commit "Free unused Material and Memoize paths in consider_parallel_nestloop"
+--
+-- consider_parallel_nestloop() builds a MaterialPath once for the cheapest
+-- inner path, and a MemoizePath (with its own cache key lists) for every
+-- pair of outer partial path and parameterized inner path.  When the
+-- resulting partial nestloop is rejected, these are never referenced and
+-- were leaked.  match_unsorted_outer() frees them already; do the same for
+-- partial paths, by making add_partial_path() and try_partial_nestloop_path()
+-- report whether the path was accepted.  This matters for partitionwise
+-- joins, which plan every child join pair separately.
+--
+-- Query: 6 hash-partitioned tables (1000 partitions each) joined on the
+-- partition key, with enable_partitionwise_join = on.
+--
+-- This is a larger variant of 29-free-parallel-nestloop-inner.sql, which
+-- uses 8 partitions per table, to show how the savings scale with the
+-- number of partitions.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/29-free-parallel-nestloop-inner-1000.sql
+--
+-- The tables are created in schema repro_29_1000, 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.
+--
+-- Creating the tables locks about 18000 objects (partitions, indexes and
+-- row types) in a single transaction, and dropping them about 24000.  The
+-- lock table is too small for that with the default settings ("out of
+-- shared memory"), so set max_locks_per_transaction = 256 and restart the
+-- server before running this.  Planning takes about 8 seconds, and as much
+-- memory as reported below (up to 2 GB).
+--
+-- Planning memory in kB, measured on builds without assertions
+-- (meson buildtype=debugoptimized):
+--
+--                    used  allocated
+--   parent commit 1940172    1949491
+--   this commit   1477266    1482547   (-23.9% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_29_1000 CASCADE;
+CREATE SCHEMA repro_29_1000;
+SET search_path = repro_29_1000;
+
+-- Six tables p1 .. p6 (10000 rows each), hash-partitioned on column k into
+-- 1000 partitions, with an index on k.
+DO $$
+BEGIN
+    FOR i IN 1..6 LOOP
+        EXECUTE format('CREATE TABLE p%s (k int, v int) PARTITION BY HASH (k)', i);
+        FOR j IN 0..999 LOOP
+            EXECUTE format('CREATE TABLE p%s_%s PARTITION OF p%s '
+                           'FOR VALUES WITH (MODULUS 1000, REMAINDER %s)', i, j, i, j);
+        END LOOP;
+        EXECUTE format('INSERT INTO p%s SELECT g, g FROM generate_series(1, 10000) g', i);
+        EXECUTE format('CREATE INDEX ON p%s (k)', i);
+        EXECUTE format('ANALYZE p%s', i);
+    END LOOP;
+END
+$$;
+
+SET enable_partitionwise_join = on;
+
+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 p1
+  JOIN p2 ON p1.k = p2.k
+  JOIN p3 ON p2.k = p3.k
+  JOIN p4 ON p3.k = p4.k
+  JOIN p5 ON p4.k = p5.k
+  JOIN p6 ON p5.k = p6.k
+$q$);
diff --git a/reproducers/29-free-parallel-nestloop-inner.sql b/reproducers/29-free-parallel-nestloop-inner.sql
new file mode 100644
index 00000000000..5f8677fd2be
--- /dev/null
+++ b/reproducers/29-free-parallel-nestloop-inner.sql
@@ -0,0 +1,85 @@
+-- Reproducer for commit "Free unused Material and Memoize paths in consider_parallel_nestloop"
+--
+-- consider_parallel_nestloop() builds a MaterialPath once for the cheapest
+-- inner path, and a MemoizePath (with its own cache key lists) for every
+-- pair of outer partial path and parameterized inner path.  When the
+-- resulting partial nestloop is rejected, these are never referenced and
+-- were leaked.  match_unsorted_outer() frees them already; do the same for
+-- partial paths, by making add_partial_path() and try_partial_nestloop_path()
+-- report whether the path was accepted.  This matters for partitionwise
+-- joins, which plan every child join pair separately.
+--
+-- Query: 6 hash-partitioned tables (8 partitions each) joined on the
+-- partition key, with enable_partitionwise_join = on.
+--
+-- Run it on a build of the parent commit and of this commit, and compare
+-- the reported planning memory:
+--
+--   psql -X -f reproducers/29-free-parallel-nestloop-inner.sql
+--
+-- The tables are created in schema repro_29, 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   10249      16445
+--   this commit      6099       8253   (-40.5% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_29 CASCADE;
+CREATE SCHEMA repro_29;
+SET search_path = repro_29;
+
+-- Six tables p1 .. p6 (10000 rows each), hash-partitioned on column k into 8
+-- partitions, with an index on k.
+DO $$
+BEGIN
+    FOR i IN 1..6 LOOP
+        EXECUTE format('CREATE TABLE p%s (k int, v int) PARTITION BY HASH (k)', i);
+        FOR j IN 0..7 LOOP
+            EXECUTE format('CREATE TABLE p%s_%s PARTITION OF p%s '
+                           'FOR VALUES WITH (MODULUS 8, REMAINDER %s)', i, j, i, j);
+        END LOOP;
+        EXECUTE format('INSERT INTO p%s SELECT g, g FROM generate_series(1, 10000) g', i);
+        EXECUTE format('CREATE INDEX ON p%s (k)', i);
+        EXECUTE format('ANALYZE p%s', i);
+    END LOOP;
+END
+$$;
+
+SET enable_partitionwise_join = on;
+
+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 p1
+  JOIN p2 ON p1.k = p2.k
+  JOIN p3 ON p2.k = p3.k
+  JOIN p4 ON p3.k = p4.k
+  JOIN p5 ON p4.k = p5.k
+  JOIN p6 ON p5.k = p6.k
+$q$);
diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index beb2856dd21..16be028f697 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -1148,8 +1148,10 @@ try_nestloop_path(PlannerInfo *root,
  * try_partial_nestloop_path
  *	  Consider a partial nestloop join path; if it appears useful, push it into
  *	  the joinrel's partial_pathlist via add_partial_path().
+ *
+ * Returns true if the path was added to the partial_pathlist.
  */
-static void
+static bool
 try_partial_nestloop_path(PlannerInfo *root,
 						  RelOptInfo *joinrel,
 						  Path *outer_path,
@@ -1186,7 +1188,7 @@ try_partial_nestloop_path(PlannerInfo *root,
 			outerrelids = outerrel->relids;
 
 		if (!bms_is_subset(inner_paramrels, outerrelids))
-			return;
+			return false;
 	}
 
 	/*
@@ -1198,7 +1200,7 @@ try_partial_nestloop_path(PlannerInfo *root,
 	 */
 	if (PATH_PARAM_BY_PARENT(inner_path, outer_path->parent) &&
 		!path_is_reparameterizable_by_child(inner_path, outer_path->parent))
-		return;
+		return false;
 
 	/*
 	 * Before creating a path, get a quick lower bound on what it is likely to
@@ -1209,20 +1211,20 @@ try_partial_nestloop_path(PlannerInfo *root,
 	if (!add_partial_path_precheck(joinrel, workspace.disabled_nodes,
 								   workspace.startup_cost,
 								   workspace.total_cost, pathkeys))
-		return;
+		return false;
 
 	/* Might be good enough to be worth trying, so let's try it. */
-	add_partial_path(joinrel, (Path *)
-					 create_nestloop_path(root,
-										  joinrel,
-										  jointype,
-										  &workspace,
-										  extra,
-										  outer_path,
-										  inner_path,
-										  extra->restrictlist,
-										  pathkeys,
-										  NULL));
+	return add_partial_path(joinrel, (Path *)
+							create_nestloop_path(root,
+												 joinrel,
+												 jointype,
+												 &workspace,
+												 extra,
+												 outer_path,
+												 inner_path,
+												 extra->restrictlist,
+												 pathkeys,
+												 NULL));
 }
 
 /*
@@ -2260,6 +2262,7 @@ consider_parallel_nestloop(PlannerInfo *root,
 {
 	Path	   *inner_cheapest_total = innerrel->cheapest_total_path;
 	Path	   *matpath = NULL;
+	bool		matused = false;
 	ListCell   *lc1;
 
 	/*
@@ -2314,18 +2317,28 @@ consider_parallel_nestloop(PlannerInfo *root,
 			mpath = get_memoize_path(root, innerrel, outerrel,
 									 innerpath, outerpath, jointype,
 									 extra);
-			if (mpath != NULL)
-				try_partial_nestloop_path(root, joinrel, outerpath, mpath,
-										  pathkeys, jointype,
-										  PGS_NESTLOOP_MEMOIZE, extra);
+			if (mpath != NULL &&
+				!try_partial_nestloop_path(root, joinrel, outerpath, mpath,
+										   pathkeys, jointype,
+										   PGS_NESTLOOP_MEMOIZE, extra))
+			{
+				/* The cache key lists were built just for this path */
+				list_free(((MemoizePath *) mpath)->param_exprs);
+				list_free(((MemoizePath *) mpath)->hash_operators);
+				pfree(mpath);
+			}
 		}
 
 		/* Also consider materialized form of the cheapest inner path */
-		if (matpath != NULL)
+		if (matpath != NULL &&
 			try_partial_nestloop_path(root, joinrel, outerpath, matpath,
 									  pathkeys, jointype,
-									  PGS_NESTLOOP_MATERIALIZE, extra);
+									  PGS_NESTLOOP_MATERIALIZE, extra))
+			matused = true;
 	}
+
+	if (matpath != NULL && !matused)
+		pfree(matpath);
 }
 
 /*
diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index 5f28174a5fa..43d21245164 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -463,7 +463,8 @@ set_cheapest(RelOptInfo *parent_rel)
  * 'parent_rel' is the relation entry to which the path corresponds.
  * 'new_path' is a potential path for parent_rel.
  *
- * Returns nothing, but modifies parent_rel->pathlist.
+ * Returns true if new_path was added to parent_rel->pathlist, false if it
+ * was rejected (and freed).
  */
 void
 add_path(RelOptInfo *parent_rel, Path *new_path)
@@ -807,8 +808,11 @@ add_path_precheck(RelOptInfo *parent_rel, int disabled_nodes,
  *	  levels).  In that usage there are edge cases where add_path can keep a
  *	  Gather while add_partial_path will reject its underlying partial path,
  *	  so that if we pfree the partial path we'll have a broken Gather path.
+ *
+ *	  Returns true if new_path was added to parent_rel->partial_pathlist,
+ *	  false if it was rejected (and freed).
  */
-void
+bool
 add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 {
 	bool		accept_new = true;	/* unless we find a superior old path */
@@ -919,6 +923,8 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 		if (new_path->parent == parent_rel)
 			pfree(new_path);
 	}
+
+	return accept_new;
 }
 
 /*
diff --git a/src/include/optimizer/pathnode.h b/src/include/optimizer/pathnode.h
index e74a95d0d22..2c8d5707ead 100644
--- a/src/include/optimizer/pathnode.h
+++ b/src/include/optimizer/pathnode.h
@@ -59,7 +59,7 @@ extern void add_path(RelOptInfo *parent_rel, Path *new_path);
 extern bool add_path_precheck(RelOptInfo *parent_rel, int disabled_nodes,
 							  Cost startup_cost, Cost total_cost,
 							  List *pathkeys, Relids required_outer);
-extern void add_partial_path(RelOptInfo *parent_rel, Path *new_path);
+extern bool add_partial_path(RelOptInfo *parent_rel, Path *new_path);
 extern bool add_partial_path_precheck(RelOptInfo *parent_rel,
 									  int disabled_nodes, Cost startup_cost,
 									  Cost total_cost, List *pathkeys);
-- 
2.56.1

