From 283fec12df34561852425024c0ff744ce5cf7896 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 07/30] Exclude sampled dimensions from starjoin clusters

A matched foreign key does not guarantee a match in a sample of the
dimension.  Exclude sampled dimensions from the clusters, without
excluding sampled facts, and document the exclusion.

Update STARJOINS.md.  Add starjoin_sample, where an index on the fact's
reference to a dimension makes the cheapest plan start with a one-row
sample of the dimension, which the canonical order would join last.  It
checks that the GUC does not change such plans, and that the join search
for a sampled fact is still pruned.
---
 STARJOINS.md                                  |  11 +-
 doc/src/sgml/config.sgml                      |   5 +-
 src/backend/optimizer/plan/initsplan.c        |   7 +-
 src/test/regress/expected/starjoin_sample.out | 162 ++++++++++++++++++
 src/test/regress/parallel_schedule            |   2 +-
 src/test/regress/sql/starjoin_sample.sql      | 133 ++++++++++++++
 6 files changed, 314 insertions(+), 6 deletions(-)
 create mode 100644 src/test/regress/expected/starjoin_sample.out
 create mode 100644 src/test/regress/sql/starjoin_sample.sql

diff --git a/STARJOINS.md b/STARJOINS.md
index 72dd4541e63..322782b56b4 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -164,10 +164,13 @@ The fact has to be a base relation too.
    reference.  The check uses the NOT NULL constraints of the columns
    (`notnullattnums`).
 
-3. The dimension has no local restriction quals (`baserestrictinfo`).
+3. The dimension has neither local restriction quals
+   (`baserestrictinfo`) nor a TABLESAMPLE clause.
 
    A restriction removes some dimension rows, so some fact rows might
-   lose their match.
+   lose their match.  Similarly, a sample of the dimension need not
+   contain the referenced row.  A sampled fact is fine, as each
+   remaining fact row still has its match.
 
 4. The dimension has no relevant join clauses to any rel other than the
    fact (checked via `have_relevant_joinclause`, which also covers
@@ -318,3 +321,7 @@ the plans, the planning cost, or the regression tests.
   subproblems, GEQO, and eager aggregation.  Each check is a single
   boolean, so that the output does not depend on platform-specific costs
   or memory usage, and some checks show the known limitations.
+- starjoin_sample checks that the GUC does not change the plans starting
+  with a sample of a dimension estimated to have a single row (which the
+  canonical order would join last), and that the join search for a
+  sampled fact is still pruned.
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 8f04e2cba4a..7ee22a69589 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -6330,8 +6330,9 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         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.
-        Only inner joins of plain tables, with no other conditions on the
-        dimension tables, are optimized.  The default is <literal>on</literal>.
+        Only inner joins of plain tables, with no other conditions or
+        <literal>TABLESAMPLE</literal> clauses on the dimension tables, are
+        optimized.  The default is <literal>on</literal>.
        </para>
       </listitem>
      </varlistentry>
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index 8a4e994ed16..1a54d021c64 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -4207,7 +4207,8 @@ has_extra_starjoin_quals(PlannerInfo *root, RelOptInfo *dim_rel,
  *
  *	2. All join columns on the fact are NOT NULL.
  *
- *	3. The dimension has no local restriction quals (baserestrictinfo).
+ *	3. The dimension has neither local restriction quals (baserestrictinfo)
+ *	   nor a TABLESAMPLE clause.
  *
  *	4. The dimension has no relevant join clauses to any rel other than
  *	   the fact (checked via have_relevant_joinclause, which also covers
@@ -4334,6 +4335,10 @@ generate_starjoin_clusters(PlannerInfo *root)
 			if (dim_rel == NULL || dim_rel->reloptkind != RELOPT_BASEREL)
 				continue;
 
+			/* Sampling may remove the row referenced by the foreign key. */
+			if (root->simple_rte_array[d]->tablesample != NULL)
+				continue;
+
 			/* No local restriction quals on the dimension. */
 			if (dim_rel->baserestrictinfo != NIL)
 				continue;
diff --git a/src/test/regress/expected/starjoin_sample.out b/src/test/regress/expected/starjoin_sample.out
new file mode 100644
index 00000000000..d55709124a2
--- /dev/null
+++ b/src/test/regress/expected/starjoin_sample.out
@@ -0,0 +1,162 @@
+--
+-- Checks for star queries with sampled relations and enable_starjoin_ordering
+--
+-- A foreign key guarantees a matching row in the referenced table, but not in
+-- a sample of it.  So a join to a sampled dimension may eliminate fact rows,
+-- and the dimension must not be part of the starjoin cluster.  Each row of a
+-- sampled fact still matches one row of each dimension, so the dimensions of
+-- a sampled fact still form a cluster.
+--
+-- The check for a sampled fact is about the planning effort (the number of
+-- join rels the join search builds), which is not visible in SQL.  So it
+-- compares the planner memory usage reported by EXPLAIN (MEMORY), which is
+-- proportional to the number of join rels and paths.
+--
+SET max_parallel_workers_per_gather = 0;
+-- the plan (without costs), with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_sample_plan(query text, starjoin bool) RETURNS text
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (COSTS OFF, FORMAT JSON) ' || query INTO plan;
+  RETURN plan::text;
+END;
+$$;
+-- memory used by the planner (in kB), with enable_starjoin_ordering
+-- enabled/disabled
+CREATE FUNCTION starjoin_sample_memory(query text, starjoin bool) RETURNS bigint
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Planning'->>'Memory Used')::bigint;
+END;
+$$;
+-- star with 6 dimensions d1-d6, with an index on the reference to d6
+DO $$
+BEGIN
+  FOR i IN 1..6 LOOP
+    EXECUTE format('CREATE TABLE starjoin_sample_d%s (id int PRIMARY KEY) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_sample_d%s SELECT generate_series(1, 1000)', i);
+  END LOOP;
+END;
+$$;
+CREATE TABLE starjoin_sample_f (id int PRIMARY KEY, d1 int NOT NULL,
+  d2 int NOT NULL, d3 int NOT NULL, d4 int NOT NULL, d5 int NOT NULL,
+  d6 int NOT NULL) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_sample_f
+SELECT i, 1 + (i * 3) % 1000, 1 + (i * 7) % 1000, 1 + (i * 11) % 1000,
+       1 + (i * 13) % 1000, 1 + (i * 17) % 1000, 1 + (i * 19) % 1000
+  FROM generate_series(1, 20000) i;
+-- add the foreign keys after loading the data (faster than checking each row)
+ALTER TABLE starjoin_sample_f
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_sample_d1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_sample_d2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_sample_d3,
+  ADD FOREIGN KEY (d4) REFERENCES starjoin_sample_d4,
+  ADD FOREIGN KEY (d5) REFERENCES starjoin_sample_d5,
+  ADD FOREIGN KEY (d6) REFERENCES starjoin_sample_d6;
+CREATE INDEX ON starjoin_sample_f (d6);
+VACUUM ANALYZE starjoin_sample_f, starjoin_sample_d1, starjoin_sample_d2,
+  starjoin_sample_d3, starjoin_sample_d4, starjoin_sample_d5,
+  starjoin_sample_d6;
+SELECT $$
+SELECT count(*) FROM starjoin_sample_f AS f
+  JOIN starjoin_sample_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_sample_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_sample_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_sample_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_sample_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_sample_d6 AS d6 ON f.d6 = d6.id
+$$ AS q_star \gset
+--
+-- Sampled dimension
+--
+-- A 0.1% sample of d6 is estimated to have a single row, matching only 20
+-- rows of the fact.  Fetching them through the index is cheaper than scanning
+-- the whole fact, so the cheapest plan starts with the sample, while the
+-- canonical order of a cluster with d6 would join it last.
+--
+SELECT replace(:'q_star', 'starjoin_sample_d6 AS d6',
+               'starjoin_sample_d6 AS d6 TABLESAMPLE BERNOULLI (0.1)')
+       AS q_bernoulli,
+       replace(:'q_star', 'starjoin_sample_d6 AS d6',
+               'starjoin_sample_d6 AS d6 TABLESAMPLE SYSTEM (0.1)')
+       AS q_system \gset
+-- the plan starts with the sample of d6
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) :q_bernoulli;
+                                          QUERY PLAN                                           
+-----------------------------------------------------------------------------------------------
+ Aggregate
+   ->  Hash Join
+         Hash Cond: (f.d5 = d5.id)
+         ->  Hash Join
+               Hash Cond: (f.d4 = d4.id)
+               ->  Hash Join
+                     Hash Cond: (f.d3 = d3.id)
+                     ->  Hash Join
+                           Hash Cond: (f.d2 = d2.id)
+                           ->  Hash Join
+                                 Hash Cond: (f.d1 = d1.id)
+                                 ->  Nested Loop
+                                       ->  Sample Scan on starjoin_sample_d6 d6
+                                             Sampling: bernoulli ('0.1'::real)
+                                       ->  Bitmap Heap Scan on starjoin_sample_f f
+                                             Recheck Cond: (d6 = d6.id)
+                                             ->  Bitmap Index Scan on starjoin_sample_f_d6_idx
+                                                   Index Cond: (d6 = d6.id)
+                                 ->  Hash
+                                       ->  Seq Scan on starjoin_sample_d1 d1
+                           ->  Hash
+                                 ->  Seq Scan on starjoin_sample_d2 d2
+                     ->  Hash
+                           ->  Seq Scan on starjoin_sample_d3 d3
+               ->  Hash
+                     ->  Seq Scan on starjoin_sample_d4 d4
+         ->  Hash
+               ->  Seq Scan on starjoin_sample_d5 d5
+(28 rows)
+
+RESET enable_starjoin_ordering;
+-- the GUC does not change the plan
+SELECT starjoin_sample_plan(:'q_bernoulli', true)
+       = starjoin_sample_plan(:'q_bernoulli', false) AS bernoulli_plan_ok;
+ bernoulli_plan_ok 
+-------------------
+ t
+(1 row)
+
+SELECT starjoin_sample_plan(:'q_system', true)
+       = starjoin_sample_plan(:'q_system', false) AS system_plan_ok;
+ system_plan_ok 
+----------------
+ t
+(1 row)
+
+--
+-- Sampled fact
+--
+-- The dimensions of a sampled fact form a cluster, so the join search is
+-- pruned.
+--
+SELECT replace(:'q_star', 'starjoin_sample_f AS f',
+               'starjoin_sample_f AS f TABLESAMPLE BERNOULLI (10)')
+       AS q_fact \gset
+SELECT starjoin_sample_memory(:'q_fact', true)
+       < starjoin_sample_memory(:'q_fact', false) * 0.5 AS sampled_fact_pruned;
+ sampled_fact_pruned 
+---------------------
+ t
+(1 row)
+
+RESET max_parallel_workers_per_gather;
+DROP FUNCTION starjoin_sample_plan(text, bool);
+DROP FUNCTION starjoin_sample_memory(text, bool);
+DROP TABLE starjoin_sample_f, starjoin_sample_d1, starjoin_sample_d2,
+  starjoin_sample_d3, starjoin_sample_d4, starjoin_sample_d5,
+  starjoin_sample_d6;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 70dfcd21d24..ae5a40811f2 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
+test: starjoin_planning starjoin_eager starjoin_plan starjoin_width starjoin_reproducers starjoin_other starjoin_sample
 
 # 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_sample.sql b/src/test/regress/sql/starjoin_sample.sql
new file mode 100644
index 00000000000..8543971fab5
--- /dev/null
+++ b/src/test/regress/sql/starjoin_sample.sql
@@ -0,0 +1,133 @@
+--
+-- Checks for star queries with sampled relations and enable_starjoin_ordering
+--
+-- A foreign key guarantees a matching row in the referenced table, but not in
+-- a sample of it.  So a join to a sampled dimension may eliminate fact rows,
+-- and the dimension must not be part of the starjoin cluster.  Each row of a
+-- sampled fact still matches one row of each dimension, so the dimensions of
+-- a sampled fact still form a cluster.
+--
+-- The check for a sampled fact is about the planning effort (the number of
+-- join rels the join search builds), which is not visible in SQL.  So it
+-- compares the planner memory usage reported by EXPLAIN (MEMORY), which is
+-- proportional to the number of join rels and paths.
+--
+
+SET max_parallel_workers_per_gather = 0;
+
+-- the plan (without costs), with enable_starjoin_ordering enabled/disabled
+CREATE FUNCTION starjoin_sample_plan(query text, starjoin bool) RETURNS text
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (COSTS OFF, FORMAT JSON) ' || query INTO plan;
+  RETURN plan::text;
+END;
+$$;
+
+-- memory used by the planner (in kB), with enable_starjoin_ordering
+-- enabled/disabled
+CREATE FUNCTION starjoin_sample_memory(query text, starjoin bool) RETURNS bigint
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (MEMORY, FORMAT JSON) ' || query INTO plan;
+  RETURN (plan->0->'Planning'->>'Memory Used')::bigint;
+END;
+$$;
+
+-- star with 6 dimensions d1-d6, with an index on the reference to d6
+DO $$
+BEGIN
+  FOR i IN 1..6 LOOP
+    EXECUTE format('CREATE TABLE starjoin_sample_d%s (id int PRIMARY KEY) WITH (autovacuum_enabled = off)', i);
+    EXECUTE format('INSERT INTO starjoin_sample_d%s SELECT generate_series(1, 1000)', i);
+  END LOOP;
+END;
+$$;
+
+CREATE TABLE starjoin_sample_f (id int PRIMARY KEY, d1 int NOT NULL,
+  d2 int NOT NULL, d3 int NOT NULL, d4 int NOT NULL, d5 int NOT NULL,
+  d6 int NOT NULL) WITH (autovacuum_enabled = off);
+
+INSERT INTO starjoin_sample_f
+SELECT i, 1 + (i * 3) % 1000, 1 + (i * 7) % 1000, 1 + (i * 11) % 1000,
+       1 + (i * 13) % 1000, 1 + (i * 17) % 1000, 1 + (i * 19) % 1000
+  FROM generate_series(1, 20000) i;
+
+-- add the foreign keys after loading the data (faster than checking each row)
+ALTER TABLE starjoin_sample_f
+  ADD FOREIGN KEY (d1) REFERENCES starjoin_sample_d1,
+  ADD FOREIGN KEY (d2) REFERENCES starjoin_sample_d2,
+  ADD FOREIGN KEY (d3) REFERENCES starjoin_sample_d3,
+  ADD FOREIGN KEY (d4) REFERENCES starjoin_sample_d4,
+  ADD FOREIGN KEY (d5) REFERENCES starjoin_sample_d5,
+  ADD FOREIGN KEY (d6) REFERENCES starjoin_sample_d6;
+
+CREATE INDEX ON starjoin_sample_f (d6);
+
+VACUUM ANALYZE starjoin_sample_f, starjoin_sample_d1, starjoin_sample_d2,
+  starjoin_sample_d3, starjoin_sample_d4, starjoin_sample_d5,
+  starjoin_sample_d6;
+
+SELECT $$
+SELECT count(*) FROM starjoin_sample_f AS f
+  JOIN starjoin_sample_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_sample_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_sample_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_sample_d4 AS d4 ON f.d4 = d4.id
+  JOIN starjoin_sample_d5 AS d5 ON f.d5 = d5.id
+  JOIN starjoin_sample_d6 AS d6 ON f.d6 = d6.id
+$$ AS q_star \gset
+
+--
+-- Sampled dimension
+--
+-- A 0.1% sample of d6 is estimated to have a single row, matching only 20
+-- rows of the fact.  Fetching them through the index is cheaper than scanning
+-- the whole fact, so the cheapest plan starts with the sample, while the
+-- canonical order of a cluster with d6 would join it last.
+--
+SELECT replace(:'q_star', 'starjoin_sample_d6 AS d6',
+               'starjoin_sample_d6 AS d6 TABLESAMPLE BERNOULLI (0.1)')
+       AS q_bernoulli,
+       replace(:'q_star', 'starjoin_sample_d6 AS d6',
+               'starjoin_sample_d6 AS d6 TABLESAMPLE SYSTEM (0.1)')
+       AS q_system \gset
+
+-- the plan starts with the sample of d6
+SET enable_starjoin_ordering = on;
+EXPLAIN (COSTS OFF) :q_bernoulli;
+RESET enable_starjoin_ordering;
+
+-- the GUC does not change the plan
+SELECT starjoin_sample_plan(:'q_bernoulli', true)
+       = starjoin_sample_plan(:'q_bernoulli', false) AS bernoulli_plan_ok;
+SELECT starjoin_sample_plan(:'q_system', true)
+       = starjoin_sample_plan(:'q_system', false) AS system_plan_ok;
+
+--
+-- Sampled fact
+--
+-- The dimensions of a sampled fact form a cluster, so the join search is
+-- pruned.
+--
+SELECT replace(:'q_star', 'starjoin_sample_f AS f',
+               'starjoin_sample_f AS f TABLESAMPLE BERNOULLI (10)')
+       AS q_fact \gset
+
+SELECT starjoin_sample_memory(:'q_fact', true)
+       < starjoin_sample_memory(:'q_fact', false) * 0.5 AS sampled_fact_pruned;
+
+RESET max_parallel_workers_per_gather;
+
+DROP FUNCTION starjoin_sample_plan(text, bool);
+DROP FUNCTION starjoin_sample_memory(text, bool);
+
+DROP TABLE starjoin_sample_f, starjoin_sample_d1, starjoin_sample_d2,
+  starjoin_sample_d3, starjoin_sample_d4, starjoin_sample_d5,
+  starjoin_sample_d6;
-- 
2.56.1

