From df8c50527b87602d4a98c2627f3740eac59370aa Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Wed, 25 Nov 2026 13:47:05 +0100
Subject: [PATCH v7 23/30] FK: Check operator and input coercions for starjoin
 dimensions

An equality useful for estimating the join selectivity need not preserve
fact rows.  For example, a varchar foreign key referencing a name key is
checked with name = name, which truncates the converted reference, while
the ordinary join uses name = text and compares the full string.  Even
an immediate, validated foreign key can therefore match every fact
during enforcement and none during the join.

For the starjoin eligibility, require the equivalence class source
clauses involving the dimension, and the loose quals, to use the stored
PK = FK operator (or its commutator for reversed operands), and require
that RI passes each key column to that operator using only
binary-coercible casts.  The operator alone is not enough, as a binary
cast through a third type can bypass the implicit cast used by RI.  Also
check the equivalence class members that are the foreign key column, and
don't let binary relabels change the actual type seen by a polymorphic
operator.

Update STARJOINS.md, and document that keys needing a cast that is not
binary-coercible are not used.  Add starjoin_fk_coercion, covering the
name truncation through an equivalence class, and a same-operator cast
that bypasses lowercasing, as a loose qual and in an equivalence class,
including through another fact column.  It checks that a commuted
name/text comparison, a binary varchar-to-text conversion and a
fact-only expression in the equivalence class still qualify.
---
 STARJOINS.md                                  |  39 ++++-
 doc/src/sgml/config.sgml                      |   8 +-
 src/backend/optimizer/path/equivclass.c       |   6 +-
 src/backend/optimizer/plan/initsplan.c        | 152 ++++++++++++++----
 .../regress/expected/starjoin_fk_coercion.out | 112 +++++++++++++
 src/test/regress/parallel_schedule            |   2 +-
 src/test/regress/sql/starjoin_fk_coercion.sql |  95 +++++++++++
 7 files changed, 370 insertions(+), 44 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_coercion.out
 create mode 100644 src/test/regress/sql/starjoin_fk_coercion.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index ee905f22361..917b8ee39db 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -57,8 +57,9 @@ The optimization consists of these parts:
 - `has_starjoin_fk` looks for a foreign key of the fact that makes a
   relation its dimension, using `has_extra_starjoin_quals` to check that
   the foreign key accounts for all the join clauses between them.
-- `starjoin_fk_collations_match` and `starjoin_equality_implies` check
-  the collations of the join clauses.
+- `starjoin_fk_comparisons_match`, `starjoin_fk_operand_matches` and
+  `starjoin_equality_implies` check the operators, input coercions and
+  collations of the join clauses.
 - `starjoin_order_invalid`, called by `make_join_rel`, rejects joins
   violating the canonical order, just like various other join
   restrictions.
@@ -399,7 +400,7 @@ orders.  For example, a case-insensitive join to a text primary key
 using the C collation can match both 'a' and 'A' for a single fact row.
 A satisfied foreign key guarantees a match under the equality of the
 referenced column, and the unique index enforces uniqueness under its
-own equality.  `starjoin_fk_collations_match` finds the unique index of
+own equality.  `starjoin_fk_comparisons_match` finds the unique index of
 the foreign key (`conindid`), and matches its keys to the referenced
 columns, not to the foreign key positions (REFERENCES can list the
 columns in a different order).  If the index is not available to the
@@ -430,6 +431,30 @@ collations have to be the same.  Both are checked, as extensions can add
 cross-type operators to a built-in family.  Identical collations need no
 such proof.
 
+An equality useful for estimating join selectivity need not preserve
+fact rows either.  For example, a varchar foreign key referencing a name
+key is checked with "name = name", so converting the reference to name
+truncates it, while the join uses "name = text" and compares the full
+string.  Both operators are immutable and in the same B-tree family.  So
+the equivalence class source clauses involving the dimension, and the
+loose quals matched outside equivalence classes, have to use the PK = FK
+operator of the foreign key (`conpfeqop`), or its commutator for
+reversed operands.  Both matchers look through binary relabels, so
+`starjoin_fk_operand_matches` checks that the referential integrity
+checks pass each column to that operator using only binary-coercible
+casts too.  The operator OID alone is not enough, as a binary cast
+through a third type can bypass the implicit cast used by the
+referential integrity checks.  For polymorphic inputs, the relabel must
+not change the actual type seen by the operator either.  The equivalence
+class source clauses not involving the dimension only filter fact rows.
+But such a clause can bring the foreign key column into the equivalence
+class, while the clauses involving the dimension name another fact
+column, so the members that are the foreign key column are checked the
+same way as the operands.  Genuine cross-type operators and
+binary-compatible coercions remain eligible, and the collation checks
+still apply.  Keys needing a cast that is not binary-coercible (e.g.
+integer to numeric) are not used, even if the cast preserves the value.
+
 These checks change only which relations are treated as dimensions, not
 foreign key enforcement or selectivity estimation.
 
@@ -511,6 +536,8 @@ the plans, the planning cost, or the regression tests.
   planning the canonical order (see the regression tests).  That's an
   indirect check, and changes of the planning memory use could flip its
   results.
+- No regression test makes `starjoin_fk_operand_matches` reject a
+  relabel changing the actual type seen by a polymorphic operator.
 
 ## Regression tests
 
@@ -609,3 +636,9 @@ the plans, the planning cost, or the regression tests.
     An otherwise identical foreign key using timestamptz on both sides
     still qualifies, including with an immutable int/smallint comparison
     on its first column.
+  - starjoin_fk_coercion: the name truncation through an equivalence
+    class, and a same-operator cast that bypasses lowercasing, both as a
+    loose qual and as an equivalence class (including through another
+    fact column).  A commuted name/text comparison, a binary
+    varchar-to-text conversion and a fact-only expression in the
+    equivalence class still qualify.
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index db8d9b31a7d..8454a3f4e6a 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6327,8 +6327,12 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         non-temporal foreign key with <literal>NOT NULL</literal> referencing
         columns, the join preserves the number of fact rows if the key's
         equality operators are immutable and the join uses the same equality
-        semantics as the key.  The planner assumes this even for foreign keys
-        marked <literal>NOT VALID</literal>.
+        semantics as the key.  Keys are not used for this optimization if
+        either column needs a cast that is not binary-coercible to match the
+        key's equality operator, even one that preserves the value, such as
+        from <type>integer</type> to <type>numeric</type>.  The planner
+        assumes row preservation even for foreign keys marked
+        <literal>NOT VALID</literal>.
         All orders of joining such dimension tables to the fact table thus
         produce the same number of rows, and the planner considers only one
         of them.
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 5a1204c6ef0..e7535a06c2d 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -2724,9 +2724,9 @@ exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
  *
  * If the referenced and referencing Vars of the fkey's colno'th column are
  * known equal due to any eclass, return that eclass; otherwise return NULL.
- * There can be matches under different collations.  For selectivity
- * estimation we accept any of them; callers relying on the FK's equality
- * semantics must check the collation separately.
+ * For selectivity estimation it suffices to match the operator families.
+ * Callers relying on the FK's equality semantics must also check the
+ * comparison operator, input coercions, and collation.
  *
  * On success, we also set fkinfo->eclass[colno] to the matching eclass,
  * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index 01e7a1636bc..dbe12a71e13 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -34,6 +34,7 @@
 #include "optimizer/planmain.h"
 #include "optimizer/restrictinfo.h"
 #include "parser/analyze.h"
+#include "parser/parse_coerce.h"
 #include "rewrite/rewriteManip.h"
 #include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
@@ -158,9 +159,10 @@ static bool has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 									 ForeignKeyOptInfo *fkinfo);
 static bool starjoin_equality_implies(Oid coll1, Oid coll2, Oid opfamily,
 									  Oid eqop);
-static bool starjoin_fk_collations_match(PlannerInfo *root,
-										 RelOptInfo *dim_rel,
-										 ForeignKeyOptInfo *fkinfo);
+static bool starjoin_fk_operand_matches(Node *arg, Oid inputtype);
+static bool starjoin_fk_comparisons_match(PlannerInfo *root,
+										  RelOptInfo *dim_rel,
+										  ForeignKeyOptInfo *fkinfo);
 static bool has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel,
 							RelOptInfo *dim_rel);
 
@@ -4252,14 +4254,42 @@ starjoin_equality_implies(Oid coll1, Oid coll2, Oid opfamily, Oid eqop)
 }
 
 /*
- * The FK guarantees a match under the referenced column's equality, while
- * uniqueness is enforced under the index key's equality.  So a row matching
- * under the referenced column's equality must also match under the join's,
- * and rows matching under the join's must be equal under the index key's.
+ * The FK matcher accepts Vars under binary relabels.  That gives the join
+ * the column's original Datum, so RI's direct conversion from the column
+ * type to the operator input must not change the value either.
  */
 static bool
-starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
-							 ForeignKeyOptInfo *fkinfo)
+starjoin_fk_operand_matches(Node *arg, Oid inputtype)
+{
+	Oid			argtype = exprType(arg);
+	Var		   *var;
+
+	while (IsA(arg, RelabelType))
+		arg = (Node *) ((RelabelType *) arg)->arg;
+	if (!IsA(arg, Var))
+		return false;
+	var = (Var *) arg;
+
+	/*
+	 * Normally the operand exposes the operator's declared input type.  A
+	 * polymorphic operator sees the actual type instead; in that case don't
+	 * let a relabel substitute a different actual type.
+	 */
+	if (argtype != inputtype &&
+		((!IsPolymorphicType(inputtype) && inputtype != RECORDOID) ||
+		 argtype != var->vartype))
+		return false;
+	return IsBinaryCoercible(var->vartype, inputtype);
+}
+
+/*
+ * Does the join use the same comparison of the key values as RI?  The FK
+ * guarantees a match under the referenced column's collation, but uniqueness
+ * is enforced under the index collation.  Check both implications.
+ */
+static bool
+starjoin_fk_comparisons_match(PlannerInfo *root, RelOptInfo *dim_rel,
+							  ForeignKeyOptInfo *fkinfo)
 {
 	RangeTblEntry *dim_rte = root->simple_rte_array[dim_rel->relid];
 
@@ -4274,15 +4304,12 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 			Oid			indcoll = index->indexcollations[j];
 			Oid			opfamily = index->opfamily[j];
 			Oid			eqop;
-			Oid			attcoll;
-			Oid			typid;
-			int32		typmod;
+			Oid			pktype;
+			Oid			fktype;
+			Oid			attcoll = InvalidOid;
+			List	   *clauses;
 			int			i;
 
-			/* No collation to check for a noncollatable key. */
-			if (!OidIsValid(indcoll))
-				continue;
-
 			/* REFERENCES can list the columns in a different order. */
 			for (i = 0; i < fkinfo->nkeys; i++)
 			{
@@ -4293,32 +4320,87 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 				return false;
 
 			eqop = fkinfo->conpfeqop[i];
-			get_atttypetypmodcoll(dim_rte->relid, attno,
-								  &typid, &typmod, &attcoll);
-			if (fkinfo->eclass[i] != NULL)
+			op_input_types(eqop, &pktype, &fktype);
+			if (OidIsValid(indcoll))
 			{
-				Oid			joincoll = fkinfo->eclass[i]->ec_collation;
+				Oid			typid;
+				int32		typmod;
 
-				if (!starjoin_equality_implies(attcoll, joincoll,
-											   opfamily, eqop) ||
-					!starjoin_equality_implies(joincoll, indcoll,
-											   opfamily, eqop))
-					return false;
+				get_atttypetypmodcoll(dim_rte->relid, attno,
+									  &typid, &typmod, &attcoll);
 			}
-			else
+
+			/*
+			 * has_extra_starjoin_quals already ruled out EC members other
+			 * than the dimension's FK column and expressions of the fact.
+			 * Check the source clauses, not just the EC's operator families:
+			 * e.g. name = name and name = text are in the same family.
+			 * Clauses not involving the dimension only filter fact rows.
+			 */
+			clauses = fkinfo->eclass[i] ? fkinfo->eclass[i]->ec_sources :
+				fkinfo->rinfos[i];
+			if (clauses == NIL)
+				return false;
+
+			/*
+			 * A clause not involving the dimension can still bring the FK
+			 * column into the EC, while the clauses involving the dimension
+			 * name other fact columns.  The EC then equates the FK column
+			 * with the key through a member the loop below doesn't check, so
+			 * check the members that are the FK column directly.
+			 */
+			if (fkinfo->eclass[i])
 			{
-				foreach_node(RestrictInfo, rinfo, fkinfo->rinfos[i])
+				foreach_node(EquivalenceMember, em,
+							 fkinfo->eclass[i]->ec_members)
 				{
-					Oid			joincoll;
-
-					joincoll = exprInputCollation((Node *) rinfo->clause);
-					if (!starjoin_equality_implies(attcoll, joincoll,
-												   opfamily, eqop) ||
-						!starjoin_equality_implies(joincoll, indcoll,
-												   opfamily, eqop))
+					Node	   *expr = (Node *) em->em_expr;
+
+					while (IsA(expr, RelabelType))
+						expr = (Node *) ((RelabelType *) expr)->arg;
+					if (IsA(expr, Var) &&
+						((Var *) expr)->varno == fkinfo->con_relid &&
+						((Var *) expr)->varattno == fkinfo->conkey[i] &&
+						!starjoin_fk_operand_matches((Node *) em->em_expr,
+													 fktype))
 						return false;
 				}
 			}
+
+			foreach_node(RestrictInfo, rinfo, clauses)
+			{
+				OpExpr	   *clause = castNode(OpExpr, rinfo->clause);
+				Oid			required_op = eqop;
+				Oid			joincoll = clause->inputcollid;
+				Node	   *pkarg;
+				Node	   *fkarg;
+
+				if (!bms_is_member(fkinfo->ref_relid, rinfo->clause_relids))
+					continue;
+
+				if (bms_is_member(fkinfo->ref_relid, rinfo->left_relids))
+				{
+					pkarg = linitial(clause->args);
+					fkarg = lsecond(clause->args);
+				}
+				else
+				{
+					pkarg = lsecond(clause->args);
+					fkarg = linitial(clause->args);
+					required_op = get_commutator(eqop);
+				}
+
+				if (clause->opno != required_op ||
+					!starjoin_fk_operand_matches(pkarg, pktype) ||
+					!starjoin_fk_operand_matches(fkarg, fktype))
+					return false;
+				if (OidIsValid(indcoll) &&
+					(!starjoin_equality_implies(attcoll, joincoll,
+												opfamily, eqop) ||
+					 !starjoin_equality_implies(joincoll, indcoll,
+												opfamily, eqop)))
+					return false;
+			}
 		}
 		return true;
 	}
@@ -4388,7 +4470,7 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
 		}
 		if (i == fkinfo->nkeys &&
 			!has_extra_starjoin_quals(root, dim_rel, fkinfo) &&
-			starjoin_fk_collations_match(root, dim_rel, fkinfo))
+			starjoin_fk_comparisons_match(root, dim_rel, fkinfo))
 			return true;
 	}
 
diff --git a/src/test/regress/expected/starjoin_fk_coercion.out b/src/test/regress/expected/starjoin_fk_coercion.out
new file mode 100644
index 00000000000..5576fd468b8
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_coercion.out
@@ -0,0 +1,112 @@
+-- Does the join compare the same values as the foreign key?
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+SET LOCAL client_min_messages = warning;
+CREATE TEMP TABLE d (id int PRIMARY KEY);
+INSERT INTO d VALUES (1);
+CREATE TEMP TABLE names (k name COLLATE "C" PRIMARY KEY);
+SELECT repeat('a', current_setting('max_identifier_length')::int) AS prefix \gset
+INSERT INTO names VALUES (:'prefix');
+-- RI lowercases folded values when comparing them to text. A binary
+-- detour through varchar can pass the original bytes to the same operator.
+CREATE TYPE pg_temp.folded;
+CREATE FUNCTION pg_temp.folded_in(cstring) RETURNS pg_temp.folded
+  AS 'textin' LANGUAGE internal IMMUTABLE STRICT;
+CREATE FUNCTION pg_temp.folded_out(pg_temp.folded) RETURNS cstring
+  AS 'textout' LANGUAGE internal IMMUTABLE STRICT;
+CREATE TYPE pg_temp.folded (INPUT = pg_temp.folded_in, OUTPUT = pg_temp.folded_out,
+                            LIKE = text, COLLATABLE = true);
+CREATE FUNCTION pg_temp.folded_text(pg_temp.folded) RETURNS text
+  AS 'lower' LANGUAGE internal IMMUTABLE STRICT;
+CREATE CAST (pg_temp.folded AS text) WITH FUNCTION pg_temp.folded_text(pg_temp.folded) AS IMPLICIT;
+CREATE CAST (pg_temp.folded AS varchar) WITHOUT FUNCTION;
+CREATE OPERATOR pg_temp.=== (LEFTARG = text, RIGHTARG = text, FUNCTION = texteq);
+CREATE OPERATOR CLASS pg_temp.loose_ops FOR TYPE text USING btree AS
+  OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 pg_temp.===, OPERATOR 4 >=, OPERATOR 5 >,
+  FUNCTION 1 bttextcmp(text, text);
+CREATE TEMP TABLE words (k text COLLATE "C" NOT NULL);
+CREATE UNIQUE INDEX ON words (k pg_temp.loose_ops);
+INSERT INTO words VALUES ('abc');
+CREATE TEMP TABLE fact (
+  v varchar COLLATE "C" NOT NULL REFERENCES names,
+  t text COLLATE "C" NOT NULL REFERENCES names,
+  folded pg_temp.folded COLLATE "C" NOT NULL REFERENCES words(k),
+  plain varchar COLLATE "C" NOT NULL REFERENCES words(k),
+  x text COLLATE "C" NOT NULL,
+  a int NOT NULL REFERENCES d, b int NOT NULL REFERENCES d,
+  c int NOT NULL REFERENCES d, d int NOT NULL REFERENCES d
+);
+INSERT INTO fact SELECT :'prefix' || 'b', :'prefix', 'ABC', 'abc', 'ABC', 1, 1, 1, 1
+  FROM generate_series(1, 100);
+ANALYZE fact, names, words, d;
+-- As in starjoin_fk_collation, compare planning memory for flat and forced
+-- join order. The four other dimensions always qualify.
+CREATE FUNCTION pg_temp.qualifies(candidate text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  query text := 'SELECT count(*) FROM fact f JOIN ' || candidate ||
+    ' JOIN d d1 ON f.a = d1.id JOIN d d2 ON f.b = d2.id
+      JOIN d d3 ON f.c = d3.id JOIN d d4 ON f.d = d4.id';
+  plan json;
+  search_memory bigint;
+BEGIN
+  EXECUTE 'EXPLAIN ' || query;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  search_memory := plan->0->'Planning'->>'Memory Used';
+  SET LOCAL join_collapse_limit = 1;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN search_memory <= (plan->0->'Planning'->>'Memory Used')::bigint * 1.1;
+END;
+$$;
+-- The varchar FK truncates to name, but the join compares the full text.
+-- The text FK actually uses name = text, including in commuted joins.
+SELECT (SELECT count(*) FROM fact f JOIN names n ON n.k = f.v::name) AS fk_matches,
+       (SELECT count(*) FROM fact f JOIN names n ON n.k = f.v) AS join_matches,
+       pg_temp.qualifies('names n ON n.k = f.v') AS varchar_qualifies,
+       pg_temp.qualifies('names n ON f.t = n.k') AS text_qualifies;
+ fk_matches | join_matches | varchar_qualifies | text_qualifies 
+------------+--------------+-------------------+----------------
+        100 |            0 | f                 | t
+(1 row)
+
+-- An exact operator match in joininfo does not prove that the correct cast
+-- was applied. A varchar FK that needs only a binary relabel still qualifies.
+SELECT (SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.folded)
+         AS fk_matches,
+       (SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.folded::varchar::text)
+         AS join_matches;
+ fk_matches | join_matches 
+------------+--------------
+        100 |            0
+(1 row)
+
+\set bypass 'words w ON w.k OPERATOR(pg_temp.===) f.folded::varchar::text'
+\set binary 'words w ON w.k OPERATOR(pg_temp.===) f.plain'
+SELECT pg_temp.qualifies(:'bypass') AS loose_bypass, pg_temp.qualifies(:'binary') AS loose_binary;
+ loose_bypass | loose_binary 
+--------------+--------------
+ f            | t
+(1 row)
+
+-- Exercise the same pair of comparisons through equivalence classes.
+ALTER OPERATOR pg_temp.=== (text, text) SET (COMMUTATOR = OPERATOR(pg_temp.===), MERGES);
+SELECT pg_temp.qualifies(:'bypass') AS ec_bypass, pg_temp.qualifies(:'binary') AS ec_binary;
+ ec_bypass | ec_binary 
+-----------+-----------
+ f         | t
+(1 row)
+
+-- Clauses not involving the dimension only filter fact rows, but they can
+-- also bring the FK column into the EC while the dimension's clause names
+-- another fact column.
+\set filter 'words w ON w.k OPERATOR(pg_temp.===) f.plain AND f.plain OPERATOR(pg_temp.===) lower(f.x)'
+\set relay 'words w ON w.k OPERATOR(pg_temp.===) f.x AND f.x OPERATOR(pg_temp.===) f.folded::varchar::text'
+SELECT pg_temp.qualifies(:'filter') AS ec_fact_filter, pg_temp.qualifies(:'relay') AS ec_relay_bypass;
+ ec_fact_filter | ec_relay_bypass 
+----------------+-----------------
+ t              | f
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index b9328370875..1e56db7d4e6 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -149,7 +149,7 @@ test: event_trigger_login
 test: fast_default
 
 # some tests for starjoin planning
-test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap starjoin_fk_period starjoin_fk_collation starjoin_fk_opclass starjoin_fk_only starjoin_fk_partition starjoin_fk_timezone starjoin_geqo
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap starjoin_fk_period starjoin_fk_collation starjoin_fk_opclass starjoin_fk_only starjoin_fk_partition starjoin_fk_timezone starjoin_fk_coercion starjoin_geqo
 
 # more expensive tests for starjoin planning (larger variants of earlier tests)
 # test: starjoin_eager_large starjoin_plan_large starjoin_width_large
diff --git a/src/test/regress/sql/starjoin_fk_coercion.sql b/src/test/regress/sql/starjoin_fk_coercion.sql
new file mode 100644
index 00000000000..275e4cb7b25
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_coercion.sql
@@ -0,0 +1,95 @@
+-- Does the join compare the same values as the foreign key?
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+SET LOCAL client_min_messages = warning;
+
+CREATE TEMP TABLE d (id int PRIMARY KEY);
+INSERT INTO d VALUES (1);
+CREATE TEMP TABLE names (k name COLLATE "C" PRIMARY KEY);
+SELECT repeat('a', current_setting('max_identifier_length')::int) AS prefix \gset
+INSERT INTO names VALUES (:'prefix');
+
+-- RI lowercases folded values when comparing them to text. A binary
+-- detour through varchar can pass the original bytes to the same operator.
+CREATE TYPE pg_temp.folded;
+CREATE FUNCTION pg_temp.folded_in(cstring) RETURNS pg_temp.folded
+  AS 'textin' LANGUAGE internal IMMUTABLE STRICT;
+CREATE FUNCTION pg_temp.folded_out(pg_temp.folded) RETURNS cstring
+  AS 'textout' LANGUAGE internal IMMUTABLE STRICT;
+CREATE TYPE pg_temp.folded (INPUT = pg_temp.folded_in, OUTPUT = pg_temp.folded_out,
+                            LIKE = text, COLLATABLE = true);
+CREATE FUNCTION pg_temp.folded_text(pg_temp.folded) RETURNS text
+  AS 'lower' LANGUAGE internal IMMUTABLE STRICT;
+CREATE CAST (pg_temp.folded AS text) WITH FUNCTION pg_temp.folded_text(pg_temp.folded) AS IMPLICIT;
+CREATE CAST (pg_temp.folded AS varchar) WITHOUT FUNCTION;
+
+CREATE OPERATOR pg_temp.=== (LEFTARG = text, RIGHTARG = text, FUNCTION = texteq);
+CREATE OPERATOR CLASS pg_temp.loose_ops FOR TYPE text USING btree AS
+  OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 pg_temp.===, OPERATOR 4 >=, OPERATOR 5 >,
+  FUNCTION 1 bttextcmp(text, text);
+CREATE TEMP TABLE words (k text COLLATE "C" NOT NULL);
+CREATE UNIQUE INDEX ON words (k pg_temp.loose_ops);
+INSERT INTO words VALUES ('abc');
+CREATE TEMP TABLE fact (
+  v varchar COLLATE "C" NOT NULL REFERENCES names,
+  t text COLLATE "C" NOT NULL REFERENCES names,
+  folded pg_temp.folded COLLATE "C" NOT NULL REFERENCES words(k),
+  plain varchar COLLATE "C" NOT NULL REFERENCES words(k),
+  x text COLLATE "C" NOT NULL,
+  a int NOT NULL REFERENCES d, b int NOT NULL REFERENCES d,
+  c int NOT NULL REFERENCES d, d int NOT NULL REFERENCES d
+);
+INSERT INTO fact SELECT :'prefix' || 'b', :'prefix', 'ABC', 'abc', 'ABC', 1, 1, 1, 1
+  FROM generate_series(1, 100);
+ANALYZE fact, names, words, d;
+
+-- As in starjoin_fk_collation, compare planning memory for flat and forced
+-- join order. The four other dimensions always qualify.
+CREATE FUNCTION pg_temp.qualifies(candidate text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  query text := 'SELECT count(*) FROM fact f JOIN ' || candidate ||
+    ' JOIN d d1 ON f.a = d1.id JOIN d d2 ON f.b = d2.id
+      JOIN d d3 ON f.c = d3.id JOIN d d4 ON f.d = d4.id';
+  plan json;
+  search_memory bigint;
+BEGIN
+  EXECUTE 'EXPLAIN ' || query;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  search_memory := plan->0->'Planning'->>'Memory Used';
+  SET LOCAL join_collapse_limit = 1;
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN search_memory <= (plan->0->'Planning'->>'Memory Used')::bigint * 1.1;
+END;
+$$;
+
+-- The varchar FK truncates to name, but the join compares the full text.
+-- The text FK actually uses name = text, including in commuted joins.
+SELECT (SELECT count(*) FROM fact f JOIN names n ON n.k = f.v::name) AS fk_matches,
+       (SELECT count(*) FROM fact f JOIN names n ON n.k = f.v) AS join_matches,
+       pg_temp.qualifies('names n ON n.k = f.v') AS varchar_qualifies,
+       pg_temp.qualifies('names n ON f.t = n.k') AS text_qualifies;
+
+-- An exact operator match in joininfo does not prove that the correct cast
+-- was applied. A varchar FK that needs only a binary relabel still qualifies.
+SELECT (SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.folded)
+         AS fk_matches,
+       (SELECT count(*) FROM fact f JOIN words w ON w.k OPERATOR(pg_temp.===) f.folded::varchar::text)
+         AS join_matches;
+\set bypass 'words w ON w.k OPERATOR(pg_temp.===) f.folded::varchar::text'
+\set binary 'words w ON w.k OPERATOR(pg_temp.===) f.plain'
+SELECT pg_temp.qualifies(:'bypass') AS loose_bypass, pg_temp.qualifies(:'binary') AS loose_binary;
+
+-- Exercise the same pair of comparisons through equivalence classes.
+ALTER OPERATOR pg_temp.=== (text, text) SET (COMMUTATOR = OPERATOR(pg_temp.===), MERGES);
+SELECT pg_temp.qualifies(:'bypass') AS ec_bypass, pg_temp.qualifies(:'binary') AS ec_binary;
+
+-- Clauses not involving the dimension only filter fact rows, but they can
+-- also bring the FK column into the EC while the dimension's clause names
+-- another fact column.
+\set filter 'words w ON w.k OPERATOR(pg_temp.===) f.plain AND f.plain OPERATOR(pg_temp.===) lower(f.x)'
+\set relay 'words w ON w.k OPERATOR(pg_temp.===) f.x AND f.x OPERATOR(pg_temp.===) f.folded::varchar::text'
+SELECT pg_temp.qualifies(:'filter') AS ec_fact_filter, pg_temp.qualifies(:'relay') AS ec_relay_bypass;
+ROLLBACK;
-- 
2.56.1

