From bc4d2d1af0beb9a5ccf681633be4832a95b6bb5e 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 16/30] FK: Exclude PERIOD foreign keys from starjoin
 dimensions

A temporal foreign key guarantees that the union of the matching
referenced periods covers the referencing period.  The join on the
overlap operator can therefore return several rows per fact row, even
when the constraint is validated and satisfied.

Pass conperiod through the relcache and the planner's foreign key
metadata.  Ignore such constraints only when looking for a starjoin
foreign key, not when matching foreign keys for selectivity estimation.
An ordinary equality foreign key between the same relations remains
eligible.

Update STARJOINS.md and the documentation of enable_starjoin_ordering.
Add starjoin_fk_period, where eight adjacent periods cover each fact
row, with the ordinary range-key equality as a positive control.
---
 STARJOINS.md                                  | 13 +++
 doc/src/sgml/config.sgml                      |  9 ++-
 src/backend/nodes/outfuncs.c                  |  1 +
 src/backend/optimizer/plan/initsplan.c        |  8 +-
 src/backend/optimizer/util/plancat.c          |  1 +
 src/backend/utils/cache/relcache.c            |  1 +
 src/include/nodes/pathnodes.h                 | 12 +--
 src/include/utils/rel.h                       |  2 +
 .../regress/expected/starjoin_fk_period.out   | 79 +++++++++++++++++++
 src/test/regress/parallel_schedule            |  2 +-
 src/test/regress/sql/starjoin_fk_period.sql   | 63 +++++++++++++++
 11 files changed, 179 insertions(+), 12 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_period.out
 create mode 100644 src/test/regress/sql/starjoin_fk_period.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index 7dfff49ffbd..ab2eae08886 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -350,6 +350,16 @@ key accounts for both equalities.  It never combines evidence from
 different foreign keys, as their keys need not reference the same
 dimension row.
 
+Temporal (PERIOD) foreign keys are skipped, using `conperiod` from the
+relcache and the planner foreign key metadata.  Such a foreign key
+guarantees only that the union of the matching referenced periods covers
+the referencing period, so the join on the overlap operator can return
+several rows per fact row, even when the constraint is validated and
+satisfied.  They are skipped only when looking for a starjoin foreign
+key, not when matching foreign keys for selectivity estimation, and an
+ordinary equality foreign key between the same relations remains
+eligible.
+
 ### Conditions inherited from foreign key matching
 
 The clusters are built from the foreign keys the planner matches to the
@@ -492,3 +502,6 @@ the plans, the planning cost, or the regression tests.
     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.
+  - 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.
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 837f3acceeb..ead0a0e6e17 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6324,10 +6324,11 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         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 foreign key with <literal>NOT NULL</literal> referencing
-        columns, joining it does not change the number of rows.  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.
+        matching a non-temporal foreign key with <literal>NOT NULL</literal>
+        referencing columns, joining it does not change the number of rows.
+        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.
         This can significantly reduce planning time for queries joining many
         dimension tables, but may occasionally miss a cheaper join order.
         The genetic query optimizer does not use this optimization, but when
diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index 40990143927..a2354c45cc9 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_BOOL_FIELD(conperiod);
 	WRITE_INT_FIELD(nkeys);
 	WRITE_ATTRNUMBER_ARRAY(conkey, node->nkeys);
 	WRITE_ATTRNUMBER_ARRAY(confkey, node->nkeys);
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index effb64b00b6..baf25dc7548 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -4215,6 +4215,10 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
 			fkinfo->ref_relid != dim_rel->relid)
 			continue;
 
+		/* Several referenced rows may together cover a PERIOD key. */
+		if (fkinfo->conperiod)
+			continue;
+
 		for (i = 0; i < fkinfo->nkeys; i++)
 		{
 			if (!bms_is_member(fkinfo->conkey[i], fact_rel->notnullattnums))
@@ -4233,8 +4237,8 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
  *		Detect star-shaped sub-joins and determine canonical join order.
  *
  * A starjoin cluster is a fact relation joined to two or more dimensions
- * via an equality condition matching a foreign key, satisfying these
- * conditions:
+ * via an equality condition matching a non-temporal foreign key, satisfying
+ * these conditions:
  *
  *	1. The dimension is a plain base relation (RELOPT_BASEREL).
  *
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index 22e0e8b11f8..d76c69608fd 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->conperiod = cachedfk->conperiod;
 			info->nkeys = cachedfk->nkeys;
 			memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
 			memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 07868bafee2..3ed28d507af 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->conenforced = constraint->conenforced;
+		info->conperiod = constraint->conperiod;
 
 		DeconstructFkConstraintRow(htup, &info->nkeys,
 								   info->conkey,
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 392589f3262..22835fb7e37 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;
+	/* Does the FK have a PERIOD column? */
+	bool		conperiod;
 	/* number of columns in the foreign key */
 	int			nkeys;
 	/* cols in referencing table */
@@ -1518,11 +1520,11 @@ typedef struct ForeignKeyOptInfo
  * A "star cluster" consists of a single "fact" base relation joined to a
  * set of "dimension" base relations.  For the cluster to be recognized,
  * each dimension must be joined to the fact via an equality condition that
- * matches a foreign key on the fact referencing the dimension. The columns
- * on the fact must all be NOT NULL, and the dimension must have no other
- * join clauses, no local restriction quals, no join order restrictions from
- * special joins, no lateral references, etc. (see generate_starjoin_clusters
- * for the full list of preconditions).
+ * matches a non-temporal foreign key on the fact referencing the dimension.
+ * The columns on the fact must all be NOT NULL, and the dimension must have
+ * no other join clauses, no local restriction quals, no join order
+ * restrictions from special joins, no lateral references, etc. (see
+ * generate_starjoin_clusters for the full list of preconditions).
  *
  * When all of these conditions hold, every join ordering that has the fact
  * as the driver produces the same row counts.  The costs may still differ
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index 7b8c2b1e362..821c653b64e 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -295,6 +295,8 @@ typedef struct ForeignKeyCacheInfo
 
 	/* Is enforced ? */
 	bool		conenforced;
+	/* Does the FK have a PERIOD column? */
+	bool		conperiod;
 
 	/*
 	 * these arrays each have nkeys valid entries:
diff --git a/src/test/regress/expected/starjoin_fk_period.out b/src/test/regress/expected/starjoin_fk_period.out
new file mode 100644
index 00000000000..1a8539969ea
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_period.out
@@ -0,0 +1,79 @@
+--
+-- A PERIOD foreign key guarantees coverage, not one matching row.
+--
+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 TEMP TABLE periods (
+  k int4range, r int4range UNIQUE, PRIMARY KEY (k, r WITHOUT OVERLAPS)
+);
+INSERT INTO periods
+  SELECT '[1,2)'::int4range, int4range(i, i + 1) FROM generate_series(0, 7) i;
+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 int4range NOT NULL, r int4range NOT NULL,
+  CONSTRAINT coverage FOREIGN KEY (k, PERIOD r) REFERENCES periods,
+  piece int4range NOT NULL REFERENCES periods (r)
+);
+INSERT INTO fact
+  SELECT 1, 1, 1, 1, '[1,2)', '[0,8)', '[0,1)' FROM generate_series(1, 100);
+SELECT $$SELECT count(*) FROM fact f JOIN periods p ON f.k = p.k AND f.r && p.r
+  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
+SELECT (SELECT count(*) FROM fact) AS fact_rows, (:query) AS joined_rows;
+ fact_rows | joined_rows 
+-----------+-------------
+       100 |         800
+(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;
+$$;
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS period_does_not_qualify;
+ period_does_not_qualify 
+-------------------------
+ t
+(1 row)
+
+-- An ordinary equality FK on the same pair of tables still qualifies.
+SELECT pg_temp.dimensions_qualify(replace(:'query', 'f.k = p.k AND f.r && p.r',
+                                          'f.piece = p.r')) AS ordinary_qualifies;
+ ordinary_qualifies 
+--------------------
+ t
+(1 row)
+
+ALTER TABLE fact DROP CONSTRAINT coverage;
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS without_period_fk_does_not_qualify;
+ without_period_fk_does_not_qualify 
+------------------------------------
+ t
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index c27f8890035..eb5058cbdea 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_geqo
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample starjoin_fk_overlap starjoin_fk_period 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_period.sql b/src/test/regress/sql/starjoin_fk_period.sql
new file mode 100644
index 00000000000..55863db6eb8
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_period.sql
@@ -0,0 +1,63 @@
+--
+-- A PERIOD foreign key guarantees coverage, not one matching row.
+--
+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 TEMP TABLE periods (
+  k int4range, r int4range UNIQUE, PRIMARY KEY (k, r WITHOUT OVERLAPS)
+);
+INSERT INTO periods
+  SELECT '[1,2)'::int4range, int4range(i, i + 1) FROM generate_series(0, 7) i;
+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 int4range NOT NULL, r int4range NOT NULL,
+  CONSTRAINT coverage FOREIGN KEY (k, PERIOD r) REFERENCES periods,
+  piece int4range NOT NULL REFERENCES periods (r)
+);
+INSERT INTO fact
+  SELECT 1, 1, 1, 1, '[1,2)', '[0,8)', '[0,1)' FROM generate_series(1, 100);
+
+SELECT $$SELECT count(*) FROM fact f JOIN periods p ON f.k = p.k AND f.r && p.r
+  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
+SELECT (SELECT count(*) FROM fact) AS fact_rows, (:query) AS joined_rows;
+
+-- 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;
+$$;
+
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS period_does_not_qualify;
+-- An ordinary equality FK on the same pair of tables still qualifies.
+SELECT pg_temp.dimensions_qualify(replace(:'query', 'f.k = p.k AND f.r && p.r',
+                                          'f.piece = p.r')) AS ordinary_qualifies;
+ALTER TABLE fact DROP CONSTRAINT coverage;
+SELECT NOT pg_temp.dimensions_qualify(:'query') AS without_period_fk_does_not_qualify;
+ROLLBACK;
-- 
2.56.1

