From 51e99613c7f4ea39c8d07dbac51331c81ae95955 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 15/30] FK: Consider all matching foreign keys for a
 starjoin dimension

A fact can reference the same dimension through both a short key and a
composite key.  If the short foreign key was examined first, the join on
the other column looked like an extra restriction, even when the
composite foreign key accounted for both equalities.  Adding a redundant
foreign key could therefore exclude the dimension from its cluster.

Check the relation-level conditions once, then try the matching foreign
keys until one has non-nullable referencing columns and covers all the
join quals.  Do not combine evidence from different constraints, as
their keys need not reference the same dimension row.

Update STARJOINS.md, also describing how the foreign key tests infer
from the planning memory whether a dimension qualifies.  Add
starjoin_fk_overlap, exercising both orders of the foreign keys, a lone
short key, and two separate single-column foreign keys.
---
 STARJOINS.md                                  | 34 +++++++-
 src/backend/optimizer/plan/initsplan.c        | 68 ++++++++--------
 .../regress/expected/starjoin_fk_overlap.out  | 80 +++++++++++++++++++
 src/test/regress/parallel_schedule            |  2 +-
 src/test/regress/sql/starjoin_fk_overlap.sql  | 60 ++++++++++++++
 5 files changed, 205 insertions(+), 39 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_overlap.out
 create mode 100644 src/test/regress/sql/starjoin_fk_overlap.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index 2fc8a536349..7dfff49ffbd 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -54,8 +54,9 @@ The optimization consists of these parts:
   `starjoin_clusters` list of `PlannerInfo`, as `StarJoinClusterInfo`
   nodes.  Like other planner-only nodes, `StarJoinClusterInfo` needs no
   copy, equal, read or query jumble support.
-- `has_extra_starjoin_quals` checks that the foreign key accounts for
-  all the join clauses between the fact and a dimension.
+- `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_order_invalid`, called by `make_join_rel`, rejects joins
   violating the canonical order, just like various other join
   restrictions.
@@ -339,8 +340,15 @@ The fact has to be a base relation too.
 
 ### Foreign key requirements
 
-If the fact has several foreign keys referencing the dimension, the
-conditions are checked for the first one in `fkey_list`.
+A fact can reference a dimension through several foreign keys, e.g.
+through both a short key and a composite key.  `has_starjoin_fk` checks
+the conditions on the relations once, and then tries each matching
+foreign key, until one has NOT NULL referencing columns and accounts for
+all the join clauses.  So the join on the other column of the composite
+key is not mistaken for an extra restriction, when the composite foreign
+key accounts for both equalities.  It never combines evidence from
+different foreign keys, as their keys need not reference the same
+dimension row.
 
 ### Conditions inherited from foreign key matching
 
@@ -415,6 +423,11 @@ the plans, the planning cost, or the regression tests.
   discount, so an extension implementing its own join search has to call
   `starjoin_geqo_levels` to make the same choice between the standard
   join search and GEQO.
+- The foreign key suites infer whether a relation qualifies as a
+  dimension from the planning memory, accepting up to 10% more than when
+  planning the canonical order (see the regression tests).  That's an
+  indirect check, and changes of the planning memory use could flip its
+  results.
 
 ## Regression tests
 
@@ -466,3 +479,16 @@ the plans, the planning cost, or the regression tests.
   join search is used.  It compares the plan costs, and reports the
   planning times through the starjoin_geqo_timings psql variable.  It's
   commented out in parallel_schedule, like the other _large suites.
+- The foreign key suites check which relations qualify as dimensions.
+  If all the dimensions of a star qualify, the join search builds only
+  the joinrels of the canonical order, and needs about as much planning
+  memory as with `join_collapse_limit` set to 1, which forces that
+  order.  A relation that does not qualify can be joined at any other
+  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.
+  - 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
+    separate single-column foreign keys don't.
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index 1a54d021c64..effb64b00b6 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -151,6 +151,8 @@ 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 has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel,
+							RelOptInfo *dim_rel);
 
 
 /*****************************************************************************
@@ -4195,6 +4197,37 @@ has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
 	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.
+ */
+static bool
+has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
+{
+	ListCell   *lc;
+
+	foreach(lc, root->fkey_list)
+	{
+		ForeignKeyOptInfo *fkinfo = lfirst_node(ForeignKeyOptInfo, lc);
+		int			i;
+
+		if (fkinfo->con_relid != fact_rel->relid ||
+			fkinfo->ref_relid != dim_rel->relid)
+			continue;
+
+		for (i = 0; i < fkinfo->nkeys; i++)
+		{
+			if (!bms_is_member(fkinfo->conkey[i], fact_rel->notnullattnums))
+				break;
+		}
+		if (i == fkinfo->nkeys &&
+			!has_extra_starjoin_quals(root, dim_rel, fkinfo))
+			return true;
+	}
+
+	return false;
+}
+
 /*
  * generate_starjoin_clusters
  *		Detect star-shaped sub-joins and determine canonical join order.
@@ -4325,10 +4358,8 @@ generate_starjoin_clusters(PlannerInfo *root)
 		{
 			Index		d = (Index) lfirst_int(lc2);
 			RelOptInfo *dim_rel = root->simple_rel_array[d];
-			ForeignKeyOptInfo *fkinfo = NULL;
 			ListCell   *lc3;
 			bool		ok = true;
-			int			colno;
 			int			r;
 
 			/* has to be a baserel (it's referenced by a FK, so?) */
@@ -4349,37 +4380,6 @@ generate_starjoin_clusters(PlannerInfo *root)
 			if (!bms_is_empty(dim_rel->lateral_referencers))
 				continue;
 
-			/* Find the matching FK so we can check NOT NULL on conkey cols */
-			foreach(lc3, root->fkey_list)
-			{
-				ForeignKeyOptInfo *fki = (ForeignKeyOptInfo *) lfirst(lc3);
-
-				if ((fki->con_relid == f) && (fki->ref_relid == d))
-				{
-					fkinfo = fki;
-					break;
-				}
-			}
-
-			/* we should have found a FK, that's how we got the array */
-			Assert(fkinfo != NULL);
-
-			/*
-			 * Make sure all columns on the fact side are NOT NULL. We know
-			 * the FK is fully matched by the join, so use that.
-			 */
-			for (colno = 0; colno < fkinfo->nkeys; colno++)
-			{
-				if (!bms_is_member(fkinfo->conkey[colno],
-								   fact_rel->notnullattnums))
-				{
-					ok = false;
-					break;
-				}
-			}
-			if (!ok)
-				continue;
-
 			/*
 			 * Should not be constrained by any SpecialJoinInfo (for now the
 			 * starjoin is done only for inner joins).  Only the minimal sets
@@ -4446,7 +4446,7 @@ generate_starjoin_clusters(PlannerInfo *root)
 			if (!ok)
 				continue;
 
-			if (has_extra_starjoin_quals(root, dim_rel, fkinfo))
+			if (!has_starjoin_fk(root, fact_rel, dim_rel))
 				continue;
 
 			/* Qualifies as a dimension. */
diff --git a/src/test/regress/expected/starjoin_fk_overlap.out b/src/test/regress/expected/starjoin_fk_overlap.out
new file mode 100644
index 00000000000..38c36ec02fc
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_overlap.out
@@ -0,0 +1,80 @@
+--
+-- Overlapping foreign keys between a starjoin fact and dimension
+--
+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);
+CREATE TEMP TABLE pair (k int PRIMARY KEY, v int UNIQUE NOT NULL, UNIQUE (k, v));
+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 int NOT NULL, v int NOT NULL,
+  CONSTRAINT a_short FOREIGN KEY (k) REFERENCES pair (k),
+  CONSTRAINT m_full FOREIGN KEY (k, v) REFERENCES pair (k, v)
+);
+SELECT $$SELECT count(*) FROM fact f JOIN pair p ON f.k = p.k AND f.v = p.v
+  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 query \gset
+-- 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;
+$$;
+-- The composite FK accounts for both equalities, regardless of which FK
+-- is examined first.  Vary both creation and name order.
+SELECT pg_temp.dimensions_qualify(:'query') AS short_first_qualifies;
+ short_first_qualifies 
+-----------------------
+ t
+(1 row)
+
+ALTER TABLE fact DROP CONSTRAINT a_short;
+SELECT pg_temp.dimensions_qualify(:'query') AS full_only_qualifies;
+ full_only_qualifies 
+---------------------
+ t
+(1 row)
+
+ALTER TABLE fact ADD CONSTRAINT z_short FOREIGN KEY (k) REFERENCES pair (k);
+SELECT pg_temp.dimensions_qualify(:'query') AS full_first_qualifies;
+ full_first_qualifies 
+----------------------
+ t
+(1 row)
+
+-- The short FK alone is insufficient.  Nor can two independent FKs
+-- prove that both equalities match the same dimension row.
+ALTER TABLE fact DROP CONSTRAINT m_full;
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS short_only_does_not_qualify;
+ short_only_does_not_qualify 
+-----------------------------
+ t
+(1 row)
+
+ALTER TABLE fact ADD FOREIGN KEY (v) REFERENCES pair (v);
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS separate_keys_do_not_qualify;
+ separate_keys_do_not_qualify 
+------------------------------
+ t
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 660f1c75611..c27f8890035 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_geqo
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap 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_overlap.sql b/src/test/regress/sql/starjoin_fk_overlap.sql
new file mode 100644
index 00000000000..1e536f9b293
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_overlap.sql
@@ -0,0 +1,60 @@
+--
+-- Overlapping foreign keys between a starjoin fact and dimension
+--
+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);
+CREATE TEMP TABLE pair (k int PRIMARY KEY, v int UNIQUE NOT NULL, UNIQUE (k, v));
+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 int NOT NULL, v int NOT NULL,
+  CONSTRAINT a_short FOREIGN KEY (k) REFERENCES pair (k),
+  CONSTRAINT m_full FOREIGN KEY (k, v) REFERENCES pair (k, v)
+);
+
+SELECT $$SELECT count(*) FROM fact f JOIN pair p ON f.k = p.k AND f.v = p.v
+  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 query \gset
+
+-- 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;
+$$;
+
+-- The composite FK accounts for both equalities, regardless of which FK
+-- is examined first.  Vary both creation and name order.
+SELECT pg_temp.dimensions_qualify(:'query') AS short_first_qualifies;
+ALTER TABLE fact DROP CONSTRAINT a_short;
+SELECT pg_temp.dimensions_qualify(:'query') AS full_only_qualifies;
+ALTER TABLE fact ADD CONSTRAINT z_short FOREIGN KEY (k) REFERENCES pair (k);
+SELECT pg_temp.dimensions_qualify(:'query') AS full_first_qualifies;
+
+-- The short FK alone is insufficient.  Nor can two independent FKs
+-- prove that both equalities match the same dimension row.
+ALTER TABLE fact DROP CONSTRAINT m_full;
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS short_only_does_not_qualify;
+ALTER TABLE fact ADD FOREIGN KEY (v) REFERENCES pair (v);
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS separate_keys_do_not_qualify;
+ROLLBACK;
-- 
2.56.1

