From cf670a6e91c4945f59ee113fc15f82a936bdfe39 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 22/30] FK: Require immutable equality for starjoin
 dimensions

A fully matched foreign key need not still have a match under the
query's comparison.  For example, a timestamptz referencing a timestamp
key is compared by interpreting the timestamp in the session's TimeZone,
so a fact inserted at noon UTC can lose its match when queried in New
York.  Neither type is collatable, so the collation checks don't prevent
treating this selective join as a lookup.

Require the PK = FK operator of every key column to be immutable before
using the foreign key to prune join orders.  This changes only the
starjoin eligibility, not the foreign key enforcement, the selectivity
estimates or the general index uniqueness proofs.

Update STARJOINS.md and the documentation of enable_starjoin_ordering.
Add starjoin_fk_timezone, with a composite foreign key whose second
comparison depends on the time zone, so that the join returns all 100
rows in UTC and none in New York, and an otherwise identical foreign key
using timestamptz on both sides, which still qualifies.
---
 STARJOINS.md                                  | 17 ++++-
 doc/src/sgml/config.sgml                      |  7 +-
 src/backend/optimizer/plan/initsplan.c        | 14 +++-
 .../regress/expected/starjoin_fk_timezone.out | 71 +++++++++++++++++++
 src/test/regress/parallel_schedule            |  2 +-
 src/test/regress/sql/starjoin_fk_timezone.sql | 59 +++++++++++++++
 6 files changed, 162 insertions(+), 8 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_fk_timezone.out
 create mode 100644 src/test/regress/sql/starjoin_fk_timezone.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index 189d6575bd8..ee905f22361 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -282,11 +282,18 @@ The fact has to be a base relation too.
    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.
+2. All join columns on the fact are NOT NULL, and their foreign key
+   equality operators are immutable.
 
    A NULL never matches, so the join would remove a fact row with a NULL
    reference.  The check uses the NOT NULL constraints of the columns
-   (`notnullattnums`).
+   (`notnullattnums`).  A satisfied foreign key need not have a match
+   under a comparison that is not immutable.  For example, a timestamptz
+   column referencing a timestamp key is compared by interpreting the
+   timestamp in the session's TimeZone, so a fact row inserted at noon
+   UTC can lose its match when queried in New York.  Neither type is
+   collatable, so the collation checks don't help.  Immutable cross-type
+   comparisons are fine.
 
 3. The dimension has neither local restriction quals
    (`baserestrictinfo`) nor a TABLESAMPLE clause.
@@ -596,3 +603,9 @@ the plans, the planning cost, or the regression tests.
     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.
+  - starjoin_fk_timezone: a composite foreign key whose second
+    comparison is time-zone-dependent, so the join returns all 100 rows
+    in UTC and none in New York, and must not qualify in either zone.
+    An otherwise identical foreign key using timestamptz on both sides
+    still qualifies, including with an immutable int/smallint comparison
+    on its first column.
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index f03ad59a832..db8d9b31a7d 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6325,9 +6325,10 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         <quote>dimension</quote> tables using foreign keys.  When a dimension
         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>.
+        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>.
         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/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index 95928d93cdf..01e7a1636bc 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -19,6 +19,7 @@
 #include "access/sysattr.h"
 #include "catalog/pg_constraint.h"
 #include "catalog/pg_opfamily.h"
+#include "catalog/pg_proc.h"
 #include "catalog/pg_type.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -4278,7 +4279,7 @@ starjoin_fk_collations_match(PlannerInfo *root, RelOptInfo *dim_rel,
 			int32		typmod;
 			int			i;
 
-			/* No collation check or catalog lookup for a noncollatable key. */
+			/* No collation to check for a noncollatable key. */
 			if (!OidIsValid(indcoll))
 				continue;
 
@@ -4376,6 +4377,14 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
 		{
 			if (!bms_is_member(fkinfo->conkey[i], fact_rel->notnullattnums))
 				break;
+
+			/*
+			 * A mutable comparison need not still find the row that matched
+			 * when the FK was checked (e.g. timestamp = timestamptz depends
+			 * on TimeZone).
+			 */
+			if (op_volatile(fkinfo->conpfeqop[i]) != PROVOLATILE_IMMUTABLE)
+				break;
 		}
 		if (i == fkinfo->nkeys &&
 			!has_extra_starjoin_quals(root, dim_rel, fkinfo) &&
@@ -4397,7 +4406,8 @@ has_starjoin_fk(PlannerInfo *root, RelOptInfo *fact_rel, RelOptInfo *dim_rel)
  *	1. The dimension is a plain base relation (RELOPT_BASEREL), not an ONLY
  *	   scan of a partitioned table.
  *
- *	2. All join columns on the fact are NOT NULL.
+ *	2. All join columns on the fact are NOT NULL and their FK equality
+ *	   operators are immutable.
  *
  *	3. The dimension has neither local restriction quals (baserestrictinfo)
  *	   nor a TABLESAMPLE clause.
diff --git a/src/test/regress/expected/starjoin_fk_timezone.out b/src/test/regress/expected/starjoin_fk_timezone.out
new file mode 100644
index 00000000000..3f54dd1fb73
--- /dev/null
+++ b/src/test/regress/expected/starjoin_fk_timezone.out
@@ -0,0 +1,71 @@
+-- A time-zone-dependent FK comparison is not a guaranteed lookup.
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+SET LOCAL TIME ZONE 'UTC';
+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 local_times (tag int, k timestamp, PRIMARY KEY (tag, k));
+CREATE TEMP TABLE instants (tag int, k timestamptz, PRIMARY KEY (tag, k));
+INSERT INTO local_times VALUES (7, '2024-01-15 12:00');
+INSERT INTO instants VALUES (7, '2024-01-15 12:00+00');
+CREATE TEMP TABLE fact (
+  tag smallint NOT NULL, k timestamptz NOT NULL,
+  FOREIGN KEY (tag, k) REFERENCES local_times,
+  FOREIGN KEY (tag, k) REFERENCES instants,
+  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 7, '2024-01-15 12:00+00', 1, 1, 1, 1
+  FROM generate_series(1, 100);
+ANALYZE fact, local_times, instants, d1, d2, d3, d4;
+SELECT $$SELECT count(*) FROM fact f JOIN local_times t ON f.tag = t.tag AND f.k = t.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_local \gset
+SELECT replace(:'q_local', 'JOIN local_times', 'JOIN instants') AS q_instant \gset
+-- Compare flat and forced join order, as in starjoin_fk_collation.
+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_local) AS utc_matches,
+       pg_temp.dimensions_qualify(:'q_local') AS utc_qualifies;
+ utc_matches | utc_qualifies 
+-------------+---------------
+         100 | f
+(1 row)
+
+SET LOCAL TIME ZONE 'America/New_York';
+SELECT (:q_local) AS ny_matches,
+       pg_temp.dimensions_qualify(:'q_local') AS ny_qualifies;
+ ny_matches | ny_qualifies 
+------------+--------------
+          0 | f
+(1 row)
+
+-- The int/smallint comparison is cross-type but immutable. With two
+-- timestamptz operands for the second column, this FK still qualifies.
+SELECT (:q_instant) AS instant_matches,
+       pg_temp.dimensions_qualify(:'q_instant') AS instant_qualifies;
+ instant_matches | instant_qualifies 
+-----------------+-------------------
+             100 | t
+(1 row)
+
+ROLLBACK;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 69f8e0c8854..b9328370875 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_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_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_timezone.sql b/src/test/regress/sql/starjoin_fk_timezone.sql
new file mode 100644
index 00000000000..5f5720dc6fe
--- /dev/null
+++ b/src/test/regress/sql/starjoin_fk_timezone.sql
@@ -0,0 +1,59 @@
+-- A time-zone-dependent FK comparison is not a guaranteed lookup.
+BEGIN;
+SET LOCAL geqo = off;
+SET LOCAL enable_starjoin_ordering = on;
+SET LOCAL TIME ZONE 'UTC';
+
+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 local_times (tag int, k timestamp, PRIMARY KEY (tag, k));
+CREATE TEMP TABLE instants (tag int, k timestamptz, PRIMARY KEY (tag, k));
+INSERT INTO local_times VALUES (7, '2024-01-15 12:00');
+INSERT INTO instants VALUES (7, '2024-01-15 12:00+00');
+CREATE TEMP TABLE fact (
+  tag smallint NOT NULL, k timestamptz NOT NULL,
+  FOREIGN KEY (tag, k) REFERENCES local_times,
+  FOREIGN KEY (tag, k) REFERENCES instants,
+  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 7, '2024-01-15 12:00+00', 1, 1, 1, 1
+  FROM generate_series(1, 100);
+ANALYZE fact, local_times, instants, d1, d2, d3, d4;
+
+SELECT $$SELECT count(*) FROM fact f JOIN local_times t ON f.tag = t.tag AND f.k = t.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_local \gset
+SELECT replace(:'q_local', 'JOIN local_times', 'JOIN instants') AS q_instant \gset
+
+-- Compare flat and forced join order, as in starjoin_fk_collation.
+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_local) AS utc_matches,
+       pg_temp.dimensions_qualify(:'q_local') AS utc_qualifies;
+SET LOCAL TIME ZONE 'America/New_York';
+SELECT (:q_local) AS ny_matches,
+       pg_temp.dimensions_qualify(:'q_local') AS ny_qualifies;
+-- The int/smallint comparison is cross-type but immutable. With two
+-- timestamptz operands for the second column, this FK still qualifies.
+SELECT (:q_instant) AS instant_matches,
+       pg_temp.dimensions_qualify(:'q_instant') AS instant_qualifies;
+ROLLBACK;
-- 
2.56.1

