From 2bd10e97874a7756506e03cd70500712e45d7c43 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 28/30] PSEUDOCONST: Ignore pseudoconstant quals when
 choosing clauseless joins

Commit b40e9d769a4 made have_relevant_joinclause() ignore pseudoconstant
quals, so that a qual like "now() > '2000-01-01'", which is in the
joininfo list of every rel in its join domain, does not make all the
rels joinable to each other.  But join_search_one_level() still decided
which rels to join by clauseless joins by checking whether the joininfo
list is empty, and with such a qual it never is.  So a rel without any
join clauses was joined only in the last-ditch pass, once nothing else
could be joined, even if joining it at the bottom of the join tree would
be much cheaper.  This does not depend on enable_starjoin_ordering.

Fix by checking for join clauses the same way as
have_relevant_joinclause() does, ignoring pseudoconstant quals, in a new
function has_join_clauses().  In 1500 random star queries, 603 of them
with such a qual, this makes 362 of those plans cheaper with the GUC
enabled, 381 cheaper with the GUC disabled, and 4 more expensive.

Commit 04d202a6ad1 allowed joining a starjoin dimension without the fact
only to a rel without join clauses.  With the qual no longer making all
the rels joinable, that condition matters only for the last-ditch pass,
where it may reject the cheapest plan.  So remove it, and allow any
joinrel with a single dimension but without the fact.  Joinrels with
multiple dimensions but without the fact are still rejected.

Update STARJOINS.md, also describing the effect on the other random
queries and on the planning memory.  Add starjoin_other checks that the
last-ditch case gets a plan as cheap as with the GUC disabled, and that
the search still rejects the joinrels with multiple dimensions but
without the fact, which the last-ditch pass would otherwise build.  Add
starjoin_var_free checks that the qual does not double the planning
memory for a chain of eight rels without starjoin clusters, and does not
change the join tree of a star with two rels without join clauses.
Adjust the comments in starjoin_other and starjoin_reproducers.
---
 STARJOINS.md                                  | 139 ++++++++++++++----
 src/backend/optimizer/path/joinrels.c         |  86 ++++++-----
 src/test/regress/expected/starjoin_other.out  |  92 +++++++++++-
 .../regress/expected/starjoin_reproducers.out |  13 +-
 .../regress/expected/starjoin_var_free.out    |  64 ++++++++
 src/test/regress/sql/starjoin_other.sql       |  88 ++++++++++-
 src/test/regress/sql/starjoin_reproducers.sql |  13 +-
 src/test/regress/sql/starjoin_var_free.sql    |  59 ++++++++
 8 files changed, 457 insertions(+), 97 deletions(-)

diff --git a/STARJOINS.md b/STARJOINS.md
index 321a3870c59..810a4e20542 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -70,6 +70,8 @@ The optimization consists of these parts:
   subproblem.
 - `starjoin_geqo_levels` counts the dimensions as fewer rels toward
   `geqo_threshold`.
+- `has_join_clauses` decides which rels `join_search_one_level` joins by
+  clauseless joins.
 
 The clusters are determined in `src/backend/optimizer/plan/initsplan.c`,
 and the join order is restricted in
@@ -125,15 +127,9 @@ 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.
+join of the last dimension to the fact) may be much cheaper.  So
+joinrels with a single dimension but without the fact are allowed, while
+joinrels with multiple dimensions but without the fact are rejected.
 
 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)
@@ -166,15 +162,43 @@ 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).
+If pseudoconstant quals made all the rels joinable to each other, a
+single dimension would have to be allowed only if the input without it
+has no join clauses (no equivalence class joins and no joininfo clauses
+other than pseudoconstant ones), as otherwise the search would consider
+each dimension with all subsets of the other rels.  But they don't (see
+the pseudoconstant quals below), so such a condition would matter only
+for the last-ditch pass, which joins rels by cartesian products when
+nothing else can be joined, including rels with join clauses (to rels
+outside the subproblem).  In the 3300 random queries of the four
+corpora, the condition rejects joins in 25 queries, all of them in that
+pass, and there it may reject the cheapest plan.  In a starjoin_other
+test, the cheapest plan with the GUC disabled joins the product of three
+rels and a dimension to the join of the fact and the other dimension
+(cost 1855.87).  With the condition, the product has to be joined to the
+fact first, and the following joins to the dimensions process the
+multiplied rows (cost 2364.13, 27% more).  Without it, the test query
+gets the same plan as with the GUC disabled, and no plan cost changes in
+the 3300 queries.  The search builds more joinrels in the 25 queries,
+which increases their planning memory by up to 17%, but it's still only
+65% to 91% of the planning memory with the GUC disabled.
 
 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.
+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.  The last-ditch pass may join a dimension to a rel with
+join clauses to other rels (not the fact), and those clauses may then
+join the result to other such joinrels.  In a starjoin_other test with a
+star of four dimensions and four groups of five rels, linked by join
+clauses that can be used only above outer joins (so that the last-ditch
+pass joins each group to each dimension), the planning memory with the
+GUC enabled is 21% of that with the GUC disabled.  It would be 31% if
+joinrels with multiple dimensions but without the fact were allowed.
 
 ### Join search subproblems
 
@@ -291,14 +315,53 @@ Var-free quals and non-gating outer-join ON quals retain their
 treatment.  This is deliberately a generic planner change, not
 conditional on the GUC.  It affects clause-based join enumeration in the
 standard join search and GEQO, including queries without starjoin
-clusters, and with the GUC disabled.  In the 1500 random star queries,
-it makes 384 of the 603 plans with a pseudoconstant qual more expensive
-with the GUC disabled (by up to 16%), and 1 cheaper (by 38%).  In the
-three other corpora, it makes 45 plans more expensive with the GUC
-disabled (by up to 25%, or 42% for a query planned by GEQO), and 11
-cheaper (by up to 1.9%).  The plans that get more expensive relied on
-the qual making all the rels joinable to each other.  The plans of
-queries without a pseudoconstant qual do not change.
+clusters, and with the GUC disabled.  In the three other corpora, it
+makes 45 plans more expensive with the GUC disabled (by up to 25%, or
+42% for a query planned by GEQO), and 11 cheaper (by up to 1.9%).  The
+plans of queries without a pseudoconstant qual do not change.
+
+`join_search_one_level` decides which rels to join by clauseless joins
+using `has_join_clauses`, which checks for join clauses the same way as
+`have_relevant_joinclause`, ignoring pseudoconstant quals.  A rel whose
+joininfo list has only pseudoconstant quals is then joined by clauseless
+joins, just like a rel with an empty joininfo list.  That doesn't depend
+on the GUC either.  If `join_search_one_level` checked whether the
+joininfo list is empty instead, a rel without join clauses (e.g. a table
+listed in FROM without a join condition) would be treated as having some
+in a query with a pseudoconstant qual.  It would be joined only to rels
+it has a relevant join clause to, of which there are none, so it would
+get joined only in the last-ditch pass, once nothing else can be joined
+(typically at the top of the join tree), even if joining it at the
+bottom (e.g. to a small dimension, in the inner of a hash join) is much
+cheaper.
+
+Compared to that, `has_join_clauses` doesn't change the plans of the 897
+random star queries without a pseudoconstant qual.  Of the 603 queries
+with the qual, it makes 362 plans cheaper with the GUC enabled, and 381
+with the GUC disabled (they were up to 16% more expensive), and 4 plans
+more expensive (by 55%, 30%, 2% and 2%).  All 603 queries get the same
+join order as without the qual (including the 4 more expensive plans,
+where the last-ditch pass happened to be cheaper), while otherwise
+that's the case for only 226 of them with the GUC enabled, and for 207
+with the GUC disabled.  No plan costs change in the three other corpora,
+one of them with 445 queries with a pseudoconstant qual.  The search
+builds the clauseless joins for the queries with the qual, which
+increases their planning memory, by up to 3.7 times with the GUC enabled
+and 6.8 times with the GUC disabled, to within 75kB of the planning
+memory without the qual.
+
+Compared to the qual making all the rels joinable to each other, as when
+`have_relevant_joinclause` does not ignore pseudoconstant quals, 541 of
+the 603 plans cost the same with the GUC disabled, 1 is cheaper and 61
+are more expensive (by up to 7.4%, except for the two by 55% and 30%).
+Ignoring the quals only in `have_relevant_joinclause` would make 384 of
+the 603 plans more expensive (by up to 16%).  With the GUC disabled, the
+planning memory is lower than when the qual makes all the rels joinable
+to each other for 464 of the 603 queries (by up to 17 times), and higher
+for 71 of them (by up to 1.7%).  For a chain of eight rels without
+starjoin clusters, the planning memory is 258kB without the qual and
+259kB with it, but 2864kB if the qual makes all the rels joinable to
+each other.
 
 ## Conditions for a dimension
 
@@ -569,17 +632,27 @@ the plans, the planning cost, or the regression tests.
   dimension from the planning memory, accepting up to 10% more than when
   planning the canonical order (see the regression tests).  That's an
   indirect check, and changes of the planning memory use could flip its
-  results.
+  results.  The qualifying cases measure at most 1.0 times the memory of
+  the canonical order, while the lowest of the others measure 1.153
+  times (release build) and 1.163 times (assert-enabled build), both in
+  starjoin_fk_opclass.
 - No regression test makes `starjoin_fk_operand_matches` reject a
   relabel changing the actual type seen by a polymorphic operator.
 - Volatile Var-free quals are not pseudoconstant, so they still disable
   the clusters, which is conservative.
-- Ignoring pseudoconstant quals in `have_relevant_joinclause` changes
-  the plans also with the GUC disabled.  It makes 384 of the 603 plans
-  with a pseudoconstant qual in the 1500 random star queries more
-  expensive (by up to 16%), and 45 plans in the three other corpora (by
-  up to 25%, or 42% for a query planned by GEQO), as they relied on the
-  qual making all the rels joinable to each other.
+- Ignoring pseudoconstant quals for join connectivity makes some plans
+  with such a qual more expensive than when the qual made all the rels
+  joinable to each other, also with the GUC disabled.  That's the case
+  for 61 of the 603 plans with the qual in the 1500 random star queries
+  (by up to 7.4%, except for two by 55% and 30%), and for 45 plans in
+  the three other corpora (by up to 25%, or 42% for a query planned by
+  GEQO).
+- With the GUC enabled, plans cost more than with the GUC disabled (by
+  more than 0.1%) in 481 of the 1500 random star queries (by up to
+  7.5%), and in 32, 29 and 4 of the 600 queries in each of the three
+  other corpora (by up to 11%, 7% and 0.9%), while 6 plans of the last
+  of them are cheaper (by up to 1.9%).  All of them come from the
+  limitations of the canonical order described above.
 
 ## Regression tests
 
@@ -693,4 +766,8 @@ the plans, the planning cost, or the regression tests.
   control, and checks the execution-time TRUE, FALSE and NULL gates with
   the GUC enabled and disabled, in the standard join search and in GEQO,
   the outer-join ON semantics, and the cartesian fallback needed by a
-  subproblem without the fact.
+  subproblem without the fact.  For a chain of eight rels without
+  starjoin clusters, it checks that such a qual does not double the
+  planning memory.  For a star with two rels without join clauses, it
+  checks that the qual does not change the join tree, with the GUC
+  enabled and disabled.
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index 55029d1bbcb..ffd8212f703 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -36,6 +36,7 @@ static void make_rels_by_clauseless_joins(PlannerInfo *root,
 static bool starjoin_order_invalid(PlannerInfo *root,
 								   RelOptInfo *rel1,
 								   RelOptInfo *rel2);
+static bool has_join_clauses(RelOptInfo *rel);
 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
 static bool has_legal_joinclause(PlannerInfo *root, RelOptInfo *rel);
 static bool restriction_is_constant_false(List *restrictlist,
@@ -101,8 +102,7 @@ join_search_one_level(PlannerInfo *root, int level)
 	{
 		RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
 
-		if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
-			has_join_restriction(root, old_rel))
+		if (has_join_clauses(old_rel) || has_join_restriction(root, old_rel))
 		{
 			int			first_rel;
 
@@ -176,7 +176,7 @@ join_search_one_level(PlannerInfo *root, int level)
 			 * participate in join-order restrictions --- then we might have
 			 * to force a bushy join plan.
 			 */
-			if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
+			if (!has_join_clauses(old_rel) &&
 				!has_join_restriction(root, old_rel))
 				continue;
 
@@ -1412,6 +1412,37 @@ have_join_order_restriction(PlannerInfo *root,
 }
 
 
+/*
+ * has_join_clauses
+ *		Detect whether the specified relation has any join clauses, either
+ *		in its joininfo list or as EquivalenceClass joins.
+ *
+ * Pseudoconstant quals are ignored, as in have_relevant_joinclause().  They
+ * are in the joininfo lists only because their required_relids determine
+ * where they get evaluated, and have_relevant_joinclause() does not consider
+ * them a reason to join any rels.  A rel with no other join clauses has to
+ * be joined by cartesian products, just like a rel with no joininfo at all.
+ */
+static bool
+has_join_clauses(RelOptInfo *rel)
+{
+	ListCell   *lc;
+
+	if (rel->has_eclass_joins)
+		return true;
+
+	foreach(lc, rel->joininfo)
+	{
+		RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
+
+		if (!rinfo->pseudoconstant)
+			return true;
+	}
+
+	return false;
+}
+
+
 /*
  * has_join_restriction
  *		Detect whether the specified relation has join-order restrictions,
@@ -2251,8 +2282,7 @@ starjoin_setup_subproblem(PlannerInfo *root)
  * 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 may contain only a single dimension, joined to rels without join
- * clauses.
+ * the fact may contain only a single dimension.
  *
  * Clusters are computed for the whole query, but the join search may be split
  * into multiple subproblems (join_collapse_limit, from_collapse_limit, FULL
@@ -2324,18 +2354,16 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 		 * 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, which is consistent with how the dimensions count toward
-		 * geqo_threshold (see starjoin_geqo_levels).
+		 * 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 we allow joinrels with a single dimension.
+		 * 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, which is consistent with how
+		 * the dimensions count toward geqo_threshold (see
+		 * starjoin_geqo_levels).
 		 *
 		 * 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
@@ -2347,29 +2375,7 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 		 */
 		if (!bms_is_member(c->fact_relid, join_relids))
 		{
-			if (bms_membership(cluster_dims) == BMS_MULTIPLE)
-				violates = true;
-			else
-			{
-				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;
-					}
-				}
-			}
-
+			violates = (bms_membership(cluster_dims) == BMS_MULTIPLE);
 			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 4908e2e46b3..43a74c3e7b3 100644
--- a/src/test/regress/expected/starjoin_other.out
+++ b/src/test/regress/expected/starjoin_other.out
@@ -576,13 +576,12 @@ SELECT starjoin_other_cost(:'q_clauseless_first', true)
  t
 (1 row)
 
--- But without the fact, a dimension must not be joined to rels with join
--- clauses, or the search might consider each dimension with all subsets of
--- c1-c5.  A pseudoconstant qual is in the joininfo list of every rel, but it
--- is not a join clause, so it must not make the rels joinable to each other.
--- The rels c1-c5 are joinable to each other even without the qual, through
--- an equivalence class (including f.id) or through a join clause referencing
--- all of them, so the qual should not add any joinrels.
+-- A pseudoconstant qual is in the joininfo list of every rel, but it is not a
+-- join clause, so it must not make the rels joinable to each other, or the
+-- search might consider each dimension with all subsets of c1-c5 (without
+-- the fact).  The rels c1-c5 are joinable to each other even without the
+-- qual, through an equivalence class (including f.id) or through a join
+-- clause referencing all of them, so the qual should not add any joinrels.
 SELECT $$
 SELECT count(*) FROM starjoin_other_f AS f
   JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
@@ -625,11 +624,90 @@ SELECT starjoin_other_memory(:'q_joininfo' || $$WHERE now() > '2000-01-01'$$, tr
  t
 (1 row)
 
+RESET join_collapse_limit;
+-- Without the fact, a dimension may be joined to rels with join clauses too,
+-- in the last-ditch pass of the join search, which joins rels by Cartesian
+-- products when no other joins are possible.  Here the star and c1-c3 have
+-- join clauses only to c4, which is outside the subproblem (with
+-- join_collapse_limit = 6).  The cheapest plan joins the product of c1-c3
+-- and d2 to the join of f and d1, so that the dimensions are not joined to
+-- the product of c1-c3 and f, and the plan is as cheap as with the GUC
+-- disabled.
+SELECT $$
+SELECT count(*) FROM starjoin_other_c4 AS c4 JOIN (
+  starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  CROSS JOIN (starjoin_other_c1 AS c1
+    JOIN starjoin_other_c2 AS c2 ON c1.id = c2.id
+    JOIN starjoin_other_c3 AS c3 ON c2.id = c3.id)
+) ON c3.id = c4.id AND f.a = c4.v
+$$ AS q_last_ditch \gset
+SET join_collapse_limit = 6;
+SELECT starjoin_other_cost(:'q_last_ditch', true)
+       <= starjoin_other_cost(:'q_last_ditch', false) * 1.01 AS last_ditch_cost_ok;
+ last_ditch_cost_ok 
+--------------------
+ t
+(1 row)
+
+RESET join_collapse_limit;
+-- The last-ditch pass may also join a dimension to rels with join clauses
+-- to other rels (not the fact), and those clauses might then build joinrels
+-- with several dimensions but without the fact.  Those joinrels are
+-- rejected, so that for each set of the other rels the search builds at
+-- most d+1 joinrels without the fact (and not up to 2^d).  Here the star
+-- has join clauses only to a, which is outside the subproblem (with
+-- join_collapse_limit = 25), and four groups (outer joins of s and a view
+-- joining four copies of s) only to each other.  But the clauses linking
+-- the groups reference the nullable sides of the outer joins, so they
+-- can't be used before the groups are complete.  So once the star and the
+-- groups are complete (with five rels each), the last-ditch pass joins
+-- each group to each dimension, and the clauses linking the groups then
+-- join those joinrels to each other.
+CREATE VIEW starjoin_other_v AS
+SELECT s1.id FROM starjoin_other_s AS s1
+  JOIN starjoin_other_s AS s2 USING (id)
+  JOIN starjoin_other_s AS s3 USING (id)
+  JOIN starjoin_other_s AS s4 USING (id);
+SELECT $$
+SELECT count(*) FROM starjoin_other_a AS a JOIN (
+  starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  CROSS JOIN (starjoin_other_s AS s1
+    LEFT JOIN starjoin_other_v AS v1 ON s1.id = v1.id)
+  JOIN (starjoin_other_s AS s2
+    LEFT JOIN starjoin_other_v AS v2 ON s2.id = v2.id)
+    ON coalesce(v1.id, 0) = coalesce(v2.id, 0)
+  JOIN (starjoin_other_s AS s3
+    LEFT JOIN starjoin_other_v AS v3 ON s3.id = v3.id)
+    ON coalesce(v2.id, 0) = coalesce(v3.id, 0)
+  JOIN (starjoin_other_s AS s4
+    LEFT JOIN starjoin_other_v AS v4 ON s4.id = v4.id)
+    ON coalesce(v3.id, 0) = coalesce(v4.id, 0)
+) ON f.a = a.id
+$$ AS q_last_ditch_dims \gset
+-- single subproblem with 25 rels, without GEQO
+SET join_collapse_limit = 25;
+SET geqo = off;
+SELECT starjoin_other_memory(:'q_last_ditch_dims', true)
+       < starjoin_other_memory(:'q_last_ditch_dims', false) * 0.25
+       AS last_ditch_dims_pruned;
+ last_ditch_dims_pruned 
+------------------------
+ t
+(1 row)
+
+RESET geqo;
 RESET join_collapse_limit;
 RESET max_parallel_workers_per_gather;
 DROP FUNCTION starjoin_other_cost(text, bool);
 DROP FUNCTION starjoin_other_memory(text, bool);
 DROP FUNCTION starjoin_other_plan(text, bool);
+DROP VIEW starjoin_other_v;
 DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
   starjoin_other_p3, starjoin_other_wf, starjoin_other_wa, starjoin_other_wb,
   starjoin_other_wc, starjoin_other_hf, starjoin_other_h1, starjoin_other_h2,
diff --git a/src/test/regress/expected/starjoin_reproducers.out b/src/test/regress/expected/starjoin_reproducers.out
index 032dc4e9c35..5ee0ce10a9e 100644
--- a/src/test/regress/expected/starjoin_reproducers.out
+++ b/src/test/regress/expected/starjoin_reproducers.out
@@ -10,10 +10,10 @@
 -- subproblem can build, otherwise the planning fails with "ERROR:  failed to
 -- build any N-way joins".
 --
--- In query J, the last-ditch pass would join dimensions to rels without the
--- 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.
+-- In query J, the last-ditch pass joins dimensions to rels without the fact,
+-- and two such joinrels would then get joined.  The result would contain two
+-- dimensions without the fact, which is not allowed, and the join search
+-- must not fail without it.
 --
 -- 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.
@@ -564,8 +564,9 @@ 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 (without the
--- fact, a dimension may be joined only to rels without join clauses).
+-- joins the outer joins to other rels, including the dimensions, but the
+-- joinrels with different dimensions can't be joined to each other (without
+-- the fact, a joinrel may contain only a single dimension).
 SET from_collapse_limit = 9;
 EXPLAIN (COSTS OFF)
 SELECT count(*)
diff --git a/src/test/regress/expected/starjoin_var_free.out b/src/test/regress/expected/starjoin_var_free.out
index 7b98672ea25..9c4f152211e 100644
--- a/src/test/regress/expected/starjoin_var_free.out
+++ b/src/test/regress/expected/starjoin_var_free.out
@@ -38,6 +38,22 @@ BEGIN
   RETURN (plan->0->'Planning'->>'Memory Used')::bigint;
 END;
 $$;
+-- plan of the join tree of an aggregate query, below the gating Result node
+-- of a pseudoconstant qual (with enable_starjoin_ordering enabled/disabled)
+CREATE FUNCTION starjoin_var_free_join_tree(query text, starjoin bool) RETURNS jsonb
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan jsonb;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (FORMAT JSON, COSTS OFF) ' || query INTO plan;
+  plan := plan #> '{0,Plan,Plans,0}';
+  IF plan->>'Node Type' = 'Result' THEN
+    plan := plan #> '{Plans,0}';
+  END IF;
+  RETURN plan;
+END;
+$$;
 -- Execute with both search strategies for the eleven-dimension star.
 CREATE FUNCTION starjoin_var_free_check(query text,
                                         OUT starjoin_on text,
@@ -148,6 +164,53 @@ SELECT starjoin_var_free_planning_memory(:'q_star' || $$WHERE now() > '2000-01-0
  t
 (1 row)
 
+-- Nor does it make rels without a join clause between them joinable, even
+-- without starjoin clusters (there are no foreign key joins in this chain),
+-- as the search would then join all subsets of the rels.  The join clauses
+-- are inequalities, so that they don't link all the rels through a single
+-- equivalence class.
+SELECT $$
+SELECT count(*) FROM starjoin_var_free_d1 AS c1
+  JOIN starjoin_var_free_d2 AS c2 ON c1.id < c2.id
+  JOIN starjoin_var_free_d3 AS c3 ON c2.id < c3.id
+  JOIN starjoin_var_free_d4 AS c4 ON c3.id < c4.id
+  JOIN starjoin_var_free_d5 AS c5 ON c4.id < c5.id
+  JOIN starjoin_var_free_d6 AS c6 ON c5.id < c6.id
+  JOIN starjoin_var_free_d7 AS c7 ON c6.id < c7.id
+  JOIN starjoin_var_free_d8 AS c8 ON c7.id < c8.id
+$$ AS q_chain \gset
+SELECT starjoin_var_free_planning_memory(:'q_chain' || $$WHERE now() > '2000-01-01'$$)
+       < 2 * starjoin_var_free_planning_memory(:'q_chain')
+       AS chain_where_now_planning_memory;
+ chain_where_now_planning_memory 
+---------------------------------
+ t
+(1 row)
+
+-- Nor does the qual make rels without join clauses look like they have some,
+-- which would leave their Cartesian products to the last-ditch joins at the
+-- top of the join tree.  The plan is the same as without the qual, with
+-- starjoin ordering enabled or disabled.
+SELECT $$
+SELECT count(*) FROM starjoin_var_free_f AS f
+  JOIN starjoin_var_free_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_var_free_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_var_free_d3 AS d3 ON f.d3 = d3.id
+  CROSS JOIN starjoin_var_free_d4 AS x1
+  CROSS JOIN starjoin_var_free_d5 AS x2
+ WHERE x1.id <= 2 AND x2.id = 1
+$$ AS q_cross \gset
+SELECT starjoin_var_free_join_tree(:'q_cross', false) =
+       starjoin_var_free_join_tree(:'q_cross' || $$AND now() > '2000-01-01'$$, false)
+       AS cross_where_now_same_plan_off,
+       starjoin_var_free_join_tree(:'q_cross', true) =
+       starjoin_var_free_join_tree(:'q_cross' || $$AND now() > '2000-01-01'$$, true)
+       AS cross_where_now_same_plan_on;
+ cross_where_now_same_plan_off | cross_where_now_same_plan_on 
+-------------------------------+------------------------------
+ t                             | t
+(1 row)
+
 -- A volatile Var-free qual is not pseudoconstant and still excludes dimensions.
 SELECT starjoin_var_free_geqo_used(:'q_star' || 'WHERE random() < 0.5', true)
        AS where_volatile_geqo;
@@ -208,6 +271,7 @@ $$);
 RESET join_collapse_limit;
 DROP FUNCTION starjoin_var_free_geqo_used(text, bool);
 DROP FUNCTION starjoin_var_free_planning_memory(text);
+DROP FUNCTION starjoin_var_free_join_tree(text, bool);
 DROP FUNCTION starjoin_var_free_check(text);
 DROP TABLE starjoin_var_free_f, starjoin_var_free_d1, starjoin_var_free_d2,
   starjoin_var_free_d3, starjoin_var_free_d4, starjoin_var_free_d5,
diff --git a/src/test/regress/sql/starjoin_other.sql b/src/test/regress/sql/starjoin_other.sql
index 0a78a9a9afb..ef8faa4fc6b 100644
--- a/src/test/regress/sql/starjoin_other.sql
+++ b/src/test/regress/sql/starjoin_other.sql
@@ -534,13 +534,12 @@ $$ 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;
 
--- But without the fact, a dimension must not be joined to rels with join
--- clauses, or the search might consider each dimension with all subsets of
--- c1-c5.  A pseudoconstant qual is in the joininfo list of every rel, but it
--- is not a join clause, so it must not make the rels joinable to each other.
--- The rels c1-c5 are joinable to each other even without the qual, through
--- an equivalence class (including f.id) or through a join clause referencing
--- all of them, so the qual should not add any joinrels.
+-- A pseudoconstant qual is in the joininfo list of every rel, but it is not a
+-- join clause, so it must not make the rels joinable to each other, or the
+-- search might consider each dimension with all subsets of c1-c5 (without
+-- the fact).  The rels c1-c5 are joinable to each other even without the
+-- qual, through an equivalence class (including f.id) or through a join
+-- clause referencing all of them, so the qual should not add any joinrels.
 SELECT $$
 SELECT count(*) FROM starjoin_other_f AS f
   JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
@@ -577,12 +576,87 @@ SELECT starjoin_other_memory(:'q_joininfo' || $$WHERE now() > '2000-01-01'$$, tr
        AS joininfo_where_now_memory_ok;
 RESET join_collapse_limit;
 
+-- Without the fact, a dimension may be joined to rels with join clauses too,
+-- in the last-ditch pass of the join search, which joins rels by Cartesian
+-- products when no other joins are possible.  Here the star and c1-c3 have
+-- join clauses only to c4, which is outside the subproblem (with
+-- join_collapse_limit = 6).  The cheapest plan joins the product of c1-c3
+-- and d2 to the join of f and d1, so that the dimensions are not joined to
+-- the product of c1-c3 and f, and the plan is as cheap as with the GUC
+-- disabled.
+SELECT $$
+SELECT count(*) FROM starjoin_other_c4 AS c4 JOIN (
+  starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  CROSS JOIN (starjoin_other_c1 AS c1
+    JOIN starjoin_other_c2 AS c2 ON c1.id = c2.id
+    JOIN starjoin_other_c3 AS c3 ON c2.id = c3.id)
+) ON c3.id = c4.id AND f.a = c4.v
+$$ AS q_last_ditch \gset
+
+SET join_collapse_limit = 6;
+SELECT starjoin_other_cost(:'q_last_ditch', true)
+       <= starjoin_other_cost(:'q_last_ditch', false) * 1.01 AS last_ditch_cost_ok;
+RESET join_collapse_limit;
+
+-- The last-ditch pass may also join a dimension to rels with join clauses
+-- to other rels (not the fact), and those clauses might then build joinrels
+-- with several dimensions but without the fact.  Those joinrels are
+-- rejected, so that for each set of the other rels the search builds at
+-- most d+1 joinrels without the fact (and not up to 2^d).  Here the star
+-- has join clauses only to a, which is outside the subproblem (with
+-- join_collapse_limit = 25), and four groups (outer joins of s and a view
+-- joining four copies of s) only to each other.  But the clauses linking
+-- the groups reference the nullable sides of the outer joins, so they
+-- can't be used before the groups are complete.  So once the star and the
+-- groups are complete (with five rels each), the last-ditch pass joins
+-- each group to each dimension, and the clauses linking the groups then
+-- join those joinrels to each other.
+CREATE VIEW starjoin_other_v AS
+SELECT s1.id FROM starjoin_other_s AS s1
+  JOIN starjoin_other_s AS s2 USING (id)
+  JOIN starjoin_other_s AS s3 USING (id)
+  JOIN starjoin_other_s AS s4 USING (id);
+
+SELECT $$
+SELECT count(*) FROM starjoin_other_a AS a JOIN (
+  starjoin_other_f AS f
+  JOIN starjoin_other_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_other_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_other_d3 AS d3 ON f.d3 = d3.id
+  JOIN starjoin_other_d4 AS d4 ON f.d4 = d4.id
+  CROSS JOIN (starjoin_other_s AS s1
+    LEFT JOIN starjoin_other_v AS v1 ON s1.id = v1.id)
+  JOIN (starjoin_other_s AS s2
+    LEFT JOIN starjoin_other_v AS v2 ON s2.id = v2.id)
+    ON coalesce(v1.id, 0) = coalesce(v2.id, 0)
+  JOIN (starjoin_other_s AS s3
+    LEFT JOIN starjoin_other_v AS v3 ON s3.id = v3.id)
+    ON coalesce(v2.id, 0) = coalesce(v3.id, 0)
+  JOIN (starjoin_other_s AS s4
+    LEFT JOIN starjoin_other_v AS v4 ON s4.id = v4.id)
+    ON coalesce(v3.id, 0) = coalesce(v4.id, 0)
+) ON f.a = a.id
+$$ AS q_last_ditch_dims \gset
+
+-- single subproblem with 25 rels, without GEQO
+SET join_collapse_limit = 25;
+SET geqo = off;
+SELECT starjoin_other_memory(:'q_last_ditch_dims', true)
+       < starjoin_other_memory(:'q_last_ditch_dims', false) * 0.25
+       AS last_ditch_dims_pruned;
+RESET geqo;
+RESET join_collapse_limit;
+
 RESET max_parallel_workers_per_gather;
 
 DROP FUNCTION starjoin_other_cost(text, bool);
 DROP FUNCTION starjoin_other_memory(text, bool);
 DROP FUNCTION starjoin_other_plan(text, bool);
 
+DROP VIEW starjoin_other_v;
+
 DROP TABLE starjoin_other_pf, starjoin_other_p1, starjoin_other_p2,
   starjoin_other_p3, starjoin_other_wf, starjoin_other_wa, starjoin_other_wb,
   starjoin_other_wc, starjoin_other_hf, starjoin_other_h1, starjoin_other_h2,
diff --git a/src/test/regress/sql/starjoin_reproducers.sql b/src/test/regress/sql/starjoin_reproducers.sql
index 62b8a004317..d2c4543ae52 100644
--- a/src/test/regress/sql/starjoin_reproducers.sql
+++ b/src/test/regress/sql/starjoin_reproducers.sql
@@ -10,10 +10,10 @@
 -- subproblem can build, otherwise the planning fails with "ERROR:  failed to
 -- build any N-way joins".
 --
--- In query J, the last-ditch pass would join dimensions to rels without the
--- 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.
+-- In query J, the last-ditch pass joins dimensions to rels without the fact,
+-- and two such joinrels would then get joined.  The result would contain two
+-- dimensions without the fact, which is not allowed, and the join search
+-- must not fail without it.
 --
 -- 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.
@@ -279,8 +279,9 @@ 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 (without the
--- fact, a dimension may be joined only to rels without join clauses).
+-- joins the outer joins to other rels, including the dimensions, but the
+-- joinrels with different dimensions can't be joined to each other (without
+-- the fact, a joinrel may contain only a single dimension).
 SET from_collapse_limit = 9;
 EXPLAIN (COSTS OFF)
 SELECT count(*)
diff --git a/src/test/regress/sql/starjoin_var_free.sql b/src/test/regress/sql/starjoin_var_free.sql
index a7bcbff83e7..cef4758533f 100644
--- a/src/test/regress/sql/starjoin_var_free.sql
+++ b/src/test/regress/sql/starjoin_var_free.sql
@@ -41,6 +41,23 @@ BEGIN
 END;
 $$;
 
+-- plan of the join tree of an aggregate query, below the gating Result node
+-- of a pseudoconstant qual (with enable_starjoin_ordering enabled/disabled)
+CREATE FUNCTION starjoin_var_free_join_tree(query text, starjoin bool) RETURNS jsonb
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan jsonb;
+BEGIN
+  PERFORM set_config('enable_starjoin_ordering', starjoin::text, true);
+  EXECUTE 'EXPLAIN (FORMAT JSON, COSTS OFF) ' || query INTO plan;
+  plan := plan #> '{0,Plan,Plans,0}';
+  IF plan->>'Node Type' = 'Result' THEN
+    plan := plan #> '{Plans,0}';
+  END IF;
+  RETURN plan;
+END;
+$$;
+
 -- Execute with both search strategies for the eleven-dimension star.
 CREATE FUNCTION starjoin_var_free_check(query text,
                                         OUT starjoin_on text,
@@ -133,6 +150,47 @@ SELECT starjoin_var_free_planning_memory(:'q_star' || $$WHERE now() > '2000-01-0
        < 2 * starjoin_var_free_planning_memory(:'q_star')
        AS where_now_planning_memory;
 
+-- Nor does it make rels without a join clause between them joinable, even
+-- without starjoin clusters (there are no foreign key joins in this chain),
+-- as the search would then join all subsets of the rels.  The join clauses
+-- are inequalities, so that they don't link all the rels through a single
+-- equivalence class.
+SELECT $$
+SELECT count(*) FROM starjoin_var_free_d1 AS c1
+  JOIN starjoin_var_free_d2 AS c2 ON c1.id < c2.id
+  JOIN starjoin_var_free_d3 AS c3 ON c2.id < c3.id
+  JOIN starjoin_var_free_d4 AS c4 ON c3.id < c4.id
+  JOIN starjoin_var_free_d5 AS c5 ON c4.id < c5.id
+  JOIN starjoin_var_free_d6 AS c6 ON c5.id < c6.id
+  JOIN starjoin_var_free_d7 AS c7 ON c6.id < c7.id
+  JOIN starjoin_var_free_d8 AS c8 ON c7.id < c8.id
+$$ AS q_chain \gset
+
+SELECT starjoin_var_free_planning_memory(:'q_chain' || $$WHERE now() > '2000-01-01'$$)
+       < 2 * starjoin_var_free_planning_memory(:'q_chain')
+       AS chain_where_now_planning_memory;
+
+-- Nor does the qual make rels without join clauses look like they have some,
+-- which would leave their Cartesian products to the last-ditch joins at the
+-- top of the join tree.  The plan is the same as without the qual, with
+-- starjoin ordering enabled or disabled.
+SELECT $$
+SELECT count(*) FROM starjoin_var_free_f AS f
+  JOIN starjoin_var_free_d1 AS d1 ON f.d1 = d1.id
+  JOIN starjoin_var_free_d2 AS d2 ON f.d2 = d2.id
+  JOIN starjoin_var_free_d3 AS d3 ON f.d3 = d3.id
+  CROSS JOIN starjoin_var_free_d4 AS x1
+  CROSS JOIN starjoin_var_free_d5 AS x2
+ WHERE x1.id <= 2 AND x2.id = 1
+$$ AS q_cross \gset
+
+SELECT starjoin_var_free_join_tree(:'q_cross', false) =
+       starjoin_var_free_join_tree(:'q_cross' || $$AND now() > '2000-01-01'$$, false)
+       AS cross_where_now_same_plan_off,
+       starjoin_var_free_join_tree(:'q_cross', true) =
+       starjoin_var_free_join_tree(:'q_cross' || $$AND now() > '2000-01-01'$$, true)
+       AS cross_where_now_same_plan_on;
+
 -- A volatile Var-free qual is not pseudoconstant and still excludes dimensions.
 SELECT starjoin_var_free_geqo_used(:'q_star' || 'WHERE random() < 0.5', true)
        AS where_volatile_geqo;
@@ -168,6 +226,7 @@ RESET join_collapse_limit;
 
 DROP FUNCTION starjoin_var_free_geqo_used(text, bool);
 DROP FUNCTION starjoin_var_free_planning_memory(text);
+DROP FUNCTION starjoin_var_free_join_tree(text, bool);
 DROP FUNCTION starjoin_var_free_check(text);
 
 DROP TABLE starjoin_var_free_f, starjoin_var_free_d1, starjoin_var_free_d2,
-- 
2.56.1

