From 168b417ae3c9c6441c0b6edfd2e9ff17ac77cac8 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 21/30] FK: Exclude referenced-side partition entries from
 starjoin dimensions

A foreign key referencing a partitioned table has a pg_constraint row
for each referenced partition, with the OID of that partition and its
unique index.  A join directly to a leaf can therefore match such an
entry, even though the foreign key guarantees a match only somewhere in
the partition tree.  The unique index of the leaf proves at most one
match, not that there is one.

Pass conparentid through the foreign key cache and the planner's
metadata.  For a foreign key with a parent constraint, check whether the
parent references the same relation.  A constraint inherited on the
referencing side keeps the target and is valid evidence, as is a
separately declared foreign key to the leaf.  Foreign keys without a
parent need no extra catalog lookup.

Update STARJOINS.md.  Add starjoin_fk_partition, where all 100 facts
join to the parent but only one joins to the selected leaf.  It checks
that the leaf does not qualify on the foreign key of the parent alone,
but does on a genuine foreign key to it, both before and after attaching
the fact table as a referencing partition.
---
 STARJOINS.md                                  | 21 ++++-
 src/backend/nodes/outfuncs.c                  |  1 +
 src/backend/optimizer/plan/initsplan.c        | 26 ++++++
 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_partition.out        | 81 +++++++++++++++++++
 src/test/regress/parallel_schedule            |  2 +-
 .../regress/sql/starjoin_fk_partition.sql     | 66 +++++++++++++++
 10 files changed, 200 insertions(+), 3 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_partition.out
 create mode 100644 src/test/regress/sql/starjoin_fk_partition.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index d070ebee587..189d6575bd8 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -279,8 +279,8 @@ The fact has to be a base relation too.
    would remove every fact row instead of preserving it.  Joins to the
    whole partitioned table never qualify, as the referenced relation has
    to be scanned without inheritance (see the conditions inherited from
-   foreign key matching).  Direct joins to leaf partitions are not
-   affected.
+   foreign key matching).  Direct joins to leaf partitions are subject
+   to the foreign key requirements below.
 
 2. All join columns on the fact are NOT NULL.
 
@@ -372,6 +372,18 @@ key, not when matching foreign keys for selectivity estimation, and an
 ordinary equality foreign key between the same relations remains
 eligible.
 
+A foreign key referencing a partitioned table has a pg_constraint row
+for each referenced partition, with the OID of that partition and its
+unique index.  A join directly to a leaf partition can match such an
+entry, although the foreign key guarantees a match only somewhere in the
+partition tree, so the unique index of the leaf proves at most one
+match, not that there is one.  So a foreign key whose parent constraint
+(`conparentid`) references a different relation is rejected, as it's a
+referenced-side partition entry.  A constraint inherited on the
+referencing side keeps the referenced relation, and is valid evidence,
+as is a separately declared foreign key to the leaf.  Foreign keys
+without a parent constraint need no extra catalog lookup.
+
 ### Equality semantics
 
 Matching foreign keys to join clauses for selectivity estimation does
@@ -579,3 +591,8 @@ the plans, the planning cost, or the regression tests.
   - starjoin_fk_only: an ONLY scan of the referenced partitioned parent
     matches no rows and does not qualify, while an ONLY scan of a
     directly referenced leaf partition does.
+  - starjoin_fk_partition: all 100 fact rows join the partitioned
+    parent, but only one joins the selected leaf, which does not qualify
+    on the foreign key of the parent alone, but does on a genuine
+    foreign key to it, both before and after attaching the fact table as
+    a referencing partition.
diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index 7782bc71514..e09c8225664 100644
--- a/src/backend/nodes/outfuncs.c
+++ b/src/backend/nodes/outfuncs.c
@@ -438,6 +438,7 @@ _outForeignKeyOptInfo(StringInfo str, const ForeignKeyOptInfo *node)
 	WRITE_UINT_FIELD(con_relid);
 	WRITE_UINT_FIELD(ref_relid);
 	WRITE_OID_FIELD(conindid);
+	WRITE_OID_FIELD(conparentid);
 	WRITE_BOOL_FIELD(conperiod);
 	WRITE_INT_FIELD(nkeys);
 	WRITE_ATTRNUMBER_ARRAY(conkey, node->nkeys);
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index a9e0f7e4899..95928d93cdf 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -14,6 +14,7 @@
  */
 #include "postgres.h"
 
+#include "access/htup_details.h"
 #include "access/nbtree.h"
 #include "access/sysattr.h"
 #include "catalog/pg_constraint.h"
@@ -36,6 +37,7 @@
 #include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
 #include "utils/rel.h"
+#include "utils/syscache.h"
 #include "utils/typcache.h"
 
 /* These parameters are set by GUC */
@@ -4346,6 +4348,30 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
 		if (fkinfo->conperiod)
 			continue;
 
+		/*
+		 * An FK to a partitioned table has a pg_constraint row for each
+		 * referenced partition, but the match can be in any partition. A
+		 * child FK on the referencing side is fine: it references the same
+		 * table as its parent constraint.
+		 */
+		if (OidIsValid(fkinfo->conparentid))
+		{
+			HeapTuple	tuple;
+			Form_pg_constraint parent;
+			bool		same_target;
+
+			tuple = SearchSysCache1(CONSTROID,
+									ObjectIdGetDatum(fkinfo->conparentid));
+			if (!HeapTupleIsValid(tuple))
+				continue;
+			parent = (Form_pg_constraint) GETSTRUCT(tuple);
+			same_target = parent->confrelid ==
+				root->simple_rte_array[dim_rel->relid]->relid;
+			ReleaseSysCache(tuple);
+			if (!same_target)
+				continue;
+		}
+
 		for (i = 0; i < fkinfo->nkeys; i++)
 		{
 			if (!bms_is_member(fkinfo->conkey[i], fact_rel->notnullattnums))
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index d8ea695d719..273ab7e360c 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -661,6 +661,7 @@ get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
 			info->con_relid = rel->relid;
 			info->ref_relid = rti;
 			info->conindid = cachedfk->conindid;
+			info->conparentid = cachedfk->conparentid;
 			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 1c68ffa062d..384064eeeb4 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -4816,6 +4816,7 @@ RelationGetFKeyList(Relation relation)
 		info->conrelid = constraint->conrelid;
 		info->confrelid = constraint->confrelid;
 		info->conindid = constraint->conindid;
+		info->conparentid = constraint->conparentid;
 		info->conenforced = constraint->conenforced;
 		info->conperiod = constraint->conperiod;
 
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index e1250386327..4034db2160e 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -1484,6 +1484,8 @@ typedef struct ForeignKeyOptInfo
 	Index		ref_relid;
 	/* OID of the index supporting the referenced key */
 	Oid			conindid;
+	/* OID of the parent constraint, if any */
+	Oid			conparentid;
 	/* 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 2641210c0d7..0fd66f6d9d8 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -292,6 +292,8 @@ typedef struct ForeignKeyCacheInfo
 	Oid			confrelid;
 	/* index supporting the referenced key */
 	Oid			conindid;
+	/* parent constraint, if this entry derives from partitioning */
+	Oid			conparentid;
 	/* number of columns in the foreign key */
 	int			nkeys;
 
diff --git a/src/test/regress/expected/starjoin_fk_partition.out b/src/test/regress/expected/starjoin_fk_partition.out
new file mode 100644
index 00000000000..79fd8de7fc0
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_partition.out
@@ -0,0 +1,81 @@
+-- An FK to a partitioned dimension does not guarantee a match in one leaf.
+BEGIN;
+SET LOCAL geqo = off;
+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 TEMP TABLE dim (k int PRIMARY KEY) PARTITION BY LIST (k);
+CREATE TEMP TABLE dim_one PARTITION OF dim FOR VALUES IN (1);
+CREATE TEMP TABLE dim_rest PARTITION OF dim DEFAULT;
+INSERT INTO dim VALUES (1), (2);
+CREATE TEMP TABLE fact (
+  k int NOT NULL REFERENCES dim,
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4
+);
+INSERT INTO fact SELECT CASE WHEN i = 1 THEN 1 ELSE 2 END, 1, 1, 1, 1
+  FROM generate_series(1, 100) i;
+ANALYZE fact, dim_one, d1, d2, d3, d4;
+SELECT $$SELECT count(*) FROM fact f 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
+  JOIN dim_one p ON f.k = p.k$$ AS q_leaf \gset
+SELECT replace(:'q_leaf', 'JOIN dim_one', 'JOIN dim') AS q_parent \gset
+-- As in starjoin_fk_only, compare planner memory for flat and forced join
+-- order. If the leaf qualifies, both searches build the canonical order.
+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
+  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;
+$$;
+SELECT (:q_parent) AS parent_matches, (:q_leaf) AS leaf_matches,
+       pg_temp.dimensions_qualify(:'q_leaf') AS parent_fk_qualifies;
+ parent_matches | leaf_matches | parent_fk_qualifies 
+----------------+--------------+---------------------
+            100 |            1 | f
+(1 row)
+
+-- A genuine FK to the same leaf suffices, even alongside the parent's FK.
+UPDATE fact SET k = 1;
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES dim_one;
+SELECT (:q_leaf) AS leaf_matches,
+       pg_temp.dimensions_qualify(:'q_leaf') AS direct_fk_qualifies;
+ leaf_matches | direct_fk_qualifies 
+--------------+---------------------
+          100 | t
+(1 row)
+
+-- Attach that FK to one on the referencing parent. It still guarantees a
+-- match for this fact partition, unlike the referenced-side child entry.
+CREATE TEMP TABLE fact_parent (
+  LIKE fact, CONSTRAINT leaf_fk FOREIGN KEY (k) REFERENCES dim_one
+) PARTITION BY LIST (k);
+ALTER TABLE fact_parent ATTACH PARTITION fact DEFAULT;
+SELECT pg_temp.dimensions_qualify(:'q_leaf') AS inherited_fk_qualifies;
+ inherited_fk_qualifies 
+------------------------
+ t
+(1 row)
+
+ALTER TABLE fact_parent DROP CONSTRAINT leaf_fk;
+SELECT pg_temp.dimensions_qualify(:'q_leaf') AS parent_fk_alone_qualifies;
+ parent_fk_alone_qualifies 
+---------------------------
+ f
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index c76847b6406..69f8e0c8854 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_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_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_partition.sql b/src/test/regress/sql/starjoin_fk_partition.sql
new file mode 100644
index 00000000000..05177751ed3
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_partition.sql
@@ -0,0 +1,66 @@
+-- An FK to a partitioned dimension does not guarantee a match in one leaf.
+BEGIN;
+SET LOCAL geqo = off;
+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 TEMP TABLE dim (k int PRIMARY KEY) PARTITION BY LIST (k);
+CREATE TEMP TABLE dim_one PARTITION OF dim FOR VALUES IN (1);
+CREATE TEMP TABLE dim_rest PARTITION OF dim DEFAULT;
+INSERT INTO dim VALUES (1), (2);
+CREATE TEMP TABLE fact (
+  k int NOT NULL REFERENCES dim,
+  a int NOT NULL REFERENCES d1, b int NOT NULL REFERENCES d2,
+  c int NOT NULL REFERENCES d3, d int NOT NULL REFERENCES d4
+);
+INSERT INTO fact SELECT CASE WHEN i = 1 THEN 1 ELSE 2 END, 1, 1, 1, 1
+  FROM generate_series(1, 100) i;
+ANALYZE fact, dim_one, d1, d2, d3, d4;
+
+SELECT $$SELECT count(*) FROM fact f 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
+  JOIN dim_one p ON f.k = p.k$$ AS q_leaf \gset
+SELECT replace(:'q_leaf', 'JOIN dim_one', 'JOIN dim') AS q_parent \gset
+
+-- As in starjoin_fk_only, compare planner memory for flat and forced join
+-- order. If the leaf qualifies, both searches build the canonical order.
+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
+  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;
+$$;
+SELECT (:q_parent) AS parent_matches, (:q_leaf) AS leaf_matches,
+       pg_temp.dimensions_qualify(:'q_leaf') AS parent_fk_qualifies;
+
+-- A genuine FK to the same leaf suffices, even alongside the parent's FK.
+UPDATE fact SET k = 1;
+ALTER TABLE fact ADD FOREIGN KEY (k) REFERENCES dim_one;
+SELECT (:q_leaf) AS leaf_matches,
+       pg_temp.dimensions_qualify(:'q_leaf') AS direct_fk_qualifies;
+
+-- Attach that FK to one on the referencing parent. It still guarantees a
+-- match for this fact partition, unlike the referenced-side child entry.
+CREATE TEMP TABLE fact_parent (
+  LIKE fact, CONSTRAINT leaf_fk FOREIGN KEY (k) REFERENCES dim_one
+) PARTITION BY LIST (k);
+ALTER TABLE fact_parent ATTACH PARTITION fact DEFAULT;
+SELECT pg_temp.dimensions_qualify(:'q_leaf') AS inherited_fk_qualifies;
+ALTER TABLE fact_parent DROP CONSTRAINT leaf_fk;
+SELECT pg_temp.dimensions_qualify(:'q_leaf') AS parent_fk_alone_qualifies;
+ROLLBACK;
-- 
2.56.1

