BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

Started by PG Bug reporting form3 months ago20 messagesbugs
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19633
Logged by: Suyang Zhong
Email address: syzhong16@gmail.com
PostgreSQL version: 19beta3
Operating system: Ubuntu 22.04
Description:

Hi,

Consider the following test case:

```
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level1',
deterministic = false);

CREATE TABLE t_lhs(c1 text COLLATE ci);
CREATE TABLE t_rhs(c0 text);
INSERT INTO t_lhs VALUES ('a'), ('x'), ('y');
INSERT INTO t_rhs VALUES ('a'), ('a');
ANALYZE t_lhs;
ANALYZE t_rhs;
INSERT INTO t_rhs VALUES ('A');

SELECT c1, c1 IN (SELECT c0 FROM t_rhs) AS p FROM t_lhs;
-- a | t
-- x | f
-- y | f

SELECT count(*) FROM t_lhs WHERE c1 IN (SELECT c0 FROM t_rhs);
-- Expected: 1, Actual: 2
```

The predicate evaluates to true for one row, so filtering on the same
predicate should return one row.

Reproduced on 20devel and 19beta3.

#2Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: PG Bug reporting form (#1)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

чт, 20 авг. 2026 г. в 23:41, PG Bug reporting form <noreply@postgresql.org>:

The following bug has been logged on the website:

Bug reference: 19633
Logged by: Suyang Zhong
Email address: syzhong16@gmail.com
PostgreSQL version: 19beta3
Operating system: Ubuntu 22.04
Description:

Hi,

Consider the following test case:

```
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level1',
deterministic = false);

CREATE TABLE t_lhs(c1 text COLLATE ci);
CREATE TABLE t_rhs(c0 text);
INSERT INTO t_lhs VALUES ('a'), ('x'), ('y');
INSERT INTO t_rhs VALUES ('a'), ('a');
ANALYZE t_lhs;
ANALYZE t_rhs;
INSERT INTO t_rhs VALUES ('A');

SELECT c1, c1 IN (SELECT c0 FROM t_rhs) AS p FROM t_lhs;
-- a | t
-- x | f
-- y | f

SELECT count(*) FROM t_lhs WHERE c1 IN (SELECT c0 FROM t_rhs);
-- Expected: 1, Actual: 2
```

Hi, Suyang!

Thanks for the report.

With enable_hashagg off that looks like:

Aggregate
-> Nested Loop
Join Filter: (t_semi_ci.c1 = ((t_semi_cs.c0)::text))
-> Unique
-> Sort
Sort Key: t_semi_cs.c0
-> Seq Scan on t_semi_cs
-> Seq Scan on t_semi_ci

Under gdb that path is create_unique_paths from the join search:

#0 create_unique_paths at planner.c:8673
#1 populate_joinrel_with_paths at joinrels.c:1189
#2 make_join_rel at joinrels.c:774
#3 make_rels_by_clause_joins at joinrels.c:300
#4 join_search_one_level at joinrels.c:123
#5 standard_join_search at allpaths.c:3987

(gdb) pgprint sjinfo
SpecialJoinInfo [jointype=JOIN_SEMI semi_can_btree=true
semi_can_hash=false]
[semi_operators] OidList: [98]
[semi_rhs_exprs]
Var [varno=3 varattno=1 vartype=25 varcollid=100]

Unique/HashAgg take the collation from the RHS expression. Here that
is the default collation of t_rhs.c0 (varcollid 100), not the join's
input collation (ci). So Sort+Unique keeps both 'a' and 'A'. Under
ci those values are equal, and the inner join emits the outer 'a'
twice (count is 2).

The attached patch labels each semi_rhs_expr with the join operator's
inputcollid via canonicalize_ec_expression (RelabelType when needed),
so unique-ification uses the same equality as the join. Sort then
shows

Sort Key: t_semi_cs.c0 COLLATE case_insensitive

and the count is 1. A regress case is included in collate.icu.utf8.

I am still getting familiar with this part. I am not sure this is the right
place or the right approach.

Thoughts?

--
Regards,
Rachitskiy Andrey

Attachments:

t253501_2
0001-Fix-semijoin-RHS-unique-ification-to-use-join-collation.patchtext/x-patch; charset=US-ASCII; name=0001-Fix-semijoin-RHS-unique-ification-to-use-join-collation.patchDownload+53-1
#3Tender Wang
tndrwang@gmail.com
In reply to: Andrey Rachitskiy (#2)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

Hi Andrey,

Andrey Rachitskiy <pl0h0yp1@gmail.com> 于2026年8月21日周五 04:35写道:

чт, 20 авг. 2026 г. в 23:41, PG Bug reporting form <noreply@postgresql.org>:
Under gdb that path is create_unique_paths from the join search:

#0 create_unique_paths at planner.c:8673
#1 populate_joinrel_with_paths at joinrels.c:1189
#2 make_join_rel at joinrels.c:774
#3 make_rels_by_clause_joins at joinrels.c:300
#4 join_search_one_level at joinrels.c:123
#5 standard_join_search at allpaths.c:3987

(gdb) pgprint sjinfo
SpecialJoinInfo [jointype=JOIN_SEMI semi_can_btree=true
semi_can_hash=false]
[semi_operators] OidList: [98]
[semi_rhs_exprs]
Var [varno=3 varattno=1 vartype=25 varcollid=100]

Unique/HashAgg take the collation from the RHS expression. Here that
is the default collation of t_rhs.c0 (varcollid 100), not the join's
input collation (ci). So Sort+Unique keeps both 'a' and 'A'. Under
ci those values are equal, and the inner join emits the outer 'a'
twice (count is 2).

The attached patch labels each semi_rhs_expr with the join operator's
inputcollid via canonicalize_ec_expression (RelabelType when needed),
so unique-ification uses the same equality as the join. Sort then
shows

Sort Key: t_semi_cs.c0 COLLATE case_insensitive

and the count is 1. A regress case is included in collate.icu.utf8.

I am still getting familiar with this part. I am not sure this is the right place or the right approach.

Thoughts?

The approach looks good to me. I'd suggest adjusting the comment as follows:
...
/* so far so good, keep building lists */
semi_operators = lappend_oid(semi_operators, opno);

/*
* Ensure that the RHS expression exposes the join operator's input
* collation. The expression will later be used as a grouping key when
* unique-ifying the RHS, so its collation must agree with the semijoin
* equality semantics.
*/
semi_rhs_exprs =
lappend(semi_rhs_exprs,
canonicalize_ec_expression((Expr *) copyObject(right_expr),
exprType(right_expr),
op->inputcollid));
...

--
Thanks,
Tender Wang

#4Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Tender Wang (#3)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

пт, 21 авг. 2026 г. в 06:54, Tender Wang <tndrwang@gmail.com>:

The approach looks good to me. I'd suggest adjusting the comment as
follows:
...
/* so far so good, keep building lists */
semi_operators = lappend_oid(semi_operators, opno);

/*
* Ensure that the RHS expression exposes the join operator's input
* collation. The expression will later be used as a grouping key when
* unique-ifying the RHS, so its collation must agree with the semijoin
* equality semantics.
*/
semi_rhs_exprs =
lappend(semi_rhs_exprs,
canonicalize_ec_expression((Expr *) copyObject(right_expr),
exprType(right_expr),
op->inputcollid));

Dear Tender,

Thanks for the review.
Made the changes - v2 attached.

--
Regards,
Rachitskiy Andrey

Attachments:

t253501_4
v2-0001-Fix-semijoin-RHS-unique-ification-to-use-join-collation.patchtext/x-patch; charset=US-ASCII; name=v2-0001-Fix-semijoin-RHS-unique-ification-to-use-join-collation.patchDownload+53-2
#5Alexander Korotkov
aekorotkov@gmail.com
In reply to: Andrey Rachitskiy (#4)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

Hi!

On Fri, Aug 21, 2026 at 8:02 AM Andrey Rachitskiy <pl0h0yp1@gmail.com> wrote:

пт, 21 авг. 2026 г. в 06:54, Tender Wang <tndrwang@gmail.com>:

The approach looks good to me. I'd suggest adjusting the comment as follows:
...
/* so far so good, keep building lists */
semi_operators = lappend_oid(semi_operators, opno);

/*
* Ensure that the RHS expression exposes the join operator's input
* collation. The expression will later be used as a grouping key when
* unique-ifying the RHS, so its collation must agree with the semijoin
* equality semantics.
*/
semi_rhs_exprs =
lappend(semi_rhs_exprs,
canonicalize_ec_expression((Expr *) copyObject(right_expr),
exprType(right_expr),
op->inputcollid));

Dear Tender,

Thanks for the review.
Made the changes - v2 attached.

I think this approach is right. Everybody who consumes
SpecialJoinInfo.semi_rhs_exprs takes the collation from the expression
itself, because SortGroupClause does not carry one and neither does
the pathkey machinery. So labelling the expression once, where it is
recorded, fixes every consumer at the same time; fixing it in the
consumers would mean doing the same thing in three places and getting
it right in each. The call is also exactly what process_equivalence()
already does for equivalence class members, with the same two
arguments and for the same reason, so this is not a new trick.

I've revised the patch. The v3 changes are:
1. The test now covers the hash path as well. v2 turned
enable_hashagg off, which is precisely the plan shape that was not
broken in isolation; both strategies are now exercised, each with its
plan and its result.
2. Test also checks results rows, not only the count. The bug is the
disagreement between the two: the predicate is true for one row while
filtering on it returned two.
3. Added a test for unique-ification being skipped because of a unique
index. Getting real coverage from it needs a little care: with only
'a' and 'A' in the RHS the planner keeps an ordinary semijoin and
answers correctly, so the test passes with or without the fix. Two
filler rows are enough to make unique-ification look worthwhile and
put the decision on the table. The plan is checked as well, so that a
future costing change cannot quietly turn this into a test of nothing.
4. Added a comment saying why the INSERT of 'A' comes after ANALYZE.
5. Reworded the code comment to say why rather than what:
unique-ification groups on this expression and takes the collation
from it, since SortGroupClause carries none.
6. Commit message now mentions HashAggregate, which v2 did not.

Now the part that is missing from the thread entirely. This is not a v19
regression. The line

semi_rhs_exprs = lappend(semi_rhs_exprs, copyObject(right_expr));

is identical in every supported branch back to 14, and the consumer
has the same shape there: REL_18's create_unique_path() builds a
SortGroupClause with no collation and takes the key from uniqexpr. So
this is a live wrong-results bug in all of them (I've checked it), and
I intend to backpatch it through 14.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

t253501_5
v3-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchapplication/octet-stream; name=v3-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+153-2
#6Richard Guo
guofenglinux@gmail.com
In reply to: Alexander Korotkov (#5)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Thu, Sep 10, 2026 at 7:40 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

I've revised the patch. The v3 changes are:
1. The test now covers the hash path as well. v2 turned
enable_hashagg off, which is precisely the plan shape that was not
broken in isolation; both strategies are now exercised, each with its
plan and its result.

I think it'd better to resue existing tables rather than create
new ones for the tests. Maybe we can reuse test1cs/test1ci,
test2cs/test2ci, test3cs/test3ci to reproduce this issue?

Also on master we have this new GUC enable_groupagg. Maybe it'd
better to use that instead of enable_sort?

- Richard

#7Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Richard Guo (#6)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

чт, 10 сент. 2026 г. в 05:10, Richard Guo <guofenglinux@gmail.com>:

On Thu, Sep 10, 2026 at 7:40 AM Alexander Korotkov <aekorotkov@gmail.com>
wrote:

I've revised the patch. The v3 changes are:
1. The test now covers the hash path as well. v2 turned
enable_hashagg off, which is precisely the plan shape that was not
broken in isolation; both strategies are now exercised, each with its
plan and its result.

I think it'd better to resue existing tables rather than create
new ones for the tests. Maybe we can reuse test1cs/test1ci,
test2cs/test2ci, test3cs/test3ci to reproduce this issue?

fix in v4

Also on master we have this new GUC enable_groupagg. Maybe it'd
better to use that instead of enable_sort?

This GUC exists only on master (e01b23b84e4, July 2026) and is not present

on REL_14_STABLE through REL_19_STABLE, so it is preferable to keep
enable_sort=off — that way the tests won't diverge from the backpatch.

--
Regards,
Rachitskiy Andrey

Attachments:

t253501_7
v4-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchtext/x-patch; charset=US-ASCII; name=v4-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+184-2
#8Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Andrey Rachitskiy (#7)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On backpatch the C change applies cleanly through 14. The regress
SQL hunks also apply, but the EXPLAIN text is not identical across
branches even when the counts are. I checked REL_19 through REL_14
with --with-icu. After the fix the counts are 1/1/1 and 3 everywhere.
The EXPLAIN differences are:

- Unique Sort Key on REL_18 and older prints
((test2cs.x)::text) COLLATE case_insensitive
where master/REL_19 print test2cs.x COLLATE case_insensitive

- unique-index case on REL_17 through REL_14 comes out as
Hash Semi Join rather than Hash Right Semi Join

So the backpatch will need a small expected.

--
Regards,
Rachitskiy Andrey

#9Alexander Korotkov
aekorotkov@gmail.com
In reply to: Andrey Rachitskiy (#8)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Thu, Sep 10, 2026 at 10:56 AM Andrey Rachitskiy <pl0h0yp1@gmail.com> wrote:

On backpatch the C change applies cleanly through 14. The regress
SQL hunks also apply, but the EXPLAIN text is not identical across
branches even when the counts are. I checked REL_19 through REL_14
with --with-icu. After the fix the counts are 1/1/1 and 3 everywhere.
The EXPLAIN differences are:

- Unique Sort Key on REL_18 and older prints
((test2cs.x)::text) COLLATE case_insensitive
where master/REL_19 print test2cs.x COLLATE case_insensitive

- unique-index case on REL_17 through REL_14 comes out as
Hash Semi Join rather than Hash Right Semi Join

So the backpatch will need a small expected.

OK, I'll take care about this during backpatching.

I also like idea of usage of enable_sort all the version in this case.
This would simplify backpatching and reduce divergence between
versions.

I made two changes to the patch.

1) Dropped the two filler rows in test1cs. They were needed back when
that block used a private two-row table; test1cs already has four
rows. That's enough to get the desired plan.
2) Dropped "ALTER TABLE test2cs ALTER COLUMN x RESET (n_distinct)".
With no ANALYZE after it, it does not restore the statistics anyway,
and nothing later in the file reads test2cs.

I plan to push this and backpatch through 14, adjusting the expected
file per branch along the lines you described.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

t253501_9
v5-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchapplication/octet-stream; name=v5-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+153-2
#10Richard Guo
guofenglinux@gmail.com
In reply to: Alexander Korotkov (#9)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Fri, Sep 11, 2026 at 6:54 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

I also like idea of usage of enable_sort all the version in this case.
This would simplify backpatching and reduce divergence between
versions.

I believe one of the goals of commit e01b23b84 is replacing
enable_sort with enable_groupagg in tests going forward where that's
the real intent. Re-introducing enable_sort here seems to go against
that goal.

I plan to push this and backpatch through 14, adjusting the expected
file per branch along the lines you described.

Also I don't understand why v5 is still creating new tables rather
than using existing tables in the tests.

- Richard

#11Alexander Korotkov
aekorotkov@gmail.com
In reply to: Richard Guo (#10)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Fri, Sep 11, 2026 at 4:03 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Fri, Sep 11, 2026 at 6:54 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

I also like idea of usage of enable_sort all the version in this case.
This would simplify backpatching and reduce divergence between
versions.

I believe one of the goals of commit e01b23b84 is replacing
enable_sort with enable_groupagg in tests going forward where that's
the real intent. Re-introducing enable_sort here seems to go against
that goal.

I plan to push this and backpatch through 14, adjusting the expected
file per branch along the lines you described.

Also I don't understand why v5 is still creating new tables rather
than using existing tables in the tests.

Sorry, I accidentally used the wrong branch to generate the patch.
Please, check the attached version: it doesn't create new tables.

Also I changed usage of enable_sort to enable_groupagg as you
suggested. I will have to change it to enable_sort during
backpatching.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

t253501_11
v6-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchapplication/octet-stream; name=v6-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+176-2
#12Alexander Korotkov
aekorotkov@gmail.com
In reply to: Alexander Korotkov (#11)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Fri, Sep 11, 2026 at 8:06 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

On Fri, Sep 11, 2026 at 4:03 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Fri, Sep 11, 2026 at 6:54 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

I also like idea of usage of enable_sort all the version in this case.
This would simplify backpatching and reduce divergence between
versions.

I believe one of the goals of commit e01b23b84 is replacing
enable_sort with enable_groupagg in tests going forward where that's
the real intent. Re-introducing enable_sort here seems to go against
that goal.

I plan to push this and backpatch through 14, adjusting the expected
file per branch along the lines you described.

Also I don't understand why v5 is still creating new tables rather
than using existing tables in the tests.

Sorry, I accidentally used the wrong branch to generate the patch.
Please, check the attached version: it doesn't create new tables.

Also I changed usage of enable_sort to enable_groupagg as you
suggested. I will have to change it to enable_sort during
backpatching.

Any objections if I push (and backpatch) this?

------
Regards,
Alexander Korotkov
Supabase

#13Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Alexander Korotkov (#12)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

сб, 12 сент. 2026 г., 18:57 Alexander Korotkov <aekorotkov@gmail.com>:

On Fri, Sep 11, 2026 at 8:06 AM Alexander Korotkov <aekorotkov@gmail.com>
wrote:

On Fri, Sep 11, 2026 at 4:03 AM Richard Guo <guofenglinux@gmail.com>

wrote:

On Fri, Sep 11, 2026 at 6:54 AM Alexander Korotkov <

aekorotkov@gmail.com> wrote:

I also like idea of usage of enable_sort all the version in this

case.

This would simplify backpatching and reduce divergence between
versions.

I believe one of the goals of commit e01b23b84 is replacing
enable_sort with enable_groupagg in tests going forward where that's
the real intent. Re-introducing enable_sort here seems to go against
that goal.

I plan to push this and backpatch through 14, adjusting the expected
file per branch along the lines you described.

Also I don't understand why v5 is still creating new tables rather
than using existing tables in the tests.

Sorry, I accidentally used the wrong branch to generate the patch.
Please, check the attached version: it doesn't create new tables.

Also I changed usage of enable_sort to enable_groupagg as you
suggested. I will have to change it to enable_sort during
backpatching.

Any objections if I push (and backpatch) this?

------
Regards,
Alexander Korotkov
Supabase

Hi, Alexander!

I can't possibly have any :)
LGTM

Show quoted text
#14Richard Guo
guofenglinux@gmail.com
In reply to: Alexander Korotkov (#12)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Sat, Sep 12, 2026 at 10:57 PM Alexander Korotkov
<aekorotkov@gmail.com> wrote:

Any objections if I push (and backpatch) this?

I'll have a look ASAP.

- Richard

#15Richard Guo
guofenglinux@gmail.com
In reply to: Richard Guo (#14)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Mon, Sep 14, 2026 at 5:24 PM Richard Guo <guofenglinux@gmail.com> wrote:

On Sat, Sep 12, 2026 at 10:57 PM Alexander Korotkov
<aekorotkov@gmail.com> wrote:

Any objections if I push (and backpatch) this?

I'll have a look ASAP.

I looked at v6. The fix itself looks right to me. I have some
comments on the rest of the patch, though.

* Overall, the new comments in this patch are overly verbose. I think
we should keep them in line with the style of the existing comments.
Also, the new comment in compute_semijoin_info() talks only about the
collation, but the call also keeps the expression's original type,
which I think the comment should mention as well.

* In compute_semijoin_info(), the new comment and the relabeling call
are inserted between the two appends, right after

/* so far so good, keep building lists */

That comment is about building both lists, so it reads oddly with the
appends split apart. I'd rather relabel right_expr as a separate step
before that comment, and then keep the two appends together under it.

* The tests alter tables that other test cases in this file rely on,
which is really not a good practice.

INSERT INTO test2cs VALUES ('abc');
ALTER TABLE test2cs ALTER COLUMN x SET (n_distinct = 1);
ANALYZE test1ci, test2cs;
...
ANALYZE test1cs;

The INSERT is only there so that test2cs holds both 'abc' and 'ABC',
but test3cs already holds exactly that, and it also has the unique
index under case_sensitive, so it covers the unique-index case as
well. We don't need the n_distinct hack or the ANALYZEs either:
disabling seqscan and material is enough to make the planner
unique-ify test3cs, since the semijoin's inner index-only scan on
test3cs can't use the case_insensitive join clause as an index
condition and would have to be rescanned for every outer row.

* The same query

SELECT count(*) FROM test1ci
WHERE x COLLATE case_insensitive IN
(SELECT x FROM test2cs WHERE x IN ('abc', 'ABC'));

is run three times, once under the default settings without an EXPLAIN
and once under each forced strategy. The first run adds nothing, as
its plan is one of the other two and we can't even tell which.

* The last test, the one with "ANALYZE test1cs", pins a Hash Right
Semi Join, which is a plain semijoin that never unique-ifies, so on
master it doesn't exercise this patch at all. What it does exercise
is reduce_unique_semijoins(), which was fixed in 5a55ea507 and is
already covered by the "Ensure that semijoin is not reduced to
innerjoin" tests earlier in this file. The case the comment describes
only exists in the back branches, where create_unique_path() still
consults relation_has_unique_index_for() with semi_rhs_exprs, and
using test3cs as the RHS covers that with the same query.

* One more thing for the commit message. In the back branches
create_unique_path() also has the DISTINCT-subquery shortcut, which
goes through the collation-blind two-list query_is_distinct_for()
wrapper. This patch happens to close that too, because
translate_sub_tlist() punts on the RelabelType, so it's worth a
sentence there.

Attached is v7 with these changes.

- Richard

Attachments:

t253501_15
v7-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchapplication/octet-stream; name=v7-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+95-2
#16Alexander Korotkov
aekorotkov@gmail.com
In reply to: Richard Guo (#15)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

Hi, Richard!

On Tue, Sep 15, 2026 at 4:48 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Mon, Sep 14, 2026 at 5:24 PM Richard Guo <guofenglinux@gmail.com> wrote:

On Sat, Sep 12, 2026 at 10:57 PM Alexander Korotkov
<aekorotkov@gmail.com> wrote:

Any objections if I push (and backpatch) this?

I'll have a look ASAP.

I looked at v6. The fix itself looks right to me. I have some
comments on the rest of the patch, though.

* Overall, the new comments in this patch are overly verbose. I think
we should keep them in line with the style of the existing comments.
Also, the new comment in compute_semijoin_info() talks only about the
collation, but the call also keeps the expression's original type,
which I think the comment should mention as well.

* In compute_semijoin_info(), the new comment and the relabeling call
are inserted between the two appends, right after

/* so far so good, keep building lists */

That comment is about building both lists, so it reads oddly with the
appends split apart. I'd rather relabel right_expr as a separate step
before that comment, and then keep the two appends together under it.

* The tests alter tables that other test cases in this file rely on,
which is really not a good practice.

INSERT INTO test2cs VALUES ('abc');
ALTER TABLE test2cs ALTER COLUMN x SET (n_distinct = 1);
ANALYZE test1ci, test2cs;
...
ANALYZE test1cs;

The INSERT is only there so that test2cs holds both 'abc' and 'ABC',
but test3cs already holds exactly that, and it also has the unique
index under case_sensitive, so it covers the unique-index case as
well. We don't need the n_distinct hack or the ANALYZEs either:
disabling seqscan and material is enough to make the planner
unique-ify test3cs, since the semijoin's inner index-only scan on
test3cs can't use the case_insensitive join clause as an index
condition and would have to be rescanned for every outer row.

* The same query

SELECT count(*) FROM test1ci
WHERE x COLLATE case_insensitive IN
(SELECT x FROM test2cs WHERE x IN ('abc', 'ABC'));

is run three times, once under the default settings without an EXPLAIN
and once under each forced strategy. The first run adds nothing, as
its plan is one of the other two and we can't even tell which.

* The last test, the one with "ANALYZE test1cs", pins a Hash Right
Semi Join, which is a plain semijoin that never unique-ifies, so on
master it doesn't exercise this patch at all. What it does exercise
is reduce_unique_semijoins(), which was fixed in 5a55ea507 and is
already covered by the "Ensure that semijoin is not reduced to
innerjoin" tests earlier in this file. The case the comment describes
only exists in the back branches, where create_unique_path() still
consults relation_has_unique_index_for() with semi_rhs_exprs, and
using test3cs as the RHS covers that with the same query.

* One more thing for the commit message. In the back branches
create_unique_path() also has the DISTINCT-subquery shortcut, which
goes through the collation-blind two-list query_is_distinct_for()
wrapper. This patch happens to close that too, because
translate_sub_tlist() punts on the RelabelType, so it's worth a
sentence there.

Attached is v7 with these changes.

Thank you for your corrections. I accept all of them.

I suggest we could change the test query as follows.

SELECT count(*) FROM test1ci
WHERE x COLLATE case_insensitive IN (SELECT x FROM test3cs);

This shape allows to achieve the desired plan both with
enable_groupagg = off and with enable_sort = off. Therefore sql part
for pg19- will only differ with this GUC name. I've checked it works
down to pg14 and keeps distinguishing the fix.

Attached v8 with this change.

------
Regards,
Alexander Korotkov
Supabase

Attachments:

t253501_16
v8-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchapplication/octet-stream; name=v8-0001-Use-the-join-collation-when-unique-ifying-a-semij.patchDownload+91-2
#17Alexander Korotkov
aekorotkov@gmail.com
In reply to: Alexander Korotkov (#16)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Tue, Sep 15, 2026 at 4:05 PM Alexander Korotkov <aekorotkov@gmail.com> wrote:

On Tue, Sep 15, 2026 at 4:48 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Mon, Sep 14, 2026 at 5:24 PM Richard Guo <guofenglinux@gmail.com> wrote:

On Sat, Sep 12, 2026 at 10:57 PM Alexander Korotkov
<aekorotkov@gmail.com> wrote:

Any objections if I push (and backpatch) this?

I'll have a look ASAP.

I looked at v6. The fix itself looks right to me. I have some
comments on the rest of the patch, though.

* Overall, the new comments in this patch are overly verbose. I think
we should keep them in line with the style of the existing comments.
Also, the new comment in compute_semijoin_info() talks only about the
collation, but the call also keeps the expression's original type,
which I think the comment should mention as well.

* In compute_semijoin_info(), the new comment and the relabeling call
are inserted between the two appends, right after

/* so far so good, keep building lists */

That comment is about building both lists, so it reads oddly with the
appends split apart. I'd rather relabel right_expr as a separate step
before that comment, and then keep the two appends together under it.

* The tests alter tables that other test cases in this file rely on,
which is really not a good practice.

INSERT INTO test2cs VALUES ('abc');
ALTER TABLE test2cs ALTER COLUMN x SET (n_distinct = 1);
ANALYZE test1ci, test2cs;
...
ANALYZE test1cs;

The INSERT is only there so that test2cs holds both 'abc' and 'ABC',
but test3cs already holds exactly that, and it also has the unique
index under case_sensitive, so it covers the unique-index case as
well. We don't need the n_distinct hack or the ANALYZEs either:
disabling seqscan and material is enough to make the planner
unique-ify test3cs, since the semijoin's inner index-only scan on
test3cs can't use the case_insensitive join clause as an index
condition and would have to be rescanned for every outer row.

* The same query

SELECT count(*) FROM test1ci
WHERE x COLLATE case_insensitive IN
(SELECT x FROM test2cs WHERE x IN ('abc', 'ABC'));

is run three times, once under the default settings without an EXPLAIN
and once under each forced strategy. The first run adds nothing, as
its plan is one of the other two and we can't even tell which.

* The last test, the one with "ANALYZE test1cs", pins a Hash Right
Semi Join, which is a plain semijoin that never unique-ifies, so on
master it doesn't exercise this patch at all. What it does exercise
is reduce_unique_semijoins(), which was fixed in 5a55ea507 and is
already covered by the "Ensure that semijoin is not reduced to
innerjoin" tests earlier in this file. The case the comment describes
only exists in the back branches, where create_unique_path() still
consults relation_has_unique_index_for() with semi_rhs_exprs, and
using test3cs as the RHS covers that with the same query.

* One more thing for the commit message. In the back branches
create_unique_path() also has the DISTINCT-subquery shortcut, which
goes through the collation-blind two-list query_is_distinct_for()
wrapper. This patch happens to close that too, because
translate_sub_tlist() punts on the RelabelType, so it's worth a
sentence there.

Attached is v7 with these changes.

Thank you for your corrections. I accept all of them.

I suggest we could change the test query as follows.

SELECT count(*) FROM test1ci
WHERE x COLLATE case_insensitive IN (SELECT x FROM test3cs);

This shape allows to achieve the desired plan both with
enable_groupagg = off and with enable_sort = off. Therefore sql part
for pg19- will only differ with this GUC name. I've checked it works
down to pg14 and keeps distinguishing the fix.

Attached v8 with this change.

Please, let me know if you're OK with this change. As this is major
change for the SQL tests of this patch.

------
Regards,
Alexander Korotkov
Supabase

#18Richard Guo
guofenglinux@gmail.com
In reply to: Alexander Korotkov (#17)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Wed, Sep 16, 2026 at 8:05 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

Please, let me know if you're OK with this change. As this is major
change for the SQL tests of this patch.

v8 LGTM.

- Richard

#19Alexander Korotkov
aekorotkov@gmail.com
In reply to: Richard Guo (#18)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

On Wed, Sep 16, 2026 at 3:19 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Wed, Sep 16, 2026 at 8:05 AM Alexander Korotkov <aekorotkov@gmail.com> wrote:

Please, let me know if you're OK with this change. As this is major
change for the SQL tests of this patch.

v8 LGTM.

Thank you. Committed and backpatched.
Fingers crossed, I didn't mess up anything during backpatching. WIll
keep looking at buildfarm.

------
Regards,
Alexander Korotkov
Supabase

#20Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Alexander Korotkov (#19)
Re: BUG #19633: Unexpected results of IN (subquery) with a non-deterministic collation

ср, 16 сент. 2026 г. в 15:15, Alexander Korotkov <aekorotkov@gmail.com>:

On Wed, Sep 16, 2026 at 3:19 AM Richard Guo <guofenglinux@gmail.com>
wrote:

On Wed, Sep 16, 2026 at 8:05 AM Alexander Korotkov <aekorotkov@gmail.com>

wrote:

Please, let me know if you're OK with this change. As this is major
change for the SQL tests of this patch.

v8 LGTM.

Thank you. Committed and backpatched.
Fingers crossed, I didn't mess up anything during backpatching. WIll
keep looking at buildfarm.

Richard, Alexander - Thank you for reviewing & pushing.

--
Regards,
Rachitskiy Andrey