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

