From f197473abac4468194ed7709f2fabe9c274f2185 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 09/30] Allow joining a starjoin dimension to rels without
 join clauses

Commit b501ed8a135 rejected all joinrels containing a cluster dimension
but not the fact (in subproblems with the fact).  But that also
prevented joining a dimension to rels without any join clauses (e.g.
tables listed in FROM with no join conditions).  Such rels can only be
joined by a cartesian product, and joining them to the fact multiplies
the rows for all the following joins, while joining them to a dimension,
in the inner of the hash join of the dimension to the fact, may be much
cheaper.

So allow joinrels with a single dimension but without the fact again,
when the input without the dimension has no join clauses, i.e. no
equivalence class joins and no joininfo clauses other than
pseudoconstant ones.  For each set of the other rels, the search still
builds at most d+1 joinrels without the fact, just like with the fact.

In 1500 random star queries, each with some rels without join clauses,
this makes 400 plans cheaper (they were up to 30% more expensive), and
none more expensive.

Update STARJOINS.md, also describing the effect on other random queries
and on the planning memory.  Add starjoin_other checks that a star with
two scans of a 2-row table without join clauses gets a plan as cheap as
with the GUC disabled, and showing the limitation of the canonical
order.  Adjust the comments in starjoin_reproducers.
---
 STARJOINS.md                                  | 81 +++++++++++++++++--
 src/backend/optimizer/path/joinrels.c         | 64 ++++++++++++---
 src/test/regress/expected/starjoin_other.out  | 49 ++++++++++-
 .../regress/expected/starjoin_reproducers.out |  9 ++-
 src/test/regress/sql/starjoin_other.sql       | 44 +++++++++-
 src/test/regress/sql/starjoin_reproducers.sql |  9 ++-
 6 files changed, 228 insertions(+), 28 deletions(-)

diff --git a/STARJOINS.md b/STARJOINS.md
index b4d29602783..77068f314af 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -5,6 +5,15 @@ by the `enable_starjoin_ordering` GUC: the overall design, the
 conditions for a relation to be treated as a dimension, and the open
 questions and issues.
 
+The plan costs, planning memory and timings quoted below were measured
+when the corresponding rule was introduced or the issue was found.  The
+query corpora are 1500 random star queries, each with some rels without
+join clauses (603 of them with a pseudoconstant qual), and three other
+corpora of 600 random queries, mixing stars with outer joins, subqueries
+and other rels.  One of the three was generated to make the last-ditch
+pass of `join_search_one_level` join the dimensions to rels without the
+fact.
+
 ## Overall design
 
 ### Motivation
@@ -98,9 +107,62 @@ the dimensions have join clauses only to the fact (and no join order
 restrictions).  `join_search_one_level` builds them when the other rel
 has no join clauses, or in the last-ditch pass, when no other join is
 possible at that level.  They may get joined further, and so the search
-might consider many subsets of the dimensions without the fact.  So such
-joinrels are rejected.  They are not needed, as the dimensions can
-always be joined to the joinrels with the fact, in the canonical order.
+might consider many subsets of the dimensions without the fact.  Most of
+them are not needed, as the dimensions can be joined to the joinrels
+with the fact, in the canonical order.  But joining the other rel to the
+fact by a cartesian product multiplies the rows for all the following
+joins, while joining it to a dimension (e.g. in the inner of the hash
+join of the last dimension to the fact) may be much cheaper.  So a
+joinrel with a dimension but without the fact is allowed if it has a
+single dimension, and the input without the dimension has no join
+clauses, i.e. no equivalence class joins and no joininfo clauses other
+than pseudoconstant ones.  This is similar to the test
+`join_search_one_level` uses to decide which rels to join by clauseless
+joins.  A pseudoconstant qual is in the joininfo list of every rel in
+its join domain, but it's not a join clause (it's evaluated just once,
+in a gating Result node), so it's ignored.
+
+For example, with a fact table xf (100k rows), dimensions xd1, xd2 and
+xd3 (10, 100 and 1000 rows), and tables xo1 and xo2 (1 and 2 rows)
+without join clauses:
+
+    SELECT ... FROM xo1, xd3, xf, xd2, xo2, xd1
+     WHERE xf.xd2 = xd2.id AND xf.xd3 = xd3.id AND xf.xd1 = xd1.id
+
+With the GUC disabled, the plan hashes the product of xd1, xo1 and xo2
+(20 rows) for the last join, so the hash joins process just the 100k
+fact rows (cost 9406.66).  If all joinrels with a dimension but without
+the fact were rejected, the product of xo1 and xo2 could only be joined
+to joinrels with xf, and the cheapest such plan would join it to xf
+first, so all three hash joins would process 200k rows (cost 10691.02,
+14% more).
+
+Compared to rejecting all these joinrels, allowing them made 400 of the
+1500 random star queries cheaper (they were up to 30% more expensive),
+and none more expensive.  In the three other corpora, it made 188, 231
+and 0 plans cheaper (they were up to 66% and 111% more expensive), and
+1, 9 and 0 plans more expensive, by less than 1%, but those 10 plans
+cost the same as with the GUC disabled.  The numbers of queries with
+plans more expensive than with the GUC disabled (by more than 0.1%)
+dropped from 493 to 285, from 199 to 32 and from 235 to 29 (there were
+none in the third corpus).  No query failed to plan or tripped an
+assertion.  Star queries with a pseudoconstant qual were not affected,
+as they have no starjoin clusters (see the open issues).  The search
+considers joining the dimensions to the rels without join clauses, which
+increased the planning memory with the GUC enabled by 13% for the 897
+star queries without a pseudoconstant qual, and by 2.7%, 4.3% and 0% for
+the three other corpora (by up to 48% for a single query).  That's still
+only 20%, 80%, 34% and 74% of the planning memory with the GUC disabled.
+
+Without the condition on the join clauses (allowing a single dimension
+joined to any rel), or without any restriction at all, the plan costs
+are the same in all the queries, but the search builds more joinrels.
+In 25 queries (23 of them generated for the last-ditch pass), the
+planning memory increased by up to 17% (20% without any restriction).
+
+For each set of the other rels, the search builds at most d+1 joinrels
+without the fact (with no dimension, or with one of the d dimensions),
+just like with the fact.
 
 ### Join search subproblems
 
@@ -297,6 +359,12 @@ the plans, the planning cost, or the regression tests.
   the clusters would be enough to fix this.  The quals would still make
   the dimensions joinable to each other without the fact, but such
   joinrels are restricted (see `starjoin_order_invalid`).
+- A dimension gets joined to the fact at its position in the canonical
+  order, so if a rel without join clauses is joined to a dimension
+  that's not the last one, the joins of the following dimensions process
+  the multiplied rows.  The clauseless_first_cost_higher check in
+  starjoin_other shows this, for a star with two scans of a 2-row table
+  without join clauses.
 
 ## Regression tests
 
@@ -330,9 +398,10 @@ the plans, the planning cost, or the regression tests.
   the GUC enabled and disabled.  The cases include extra join clauses
   between the fact and a dimension, OR clauses, dimensions of very
   different widths, outer joins and semijoins, stars split into
-  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.
+  subproblems, GEQO, eager aggregation, and rels without join clauses.
+  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
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index b40333d6943..c3b015bc29c 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -2181,7 +2181,8 @@ get_matching_part_pairs(PlannerInfo *root, RelOptInfo *joinrel,
  * decomposition of any joinrel containing the fact - the cluster dimensions
  * in the joinrel must form a prefix of the order determined when collecting
  * the starjoin clusters.  Joinrels containing a cluster dimension but not
- * the fact are not allowed at all.
+ * the fact may contain only a single dimension, joined to rels without join
+ * clauses.
  *
  * Clusters are computed for the whole query, but the join search may be split
  * into multiple subproblems (join_collapse_limit, from_collapse_limit, FULL
@@ -2271,18 +2272,61 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 
 		/*
 		 * With the fact in this subproblem, joinrels with a dimension but
-		 * without the fact are not needed, as the dimensions can be joined to
-		 * the joinrels with the fact (in the canonical order).  The
-		 * dimensions have join clauses only to the fact (and no join order
-		 * restrictions), so such joinrels are cartesian products, built only
-		 * when the other rel has no join clauses, or by the last-ditch pass
-		 * of join_search_one_level.  But they may get joined further, and so
-		 * the search might consider many subsets of the dimensions without
-		 * the fact.
+		 * without the fact are cartesian products, as the dimensions have
+		 * join clauses only to the fact (and no join order restrictions).
+		 * join_search_one_level builds them when the other rel has no join
+		 * clauses, or in the last-ditch pass.  They may get joined further,
+		 * and so the search might consider many subsets of the dimensions
+		 * without the fact.
+		 *
+		 * Most of them are not needed, as the dimensions can be joined to the
+		 * joinrels with the fact (in the canonical order).  But a rel without
+		 * join clauses can only be joined by a cartesian product, and joining
+		 * it to the fact multiplies the rows for all the following joins,
+		 * while joining it to a dimension (e.g. in the inner of the hash join
+		 * of the last dimension to the fact) may be much cheaper.  So we
+		 * allow joinrels with a single dimension, joined to a rel without
+		 * join clauses (ignoring pseudoconstant quals), as in the clauseless
+		 * joins of join_search_one_level.  For each set of the other rels,
+		 * the search then builds at most d+1 joinrels without the fact (with
+		 * no dimension, or with one of the d dimensions), just like with the
+		 * fact.
+		 *
+		 * Outside the last-ditch pass, join_search_one_level joins a
+		 * dimension to a rel without the fact only if that rel has no join
+		 * clauses, and the joinrel then gets joined only to rels with the
+		 * fact (by the join clauses of the dimension).  So it builds joinrels
+		 * with several dimensions but without the fact only as a result of
+		 * the last-ditch pass, and rejecting them maintains the d+1 bound
+		 * even then.
 		 */
 		if (!bms_is_member(c->fact_relid, join_relids))
 		{
-			violates = bms_overlap(cluster_dims, join_relids);
+			cluster_dims = bms_int_members(cluster_dims, join_relids);
+
+			if (bms_membership(cluster_dims) == BMS_MULTIPLE)
+				violates = true;
+			else if (cluster_dims != NULL)
+			{
+				RelOptInfo *other;
+				ListCell   *lc2;
+
+				/* the input without the dimension */
+				other = bms_overlap(rel1->relids, cluster_dims) ? rel2 : rel1;
+
+				violates = other->has_eclass_joins;
+				foreach(lc2, other->joininfo)
+				{
+					RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
+
+					if (!rinfo->pseudoconstant)
+					{
+						violates = true;
+						break;
+					}
+				}
+			}
+
 			bms_free(cluster_dims);
 			if (violates)
 				break;
diff --git a/src/test/regress/expected/starjoin_other.out b/src/test/regress/expected/starjoin_other.out
index 192a5cafc72..77f431f2a67 100644
--- a/src/test/regress/expected/starjoin_other.out
+++ b/src/test/regress/expected/starjoin_other.out
@@ -135,6 +135,9 @@ ALTER TABLE starjoin_other_f
   ADD FOREIGN KEY (d8) REFERENCES starjoin_other_d8,
   ADD FOREIGN KEY (d9) REFERENCES starjoin_other_d9,
   ADD FOREIGN KEY (d10) REFERENCES starjoin_other_d10;
+-- small table, joined to a star without join clauses
+CREATE TABLE starjoin_other_s (id int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_s VALUES (1), (2);
 VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
   starjoin_other_pf, starjoin_other_wa, starjoin_other_wb, starjoin_other_wc,
   starjoin_other_wf, starjoin_other_h1, starjoin_other_h2, starjoin_other_h3,
@@ -143,7 +146,7 @@ VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
   starjoin_other_d7, starjoin_other_d8, starjoin_other_d9, starjoin_other_d10,
   starjoin_other_c1, starjoin_other_c2, starjoin_other_c3, starjoin_other_c4,
   starjoin_other_c5, starjoin_other_c6, starjoin_other_c7, starjoin_other_c8,
-  starjoin_other_f;
+  starjoin_other_f, starjoin_other_s;
 --
 -- Extra (non-FK) join clause between the fact and a dimension
 --
@@ -537,6 +540,48 @@ SELECT starjoin_other_plan(:'q_eager_last', true)
  t
 (1 row)
 
+--
+-- Rels without join clauses
+--
+-- A rel without join clauses can only be joined by a cartesian product.
+-- Joining it to the fact multiplies the rows for all the following joins,
+-- while joining it to a dimension (in the inner of the hash join of the
+-- dimension to the fact) may be much cheaper.  So a dimension may be joined
+-- to such rels before the fact.  Here two scans of a table with 2 rows (s1
+-- and s2) have no join clauses, and the best plan joins their product to h1,
+-- the last dimension in the canonical order.
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id,
+  starjoin_other_s AS s1, starjoin_other_s AS s2
+$$ AS q_clauseless \gset
+SELECT starjoin_other_cost(:'q_clauseless', true)
+       <= starjoin_other_cost(:'q_clauseless', false) * 1.01 AS clauseless_cost_ok;
+ clauseless_cost_ok 
+--------------------
+ t
+(1 row)
+
+-- The dimension still gets joined to the fact in the canonical order.  With
+-- h1 as the first dimension, the joins to h2 and h3 process the multiplied
+-- rows, so the plan with the GUC enabled is more expensive.
+SELECT $$
+SELECT count(*) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id,
+  starjoin_other_s AS s1, starjoin_other_s AS s2
+$$ AS q_clauseless_first \gset
+SELECT starjoin_other_cost(:'q_clauseless_first', true)
+       > starjoin_other_cost(:'q_clauseless_first', false) * 1.01 AS clauseless_first_cost_higher;
+ clauseless_first_cost_higher 
+------------------------------
+ t
+(1 row)
+
 RESET max_parallel_workers_per_gather;
 DROP FUNCTION starjoin_other_cost(text, bool);
 DROP FUNCTION starjoin_other_memory(text, bool);
@@ -549,4 +594,4 @@ DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
   starjoin_other_d6, starjoin_other_d7, starjoin_other_d8, starjoin_other_d9,
   starjoin_other_d10, starjoin_other_c1, starjoin_other_c2, starjoin_other_c3,
   starjoin_other_c4, starjoin_other_c5, starjoin_other_c6, starjoin_other_c7,
-  starjoin_other_c8;
+  starjoin_other_c8, starjoin_other_s;
diff --git a/src/test/regress/expected/starjoin_reproducers.out b/src/test/regress/expected/starjoin_reproducers.out
index 4968c290776..032dc4e9c35 100644
--- a/src/test/regress/expected/starjoin_reproducers.out
+++ b/src/test/regress/expected/starjoin_reproducers.out
@@ -11,8 +11,9 @@
 -- build any N-way joins".
 --
 -- In query J, the last-ditch pass would join dimensions to rels without the
--- fact (and two such rels would then get joined), but such joinrels are not
--- allowed, and the join search must not fail without them.
+-- fact (and two such joinrels would then get joined).  Those rels have join
+-- clauses, so such joinrels are not allowed, and the join search must not
+-- fail without them.
 --
 -- For each query, show the plan with the GUC enabled, and then check that
 -- the query returns the same result with the GUC enabled and disabled.
@@ -563,8 +564,8 @@ RESET join_collapse_limit;
 -- star (the fact has a join clause only to w, outside the subquery) and two
 -- outer joins of three rels each, linked by a non-strict clause between their
 -- nullable sides.  Nothing can be joined at level 4, so the last-ditch pass
--- joins the outer joins to other rels, but not to the dimensions, as such
--- joinrels would not include the fact.
+-- joins the outer joins to other rels, but not to the dimensions (without the
+-- fact, a dimension may be joined only to rels without join clauses).
 SET from_collapse_limit = 9;
 EXPLAIN (COSTS OFF)
 SELECT count(*)
diff --git a/src/test/regress/sql/starjoin_other.sql b/src/test/regress/sql/starjoin_other.sql
index 7ecfe6d188b..3b1a7660be9 100644
--- a/src/test/regress/sql/starjoin_other.sql
+++ b/src/test/regress/sql/starjoin_other.sql
@@ -160,6 +160,10 @@ ALTER TABLE starjoin_other_f
   ADD FOREIGN KEY (d9) REFERENCES starjoin_other_d9,
   ADD FOREIGN KEY (d10) REFERENCES starjoin_other_d10;
 
+-- small table, joined to a star without join clauses
+CREATE TABLE starjoin_other_s (id int) WITH (autovacuum_enabled = off);
+INSERT INTO starjoin_other_s VALUES (1), (2);
+
 VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
   starjoin_other_pf, starjoin_other_wa, starjoin_other_wb, starjoin_other_wc,
   starjoin_other_wf, starjoin_other_h1, starjoin_other_h2, starjoin_other_h3,
@@ -168,7 +172,7 @@ VACUUM ANALYZE starjoin_other_p1, starjoin_other_p2, starjoin_other_p3,
   starjoin_other_d7, starjoin_other_d8, starjoin_other_d9, starjoin_other_d10,
   starjoin_other_c1, starjoin_other_c2, starjoin_other_c3, starjoin_other_c4,
   starjoin_other_c5, starjoin_other_c6, starjoin_other_c7, starjoin_other_c8,
-  starjoin_other_f;
+  starjoin_other_f, starjoin_other_s;
 
 --
 -- Extra (non-FK) join clause between the fact and a dimension
@@ -489,6 +493,42 @@ SELECT starjoin_other_plan(:'q_eager_first', true)
 SELECT starjoin_other_plan(:'q_eager_last', true)
        LIKE '%"Partial Mode": "Partial"%' AS eager_last_partial_agg_on;
 
+--
+-- Rels without join clauses
+--
+-- A rel without join clauses can only be joined by a cartesian product.
+-- Joining it to the fact multiplies the rows for all the following joins,
+-- while joining it to a dimension (in the inner of the hash join of the
+-- dimension to the fact) may be much cheaper.  So a dimension may be joined
+-- to such rels before the fact.  Here two scans of a table with 2 rows (s1
+-- and s2) have no join clauses, and the best plan joins their product to h1,
+-- the last dimension in the canonical order.
+--
+SELECT $$
+SELECT count(*) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id,
+  starjoin_other_s AS s1, starjoin_other_s AS s2
+$$ AS q_clauseless \gset
+
+SELECT starjoin_other_cost(:'q_clauseless', true)
+       <= starjoin_other_cost(:'q_clauseless', false) * 1.01 AS clauseless_cost_ok;
+
+-- The dimension still gets joined to the fact in the canonical order.  With
+-- h1 as the first dimension, the joins to h2 and h3 process the multiplied
+-- rows, so the plan with the GUC enabled is more expensive.
+SELECT $$
+SELECT count(*) FROM starjoin_other_hf AS hf
+  JOIN starjoin_other_h1 AS h1 ON hf.d1 = h1.id
+  JOIN starjoin_other_h2 AS h2 ON hf.d2 = h2.id
+  JOIN starjoin_other_h3 AS h3 ON hf.d3 = h3.id,
+  starjoin_other_s AS s1, starjoin_other_s AS s2
+$$ AS q_clauseless_first \gset
+
+SELECT starjoin_other_cost(:'q_clauseless_first', true)
+       > starjoin_other_cost(:'q_clauseless_first', false) * 1.01 AS clauseless_first_cost_higher;
+
 RESET max_parallel_workers_per_gather;
 
 DROP FUNCTION starjoin_other_cost(text, bool);
@@ -503,4 +543,4 @@ DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
   starjoin_other_d6, starjoin_other_d7, starjoin_other_d8, starjoin_other_d9,
   starjoin_other_d10, starjoin_other_c1, starjoin_other_c2, starjoin_other_c3,
   starjoin_other_c4, starjoin_other_c5, starjoin_other_c6, starjoin_other_c7,
-  starjoin_other_c8;
+  starjoin_other_c8, starjoin_other_s;
diff --git a/src/test/regress/sql/starjoin_reproducers.sql b/src/test/regress/sql/starjoin_reproducers.sql
index 7f53084cbfb..62b8a004317 100644
--- a/src/test/regress/sql/starjoin_reproducers.sql
+++ b/src/test/regress/sql/starjoin_reproducers.sql
@@ -11,8 +11,9 @@
 -- build any N-way joins".
 --
 -- In query J, the last-ditch pass would join dimensions to rels without the
--- fact (and two such rels would then get joined), but such joinrels are not
--- allowed, and the join search must not fail without them.
+-- fact (and two such joinrels would then get joined).  Those rels have join
+-- clauses, so such joinrels are not allowed, and the join search must not
+-- fail without them.
 --
 -- For each query, show the plan with the GUC enabled, and then check that
 -- the query returns the same result with the GUC enabled and disabled.
@@ -278,8 +279,8 @@ RESET join_collapse_limit;
 -- star (the fact has a join clause only to w, outside the subquery) and two
 -- outer joins of three rels each, linked by a non-strict clause between their
 -- nullable sides.  Nothing can be joined at level 4, so the last-ditch pass
--- joins the outer joins to other rels, but not to the dimensions, as such
--- joinrels would not include the fact.
+-- joins the outer joins to other rels, but not to the dimensions (without the
+-- fact, a dimension may be joined only to rels without join clauses).
 SET from_collapse_limit = 9;
 EXPLAIN (COSTS OFF)
 SELECT count(*)
-- 
2.56.1

