Hi,

Here's the final part of my work on reducing memory used by the planner,
focused on the partition-wise join. The patches are a bit more complex,
so I've kept it intentionally short with just 2 patches. I have a couple
more patches targeting PWJ, but the improvements are comparatively
smaller so let's not get distracted by those for now.

Each patch has a set of reproducers (in reproducers/ directory), joining
tables with 10, 100 and 1000 partitions. The reproducers are really the
same, I've kept copies to that the patches may be applied independently.

So the patches are meant to improve the same query shape - joins of
partitioned tables, with partition-wise join enabled. But they aim at
different parts of the planning, wasting memory in different ways.

Admittedly, the reproducers are a bit extreme (particularly the one with
1000 partitions). Joining 6 tables with the same partitioning scheme may
not be particularly common. It's meant to demonstrate the memory usage,
and I think the issue is valid and affecting even smaller cases.

The commit messages also include some basic numbers, illustrating the
impact of each patch - how much memory is saved, etc.


1) v1-0001-PWJ-Free-unused-Material-and-Memoize-paths-in-con.patch
----------

The planner tends to not relese memory, relying on memory contexts to do
the cleanup later. This applies to paths in most places - the path is
constructed, passed to add_(partial_)path, and then left behind as it's
not known if the path was added to the pathlist or not.

That's usually OK, but with a partition-wise join the number of such
paths explodes, as it forms joins of individual partitions. This is
particularly visible in try_partial_nestloop_path(), which constructs
Material/Memoize paths for the per-partition joins, and leaves them
allocated. In the reproducer with 1000 partitions, this is be hundreds
of megabytes worth of memory.

The patch adjusts add_partial_path() to indicate whether the path was
added or not, and uses that to free the Material/Memoize paths when
possible.

In a way, this is a partition-wise variant of the patch from [2].


2) v1-0002-PWJ-Reuse-RestrictInfos-translated-for-partitionw.patch
----------

An rather expensive part of the partition-wise join is translating the
RestrictInfo lists from the parent to child joins. Which happens in
try_partitionwise_join(), and it needs to happen at some point - but the
current code translates the same RestrictInfo multiple times when
considering joins in different orders.

Consider two joins

 * p1 joined to p2
 * p1 joined to (p2 JOIN p3)

and a join clause "p1.k = p2.k". It'll be translated twice (for each
partition), once for each considered join order. But the results are
necessarily exactly the same, of course. This wastes both memory and CPU
time.

The reproducer joins the relations on the same column, which means there
will be one large EC for all the join clauses. That probably is not a
supper common join pattern, but it's also is not all that rare.

I've seen this pattern in OLTP all the time - "base" table, and then
tables with additional details for the entries (example: table with
basic info about payments, and then tables with additional info about
different payment types). That's mostly OLTP without partitioning, but
similar schemas can be used in OLAP world too.

However, this effort is partially motivated by better handling of worst
cases, so that even rare query shapes don't risk triggering OOM. So even
if it doesn't improve the "normal" case very much.

Anyway, the patch improves this in a simple way - the translated rinfos
are kept in a hash table, and try_partitionwise_join tries to reuse the
already translated rinfos (with key being parent_rinfo + child relids).


Evaluation
----------

Here's a brief evaluation, showing the impact of the two patches. The
numbers are memory usage in kB, per EXPLAIN (MEMORY), for the reproducer
(same for both patches), with 10, 100 and 1000 partitions:

          master      0001      0002
  ------------------------------------
     10     27388     22993     19826
    100    322697    273254    228827
   1000   4200413   3710277   2823449

That's ~40% reduction, which is not bad. It still uses a lot of memory,
of course. This is not sufficient to make PWJ free, of course. But the
patches do combine with the patches shared in the two other batches,
with the total saving ~50-60%. (And I have a couple more experimental
patches, that bring the total to ~80-90% reduction.)


regards

[1]
https://www.postgresql.org/message-id/f3e94bfa-340c-4b51-9c63-1a5cb57aa27b%40vondra.me

[2]
https://www.postgresql.org/message-id/8035c306-a74b-42ab-bccd-8331b53df300%40vondra.me

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

From be32824f85ea7edabcf27ea3c2b90ed57e2cb0a4 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Wed, 2 Dec 2026 17:47:05 +0100
Subject: [PATCH v1 2/2] PWJ: Reuse RestrictInfos translated for partitionwise
 child joins

try_partitionwise_join() translates the restrictlist of each pair of
parent relations it joins into a restrictlist for each pair of child
relations, and build_child_join_rel() similarly translates the joininfo
list of the parent join relation.  A parent RestrictInfo is shared by
all the join relations using it, e.g. a join clause derived from an
EquivalenceClass is used for every join order joining the relations it
references.  So the same clause got translated many times for the same
child relations, each time producing an identical copy, which then
computed and cached its own selectivity and cost estimates.  With
partitionwise joins of many partitioned tables, these copies use more
planning memory than anything else.

Add adjust_appendrel_restrictlist(), which keeps the translated
RestrictInfos in a hash table in PlannerInfo, and returns the existing
child RestrictInfo when the same translation is needed again.  The hash
key is the parent RestrictInfo plus the child relids of the
AppendRelInfos the translation actually uses, as determined by a new
walker, which has to be kept in sync with
adjust_appendrel_attrs_mutator().  Keying by the relids of the child
join instead would be much less effective, because the same clause is
used by joins of many different sets of relations.

The child joins now share child RestrictInfos, including the estimates
cached in them, in the same way the parent joins share the parent
RestrictInfos.  GEQO uses a separate hash table for each tour, as it
does for join_rel_hash, because the child RestrictInfos built during a
tour are freed at its end.

With 6 hash-partitioned tables (8 partitions each) joined on the
partition key, planning memory goes from 4770 kB to 3014 kB (-36.8%).
With 100 partitions each, it goes from 64593 kB to 37806 kB (-41.5%),
and with 1000 partitions each, from 1350676 kB to 633144 kB (-53.1%),
while planning time drops from about 7.8 s to 4.3 s.  The plans do not
change.
---
 .../36-reuse-child-restrictinfos-100.sql      |  92 ++++++
 .../36-reuse-child-restrictinfos-1000.sql     |  99 +++++++
 reproducers/36-reuse-child-restrictinfos.sql  |  88 ++++++
 src/backend/optimizer/geqo/geqo_eval.c        |   9 +-
 src/backend/optimizer/path/allpaths.c         |   7 +-
 src/backend/optimizer/path/joinrels.c         |   8 +-
 src/backend/optimizer/plan/planmain.c         |   1 +
 src/backend/optimizer/util/appendinfo.c       | 268 ++++++++++++++++++
 src/backend/optimizer/util/relnode.c          |   8 +-
 src/include/nodes/pathnodes.h                 |   7 +
 src/include/optimizer/appendinfo.h            |   4 +
 src/tools/pgindent/typedefs.list              |   3 +
 12 files changed, 582 insertions(+), 12 deletions(-)
 create mode 100644 reproducers/36-reuse-child-restrictinfos-100.sql
 create mode 100644 reproducers/36-reuse-child-restrictinfos-1000.sql
 create mode 100644 reproducers/36-reuse-child-restrictinfos.sql

diff --git a/reproducers/36-reuse-child-restrictinfos-100.sql b/reproducers/36-reuse-child-restrictinfos-100.sql
new file mode 100644
index 00000000000..752bc7f81ec
--- /dev/null
+++ b/reproducers/36-reuse-child-restrictinfos-100.sql
@@ -0,0 +1,92 @@
+-- Reproducer for commit "Reuse RestrictInfos translated for partitionwise child joins"
+--
+-- try_partitionwise_join() translates the restrictlist of each pair of parent
+-- relations into a restrictlist for each pair of child relations, and
+-- build_child_join_rel() translates the joininfo list of the parent join
+-- relation.  A parent RestrictInfo is shared by all the joins using it, so
+-- the same clause was translated over and over for the same child relations,
+-- each time producing an identical copy (with its own cached selectivity and
+-- cost estimates, computed again).
+--
+-- Remember the translated RestrictInfos in a hash table, keyed by the parent
+-- RestrictInfo and the child relids of the AppendRelInfos the translation
+-- uses, and reuse them for all child joins needing the same translation.
+--
+-- Query: 6 hash-partitioned tables (100 partitions each) joined on the
+-- partition key, with enable_partitionwise_join = on.
+--
+-- This is a larger variant of 36-reuse-child-restrictinfos.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/36-reuse-child-restrictinfos-100.sql
+--
+-- The tables are created in schema repro_36_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   64593      66057
+--   this commit     37806      41609   (-41.5% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_36_100 CASCADE;
+CREATE SCHEMA repro_36_100;
+SET search_path = repro_36_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/36-reuse-child-restrictinfos-1000.sql b/reproducers/36-reuse-child-restrictinfos-1000.sql
new file mode 100644
index 00000000000..ad2259c665c
--- /dev/null
+++ b/reproducers/36-reuse-child-restrictinfos-1000.sql
@@ -0,0 +1,99 @@
+-- Reproducer for commit "Reuse RestrictInfos translated for partitionwise child joins"
+--
+-- try_partitionwise_join() translates the restrictlist of each pair of parent
+-- relations into a restrictlist for each pair of child relations, and
+-- build_child_join_rel() translates the joininfo list of the parent join
+-- relation.  A parent RestrictInfo is shared by all the joins using it, so
+-- the same clause was translated over and over for the same child relations,
+-- each time producing an identical copy (with its own cached selectivity and
+-- cost estimates, computed again).
+--
+-- Remember the translated RestrictInfos in a hash table, keyed by the parent
+-- RestrictInfo and the child relids of the AppendRelInfos the translation
+-- uses, and reuse them for all child joins needing the same translation.
+--
+-- Query: 6 hash-partitioned tables (1000 partitions each) joined on the
+-- partition key, with enable_partitionwise_join = on.
+--
+-- This is a larger variant of 36-reuse-child-restrictinfos.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/36-reuse-child-restrictinfos-1000.sql
+--
+-- The tables are created in schema repro_36_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 (4 seconds with this
+-- commit), and as much memory as reported below.
+--
+-- Planning memory in kB, measured on builds without assertions
+-- (meson buildtype=debugoptimized):
+--
+--                    used  allocated
+--   parent commit 1350676    1359667
+--   this commit    633144     639795   (-53.1% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_36_1000 CASCADE;
+CREATE SCHEMA repro_36_1000;
+SET search_path = repro_36_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/36-reuse-child-restrictinfos.sql b/reproducers/36-reuse-child-restrictinfos.sql
new file mode 100644
index 00000000000..3f619e613a7
--- /dev/null
+++ b/reproducers/36-reuse-child-restrictinfos.sql
@@ -0,0 +1,88 @@
+-- Reproducer for commit "Reuse RestrictInfos translated for partitionwise child joins"
+--
+-- try_partitionwise_join() translates the restrictlist of each pair of parent
+-- relations into a restrictlist for each pair of child relations, and
+-- build_child_join_rel() translates the joininfo list of the parent join
+-- relation.  A parent RestrictInfo is shared by all the joins using it, so
+-- the same clause was translated over and over for the same child relations,
+-- each time producing an identical copy (with its own cached selectivity and
+-- cost estimates, computed again).
+--
+-- Remember the translated RestrictInfos in a hash table, keyed by the parent
+-- RestrictInfo and the child relids of the AppendRelInfos the translation
+-- uses, and reuse them for all child joins needing the same translation.
+--
+-- 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/36-reuse-child-restrictinfos.sql
+--
+-- The tables are created in schema repro_36, 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    4770       8253
+--   this commit      3014       4173   (-36.8% used)
+
+\set ON_ERROR_STOP on
+SET client_min_messages = warning;
+DROP SCHEMA IF EXISTS repro_36 CASCADE;
+CREATE SCHEMA repro_36;
+SET search_path = repro_36;
+
+-- 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/geqo/geqo_eval.c b/src/backend/optimizer/geqo/geqo_eval.c
index d7851faa4d5..bf93a2a2043 100644
--- a/src/backend/optimizer/geqo/geqo_eval.c
+++ b/src/backend/optimizer/geqo/geqo_eval.c
@@ -62,6 +62,7 @@ geqo_eval(PlannerInfo *root, Gene *tour, int num_gene)
 	Fitness		fitness;
 	int			savelength;
 	struct HTAB *savehash;
+	struct HTAB *save_child_rinfo_hash;
 
 	/*
 	 * Create a private memory context that will hold all temp storage
@@ -90,13 +91,18 @@ geqo_eval(PlannerInfo *root, Gene *tour, int num_gene)
 	 * (If we are dealing with enough join rels, which we very likely are, a
 	 * new hash table will get built and used locally.)
 	 *
+	 * Likewise for child_rinfo_hash, as the child RestrictInfos added to it
+	 * will be recycled too.
+	 *
 	 * join_rel_level[] shouldn't be in use, so just Assert it isn't.
 	 */
 	savelength = list_length(root->join_rel_list);
 	savehash = root->join_rel_hash;
+	save_child_rinfo_hash = root->child_rinfo_hash;
 	Assert(root->join_rel_level == NULL);
 
 	root->join_rel_hash = NULL;
+	root->child_rinfo_hash = NULL;
 
 	/* construct the best path for the given combination of relations */
 	joinrel = gimme_tree(root, tour, num_gene);
@@ -123,11 +129,12 @@ geqo_eval(PlannerInfo *root, Gene *tour, int num_gene)
 
 	/*
 	 * Restore join_rel_list to its former state, and put back original
-	 * hashtable if any.
+	 * hashtables if any.
 	 */
 	root->join_rel_list = list_truncate(root->join_rel_list,
 										savelength);
 	root->join_rel_hash = savehash;
+	root->child_rinfo_hash = save_child_rinfo_hash;
 
 	/* release all the memory acquired within gimme_tree */
 	MemoryContextSwitchTo(oldcxt);
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index dab387c1666..a54d245a52b 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -3964,9 +3964,10 @@ make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
  * needed for these paths need have been instantiated.
  *
  * Note to plugin authors: the functions invoked during standard_join_search()
- * modify root->join_rel_list and root->join_rel_hash.  If you want to do more
- * than one join-order search, you'll probably need to save and restore the
- * original states of those data structures.  See geqo_eval() for an example.
+ * modify root->join_rel_list, root->join_rel_hash and root->child_rinfo_hash.
+ * If you want to do more than one join-order search, you'll probably need to
+ * save and restore the original states of those data structures.  See
+ * geqo_eval() for an example.
  */
 RelOptInfo *
 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index cf95021db75..ba40f768a33 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -1828,10 +1828,10 @@ try_partitionwise_join(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
 		 * Construct restrictions applicable to the child join from those
 		 * applicable to the parent join.
 		 */
-		child_restrictlist =
-			(List *) adjust_appendrel_attrs(root,
-											(Node *) parent_restrictlist,
-											nappinfos, appinfos);
+		child_restrictlist = adjust_appendrel_restrictlist(root,
+														   parent_restrictlist,
+														   nappinfos,
+														   appinfos);
 
 		/* Find or construct the child join's RelOptInfo */
 		child_joinrel = joinrel->part_rels[cnt_parts];
diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c
index 9045c490486..fa41ca27ded 100644
--- a/src/backend/optimizer/plan/planmain.c
+++ b/src/backend/optimizer/plan/planmain.c
@@ -92,6 +92,7 @@ restart:
 	root->all_query_rels = NULL;
 	root->join_rel_list = NIL;
 	root->join_rel_hash = NULL;
+	root->child_rinfo_hash = NULL;
 	root->join_rel_level = NULL;
 	root->join_cur_level = 0;
 	root->eq_classes = NIL;
diff --git a/src/backend/optimizer/util/appendinfo.c b/src/backend/optimizer/util/appendinfo.c
index ebb74c53d3b..680f348a2bf 100644
--- a/src/backend/optimizer/util/appendinfo.c
+++ b/src/backend/optimizer/util/appendinfo.c
@@ -17,6 +17,7 @@
 #include "access/htup_details.h"
 #include "access/sysattr.h"
 #include "access/table.h"
+#include "common/hashfn.h"
 #include "foreign/fdwapi.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -24,6 +25,7 @@
 #include "optimizer/pathnode.h"
 #include "optimizer/planmain.h"
 #include "parser/parsetree.h"
+#include "utils/hsearch.h"
 #include "utils/lsyscache.h"
 #include "utils/rel.h"
 #include "utils/syscache.h"
@@ -36,12 +38,44 @@ typedef struct
 	AppendRelInfo **appinfos;
 } adjust_appendrel_attrs_context;
 
+typedef struct
+{
+	int			nappinfos;
+	AppendRelInfo **appinfos;
+	bool	   *used;			/* is appinfos[i] needed for the translation? */
+} find_used_appinfos_context;
+
+/*
+ * Hash key and entry of root->child_rinfo_hash.  The key consists of the
+ * parent RestrictInfo, and the child relids of the AppendRelInfos used to
+ * translate it, in the order of the AppendRelInfo array.
+ */
+typedef struct ChildRinfoKey
+{
+	RestrictInfo *parent_rinfo;
+	int			nrelids;
+	Index	   *child_relids;
+} ChildRinfoKey;
+
+typedef struct ChildRinfoEntry
+{
+	ChildRinfoKey key;			/* hash key --- MUST BE FIRST */
+	RestrictInfo *child_rinfo;
+} ChildRinfoEntry;
+
 static void make_inh_translation_list(Relation oldrelation,
 									  Relation newrelation,
 									  Index newvarno,
 									  AppendRelInfo *appinfo);
 static Node *adjust_appendrel_attrs_mutator(Node *node,
 											adjust_appendrel_attrs_context *context);
+static bool find_used_appinfos_walker(Node *node,
+									  find_used_appinfos_context *context);
+static void find_used_appinfos_relids(Relids relids,
+									  find_used_appinfos_context *context);
+static uint32 child_rinfo_key_hash(const void *key, Size keysize);
+static int	child_rinfo_key_match(const void *key1, const void *key2,
+								  Size keysize);
 
 
 /*
@@ -215,6 +249,9 @@ adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos,
 	return adjust_appendrel_attrs_mutator(node, &context);
 }
 
+/*
+ * Note: find_used_appinfos_walker() must consider everything this translates.
+ */
 static Node *
 adjust_appendrel_attrs_mutator(Node *node,
 							   adjust_appendrel_attrs_context *context)
@@ -584,6 +621,237 @@ adjust_appendrel_attrs_mutator(Node *node,
 	return expression_tree_mutator(node, adjust_appendrel_attrs_mutator, context);
 }
 
+/*
+ * adjust_appendrel_restrictlist
+ *	  Translate a list of RestrictInfos like adjust_appendrel_attrs() does,
+ *	  but reuse the RestrictInfos translated earlier where possible.
+ *
+ * Partitionwise join translates the restrictlist of every pair of parent
+ * relations it joins, and the joininfo list of every parent join relation,
+ * for each of the child joins.  The same parent RestrictInfo appears in many
+ * such lists (for example, a clause derived from an EquivalenceClass is used
+ * by all the joins that need it), so it would get translated many times for
+ * the same child relations, each time producing an identical copy.  Instead,
+ * remember the translations in root->child_rinfo_hash, and return the same
+ * child RestrictInfo whenever the parent RestrictInfo needs to be translated
+ * with the same AppendRelInfos again.  The child joins thus share the child
+ * RestrictInfos, including the selectivity and cost estimates cached in them,
+ * in the same way the parent joins share the parent RestrictInfos.
+ *
+ * The hash key is the address of the parent RestrictInfo (RestrictInfos are
+ * not freed during join search, except by GEQO, which uses a separate hash
+ * table for each tour), plus the child relids of the AppendRelInfos actually
+ * used by the translation.  Those are the children of the relations the
+ * clause references, so a child RestrictInfo can be reused for every child
+ * join containing them.
+ *
+ * The returned List is newly built, but the RestrictInfos in it are shared,
+ * so they must not be modified (other than their cached estimates).
+ */
+List *
+adjust_appendrel_restrictlist(PlannerInfo *root, List *restrictlist,
+							  int nappinfos, AppendRelInfo **appinfos)
+{
+	List	   *result = NIL;
+	find_used_appinfos_context context;
+	Index	   *child_relids;
+
+	/* If there's nothing to adjust, don't call this function. */
+	Assert(nappinfos >= 1 && appinfos != NULL);
+
+	if (restrictlist == NIL)
+		return NIL;
+
+	if (root->child_rinfo_hash == NULL)
+	{
+		HASHCTL		hash_ctl;
+
+		hash_ctl.keysize = sizeof(ChildRinfoKey);
+		hash_ctl.entrysize = sizeof(ChildRinfoEntry);
+		hash_ctl.hash = child_rinfo_key_hash;
+		hash_ctl.match = child_rinfo_key_match;
+		hash_ctl.hcxt = CurrentMemoryContext;
+		root->child_rinfo_hash = hash_create("ChildRestrictInfoHashTable",
+											 256L,
+											 &hash_ctl,
+											 HASH_ELEM | HASH_FUNCTION |
+											 HASH_COMPARE | HASH_CONTEXT);
+	}
+
+	context.nappinfos = nappinfos;
+	context.appinfos = appinfos;
+	context.used = palloc_array(bool, nappinfos);
+	child_relids = palloc_array(Index, nappinfos);
+
+	foreach_node(RestrictInfo, rinfo, restrictlist)
+	{
+		ChildRinfoKey key;
+		ChildRinfoEntry *entry;
+		bool		found;
+
+		/* Build the hash key from the AppendRelInfos the translation uses */
+		memset(context.used, 0, nappinfos * sizeof(bool));
+		(void) find_used_appinfos_walker((Node *) rinfo, &context);
+
+		key.parent_rinfo = rinfo;
+		key.nrelids = 0;
+		key.child_relids = child_relids;
+		for (int i = 0; i < nappinfos; i++)
+		{
+			if (context.used[i])
+				child_relids[key.nrelids++] = appinfos[i]->child_relid;
+		}
+
+		entry = (ChildRinfoEntry *) hash_search(root->child_rinfo_hash,
+												&key, HASH_ENTER, &found);
+		if (!found)
+		{
+			/* The key must not point to our local array */
+			if (key.nrelids > 0)
+			{
+				entry->key.child_relids = palloc_array(Index, key.nrelids);
+				memcpy(entry->key.child_relids, child_relids,
+					   key.nrelids * sizeof(Index));
+			}
+			else
+				entry->key.child_relids = NULL;
+
+			entry->child_rinfo = (RestrictInfo *)
+				adjust_appendrel_attrs(root, (Node *) rinfo,
+									   nappinfos, appinfos);
+		}
+
+		result = lappend(result, entry->child_rinfo);
+	}
+
+	pfree(context.used);
+	pfree(child_relids);
+
+	return result;
+}
+
+/*
+ * find_used_appinfos_walker
+ *	  Mark the AppendRelInfos adjust_appendrel_attrs_mutator() would use to
+ *	  translate the given node.
+ */
+static bool
+find_used_appinfos_walker(Node *node, find_used_appinfos_context *context)
+{
+	if (node == NULL)
+		return false;
+	if (IsA(node, Var))
+	{
+		Var		   *var = (Var *) node;
+
+		if (var->varlevelsup != 0)
+			return false;
+
+		/* Translation of a row identity Var may use any AppendRelInfo */
+		if (var->varno == ROWID_VAR)
+		{
+			memset(context->used, true, context->nappinfos * sizeof(bool));
+			return false;
+		}
+
+		for (int i = 0; i < context->nappinfos; i++)
+		{
+			if (var->varno == context->appinfos[i]->parent_relid)
+				context->used[i] = true;
+		}
+		return false;
+	}
+	if (IsA(node, CurrentOfExpr))
+	{
+		CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
+
+		for (int i = 0; i < context->nappinfos; i++)
+		{
+			if (cexpr->cvarno == context->appinfos[i]->parent_relid)
+				context->used[i] = true;
+		}
+		return false;
+	}
+	if (IsA(node, PlaceHolderVar))
+	{
+		PlaceHolderVar *phv = (PlaceHolderVar *) node;
+
+		if (phv->phlevelsup == 0)
+			find_used_appinfos_relids(phv->phrels, context);
+		/* fall through to examine the contained expression */
+	}
+	if (IsA(node, RestrictInfo))
+	{
+		RestrictInfo *rinfo = (RestrictInfo *) node;
+
+		find_used_appinfos_relids(rinfo->clause_relids, context);
+		find_used_appinfos_relids(rinfo->required_relids, context);
+		find_used_appinfos_relids(rinfo->outer_relids, context);
+		find_used_appinfos_relids(rinfo->left_relids, context);
+		find_used_appinfos_relids(rinfo->right_relids, context);
+
+		if (find_used_appinfos_walker((Node *) rinfo->clause, context))
+			return true;
+		return find_used_appinfos_walker((Node *) rinfo->orclause, context);
+	}
+	return expression_tree_walker(node, find_used_appinfos_walker, context);
+}
+
+/*
+ * find_used_appinfos_relids
+ *	  Mark the AppendRelInfos adjust_child_relids() would use to translate
+ *	  the given relid set.
+ */
+static void
+find_used_appinfos_relids(Relids relids, find_used_appinfos_context *context)
+{
+	if (relids == NULL)
+		return;
+
+	for (int i = 0; i < context->nappinfos; i++)
+	{
+		if (bms_is_member(context->appinfos[i]->parent_relid, relids))
+			context->used[i] = true;
+	}
+}
+
+/*
+ * Hash and match functions for root->child_rinfo_hash.
+ */
+static uint32
+child_rinfo_key_hash(const void *key, Size keysize)
+{
+	const ChildRinfoKey *k = (const ChildRinfoKey *) key;
+	uint32		hashval;
+
+	Assert(keysize == sizeof(ChildRinfoKey));
+
+	hashval = (uint32) murmurhash64((uint64) (uintptr_t) k->parent_rinfo);
+	if (k->nrelids > 0)
+		hashval = hash_combine(hashval,
+							   hash_bytes((const unsigned char *) k->child_relids,
+										  k->nrelids * sizeof(Index)));
+
+	return hashval;
+}
+
+static int
+child_rinfo_key_match(const void *key1, const void *key2, Size keysize)
+{
+	const ChildRinfoKey *k1 = (const ChildRinfoKey *) key1;
+	const ChildRinfoKey *k2 = (const ChildRinfoKey *) key2;
+
+	Assert(keysize == sizeof(ChildRinfoKey));
+
+	if (k1->parent_rinfo != k2->parent_rinfo || k1->nrelids != k2->nrelids)
+		return 1;
+	if (k1->nrelids == 0)
+		return 0;
+
+	return memcmp(k1->child_relids, k2->child_relids,
+				  k1->nrelids * sizeof(Index));
+}
+
 /*
  * adjust_appendrel_attrs_multilevel
  *	  Apply Var translations from an appendrel parent down to a child.
diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c
index 90a687c32da..75dad969e56 100644
--- a/src/backend/optimizer/util/relnode.c
+++ b/src/backend/optimizer/util/relnode.c
@@ -1145,10 +1145,10 @@ build_child_join_rel(PlannerInfo *root, RelOptInfo *outer_rel,
 							   nappinfos, appinfos);
 
 	/* Construct joininfo list. */
-	joinrel->joininfo = (List *) adjust_appendrel_attrs(root,
-														(Node *) parent_joinrel->joininfo,
-														nappinfos,
-														appinfos);
+	joinrel->joininfo = adjust_appendrel_restrictlist(root,
+													  parent_joinrel->joininfo,
+													  nappinfos,
+													  appinfos);
 
 	/*
 	 * Lateral relids referred in child join will be same as that referred in
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 2ba1dbfb67f..78f19373fc9 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -402,6 +402,13 @@ struct PlannerInfo
 	List	   *join_rel_list;
 	struct HTAB *join_rel_hash pg_node_attr(read_write_ignore);
 
+	/*
+	 * child_rinfo_hash holds the RestrictInfos translated for child joins by
+	 * adjust_appendrel_restrictlist(), so that they can be reused for other
+	 * child joins needing the same translation.  It's NULL until first used.
+	 */
+	struct HTAB *child_rinfo_hash pg_node_attr(read_write_ignore);
+
 	/*
 	 * When doing a dynamic-programming-style join search, join_rel_level[k]
 	 * is a list of all join-relation RelOptInfos of level k, and
diff --git a/src/include/optimizer/appendinfo.h b/src/include/optimizer/appendinfo.h
index b59a6218853..e972197a1ac 100644
--- a/src/include/optimizer/appendinfo.h
+++ b/src/include/optimizer/appendinfo.h
@@ -22,6 +22,10 @@ extern AppendRelInfo *make_append_rel_info(Relation parentrel,
 										   Index parentRTindex, Index childRTindex);
 extern Node *adjust_appendrel_attrs(PlannerInfo *root, Node *node,
 									int nappinfos, AppendRelInfo **appinfos);
+extern List *adjust_appendrel_restrictlist(PlannerInfo *root,
+										   List *restrictlist,
+										   int nappinfos,
+										   AppendRelInfo **appinfos);
 extern Node *adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node,
 											   RelOptInfo *childrel,
 											   RelOptInfo *parentrel);
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..04841962f94 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -437,6 +437,8 @@ CheckpointerRequest
 CheckpointerShmemStruct
 ChecksumBarrierCondition
 ChecksumStateType
+ChildRinfoEntry
+ChildRinfoKey
 Chromosome
 CkptSortItem
 CkptTsStatus
@@ -3786,6 +3788,7 @@ fill_string_relopt
 finalize_primnode_context
 find_dependent_phvs_context
 find_expr_references_context
+find_used_appinfos_context
 fireRIRonSubLink_context
 fix_join_expr_context
 fix_scan_expr_context
-- 
2.56.1

Reply via email to