Simplify the uniqueness proof for self-join elimination
Thread notes
1 note#performance#moderate#enhancement
hackorum-bot#performance#moderate#enhancement
@global #performance #moderate #enhancement
While working on the UniqueKeys stuff, I noticed that the self-join
elimination code puts its uniqueness proof logic into several places
that are also used by other parts of the planner. This makes the
UniqueKeys work harder than it should be, because I have to take care
of SJE-specific things in places that are not related to SJE at all.
To remove a self-join, SJE needs to prove that each row of the removed
relation can only match its own row in the kept relation. Currently
it passes the self-join quals and all the restriction clauses of the
kept relation to innerrel_is_unique(), and lets
relation_has_unique_index_for() report back which restriction clauses
it used. Then it checks that the removed relation also has these
clauses. For this, an extra_clauses output parameter is added to
innerrel_is_unique(), is_innerrel_unique_for(), rel_is_distinct_for()
and relation_has_unique_index_for(). Also the UniqueRelInfo cache
entries have self_join and extra_clauses fields, and the cache lookups
need to handle them specially. IMHO it doesn't seem like a good
design to scatter SJE-specific logic across these functions in such an
ad hoc way.
Another problem is that the result depends on the order of the
indexes. This is the kind of plan instability users can't reason
about. relation_has_unique_index_for() stops at the first unique
index that it can prove, and if this index uses a restriction clause
that only the kept relation has, SJE just gives up, even if another
index could work. For example, with the table sj (a int unique, b
int, c int unique) from join.sql, and a unique index on (a, b, c), for
the query below
SELECT * FROM sj j1, sj j2
WHERE j1.b = j2.b AND j1.c = 3 AND j2.a = 2 AND j2.c = 3;
the join is not removed. This is because the index on (a, b, c) is
tried first, and it needs j2.a = 2, which j1 does not have. However,
the unique index on c together with the shared restriction c = 3 is
enough to remove the join.
So I'd like to propose the attached patch. With this patch, SJE first
finds out the restriction clauses that both relations have, and then
calls relation_has_unique_index_for() directly with the self-join
quals and these shared clauses. Since SJE does not go through
innerrel_is_unique() any more, we can remove the extra_clauses
parameters as well as all the code around that. Also, unique_for_rels
can be a plain list of Relids again, so we can remove UniqueRelInfo
structure and all the special handling around it.
One might worry that SJE does not use the cache any more. But within
SJE, the cached entries never get hit, because each pair of relations
is checked only once, and if anything is removed, we restart and
rebuild all the RelOptInfos, which discards every cache entry. The
only benefit of the SJE cache might be that join search may reuse the
entries from the *final* SJE pass, which only happens when a table is
joined to itself, and at the cost of at most one extra
relation_has_unique_index_for() call. I think this is fine, as it is
very cheap compared to the rest of planning. OTOH, because now more
self-joins can be removed, we actually can save a lot of planning
time, since join search has fewer relations to deal with.
The patch also removes the requirement that the two relations must
have a join clause between them. The shared restriction clauses alone
can prove that the join is removable, such as "WHERE j1.a = 2 AND j2.a
= 2" with a unique index on a. This enables us to remove even more
self-joins than before.
(This is a master-only patch.)
Any thoughts?
- Richard
Hi,
On Nov 13, 2026, at 17:35, Richard Guo <guofenglinux@gmail.com> wrote:
While working on the UniqueKeys stuff, I noticed that the self-join
elimination code puts its uniqueness proof logic into several places
that are also used by other parts of the planner. This makes the
UniqueKeys work harder than it should be, because I have to take care
of SJE-specific things in places that are not related to SJE at all.To remove a self-join, SJE needs to prove that each row of the removed
relation can only match its own row in the kept relation. Currently
it passes the self-join quals and all the restriction clauses of the
kept relation to innerrel_is_unique(), and lets
relation_has_unique_index_for() report back which restriction clauses
it used. Then it checks that the removed relation also has these
clauses. For this, an extra_clauses output parameter is added to
innerrel_is_unique(), is_innerrel_unique_for(), rel_is_distinct_for()
and relation_has_unique_index_for(). Also the UniqueRelInfo cache
entries have self_join and extra_clauses fields, and the cache lookups
need to handle them specially. IMHO it doesn't seem like a good
design to scatter SJE-specific logic across these functions in such an
ad hoc way.Another problem is that the result depends on the order of the
indexes. This is the kind of plan instability users can't reason
about. relation_has_unique_index_for() stops at the first unique
index that it can prove, and if this index uses a restriction clause
that only the kept relation has, SJE just gives up, even if another
index could work. For example, with the table sj (a int unique, b
int, c int unique) from join.sql, and a unique index on (a, b, c), for
the query belowSELECT * FROM sj j1, sj j2
WHERE j1.b = j2.b AND j1.c = 3 AND j2.a = 2 AND j2.c = 3;the join is not removed. This is because the index on (a, b, c) is
tried first, and it needs j2.a = 2, which j1 does not have. However,
the unique index on c together with the shared restriction c = 3 is
enough to remove the join.So I'd like to propose the attached patch. With this patch, SJE first
finds out the restriction clauses that both relations have, and then
calls relation_has_unique_index_for() directly with the self-join
quals and these shared clauses. Since SJE does not go through
innerrel_is_unique() any more, we can remove the extra_clauses
parameters as well as all the code around that. Also, unique_for_rels
can be a plain list of Relids again, so we can remove UniqueRelInfo
structure and all the special handling around it.One might worry that SJE does not use the cache any more. But within
SJE, the cached entries never get hit, because each pair of relations
is checked only once, and if anything is removed, we restart and
rebuild all the RelOptInfos, which discards every cache entry. The
only benefit of the SJE cache might be that join search may reuse the
entries from the *final* SJE pass, which only happens when a table is
joined to itself, and at the cost of at most one extra
relation_has_unique_index_for() call. I think this is fine, as it is
very cheap compared to the rest of planning. OTOH, because now more
self-joins can be removed, we actually can save a lot of planning
time, since join search has fewer relations to deal with.The patch also removes the requirement that the two relations must
have a join clause between them. The shared restriction clauses alone
can prove that the join is removable, such as "WHERE j1.a = 2 AND j2.a
= 2" with a unique index on a. This enables us to remove even more
self-joins than before.(This is a master-only patch.)
Any thoughts?
- Richard
<v1-0001-Simplify-the-uniqueness-proof-for-self-join-elimi.patch>
Thanks for working on this. I think the patch is worthwhile. As you
described, it:
1. moves the SJE-specific logic out of the shared uniqueness-proof code,
so those functions no longer need to know about SJE and stay focused
on their own job;
2. removes the dependency on index order, which is the kind of plan
instability users can't reason about;
3. allows SJE to remove more self-joins than before.
I've reviewed the patch and didn't find any issues. The change looks
reasonable and valuable to me.
--
Best regards,
Chengpeng Yan
Show quoted text
Hi Richard,
Thanks for the patch. Extracting the shared restrictions upfront and
bypassing innerrel_is_unique() is a much cleaner design, and it nicely
fixes the index-order dependency.
I read through the patch and had two minor thoughts:
1. Maybe I'm overthinking this, but now that SJE no longer goes through
innerrel_is_unique(), we no longer call rel_supports_distinctness()
anywhere in the SJE path.
Previously, if restrictlist was NIL we skipped the pair immediately;
otherwise innerrel_is_unique_ext() checked rel_supports_distinctness()
before calling relation_has_unique_index_for(), and match_unique_clauses()
(which does copyObject() + ChangeVarNodes() + equal()) was only called
after a unique index match succeeded.
With this patch, we also proceed when restrictlist is NIL, and
get_shared_restrictions() is called before relation_has_unique_index_for().
So if a query self-joins a table that has no usable unique index (e.g., no
indexes at all, or only non-unique / partial / deferred unique indexes),
remove_self_joins_one_group() will still run
generate_join_implied_equalities(), split_selfjoin_quals(), and
get_shared_restrictions() for every candidate pair in the group, only for
relation_has_unique_index_for() to find no usable unique index.
Other callers such as join_is_removable() and reduce_unique_semijoins()
check rel_supports_distinctness() before building the clause lists.
Since all relations in remove_self_joins_one_group() share the same
reloid (and have !rte->inh), would it be worth checking
rel_supports_distinctness() once in remove_self_joins_one_group() so that
we can skip the whole group early if the table has no suitable unique
index?
2. In remove_self_joins_one_group(), otherjoinquals was previously only
needed for the "list_length(otherjoinquals) == 0" argument to
innerrel_is_unique_ext(). With that call gone, otherjoinquals is only
used in:
Assert(list_length(restrictlist) ==
(list_length(selfjoinquals) + list_length(otherjoinquals)));
Perhaps we can drop otherjoinquals and simplify split_selfjoin_quals() to
just return the list of self-join quals (similar to
get_shared_restrictions())?Thanks
On Mon, Nov 23, 2026 at 7:28 PM wenhui qiu <qiuwenhuifx@gmail.com> wrote:
Since all relations in remove_self_joins_one_group() share the same
reloid (and have !rte->inh), would it be worth checking
rel_supports_distinctness() once in remove_self_joins_one_group() so that
we can skip the whole group early if the table has no suitable unique
index?
Thanks for the review!
Good point. I've added the check at the top of
remove_self_joins_one_group(), so that we skip the whole group if the
relation has no usable unique index.
Perhaps we can drop otherjoinquals and simplify split_selfjoin_quals() to
just return the list of self-join quals (similar to
get_shared_restrictions())?
Agreed. Nothing uses the other quals anymore, so I've changed the
function to return just the self-join quals, and renamed it to
get_selfjoin_quals().
Attached is the updated patch.
- Richard
Hi,
On 25/11/2026 05:37, Richard Guo wrote:
On Mon, Nov 23, 2026 at 7:28 PM wenhui qiu <qiuwenhuifx@gmail.com> wrote:
Since all relations in remove_self_joins_one_group() share the same
reloid (and have !rte->inh), would it be worth checking
rel_supports_distinctness() once in remove_self_joins_one_group() so that
we can skip the whole group early if the table has no suitable unique
index?Thanks for the review!
Good point. I've added the check at the top of
remove_self_joins_one_group(), so that we skip the whole group if the
relation has no usable unique index.Perhaps we can drop otherjoinquals and simplify split_selfjoin_quals() to
just return the list of self-join quals (similar to
get_shared_restrictions())?Agreed. Nothing uses the other quals anymore, so I've changed the
function to return just the self-join quals, and renamed it to
get_selfjoin_quals().Attached is the updated patch.
- Richard
While looking at v2 i see that test_plan_advice (001_replan_regress)
fails on
tidscan:
--- a/src/test/regress/expected/tidscan.out
+++ b/src/test/modules/test_plan_advice/tmp_check/results/tidscan.out
@@ -119,7 +119,7 @@
-> Seq Scan on tidscan t1
Filter: (id = 1)
-> Tid Scan on tidscan t2
- TID Cond: (t1.ctid = ctid)
+ TID Cond: (ctid = t1.ctid)
This is new after what you did in v2's rel_supports_distinctness() early
exit in
remove_self_joins_one_group(). tidscan has no unique indexes, so v2
skips calling generate_join_implied_equalities(), leaving ec_derives_list
empty before path generation. In the normal case,
create_tidscan_paths() we see t1 first so we would put t1.ctid = t2.ctid
in ec.
When pg_plan_advice replans, SEQ_SCAN(t1) clears PGS_TIDSCAN of course
for t1, therefore ec is never touched. Later on t2 we would generate
t2.ctid = t1.ctid.
This looks like a pre-existing order dependency in equivclass.c /
tidpath.c that SJE previously masked by pre-populating ec_derives_list
in (t1, t2) order (and IIUC, unlike indexscans and merge/hash joins, TidScan
does not commute operands to a fixed side).
I don't think we should try setting a specific ordering directly in
equivclass.c (or anywher else),
If one tries to prepare operand order in
create_join_clause() (using counterpart / em_relids) and in
generate_implied_equalities_for_column() (using em_relids).
Both would change the expectations of order in other places (e.g indexed
inner rels).
This only affects pg_plan_advice (or anything that modifies
rel->pgs_mask per-relation).
Thoughts ?
Regards,
Ayoub Kazar
HI Ayoub
Show quoted text
This looks like a pre-existing order dependency in equivclass.c /
tidpath.c that SJE previously masked by pre-populating ec_derives_list
in (t1, t2) order (and IIUC, unlike indexscans and merge/hash joins,TidScan
does not commute operands to a fixed side).
I don't think we should try setting a specific ordering directly in
equivclass.c (or anywher else),...
This only affects pg_plan_advice (or anything that modifies
rel->pgs_mask per-relation).
Thoughts ?Agreed, thanks for tracking this down.
This is indeed pre-existing on master whenever SJE does not run on the
join -- for instance, joining two different tables on ctid:CREATE TABLE tidscan2 (id int);
EXPLAIN (COSTS OFF)
SELECT * FROM tidscan t1 JOIN tidscan2 t2 ON t1.ctid = t2.ctid
WHERE t1.id = 1;or running the existing query in tidscan.sql with
enable_self_join_elimination = off produces the exact same diff under
test_plan_advice. SJE only masked it for the self-join case because it
previously called generate_join_implied_equalities() even when the
relation had no unique indexes. So we shouldn't drop the
rel_supports_distinctness() check in SJE just to hide this, and I also
agree we shouldn't try to enforce a specific operand order in
equivclass.c.It seems to me there are two ways we could address this on the tidscan
side (probably as a separate preparatory patch):1. Canonicalize parameterized TidScan quals in
BuildParameterizedTidPaths() so that the scanned relation's ctid is
always on the left (via commute_restrictinfo(rinfo, TIDEqualOperator),
similar to what match_opclause_to_indexcol() does for index scans).
That way, parameterized TidScans consistently produce "TID Cond:
(ctid = t1.ctid)" regardless of which relation populated
ec_derives_list first.Doing this only in BuildParameterizedTidPaths() leaves single-rel cases
like "WHERE '(0,1)' = ctid" alone (preserving test coverage for the
commuted OpExpr branch in nodeTidscan.c and avoiding breaking the
OR-clause list_difference() check in create_tidscan_plan()), and only
changes the two join plans in expected/tidscan.out. Note that
create_tidscan_plan() would also need to check rinfo_serial rather than
list_member_ptr(tidquals, rinfo) when removing duplicate scan_clauses,
otherwise a commuted non-EC join clause (such as the LEFT JOIN test in
tidscan.sql) would be left behind as a redundant Filter.2. Alternatively, handle PGS_TIDSCAN via disabled_nodes in
cost_tidscan() / cost_tidrangescan() instead of skipping path
generation in create_tidscan_paths(), matching PGS_SEQSCAN,
PGS_INDEXSCAN, and PGS_BITMAPSCAN. That avoids changing tidscan.out,
though as noted in pathnodes.h, skipping path generation was chosen to
preserve the historical behavior of enable_tidscan = off (e.g., when
enable_seqscan is also off).Between the two, (1) feels cleaner to me since it removes the
EXPLAIN output's sensitivity to EC derivation order altogether, but I'd
be interested to hear what others think.Thanks
On 27/11/2026 04:41, wenhui qiu wrote:
1. Canonicalize parameterized TidScan quals in
BuildParameterizedTidPaths() so that the scanned relation's ctid is
always on the left (via commute_restrictinfo(rinfo, TIDEqualOperator),
similar to what match_opclause_to_indexcol() does for index scans).
That way, parameterized TidScans consistently produce "TID Cond:
(ctid = t1.ctid)" regardless of which relation populated
ec_derives_list first.Doing this only in BuildParameterizedTidPaths() leaves single-rel
cases
like "WHERE '(0,1)' = ctid" alone (preserving test coverage for the
commuted OpExpr branch in nodeTidscan.c and avoiding breaking the
OR-clause list_difference() check in create_tidscan_plan()), and only
changes the two join plans in expected/tidscan.out. Note that
create_tidscan_plan() would also need to check rinfo_serial rather
than
list_member_ptr(tidquals, rinfo) when removing duplicate scan_clauses,
otherwise a commuted non-EC join clause (such as the LEFT JOIN test in
tidscan.sql) would be left behind as a redundant Filter.2. Alternatively, handle PGS_TIDSCAN via disabled_nodes in
cost_tidscan() / cost_tidrangescan() instead of skipping path
generation in create_tidscan_paths(), matching PGS_SEQSCAN,
PGS_INDEXSCAN, and PGS_BITMAPSCAN. That avoids changing tidscan.out,
though as noted in pathnodes.h, skipping path generation was chosen to
preserve the historical behavior of enable_tidscan = off (e.g., when
enable_seqscan is also off).Between the two, (1) feels cleaner to me since it removes the
EXPLAIN output's sensitivity to EC derivation order altogether,
but I'd
be interested to hear what others think.
Agree, option 1 seems fine.
Regards,
Ayoub Kazar