From 539ac9f58cb4494bca11db441b44c62b023df553 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 17/30] FK: Check collation equality before accepting a
 starjoin dimension

Matching foreign keys for selectivity can associate an equivalence class
or a loose join qual with a key without checking its comparison
collation.  That is not enough to prune join orders.  For example, a
case-insensitive join to a text primary key using C collation can match
both 'a' and 'A' for a single fact row.

Carry the OID of the unique index of the foreign key into the planner,
and match the index keys to the referenced attributes, not the foreign
key positions.  Require the collations of the referenced column, of the
index, and of the matched equivalence class or loose comparisons to
agree on equality.  This still accepts two different deterministic
collations, or the same nondeterministic one.  Leave the selectivity
estimation unchanged.

Update STARJOINS.md and the documentation of enable_starjoin_ordering.
Add starjoin_fk_collation, covering both forms of join qual and a
composite key with the index columns in a different order.  An index
with a collation override shows why checking only the column, or only
the index, is insufficient.
---
 STARJOINS.md                                  |  40 ++++-
 doc/src/sgml/config.sgml                      |   8 +-
 src/backend/nodes/outfuncs.c                  |   1 +
 src/backend/optimizer/path/equivclass.c       |   7 +-
 src/backend/optimizer/plan/initsplan.c        |  80 +++++++++-
 src/backend/optimizer/util/plancat.c          |   1 +
 src/backend/utils/cache/relcache.c            |   1 +
 src/include/nodes/pathnodes.h                 |   2 +
 src/include/utils/rel.h                       |   2 +
 .../expected/starjoin_fk_collation.out        | 148 ++++++++++++++++++
 .../expected/starjoin_fk_collation_1.out      |   8 +
 src/test/regress/parallel_schedule            |   2 +-
 .../regress/sql/starjoin_fk_collation.sql     | 116 ++++++++++++++
 13 files changed, 401 insertions(+), 15 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_collation.out
 create mode 100644 src/test/regress/expected/starjoin_fk_collation_1.out
 create mode 100644 src/test/regress/sql/starjoin_fk_collation.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index ab2eae08886..2353cbf61ab 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -57,6 +57,8 @@ 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` checks the 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.
@@ -306,9 +308,9 @@ The fact has to be a base relation too.
    Conditions 5 to 7 rule out join order restrictions on the dimension.
 
 8. All join conditions between the fact and the dimension are accounted
-   for by the matched foreign key, with no additional equivalence class
-   members other than expressions of the fact, in equivalence classes
-   that are not broken.
+   for by the matched foreign key, with compatible equality semantics
+   and no additional equivalence class members other than expressions of
+   the fact, in equivalence classes that are not broken.
 
    A fully matched NOT NULL foreign key does not make the join preserve
    the fact rows if other conditions connect the same pair of relations,
@@ -360,6 +362,27 @@ key, not when matching foreign keys for selectivity estimation, and an
 ordinary equality foreign key between the same relations remains
 eligible.
 
+### Equality semantics
+
+Matching foreign keys to join clauses for selectivity estimation does
+not check the comparison semantics, which is not enough to prune join
+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
+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
+planner (not in the index list of the dimension), the foreign key is not
+used.  The collations of the referenced column, the index, and the join
+clauses (the matched equivalence class or loose comparisons) then have
+to agree on equality.  That still accepts two different deterministic
+collations, or the same nondeterministic one.
+
+These checks change only which relations are treated as dimensions, not
+foreign key enforcement or selectivity estimation.
+
 ### Conditions inherited from foreign key matching
 
 The clusters are built from the foreign keys the planner matches to the
@@ -497,7 +520,9 @@ the plans, the planning cost, or the regression tests.
   point, so the search takes noticeably more memory.  So the suites
   compare the planning memory of the search and of the forced order,
   accepting up to 10% more, with four other dimensions that always
-  qualify to widen the difference.
+  qualify to widen the difference.  The starjoin_fk_collation suite
+  needs a UTF8 database with ICU collations, and has an alternative
+  output for when it's skipped.
   - starjoin_fk_overlap: a composite foreign key qualifies alone and
     together with a short one, whichever is examined first (varying both
     the creation and the name order), while a lone short key and two
@@ -505,3 +530,10 @@ the plans, the planning cost, or the regression tests.
   - starjoin_fk_period: a PERIOD foreign key, where each fact row joins
     eight adjacent periods, does not qualify, while an ordinary equality
     foreign key between the same tables does.
+  - starjoin_fk_collation: joins under deterministic collations qualify,
+    while a case-insensitive join does not, both as an equivalence class
+    and as a loose qual.  A nondeterministic collation agreeing with
+    both the column and the index qualifies, on a composite key with the
+    index columns in a different order.  An index with a collation
+    override shows that checking only the column or only the index is
+    not enough (one join matches two rows, the other none).
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index ead0a0e6e17..f03ad59a832 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6323,9 +6323,11 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         Enables or disables the query planner's optimization of star joins,
         where a <quote>fact</quote> table is joined to multiple
         <quote>dimension</quote> tables using foreign keys.  When a dimension
-        table is joined only to the fact table, using a join condition
-        matching a non-temporal foreign key with <literal>NOT NULL</literal>
-        referencing columns, joining it does not change the number of rows.
+        table is joined only to the fact table through an enforced
+        non-temporal foreign key with <literal>NOT NULL</literal> referencing
+        columns, the join preserves the number of fact rows if it uses the
+        same equality semantics as the key.  The planner assumes this 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/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index a2354c45cc9..7782bc71514 100644
--- a/src/backend/nodes/outfuncs.c
+++ b/src/backend/nodes/outfuncs.c
@@ -437,6 +437,7 @@ _outForeignKeyOptInfo(StringInfo str, const ForeignKeyOptInfo *node)
 
 	WRITE_UINT_FIELD(con_relid);
 	WRITE_UINT_FIELD(ref_relid);
+	WRITE_OID_FIELD(conindid);
 	WRITE_BOOL_FIELD(conperiod);
 	WRITE_INT_FIELD(nkeys);
 	WRITE_ATTRNUMBER_ARRAY(conkey, node->nkeys);
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 439cb651c01..5a1204c6ef0 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -2724,10 +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.
- * (In principle there might be more than one matching eclass if multiple
- * collations are involved, but since collation doesn't matter for equality,
- * we ignore that fine point here.)  This is much like exprs_known_equal,
- * except for the format of the input.
+ * 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.
  *
  * 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 baf25dc7548..dc1d1f60d65 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -151,6 +151,9 @@ static void check_hashjoinable(RestrictInfo *restrictinfo);
 static void check_memoizable(RestrictInfo *restrictinfo);
 static bool has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 									 ForeignKeyOptInfo *fkinfo);
+static bool starjoin_fk_collations_match(PlannerInfo *root,
+										 RelOptInfo *dim_rel,
+										 ForeignKeyOptInfo *fkinfo);
 static bool has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel,
 							RelOptInfo *dim_rel);
 
@@ -4197,6 +4200,75 @@ has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 	return false;
 }
 
+/*
+ * The FK guarantees a match under the referenced column's equality, while
+ * uniqueness is enforced under the index key's equality.  A join using a
+ * different collation must agree with both.
+ */
+static bool
+starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
+							 ForeignKeyOptInfo *fkinfo)
+{
+	RangeTblEntry *dim_rte = root->simple_rte_array[dim_rel->relid];
+
+	foreach_node(IndexOptInfo, index, dim_rel->indexlist)
+	{
+		if (index->indexoid != fkinfo->conindid)
+			continue;
+
+		for (int j = 0; j < index->nkeycolumns; j++)
+		{
+			AttrNumber	attno = index->indexkeys[j];
+			Oid			indcoll = index->indexcollations[j];
+			Oid			attcoll;
+			Oid			typid;
+			int32		typmod;
+			int			i;
+
+			/* No collation check or catalog lookup for a noncollatable key. */
+			if (!OidIsValid(indcoll))
+				continue;
+
+			/* REFERENCES can list the columns in a different order. */
+			for (i = 0; i < fkinfo->nkeys; i++)
+			{
+				if (fkinfo->confkey[i] == attno)
+					break;
+			}
+			if (i == fkinfo->nkeys)
+				return false;
+
+			get_atttypetypmodcoll(dim_rte->relid, attno,
+								  &typid, &typmod, &attcoll);
+			if (!collations_agree_on_equality(attcoll, indcoll))
+				return false;
+
+			if (fkinfo->eclass[i] != NULL)
+			{
+				Oid			joincoll = fkinfo->eclass[i]->ec_collation;
+
+				if (!collations_agree_on_equality(attcoll, joincoll))
+					return false;
+			}
+			else
+			{
+				foreach_node(RestrictInfo, rinfo, fkinfo->rinfos[i])
+				{
+					Oid			joincoll;
+
+					joincoll = exprInputCollation((Node *) rinfo->clause);
+					if (!collations_agree_on_equality(attcoll, joincoll))
+						return false;
+				}
+			}
+		}
+		return true;
+	}
+
+	/* The backing index isn't available to the planner. */
+	return false;
+}
+
 /*
  * Several FKs may match the same pair of rels.  A single FK must account
  * for the whole join, but it need not be the first one in fkey_list.
@@ -4225,7 +4297,8 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
 				break;
 		}
 		if (i == fkinfo->nkeys &&
-			!has_extra_starjoin_quals(root, dim_rel, fkinfo))
+			!has_extra_starjoin_quals(root, dim_rel, fkinfo) &&
+			starjoin_fk_collations_match(root, dim_rel, fkinfo))
 			return true;
 	}
 
@@ -4259,8 +4332,9 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
  *	7. The dimension is not constrained by any PlaceHolderInfo.
  *
  *	8. All join conditions between the fact and the dimension are accounted
- *	   for by the matched FK, with no additional EC members other than
- *	   expressions of the fact, in ECs that are not broken.
+ *	   for by the matched FK, with compatible equality semantics and no
+ *	   additional EC members other than expressions of the fact, in ECs
+ *	   that are not broken.
  *
  * Under these conditions, the join is strictly cardinality-preserving with
  * respect to the fact table, and all join orderings for a cluster produce
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index d76c69608fd..d8ea695d719 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -660,6 +660,7 @@ get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
 			info = makeNode(ForeignKeyOptInfo);
 			info->con_relid = rel->relid;
 			info->ref_relid = rti;
+			info->conindid = cachedfk->conindid;
 			info->conperiod = cachedfk->conperiod;
 			info->nkeys = cachedfk->nkeys;
 			memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 3ed28d507af..1c68ffa062d 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -4815,6 +4815,7 @@ RelationGetFKeyList(Relation relation)
 		info->conoid = constraint->oid;
 		info->conrelid = constraint->conrelid;
 		info->confrelid = constraint->confrelid;
+		info->conindid = constraint->conindid;
 		info->conenforced = constraint->conenforced;
 		info->conperiod = constraint->conperiod;
 
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 22835fb7e37..e1250386327 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -1482,6 +1482,8 @@ typedef struct ForeignKeyOptInfo
 	Index		con_relid;
 	/* RT index of the referenced table */
 	Index		ref_relid;
+	/* OID of the index supporting the referenced key */
+	Oid			conindid;
 	/* Does the FK have a PERIOD column? */
 	bool		conperiod;
 	/* number of columns in the foreign key */
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index 821c653b64e..2641210c0d7 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -290,6 +290,8 @@ typedef struct ForeignKeyCacheInfo
 	Oid			conrelid;
 	/* relation referenced by the foreign key */
 	Oid			confrelid;
+	/* index supporting the referenced key */
+	Oid			conindid;
 	/* number of columns in the foreign key */
 	int			nkeys;
 
diff --git a/src/test/regress/expected/starjoin_fk_collation.out b/src/test/regress/expected/starjoin_fk_collation.out
new file mode 100644
index 00000000000..91e0d572709
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_collation.out
@@ -0,0 +1,148 @@
+--
+-- Starjoin lookup semantics under different collations
+--
+SELECT getdatabaseencoding() <> 'UTF8' OR NOT EXISTS
+  (SELECT FROM pg_collation WHERE collprovider = 'i' AND collname <> 'unicode')
+  AS skip_test \gset
+\if :skip_test
+\quit
+\endif
+BEGIN;
+SET LOCAL enable_starjoin_ordering = on;
+CREATE TEMP TABLE d1 (id int PRIMARY KEY);
+CREATE TEMP TABLE d2 (id int PRIMARY KEY);
+CREATE TEMP TABLE d3 (id int PRIMARY KEY);
+CREATE TEMP TABLE d4 (id int PRIMARY KEY);
+INSERT INTO d1 VALUES (1);
+INSERT INTO d2 VALUES (1);
+INSERT INTO d3 VALUES (1);
+INSERT INTO d4 VALUES (1);
+CREATE COLLATION pg_temp.starjoin_ci
+  (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
+CREATE TEMP TABLE spellings (k text COLLATE "C" PRIMARY KEY);
+INSERT INTO spellings VALUES ('a'), ('A');
+CREATE TEMP TABLE fact (
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4,
+  k text COLLATE "C" NOT NULL CONSTRAINT exact_fk REFERENCES spellings
+);
+INSERT INTO fact SELECT 1, 1, 1, 1, 'a' FROM generate_series(1, 100);
+SELECT $$SELECT count(*) FROM fact f JOIN spellings s ON f.k = s.k
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_native \gset
+SELECT replace(:'q_native', 'f.k = s.k', 'f.k COLLATE pg_temp.starjoin_ci = s.k')
+  AS q_folded \gset
+SELECT (:q_native) AS exact_matches, (:q_folded) AS case_insensitive_matches;
+ exact_matches | case_insensitive_matches 
+---------------+--------------------------
+           100 |                      200
+(1 row)
+
+-- If all dimensions qualify, the join search builds only the join rels of
+-- the canonical order, which is the order the query lists them in.  It then
+-- needs about as much planner memory as with join_collapse_limit = 1, which
+-- forces that order.  A dimension that does not qualify can also be joined
+-- at any other point, so the search takes noticeably more memory.  The four
+-- dimensions d1 to d4 always qualify and widen the difference.
+CREATE FUNCTION pg_temp.dimensions_qualify(query text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  plan json;
+  search_memory bigint;
+BEGIN
+  -- the first planning after DDL also fills the caches
+  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;
+$$;
+-- Only comparisons with the same equality semantics are single-row lookups.
+SELECT pg_temp.dimensions_qualify(:'q_native') AS exact_qualifies,
+       NOT pg_temp.dimensions_qualify(:'q_folded') AS case_insensitive_does_not_qualify,
+       pg_temp.dimensions_qualify(replace(:'q_native', 'f.k = s.k',
+                                          'f.k COLLATE "POSIX" = s.k')) AS deterministic_qualifies;
+ exact_qualifies | case_insensitive_does_not_qualify | deterministic_qualifies 
+-----------------+-----------------------------------+-------------------------
+ t               | t                                 | t
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = off;
+SELECT NOT pg_temp.dimensions_qualify(:'q_native') AS feature_off_does_not_qualify;
+ feature_off_does_not_qualify 
+------------------------------
+ t
+(1 row)
+
+SET LOCAL enable_starjoin_ordering = on;
+ALTER TABLE fact DROP CONSTRAINT exact_fk;
+SELECT NOT pg_temp.dimensions_qualify(:'q_native') AS without_text_fk_does_not_qualify;
+ without_text_fk_does_not_qualify 
+----------------------------------
+ t
+(1 row)
+
+-- A non-mergejoinable equality stays in joininfo instead of forming an
+-- equivalence class.  Check every such clause matched to the FK column.
+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);
+ALTER TABLE spellings DROP CONSTRAINT spellings_pkey;
+CREATE UNIQUE INDEX ON spellings (k pg_temp.loose_ops);
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES spellings (k);
+SELECT replace(:'q_native', 'f.k = s.k', 's.k OPERATOR(pg_temp.===) f.k') AS q_loose \gset
+SELECT pg_temp.dimensions_qualify(:'q_loose') AS loose_native_qualifies,
+       NOT pg_temp.dimensions_qualify(:'q_loose' || ' WHERE s.k COLLATE pg_temp.starjoin_ci
+                                          OPERATOR(pg_temp.===) f.k') AS loose_mismatch_does_not_qualify;
+ loose_native_qualifies | loose_mismatch_does_not_qualify 
+------------------------+---------------------------------
+ t                      | t
+(1 row)
+
+-- A nondeterministic collation is fine if it agrees with both proofs.
+-- The index columns are deliberately in a different order from the FK.
+CREATE TEMP TABLE labels (k text COLLATE pg_temp.starjoin_ci, tag text COLLATE "C");
+CREATE UNIQUE INDEX labels_key ON labels (tag, k);
+CREATE TEMP TABLE refs (
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4,
+  k text COLLATE pg_temp.starjoin_ci NOT NULL, tag text COLLATE "C" NOT NULL,
+  CONSTRAINT label_fk FOREIGN KEY (k, tag) REFERENCES labels (k, tag)
+);
+INSERT INTO labels VALUES ('A', 'x');
+INSERT INTO refs VALUES (1, 1, 1, 1, 'a', 'x');
+SELECT $$SELECT count(*) FROM refs f JOIN labels l ON f.k = l.k AND f.tag = l.tag
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_label \gset
+SELECT pg_temp.dimensions_qualify(:'q_label') AS matching_nondeterministic_qualifies;
+ matching_nondeterministic_qualifies 
+-------------------------------------
+ t
+(1 row)
+
+-- Now only the index is case-sensitive.  A join using its collation
+-- can miss the referenced row; one using the column's can match two.
+ALTER TABLE refs DROP CONSTRAINT label_fk;
+DROP INDEX labels_key;
+CREATE UNIQUE INDEX labels_key ON labels (tag, k COLLATE "C");
+ALTER TABLE refs ADD FOREIGN KEY (k, tag) REFERENCES labels (k, tag);
+SELECT replace(:'q_label', 'f.k = l.k', 'f.k COLLATE "C" = l.k') AS q_index \gset
+SELECT (:q_index) AS index_collation_matches,
+       pg_temp.dimensions_qualify(:'q_index') AS qualifies;
+ index_collation_matches | qualifies 
+-------------------------+-----------
+                       0 | f
+(1 row)
+
+INSERT INTO labels VALUES ('a', 'x');
+SELECT (:q_label) AS column_collation_matches,
+       pg_temp.dimensions_qualify(:'q_label') AS qualifies;
+ column_collation_matches | qualifies 
+--------------------------+-----------
+                        2 | f
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/expected/starjoin_fk_collation_1.out b/src/test/regress/expected/starjoin_fk_collation_1.out
new file mode 100644
index 00000000000..6f5ca237bb0
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_collation_1.out
@@ -0,0 +1,8 @@
+--
+-- Starjoin lookup semantics under different collations
+--
+SELECT getdatabaseencoding() <> 'UTF8' OR NOT EXISTS
+  (SELECT FROM pg_collation WHERE collprovider = 'i' AND collname <> 'unicode')
+  AS skip_test \gset
+\if :skip_test
+\quit
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index eb5058cbdea..d3f7384e811 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_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_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_collation.sql b/src/test/regress/sql/starjoin_fk_collation.sql
new file mode 100644
index 00000000000..2bfb64d3a1d
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_collation.sql
@@ -0,0 +1,116 @@
+--
+-- Starjoin lookup semantics under different collations
+--
+SELECT getdatabaseencoding() <> 'UTF8' OR NOT EXISTS
+  (SELECT FROM pg_collation WHERE collprovider = 'i' AND collname <> 'unicode')
+  AS skip_test \gset
+\if :skip_test
+\quit
+\endif
+
+BEGIN;
+SET LOCAL enable_starjoin_ordering = on;
+
+CREATE TEMP TABLE d1 (id int PRIMARY KEY);
+CREATE TEMP TABLE d2 (id int PRIMARY KEY);
+CREATE TEMP TABLE d3 (id int PRIMARY KEY);
+CREATE TEMP TABLE d4 (id int PRIMARY KEY);
+INSERT INTO d1 VALUES (1);
+INSERT INTO d2 VALUES (1);
+INSERT INTO d3 VALUES (1);
+INSERT INTO d4 VALUES (1);
+CREATE COLLATION pg_temp.starjoin_ci
+  (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
+CREATE TEMP TABLE spellings (k text COLLATE "C" PRIMARY KEY);
+INSERT INTO spellings VALUES ('a'), ('A');
+CREATE TEMP TABLE fact (
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4,
+  k text COLLATE "C" NOT NULL CONSTRAINT exact_fk REFERENCES spellings
+);
+INSERT INTO fact SELECT 1, 1, 1, 1, 'a' FROM generate_series(1, 100);
+
+SELECT $$SELECT count(*) FROM fact f JOIN spellings s ON f.k = s.k
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_native \gset
+SELECT replace(:'q_native', 'f.k = s.k', 'f.k COLLATE pg_temp.starjoin_ci = s.k')
+  AS q_folded \gset
+SELECT (:q_native) AS exact_matches, (:q_folded) AS case_insensitive_matches;
+
+-- If all dimensions qualify, the join search builds only the join rels of
+-- the canonical order, which is the order the query lists them in.  It then
+-- needs about as much planner memory as with join_collapse_limit = 1, which
+-- forces that order.  A dimension that does not qualify can also be joined
+-- at any other point, so the search takes noticeably more memory.  The four
+-- dimensions d1 to d4 always qualify and widen the difference.
+CREATE FUNCTION pg_temp.dimensions_qualify(query text) RETURNS bool
+LANGUAGE plpgsql SET join_collapse_limit = 8 AS $$
+DECLARE
+  plan json;
+  search_memory bigint;
+BEGIN
+  -- the first planning after DDL also fills the caches
+  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;
+$$;
+
+-- Only comparisons with the same equality semantics are single-row lookups.
+SELECT pg_temp.dimensions_qualify(:'q_native') AS exact_qualifies,
+       NOT pg_temp.dimensions_qualify(:'q_folded') AS case_insensitive_does_not_qualify,
+       pg_temp.dimensions_qualify(replace(:'q_native', 'f.k = s.k',
+                                          'f.k COLLATE "POSIX" = s.k')) AS deterministic_qualifies;
+SET LOCAL enable_starjoin_ordering = off;
+SELECT NOT pg_temp.dimensions_qualify(:'q_native') AS feature_off_does_not_qualify;
+SET LOCAL enable_starjoin_ordering = on;
+ALTER TABLE fact DROP CONSTRAINT exact_fk;
+SELECT NOT pg_temp.dimensions_qualify(:'q_native') AS without_text_fk_does_not_qualify;
+
+-- A non-mergejoinable equality stays in joininfo instead of forming an
+-- equivalence class.  Check every such clause matched to the FK column.
+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);
+ALTER TABLE spellings DROP CONSTRAINT spellings_pkey;
+CREATE UNIQUE INDEX ON spellings (k pg_temp.loose_ops);
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES spellings (k);
+SELECT replace(:'q_native', 'f.k = s.k', 's.k OPERATOR(pg_temp.===) f.k') AS q_loose \gset
+SELECT pg_temp.dimensions_qualify(:'q_loose') AS loose_native_qualifies,
+       NOT pg_temp.dimensions_qualify(:'q_loose' || ' WHERE s.k COLLATE pg_temp.starjoin_ci
+                                          OPERATOR(pg_temp.===) f.k') AS loose_mismatch_does_not_qualify;
+
+-- A nondeterministic collation is fine if it agrees with both proofs.
+-- The index columns are deliberately in a different order from the FK.
+CREATE TEMP TABLE labels (k text COLLATE pg_temp.starjoin_ci, tag text COLLATE "C");
+CREATE UNIQUE INDEX labels_key ON labels (tag, k);
+CREATE TEMP TABLE refs (
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4,
+  k text COLLATE pg_temp.starjoin_ci NOT NULL, tag text COLLATE "C" NOT NULL,
+  CONSTRAINT label_fk FOREIGN KEY (k, tag) REFERENCES labels (k, tag)
+);
+INSERT INTO labels VALUES ('A', 'x');
+INSERT INTO refs VALUES (1, 1, 1, 1, 'a', 'x');
+SELECT $$SELECT count(*) FROM refs f JOIN labels l ON f.k = l.k AND f.tag = l.tag
+  JOIN d1 ON f.a = d1.id JOIN d2 ON f.b = d2.id
+  JOIN d3 ON f.c = d3.id JOIN d4 ON f.d = d4.id$$ AS q_label \gset
+SELECT pg_temp.dimensions_qualify(:'q_label') AS matching_nondeterministic_qualifies;
+
+-- Now only the index is case-sensitive.  A join using its collation
+-- can miss the referenced row; one using the column's can match two.
+ALTER TABLE refs DROP CONSTRAINT label_fk;
+DROP INDEX labels_key;
+CREATE UNIQUE INDEX labels_key ON labels (tag, k COLLATE "C");
+ALTER TABLE refs ADD FOREIGN KEY (k, tag) REFERENCES labels (k, tag);
+SELECT replace(:'q_label', 'f.k = l.k', 'f.k COLLATE "C" = l.k') AS q_index \gset
+SELECT (:q_index) AS index_collation_matches,
+       pg_temp.dimensions_qualify(:'q_index') AS qualifies;
+INSERT INTO labels VALUES ('a', 'x');
+SELECT (:q_label) AS column_collation_matches,
+       pg_temp.dimensions_qualify(:'q_label') AS qualifies;
+ROLLBACK;
-- 
2.56.1

