"failed to build any N-way joins" from a five-relation query
The following query fails on v14 to master:
create table t (a int);
select 1 from t t1 left join t t2 on true,
lateral (select t2.a offset 0) s1 left join t t3 on s1.a = t3.a,
lateral (select t3.a offset 0) s2
where s2.a > t1.a;
ERROR: failed to build any 5-way joins
The dependencies between the rels form a chain:
t1 --LJ--> t2 <--lateral-- s1 --LJ--> t3 <--lateral-- s2
so the only possible join order is t1, t2, s1, t3, s2.
The problem is that at level 2 join_is_legal() accepts {t1, s2}, which
are linked by the clause "s2.a > t1.a". And that misleads the
clauseless-join heuristics into thinking that legality of t1/s2 means
that the clauseless join t1/t2 need not be formed.
But {t1, s2} is a dead end. s2 needs t3 as a lateral parameter, so
{t1, s2} must end up on the inner side of some nestloop that has t3
on its outer side. Now consider which side of that nestloop the
remaining rels can go:
t2 must be on the inner side, because it is the RHS of "t1 LJ t2"
and t1 is there.
s1 must be on the inner side, because it laterally references t2.
t3 must be on the inner side, because it is the RHS of "s1 LJ t3".
So t3 would have to be on both sides. How would that be possible?
join_is_legal() already has a check for this sort of dead end. It
collects the rels that must end up on the inner side of an outer join
with the proposed join (join_plus_rhs), and rejects the join if its
lateral parameters come from any of them. However, that search only
follows outer joins from min_lefthand to min_righthand. Here it adds
t2 and stops, because the LHS of "s1 LJ t3" is s1, not t2. It misses
that s1 has to come along with t2 because of the lateral reference.
So I think we can fix it by teaching that search to also include any
rel that laterally references a rel already in the set. Hench, the
attached.
- Richard
Hi Richard Guo
Thanks for the patch and the detailed analysis.
The problem diagnosis and the example query (t1 --LJ--> t2 <--lateral-- s1
--LJ--> t3 <--lateral-- s2) are very clear. Rejecting joins whose lateral
references are trapped inside outer joins or downstream lateral
dependencies is topologically sound and nicely fixes the "failed to build
any 5-way joins" failure.*Just a couple of small thoughts regarding the implementation and
back-patching, for your consideration:*1. Leveraging existing lateral_referencers
In the patch, the search loops over simple_rel_array on every iteration of
do ... while (more):+ /* add rels that laterally reference any rel found so far */ + for (int rti = 1; rti < root->simple_rel_array_size; rti++) + { + RelOptInfo *brel = root->simple_rel_array[rti]; ... + if (!bms_is_member(rti, join_plus_rhs) && + bms_overlap(brel->lateral_relids, join_plus_rhs)) + { + join_plus_rhs = bms_add_member(join_plus_rhs, rti); + more = true; + } + }Since join_is_legal() is on the critical hot path of join search, doing a
full linear scan of simple_rel_array and checking bms_overlap() on every
iteration could introduce overhead, especially for queries on partitioned
tables where simple_rel_array_size can be large.In src/backend/optimizer/plan/initsplan.c, create_lateral_join_info()
already builds the inverse mapping with transitive closure already computed:/*
* Now that we've identified all lateral references, mark each baserel
* with the set of relids of rels that reference it laterally (possibly
* indirectly) --- that is, the inverse mapping of lateral_relids.
*/
brel2->lateral_referencers = bms_add_member(brel2->lateral_referencers,
rti);Could we take advantage of brel->lateral_referencers for the relations
already present in join_plus_rhs instead of scanning all baserels from
scratch? That would directly yield all direct and indirect lateral
referencers without repeatedly inspecting unrelated baserels.2. Interactions with PG 17+ Outer Join infrastructure (ojrelid)
The patch targets Backpatch-through: 14. However, in PG 17 and master, the
outer join infrastructure was significantly refactored by Tom Lane to give
outer joins their own ojrelid (root->outer_join_rels, sjinfo->ojrelid).Notice the check that immediately follows this loop in v17/master:
if (bms_overlap(join_lateral_rels, root->outer_join_rels))
{
foreach(l, root->join_info_list)
{
SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
if (!bms_is_member(sjinfo->ojrelid, join_lateral_rels))
continue;
if (bms_overlap(join_plus_rhs, sjinfo->min_lefthand) ||
bms_overlap(join_plus_rhs, sjinfo->min_righthand))
return false; /* OJ can't be formed outside join */
}
}In PG 17 and master, join_plus_rhs can contain ojrelids in addition to
baserel relids. The proposed loop skips anything where brel == NULL ||
brel->reloptkind != RELOPT_BASEREL. While this assumption holds cleanly on
v14–v16, on v17/master:If join_plus_rhs contains an ojrelid, looking only at baserel
lateral_relids might miss lateral dependencies that reference an outer join
(for instance, via a PlaceHolderVar evaluated at that outer join).
Conversely, whether join_plus_rhs containing ojrelids needs explicit
propagation through lateral references should probably be verified or
documented to ensure complete branch compatibility between v14–v16 and
v17/master.What are your thoughts on these two points?
Thanks
Richard Guo <guofenglinux@gmail.com> 于2026年10月8日周四 14:12写道:
So I think we can fix it by teaching that search to also include any
rel that laterally references a rel already in the set. Hench, the
attached.
Thanks for the explanation and patch. I traced this through
join_is_legal() and now understand why the existing check misses the
dead end.
Starting with {t1, s2}, the outer-join search adds t2, but stops
because it does not follow the lateral dependency from t2 to s1.
Including s1 allows the next iteration to add t3, revealing the
conflict with the proposed join's lateral parameterization.
The fix makes sense to me.
--
Thanks,
Tender Wang
Richard Guo <guofenglinux@gmail.com> 于2026年10月8日周四 14:12写道:
The following query fails on v14 to master:
create table t (a int);
select 1 from t t1 left join t t2 on true,
lateral (select t2.a offset 0) s1 left join t t3 on s1.a = t3.a,
lateral (select t3.a offset 0) s2
where s2.a > t1.a;
ERROR: failed to build any 5-way joins
I found a variant that still fails with the v1 patch applied.
Replacing the second LEFT JOIN with a FULL JOIN reproduces it:
CREATE TABLE t (a int);
SELECT 1
FROM t t1 LEFT JOIN t t2 ON true,
LATERAL (SELECT t2.a OFFSET 0) s1
FULL JOIN t t3 ON s1.a = t3.a,
LATERAL (SELECT t3.a OFFSET 0) s2
WHERE s2.a > t1.a;
This gives:
ERROR: failed to build any 4-way joins
It fails both with and without v1.
I haven't traced the exact cause yet, but wanted to flag this case.
--
Thanks,
Tender Wang
Tender Wang <tndrwang@gmail.com> 于2026年10月9日周五 16:08写道:
Richard Guo <guofenglinux@gmail.com> 于2026年10月8日周四 14:12写道:
CREATE TABLE t (a int);SELECT 1
FROM t t1 LEFT JOIN t t2 ON true,
LATERAL (SELECT t2.a OFFSET 0) s1
FULL JOIN t t3 ON s1.a = t3.a,
LATERAL (SELECT t3.a OFFSET 0) s2
WHERE s2.a > t1.a;This gives:
ERROR: failed to build any 4-way joins
It fails both with and without v1.
I haven't traced the exact cause yet, but wanted to flag this case.
I investigated the cause of the failure reported yesterday.
The FULL JOIN is planned as a separate joinlist subproblem, and its
resulting joinrel becomes an input to the outer join search.
The loop over simple_rel_array does not account for this composite
input's lateral dependencies.
The proposed fix is to also scan joinrel entries in root->initial_rels
when expanding join_plus_rhs:
diff --git a/src/backend/optimizer/path/joinrels.c
b/src/backend/optimizer/path/joinrels.c
index 1278d958fb7..b53edefa8ca 100644
--- a/src/backend/optimizer/path/joinrels.c
+++ b/src/backend/optimizer/path/joinrels.c
@@ -655,6 +655,21 @@ join_is_legal(PlannerInfo *root, RelOptInfo
*rel1, RelOptInfo *rel2,
more = true;
}
}
+ /* Add composite inputs that laterally
reference any rel found so far. */
+ foreach (l, root->initial_rels)
+ {
+ RelOptInfo *jrel =
lfirst_node(RelOptInfo, l);
+
+ if (jrel->reloptkind != RELOPT_JOINREL)
+ continue;
+
+ if
(!bms_is_subset(jrel->relids, join_plus_rhs) &&
+
bms_overlap(jrel->lateral_relids, join_plus_rhs))
+ {
+ join_plus_rhs =
bms_add_members(join_plus_rhs, jrel->relids);
+ more = true;
+ }
+ }
} while (more);
if (bms_overlap(join_plus_rhs, join_lateral_rels))
return false; /* will not be able to
join to some RHS rel */
This loop goes inside the existing more loop, alongside the baserel loop.
Using initial_rels limits the additional checks to composite inputs of
the current join search, avoiding ordinary candidate joinrels in
join_rel_list.
Your existing loop still covers baserels.
--
Thanks,
Tender Wang
On Sat, Oct 10, 2026 at 11:37 AM Tender Wang <tndrwang@gmail.com> wrote:
The FULL JOIN is planned as a separate joinlist subproblem, and its
resulting joinrel becomes an input to the outer join search.
The loop over simple_rel_array does not account for this composite
input's lateral dependencies.
Thanks for the report and the analysis. I agree that this is the key
point: the full join's joinrel is a single input to the outer join
search, so once s1 has to be included in the search, t3 has to come
along with it.
It is not specific to full joins, though. join_collapse_limit or
from_collapse_limit can also make sub-joinlist joinrels.
The proposed fix is to also scan joinrel entries in root->initial_rels
when expanding join_plus_rhs:
+1 to this idea, and I think we can take it one step further.
root->initial_rels contains all the inputs of the current join search,
base rels as well as sub-joinlist joinrels, so a single loop over it
can replace the loop over simple_rel_array in v1. For each input that
laterally references a rel found so far, we add all of its relids.
Hence, the attached v2.
- Richard
On Sat, Oct 10, 2026 at 7:49 PM Richard Guo <guofenglinux@gmail.com> wrote:
+1 to this idea, and I think we can take it one step further.
root->initial_rels contains all the inputs of the current join search,
base rels as well as sub-joinlist joinrels, so a single loop over it
can replace the loop over simple_rel_array in v1. For each input that
laterally references a rel found so far, we add all of its relids.Hence, the attached v2.
Pushed and back-patched to all supported branches. Thanks for all the
reviews.
- Richard