From ead887296e1a5fdf92212c50e681ac3a82f669b9 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Thu, 26 Nov 2026 00:02:59 +0100
Subject: [PATCH v4 5/8] postgres_fdw: Cost pushed down equi-joins like a hash
 join

Without use_remote_estimate, a pushed down join was costed as a nested
loop over the cross product of its two sides, which made it look far
more expensive than fetching both sides and joining them locally.

When the join has pushed down clauses that can be hashed, use the
planner's own hash join costing instead, with the remote costs of the
two sides as the inputs. Other joins are still costed on the cross
product.

This also changes the plan of an existing test, where the ORDER BY and
LIMIT on top of an already pushed down join are now pushed down too. A
remote sort is charged as a fraction of the cost of the path below it,
so the inflated join cost made it look more expensive than a local sort.

Discussion: https://postgr.es/m/DLRIUVXIEUOQ.2E2I0B7VZLHLI@jeltef.nl
---
 .../postgres_fdw/expected/postgres_fdw.out    |  36 ++----
 contrib/postgres_fdw/postgres_fdw.c           | 112 ++++++++++++++++++
 contrib/postgres_fdw/postgres_fdw.h           |   9 ++
 3 files changed, 133 insertions(+), 24 deletions(-)

diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 5f35f42c86e..5b21910bfbb 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -333,20 +333,13 @@ DROP FUNCTION local_project(int);
 -- joining them locally.
 EXPLAIN (VERBOSE, COSTS OFF)
 SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft1 t2 ON (t1.c1 = t2.c1);
-                       QUERY PLAN                        
----------------------------------------------------------
- Hash Join
+                                                      QUERY PLAN                                                      
+----------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
    Output: t1.c1, t2.c1
-   Hash Cond: (t1.c1 = t2.c1)
-   ->  Foreign Scan on public.ft1 t1
-         Output: t1.c1
-         Remote SQL: SELECT "C 1" FROM "S 1"."T 1"
-   ->  Hash
-         Output: t2.c1
-         ->  Foreign Scan on public.ft1 t2
-               Output: t2.c1
-               Remote SQL: SELECT "C 1" FROM "S 1"."T 1"
-(11 rows)
+   Relations: (public.ft1 t1) INNER JOIN (public.ft1 t2)
+   Remote SQL: SELECT r1."C 1", r2."C 1" FROM ("S 1"."T 1" r1 INNER JOIN "S 1"."T 1" r2 ON (((r1."C 1" = r2."C 1"))))
+(4 rows)
 
 -- ===================================================================
 -- test subscription
@@ -2104,18 +2097,13 @@ SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT
 -- full outer join + WHERE clause, only matched rows
 EXPLAIN (VERBOSE, COSTS OFF)
 SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 IS NULL) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
-                                                                            QUERY PLAN                                                                            
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
- Limit
+                                                                                                                 QUERY PLAN                                                                                                                  
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Foreign Scan
    Output: t1.c1, t2.c1
-   ->  Sort
-         Output: t1.c1, t2.c1
-         Sort Key: t1.c1, t2.c1
-         ->  Foreign Scan
-               Output: t1.c1, t2.c1
-               Relations: (public.ft4 t1) FULL JOIN (public.ft5 t2)
-               Remote SQL: SELECT r1.c1, r2.c1 FROM ("S 1"."T 3" r1 FULL JOIN "S 1"."T 4" r2 ON (((r1.c1 = r2.c1)))) WHERE (((r1.c1 = r2.c1) OR (r1.c1 IS NULL)))
-(9 rows)
+   Relations: (public.ft4 t1) FULL JOIN (public.ft5 t2)
+   Remote SQL: SELECT r1.c1, r2.c1 FROM ("S 1"."T 3" r1 FULL JOIN "S 1"."T 4" r2 ON (((r1.c1 = r2.c1)))) WHERE (((r1.c1 = r2.c1) OR (r1.c1 IS NULL))) ORDER BY r1.c1 ASC NULLS LAST, r2.c1 ASC NULLS LAST LIMIT 10::bigint OFFSET 10::bigint
+(4 rows)
 
 SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 IS NULL) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10;
  c1 | c1 
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index d0fa4c59421..a3fad73c314 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -532,6 +532,14 @@ static void adjust_foreign_grouping_path_cost(PlannerInfo *root,
 											  int *p_disabled_nodes,
 											  Cost *p_startup_cost,
 											  Cost *p_run_cost);
+static Path *make_remote_join_input_path(RelOptInfo *rel,
+										 PgFdwRelationInfo *func_fpinfo);
+static void estimate_remote_hashjoin_cost(PlannerInfo *root,
+										  RelOptInfo *joinrel,
+										  RelOptInfo *outerrel,
+										  RelOptInfo *innerrel,
+										  JoinType jointype,
+										  JoinPathExtraData *extra);
 static bool ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
 									  EquivalenceClass *ec, EquivalenceMember *em,
 									  void *arg);
@@ -3614,6 +3622,17 @@ estimate_path_cost_size(PlannerInfo *root,
 			run_cost += nrows * join_cost.per_tuple;
 			nrows = clamp_row_est(nrows * fpinfo->joinclause_sel);
 			run_cost += nrows * remote_conds_cost.per_tuple;
+
+			/*
+			 * If the foreign server can use a hash join, use what that would
+			 * cost if we did it ourselves instead of the above.  See
+			 * estimate_remote_hashjoin_cost().
+			 */
+			if (fpinfo->remote_hashjoin)
+			{
+				startup_cost = fpinfo->remote_hashjoin_startup_cost;
+				run_cost = fpinfo->remote_hashjoin_run_cost;
+			}
 		}
 		else if (IS_UPPER_REL(foreignrel))
 		{
@@ -3991,6 +4010,89 @@ adjust_foreign_grouping_path_cost(PlannerInfo *root,
 	}
 }
 
+/*
+ * Build a dummy path for one side of a pushed down join.  It carries the cost
+ * and size of computing that side on the foreign server, so that the
+ * planner's join costing functions can be used to cost the remote join.
+ *
+ * func_fpinfo is the stub fpinfo to use if the side is a FUNCTION RTE that
+ * was absorbed into the join, because such a rel has no fdw_private.
+ */
+static Path *
+make_remote_join_input_path(RelOptInfo *rel, PgFdwRelationInfo *func_fpinfo)
+{
+	PgFdwRelationInfo *fpinfo = func_fpinfo ? func_fpinfo :
+		(PgFdwRelationInfo *) rel->fdw_private;
+	Path	   *path = makeNode(Path);
+
+	path->parent = rel;
+	path->pathtarget = rel->reltarget;
+	path->rows = fpinfo->rows;
+	path->startup_cost = fpinfo->rel_startup_cost;
+	path->total_cost = fpinfo->rel_startup_cost + fpinfo->rel_run_cost;
+
+	return path;
+}
+
+/*
+ * Estimate the cost of computing a join on the foreign server with a hash
+ * join, for when we're not using remote estimates.
+ *
+ * We don't know what join strategy the foreign server is going to use.  But
+ * when there are pushed down clauses that can be hashed, it can at least use
+ * a hash join, just like we could.  So we cost the remote join with the
+ * planner's own hash join costing, using the remote costs of the two sides as
+ * the inputs.  The result is stored in the joinrel's fpinfo.
+ */
+static void
+estimate_remote_hashjoin_cost(PlannerInfo *root, RelOptInfo *joinrel,
+							  RelOptInfo *outerrel, RelOptInfo *innerrel,
+							  JoinType jointype, JoinPathExtraData *extra)
+{
+	PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
+	Path	   *outer_path = make_remote_join_input_path(outerrel,
+														 fpinfo->outer_func_fpinfo);
+	Path	   *inner_path = make_remote_join_input_path(innerrel,
+														 fpinfo->inner_func_fpinfo);
+	HashPath   *hash_path = makeNode(HashPath);
+	JoinCostWorkspace workspace;
+
+	/* Like for a local hash join, only join clauses can be hash clauses */
+	foreach_node(RestrictInfo, rinfo, fpinfo->joinclauses)
+	{
+		if (rinfo->can_join && OidIsValid(rinfo->hashjoinoperator) &&
+			clause_sides_match_join(rinfo, outerrel->relids, innerrel->relids))
+			hash_path->path_hashclauses = lappend(hash_path->path_hashclauses,
+												  rinfo);
+	}
+
+	fpinfo->remote_hashjoin = (hash_path->path_hashclauses != NIL);
+	if (!fpinfo->remote_hashjoin)
+		return;
+
+	/*
+	 * The target list is left empty, because estimate_path_cost_size() adds
+	 * the cost of evaluating it for every foreign path.
+	 */
+	hash_path->jpath.path.parent = joinrel;
+	hash_path->jpath.path.pathtarget = create_empty_pathtarget();
+	hash_path->jpath.jointype = jointype;
+	hash_path->jpath.inner_unique = extra->inner_unique;
+	hash_path->jpath.outerjoinpath = outer_path;
+	hash_path->jpath.innerjoinpath = inner_path;
+	hash_path->jpath.joinrestrictinfo = list_concat_copy(fpinfo->joinclauses,
+														 fpinfo->remote_conds);
+
+	initial_cost_hashjoin(root, &workspace, jointype,
+						  hash_path->path_hashclauses,
+						  outer_path, inner_path, extra, false);
+	final_cost_hashjoin(root, hash_path, &workspace, extra);
+
+	fpinfo->remote_hashjoin_startup_cost = hash_path->jpath.path.startup_cost;
+	fpinfo->remote_hashjoin_run_cost = hash_path->jpath.path.total_cost -
+		hash_path->jpath.path.startup_cost;
+}
+
 /*
  * Detect whether we want to process an EquivalenceClass member.
  *
@@ -7782,10 +7884,20 @@ postgresGetForeignJoinPaths(PlannerInfo *root,
 	 * selectivity here while we have special join info.
 	 */
 	if (!fpinfo->use_remote_estimate)
+	{
 		fpinfo->joinclause_sel = clauselist_selectivity(root, fpinfo->joinclauses,
 														0, fpinfo->jointype,
 														extra->sjinfo);
 
+		/*
+		 * Likewise estimate what a hash join would cost on the foreign
+		 * server, while we have the information that the hash join costing
+		 * functions need.
+		 */
+		estimate_remote_hashjoin_cost(root, joinrel, outerrel, innerrel,
+									  jointype, extra);
+	}
+
 	/* Estimate costs for bare join relation */
 	estimate_path_cost_size(root, joinrel, NIL, NIL, NULL,
 							&rows, &width, &disabled_nodes,
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index 2122d9d89a5..f3627dcb133 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -59,6 +59,15 @@ typedef struct PgFdwRelationInfo
 	/* Selectivity of join conditions */
 	Selectivity joinclause_sel;
 
+	/*
+	 * Cost of computing a join on the foreign server with a hash join, when
+	 * not using remote estimates.  Only valid if remote_hashjoin is true,
+	 * i.e. when the join has pushed down clauses that can be hashed.
+	 */
+	bool		remote_hashjoin;
+	Cost		remote_hashjoin_startup_cost;
+	Cost		remote_hashjoin_run_cost;
+
 	/* Estimated size and cost for a scan, join, or grouping/aggregation. */
 	double		rows;
 	int			width;
-- 
2.56.1

