From 2c25836ec62db3d251c1aa8689083376b8b92efe 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 10/30] Determine starjoin dimensions once per join search
 subproblem

starjoin_order_invalid() is called for every join considered by the join
search, and on each call it walked root->initial_rels, to find the base
rels of the current subproblem and whether the subproblem contains the
fact of each cluster.  But those depend only on the subproblem, and with
many dimensions the walk dominated the search.

So determine the dimensions to check once per subproblem, in a new
function starjoin_setup_subproblem(), called by make_rel_from_joinlist()
before running the join search, and keep them in a new field
subproblem_dims of each cluster.  starjoin_order_invalid() then only
intersects the joinrel with those sets.

The rules are the same.  For a star of 400 dimensions in a single
subproblem, the median planning time (release build, with GEQO disabled)
drops from 562-568 to 123-124 ms.

Update STARJOINS.md.  Add a starjoin_other check with a star in a
subproblem searched after one without the fact, which fails if the setup
ignores whether the subproblem contains the fact, or if it's done only
for the first subproblem.
---
 STARJOINS.md                                 |  22 ++-
 src/backend/optimizer/path/allpaths.c        |   6 +
 src/backend/optimizer/path/joinrels.c        | 145 +++++++++++--------
 src/include/nodes/pathnodes.h                |   7 +
 src/include/optimizer/paths.h                |   1 +
 src/test/regress/expected/starjoin_other.out |  21 +++
 src/test/regress/sql/starjoin_other.sql      |  18 +++
 7 files changed, 158 insertions(+), 62 deletions(-)

diff --git a/STARJOINS.md b/STARJOINS.md
index 77068f314af..5505085dc4c 100644
--- a/STARJOINS.md
+++ b/STARJOINS.md
@@ -57,6 +57,9 @@ The optimization consists of these parts:
 - `starjoin_order_invalid`, called by `make_join_rel`, rejects joins
   violating the canonical order, just like various other join
   restrictions.
+- `starjoin_setup_subproblem`, called by `make_rel_from_joinlist` for
+  each join search subproblem, determines the dimensions to check in the
+  subproblem.
 
 The clusters are determined in `src/backend/optimizer/plan/initsplan.c`,
 and the join order is restricted in
@@ -188,9 +191,22 @@ product of the dimensions is then joined to the fact in an upper
 subproblem, where the dimensions are not initial rels, and so are not
 checked.
 
-`starjoin_order_invalid` walks the initial rels of the current
-subproblem on each call, to find the base rels of the subproblem, and
-whether it contains the fact of each cluster.
+`starjoin_setup_subproblem` determines the dimensions to check once per
+subproblem, and keeps them in the `subproblem_dims` field of each
+cluster: the dimensions joined individually in the subproblem if it
+contains the fact, or NULL.  `make_rel_from_joinlist` calls it right
+after setting the initial rels, before running the join search
+(standard, GEQO or `join_search_hook`).  The subproblems are solved one
+at a time, and each nested one is solved before the subproblem
+containing its result is set up, so the field always describes the
+subproblem being searched.  `starjoin_order_invalid` then only
+intersects the joinrel with those sets, while walking the initial rels
+for every proposed join would dominate the search with many dimensions.
+For a star of 100, 200 and 400 dimensions in a single subproblem,
+determining the dimensions once per subproblem reduced the median
+planning time (release build, with GEQO disabled) from 11.6 to 6.7 ms,
+from 68-69 to 24-26 ms, and from 562-568 to 123-124 ms, with the same
+plan costs and planning memory (within 1 kB).
 
 ### Why the join search cannot fail
 
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 72ad61e8c24..7306fe1b9fc 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -3919,6 +3919,12 @@ make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
 		 */
 		root->initial_rels = initial_rels;
 
+		/*
+		 * Determine the starjoin dimensions this subproblem has to join in
+		 * the canonical order.
+		 */
+		starjoin_setup_subproblem(root);
+
 		if (join_search_hook)
 			return (*join_search_hook) (root, levels_needed, initial_rels);
 		else if (enable_geqo && levels_needed >= geqo_threshold)
diff --git a/src/backend/optimizer/path/joinrels.c b/src/backend/optimizer/path/joinrels.c
index c3b015bc29c..9231093493a 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -2172,6 +2172,75 @@ get_matching_part_pairs(PlannerInfo *root, RelOptInfo *joinrel,
 	}
 }
 
+/*
+ * starjoin_setup_subproblem
+ *		Determine the dimensions of each starjoin cluster that the join
+ *		search of the current subproblem has to join in the canonical order.
+ *
+ * Called by make_rel_from_joinlist for each join search subproblem, once
+ * root->initial_rels is set.  The subproblems are solved one at a time, and
+ * each nested one is solved before the subproblem containing its result is
+ * set up, so the subproblem_dims of the clusters always describe the
+ * subproblem being searched.  So starjoin_order_invalid doesn't need to look
+ * at the initial rels for every proposed join.
+ */
+void
+starjoin_setup_subproblem(PlannerInfo *root)
+{
+	ListCell   *lc;
+	Relids		all_relids = NULL;	/* all relids in this subproblem */
+	Relids		baserel_relids = NULL;	/* baserels in this subproblem */
+
+	/* no starjoins found (maybe because the option is disabled) */
+	if (root->starjoin_clusters == NIL)
+		return;
+
+	/* The initial rels of the current subproblem. */
+	foreach(lc, root->initial_rels)
+	{
+		RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
+
+		all_relids = bms_add_members(all_relids, rel->relids);
+		if (rel->reloptkind == RELOPT_BASEREL)
+			baserel_relids = bms_add_members(baserel_relids, rel->relids);
+	}
+
+	foreach(lc, root->starjoin_clusters)
+	{
+		StarJoinClusterInfo *c = (StarJoinClusterInfo *) lfirst(lc);
+
+		/*
+		 * The fact is not part of this subproblem, nothing to enforce.
+		 *
+		 * We must not enforce the canonical order without the fact.  The
+		 * order relies on joins of dimensions to the fact not changing the
+		 * cardinality of the fact.  Without the fact, the dimensions can only
+		 * be joined by cartesian products (they have join clauses only to the
+		 * fact), which do change the cardinality, so the order matters and
+		 * enforcing it might eliminate the cheapest plan.  Nor can we forbid
+		 * joining the dimensions without the fact, as that may be the only
+		 * way to join them (e.g. "d1 CROSS JOIN d2" with join_collapse_limit
+		 * set to 1).  The joinrel is joined to the fact in an upper
+		 * subproblem, where the dimensions are not initial rels, and so are
+		 * not checked.
+		 *
+		 * Snowflake joins are not an exception: a dimension with its own
+		 * dimensions is not a member of this cluster, but it may be the fact
+		 * of another cluster, enforced in subproblems including it.
+		 */
+		if (!bms_is_member(c->fact_relid, all_relids))
+			c->subproblem_dims = NULL;
+		else
+		{
+			/* dimensions joined individually in this subproblem */
+			c->subproblem_dims = bms_intersect(c->dim_relids, baserel_relids);
+		}
+	}
+
+	bms_free(all_relids);
+	bms_free(baserel_relids);
+}
+
 /*
  * starjoin_order_invalid
  *		Return true if the proposed join (rel1, rel2) would build a
@@ -2193,6 +2262,8 @@ get_matching_part_pairs(PlannerInfo *root, RelOptInfo *joinrel,
  * with the fact) can't, so we ignore them here and treat their joinrel just
  * like any other relation.  Otherwise there might be no valid join order at
  * all.  Clusters with the fact outside the current subproblem are ignored.
+ * starjoin_setup_subproblem determines the dimensions to check, once per
+ * subproblem.
  *
  * So the fact gets joined to the dimensions in the canonical order, and the
  * other orderings are pruned.  Other rels may be joined at any point.  The
@@ -2216,24 +2287,12 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 {
 	ListCell   *lc;
 	Relids		join_relids;
-	Relids		all_relids = NULL;	/* all relids in this subproblem */
-	Relids		baserel_relids = NULL;	/* baserels in this subproblem */
 	bool		violates = false;
 
 	/* no starjoins found (maybe because the option is disabled) */
 	if (root->starjoin_clusters == NIL)
 		return false;
 
-	/* The initial rels of the current subproblem. */
-	foreach(lc, root->initial_rels)
-	{
-		RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
-
-		all_relids = bms_add_members(all_relids, rel->relids);
-		if (rel->reloptkind == RELOPT_BASEREL)
-			baserel_relids = bms_add_members(baserel_relids, rel->relids);
-	}
-
 	/* relids of the result */
 	join_relids = bms_union(rel1->relids, rel2->relids);
 
@@ -2242,34 +2301,13 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 	{
 		StarJoinClusterInfo *c = (StarJoinClusterInfo *) lfirst(lc);
 		Relids		cluster_dims;
-		bool		gap = false;
-		int			idx;
+		Relids		missing_dims;
 
-		/*
-		 * The fact is not part of this subproblem, nothing to enforce.
-		 *
-		 * We must not enforce the canonical order without the fact.  The
-		 * order relies on joins of dimensions to the fact not changing the
-		 * cardinality of the fact.  Without the fact, the dimensions can only
-		 * be joined by cartesian products (they have join clauses only to the
-		 * fact), which do change the cardinality, so the order matters and
-		 * enforcing it might eliminate the cheapest plan.  Nor can we forbid
-		 * joining the dimensions without the fact, as that may be the only
-		 * way to join them (e.g. "d1 CROSS JOIN d2" with join_collapse_limit
-		 * set to 1).  The joinrel is joined to the fact in an upper
-		 * subproblem, where the dimensions are not initial rels, and so are
-		 * not checked.
-		 *
-		 * Snowflake joins are not an exception: a dimension with its own
-		 * dimensions is not a member of this cluster, but it may be the fact
-		 * of another cluster, enforced in subproblems including it.
-		 */
-		if (!bms_is_member(c->fact_relid, all_relids))
+		/* dimensions of this subproblem in the join, if any */
+		cluster_dims = bms_intersect(c->subproblem_dims, join_relids);
+		if (cluster_dims == NULL)
 			continue;
 
-		/* dimensions joined individually in this subproblem */
-		cluster_dims = bms_intersect(c->dim_relids, baserel_relids);
-
 		/*
 		 * With the fact in this subproblem, joinrels with a dimension but
 		 * without the fact are cartesian products, as the dimensions have
@@ -2302,11 +2340,9 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 		 */
 		if (!bms_is_member(c->fact_relid, 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)
+			else
 			{
 				RelOptInfo *other;
 				ListCell   *lc2;
@@ -2338,28 +2374,21 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 		 * dimensions (in relid order), i.e. there must be no dimension after
 		 * the first gap.  This applies even if only one side of the join has
 		 * dimensions, so that the fact gets joined to the dimensions in this
-		 * order, and not e.g. to the second dimension first.
+		 * order, and not e.g. to the second dimension first.  A missing
+		 * dimension is fine on its own, as the join may not include all the
+		 * dimensions yet.  It's a violation only if the join includes a
+		 * dimension after it, i.e. if the first missing dimension precedes
+		 * the last one in the join.
 		 *
 		 * XXX Using the relid order is fine for now, but if we choose to
 		 * allow snowflake joins, we'll need an explicit (ordered) list.
 		 */
-		idx = -1;
-		while ((idx = bms_next_member(cluster_dims, idx)) >= 0)
-		{
-			/*
-			 * A missing dimension is fine on its own, as the join may not
-			 * include all the dimensions yet.  It's a violation only if the
-			 * join includes a dimension after it.
-			 */
-			if (!bms_is_member(idx, join_relids))
-				gap = true;
-			else if (gap)
-			{
-				violates = true;
-				break;
-			}
-		}
+		missing_dims = bms_difference(c->subproblem_dims, join_relids);
+		violates = (missing_dims != NULL &&
+					bms_next_member(missing_dims, -1) <
+					bms_prev_member(cluster_dims, -1));
 
+		bms_free(missing_dims);
 		bms_free(cluster_dims);
 
 		if (violates)
@@ -2367,8 +2396,6 @@ starjoin_order_invalid(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 	}
 
 	bms_free(join_relids);
-	bms_free(all_relids);
-	bms_free(baserel_relids);
 
 	return violates;
 }
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 01af5467c79..392589f3262 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -1539,6 +1539,13 @@ typedef struct StarJoinClusterInfo
 	NodeTag		type;
 	Index		fact_relid;		/* index of the fact relation */
 	Relids		dim_relids;		/* indexes of the dimension relations */
+
+	/*
+	 * Dimensions the current join search subproblem has to join in the
+	 * canonical order, set by starjoin_setup_subproblem(): the dimensions
+	 * joined individually, if the fact is part of the subproblem, else NULL.
+	 */
+	Relids		subproblem_dims;
 } StarJoinClusterInfo;
 
 
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h
index 64f87da1674..061b5b05232 100644
--- a/src/include/optimizer/paths.h
+++ b/src/include/optimizer/paths.h
@@ -120,6 +120,7 @@ extern bool have_join_order_restriction(PlannerInfo *root,
 extern void mark_dummy_rel(RelOptInfo *rel);
 extern void init_dummy_sjinfo(SpecialJoinInfo *sjinfo, Relids left_relids,
 							  Relids right_relids);
+extern void starjoin_setup_subproblem(PlannerInfo *root);
 
 /*
  * equivclass.c
diff --git a/src/test/regress/expected/starjoin_other.out b/src/test/regress/expected/starjoin_other.out
index 77f431f2a67..f3050b6dbf4 100644
--- a/src/test/regress/expected/starjoin_other.out
+++ b/src/test/regress/expected/starjoin_other.out
@@ -494,6 +494,27 @@ SELECT starjoin_other_memory(:'q_subproblems', true)
  t
 (1 row)
 
+-- with the default join_collapse_limit, c1 and c2 are a separate subproblem,
+-- searched before the star, which is still pruned
+SELECT $$
+SELECT count(*)
+  FROM (starjoin_other_c1 AS c1
+        JOIN starjoin_other_c2 AS c2 ON c1.v = c2.v)
+  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
+        JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id) ON f.id = c1.id
+$$ AS q_star_second \gset
+SELECT starjoin_other_memory(:'q_star_second', true)
+       < starjoin_other_memory(:'q_star_second', false) * 0.5 AS star_second_pruned;
+ star_second_pruned 
+--------------------
+ t
+(1 row)
+
 --
 -- Eager aggregation
 --
diff --git a/src/test/regress/sql/starjoin_other.sql b/src/test/regress/sql/starjoin_other.sql
index 3b1a7660be9..ed53b58c752 100644
--- a/src/test/regress/sql/starjoin_other.sql
+++ b/src/test/regress/sql/starjoin_other.sql
@@ -459,6 +459,24 @@ $$ AS q_subproblems \gset
 SELECT starjoin_other_memory(:'q_subproblems', true)
        <= starjoin_other_memory(:'q_subproblems', false) * 1.01 AS subproblems_memory_ok;
 
+-- with the default join_collapse_limit, c1 and c2 are a separate subproblem,
+-- searched before the star, which is still pruned
+SELECT $$
+SELECT count(*)
+  FROM (starjoin_other_c1 AS c1
+        JOIN starjoin_other_c2 AS c2 ON c1.v = c2.v)
+  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
+        JOIN starjoin_other_d5 AS d5 ON f.d5 = d5.id
+        JOIN starjoin_other_d6 AS d6 ON f.d6 = d6.id) ON f.id = c1.id
+$$ AS q_star_second \gset
+
+SELECT starjoin_other_memory(:'q_star_second', true)
+       < starjoin_other_memory(:'q_star_second', false) * 0.5 AS star_second_pruned;
+
 --
 -- Eager aggregation
 --
-- 
2.56.1

