Unsafe qual pushdown through DISTINCT with simple CASE expressions

Started by Tender Wang3 months ago6 messageshackers
Jump to latest
#1Tender Wang
tndrwang@gmail.com

Hi,

I found what appears to be an unsafe qual pushdown through a DISTINCT
subquery when the qual contains a simple CASE expression.

A small example using citext is:

```
CREATE EXTENSION citext;

CREATE TABLE cit (t citext);
INSERT INTO cit VALUES ('a'), ('A'), ('b');

SELECT *
FROM (SELECT DISTINCT t FROM cit) d
WHERE (CASE t::text WHEN 'A' THEN 1 ELSE 0 END) = 1;
```

On master, the qual is pushed below the DISTINCT:

```text
Unique
-> Sort
Sort Key: cit.t
-> Seq Scan on cit
Filter: (CASE (t)::text WHEN 'A'::text THEN 1 ELSE 0 END = 1)
```

This is suspicious because DISTINCT compares `t` using citext
equality, under which `'a'` and `'A'` are equal, while the CASE
expression casts `t` to text and therefore distinguishes them.

Interestingly, writing the comparison directly does not result in pushdown:

```
SELECT *
FROM (SELECT DISTINCT t FROM cit) d
WHERE t::text = 'A';
```

In this case, the qual remains above the DISTINCT:

```text
Subquery Scan on d
Filter: ((d.t)::text = 'A'::text)
-> Unique
-> Sort
Sort Key: cit.t
-> Seq Scan on cit
```

The first example by itself does not demonstrate a deterministic wrong
result, since plain DISTINCT does not specify which representation is
retained when `'a'` and `'A'` compare equal as citext.

The problem can be demonstrated deterministically with DISTINCT ON:

```sql
SELECT *
FROM
(
SELECT DISTINCT ON (t) t
FROM cit
ORDER BY t, t::text COLLATE "C"
) d
WHERE CASE t::text WHEN 'a' THEN 1 ELSE 0 END = 1;
```

`DISTINCT ON (t)` groups `'a'` and `'A'` using citext equality, while
the secondary sort key ensures that `'A'` is selected from that group.
Therefore, if the outer qual is evaluated after the subquery as
required, `'A'` does not satisfy the text comparison with `'a'`, and
the query returns no rows.

On master, however, the CASE qual is pushed below the DISTINCT ON. It
filters out `'A'` first and leaves `'a'`, causing the query to return
one row.

I believe the problem is in the special handling of simple CASE
expressions in `grouping_conflict_walker()`.

The comment there currently explains that a simple CASE is a
comparison in disguise: parse analysis stores the CASE argument
separately and represents each WHEN comparison using a `CaseTestExpr`
in its place. It then states that the WHEN operators are always the
type-default `=`, matching the grouping equality operator, and
therefore only a collation conflict needs to be considered.

That assumption does not hold when the CASE argument changes the
equality semantics of a grouping column.

For example, in:

```
CASE t::text WHEN 'A' THEN ...
```

the grouping column is `t` of type citext, so DISTINCT uses
`citext_eq`. But the CASE argument is `t::text`, and the type-default
equality operator used by the WHEN comparison is therefore `text_eq`.

Thus we have:

```
grouping equality operator: citext_eq
CASE WHEN equality operator: text_eq
```

The collation of `t` can still be deterministic, so the existing check
for nondeterministic collations does not catch this case.

For an ordinary expression such as:

```
t::text = 'A'
```

`grouping_conflict_walker()` keeps the grouping operand and the
comparison operator together and `grouping_check_operand()` correctly
detects that `text_eq` is not compatible with the grouping equality
operator.

For a simple CASE, however, the `CaseTestExpr` representation
separates the CASE argument from the WHEN comparison operator. The
existing special handling restores enough information to check
collation conflicts, but does not check equality-operator
compatibility.

The attached patch fixes this by checking the CASE argument against
the equality operator and input collation of each WHEN comparison
using the existing `grouping_check_operand()` logic. It also adds a
regression test using the deterministic DISTINCT ON example above.

--
Thanks,
Tender Wang

Attachments:

t253458_1
0001-Fix-case-when.patchapplication/octet-stream; name=0001-Fix-case-when.patchDownload+84-22
#2pgsql-hackers
pgsql-hackers@alibaba-inc.com
In reply to: Tender Wang (#1)
Re: Unsafe qual pushdown through DISTINCT with simple CASE expressions

On Tue, Aug 18, 2026 at 8:54 AM Tender Wang <tndrwang@gmail.com> wrote:
The attached patch fixes this by checking the CASE argument against
the equality operator and input collation of each WHEN comparison
using the existing grouping_check_operand() logic.

I confirmed that this is a real wrong-result issue, and this approach
looks correct to me.

One small issue with the patch:
+               Assert(IsA(cw->expr, OpExpr));
+               opexpr = (OpExpr *) cw->expr;

cw->expr is not guaranteed to be an OpExpr. transformCaseExpr() calls
coerce_to_boolean() after constructing the "=" expression. With a
user-defined "=" operator returning a non-boolean type and an assignment
cast from that type to boolean, cw->expr becomes a FuncExpr wrapping the
OpExpr.

Therefore, the assertion can fail in an assert build, while the cast is
unsafe in a non-assert build. I think the non-OpExpr case should be
handled conservatively as a grouping conflict.

Best Regards,
Yuhang Qiu

#3Richard Guo
guofenglinux@gmail.com
In reply to: Tender Wang (#1)
Re: Unsafe qual pushdown through DISTINCT with simple CASE expressions

On Tue, Aug 18, 2026 at 9:54 AM Tender Wang <tndrwang@gmail.com> wrote:

On master, the qual is pushed below the DISTINCT:

```text
Unique
-> Sort
Sort Key: cit.t
-> Seq Scan on cit
Filter: (CASE (t)::text WHEN 'A'::text THEN 1 ELSE 0 END = 1)
```

This is suspicious because DISTINCT compares `t` using citext
equality, under which `'a'` and `'A'` are equal, while the CASE
expression casts `t` to text and therefore distinguishes them.

Thanks for the report. I looked into it and I think the root cause is
that grouping_conflict_walker() treats the arg of a simple CASE as an
operand of each WHEN comparison, but only applied the collation half
of the direct-operand check, on the assumption that the WHEN operator
is always the type-default "=" and thus matches the grouping eqop.
That is not true once the arg is relabeled. In your case with "CASE
t::text WHEN 'A'", the WHEN compares with texteq while the grouping
uses citext_eq, so the qual should be rejected just as "t::text = 'A'"
already is.

I reviewed your patch. IIUC, it fixes this by adding an
equality_ops_are_compatible() check per WHEN inside the CaseExpr
branch. That works for the reported query, but I'd rather not go that
way, for a few reasons.

It duplicates the operand check that grouping_check_operand already
implements, so the two would have to be kept in sync.

It assumes each WHEN condition is a bare OpExpr (the Assert), which
the parser does not guarantee. It also skips the
op_is_safe_index_member() gate, which is what makes the opfamily test
meaningful for the direct-operand form.

More generally, the problem is that the CaseExpr branch re-implements
how a direct operand is checked, and does so incompletely.

I think it'd be better to avoid this duplication. So I'd like to take
the approach used elsewhere in planner for the same placeholder: while
walking the WHEN conditions, the walker binds a Var arg in the context
and resolves each CaseTestExpr to it. The Var is then checked as each
WHEN uses it. This is how eval_const_expressions() handles the
CaseTestExpr nodes.

Attached is the patch doing that.

- Richard

Attachments:

t253458_3
v2-0001-Fix-qual-pushdown-past-grouping-through-simple-CA.patchapplication/octet-stream; name=v2-0001-Fix-qual-pushdown-past-grouping-through-simple-CA.patchDownload+107-41
#4Tender Wang
tndrwang@gmail.com
In reply to: Richard Guo (#3)
Re: Unsafe qual pushdown through DISTINCT with simple CASE expressions

Richard Guo <guofenglinux@gmail.com> 于2026年8月28日周五 10:20写道:

I think it'd be better to avoid this duplication. So I'd like to take
the approach used elsewhere in planner for the same placeholder: while
walking the WHEN conditions, the walker binds a Var arg in the context
and resolves each CaseTestExpr to it. The Var is then checked as each
WHEN uses it. This is how eval_const_expressions() handles the
CaseTestExpr nodes.

Attached is the patch doing that.

I took a look at the existing handling of CaseTestExpr in the planner,
and it works as you described.

I noticed that you added special handling for ArrayCoerceExpr in
grouping_conflict_walker(), but the current regression tests don't
exercise this new branch.
I think it would be better to add a test case to cover it.

For example:

CREATE TEMP TABLE case_array_test (a int[]);

EXPLAIN (COSTS OFF)
SELECT *
FROM (SELECT DISTINCT a FROM case_array_test) s
WHERE CASE a::bigint[]
WHEN ARRAY[1::bigint] THEN true
ELSE false
END;

The rest looks good to me.

--
Thanks,
Tender Wang

#5Ewan Young
kdbase.hack@gmail.com
In reply to: Richard Guo (#3)
Re: Unsafe qual pushdown through DISTINCT with simple CASE expressions

Thanks a lot for v2 -- this is a really nice cleanup. Resolving the
CaseTestExpr through case_var and reusing grouping_check_operand() is much
tidier than the special-cased v1, it correctly handles the relabel/opfamily
mismatch that started the thread, and it addresses Yuhang's concern about
the WHEN condition not always being a bare OpExpr. Overall this looks good
to me.

On correctness I'm happy: I built it --with-icu and poked at the unsafe
directions -- the original citext relabel case, and a WHEN with an explicit
differing COLLATE -- and v2 keeps both above the grouping as it should.
CaseTestExpr is a leaf, and for the CASE path v2 checks strictly more than
before (it adds the opfamily check), so I don't think it can miss a conflict
the old code caught. No wrong-results case turned up. +1 from me on the
approach.

One minor thing I noticed while testing (a missed pushdown, not a
correctness problem): v2 can resolve CaseTestExprs that don't actually
belong to the CASE arg, and over a nondeterministic collation that shows up
as a spurious refusal to push a safe qual. For example:

CREATE COLLATION ci (provider=icu, locale='und-u-ks-level2',
deterministic=false);
CREATE TABLE cit (t text COLLATE ci);
INSERT INTO cit VALUES ('a'),('A'),('b');

-- pushed on master, but v2 keeps the Filter above the grouping
EXPLAIN (COSTS OFF)
SELECT * FROM (SELECT DISTINCT t FROM cit) d
WHERE (CASE t WHEN JSON_OBJECT('a': 'b' RETURNING text)
THEN 1 ELSE 0 END) = 1;

The WHEN value is a constant that doesn't reference t, so this is safe to
push; the plain-constant version, JSON_OBJECT(...)::text (instead of
RETURNING text), and the same query over a deterministic collation are all
still pushed on the v2 build, so it's specifically the stray CaseTestExpr
that blocks it. The culprit is that JSON_OBJECT(... RETURNING text) carries
its own CaseTestExpr for the RETURNING coercion (makeJsonConstructorExpr()),
standing for the constructor output rather than the CASE arg; walked as a
non-operand with case_var bound, it gets resolved to the (nondeterministic)
grouping column and reported as a conflict. It's the same shape you already
shield for the ArrayCoerceExpr elemexpr -- JSON constructors are just another
producer that isn't (parse_jsontable.c / parse_target.c emit some too).

Thanks again -- nice work on this.

On Fri, Aug 28, 2026 at 10:20 AM Richard Guo <guofenglinux@gmail.com> wrote:

On Tue, Aug 18, 2026 at 9:54 AM Tender Wang <tndrwang@gmail.com> wrote:

On master, the qual is pushed below the DISTINCT:

```text
Unique
-> Sort
Sort Key: cit.t
-> Seq Scan on cit
Filter: (CASE (t)::text WHEN 'A'::text THEN 1 ELSE 0 END = 1)
```

This is suspicious because DISTINCT compares `t` using citext
equality, under which `'a'` and `'A'` are equal, while the CASE
expression casts `t` to text and therefore distinguishes them.

Thanks for the report. I looked into it and I think the root cause is
that grouping_conflict_walker() treats the arg of a simple CASE as an
operand of each WHEN comparison, but only applied the collation half
of the direct-operand check, on the assumption that the WHEN operator
is always the type-default "=" and thus matches the grouping eqop.
That is not true once the arg is relabeled. In your case with "CASE
t::text WHEN 'A'", the WHEN compares with texteq while the grouping
uses citext_eq, so the qual should be rejected just as "t::text = 'A'"
already is.

I reviewed your patch. IIUC, it fixes this by adding an
equality_ops_are_compatible() check per WHEN inside the CaseExpr
branch. That works for the reported query, but I'd rather not go that
way, for a few reasons.

It duplicates the operand check that grouping_check_operand already
implements, so the two would have to be kept in sync.

It assumes each WHEN condition is a bare OpExpr (the Assert), which
the parser does not guarantee. It also skips the
op_is_safe_index_member() gate, which is what makes the opfamily test
meaningful for the direct-operand form.

More generally, the problem is that the CaseExpr branch re-implements
how a direct operand is checked, and does so incompletely.

I think it'd be better to avoid this duplication. So I'd like to take
the approach used elsewhere in planner for the same placeholder: while
walking the WHEN conditions, the walker binds a Var arg in the context
and resolves each CaseTestExpr to it. The Var is then checked as each
WHEN uses it. This is how eval_const_expressions() handles the
CaseTestExpr nodes.

Attached is the patch doing that.

- Richard

--
Regards,
Ewan Young

#6Richard Guo
guofenglinux@gmail.com
In reply to: Ewan Young (#5)
Re: Unsafe qual pushdown through DISTINCT with simple CASE expressions

On Fri, Aug 28, 2026 at 4:15 PM Ewan Young <kdbase.hack@gmail.com> wrote:

CREATE COLLATION ci (provider=icu, locale='und-u-ks-level2',
deterministic=false);
CREATE TABLE cit (t text COLLATE ci);
INSERT INTO cit VALUES ('a'),('A'),('b');

-- pushed on master, but v2 keeps the Filter above the grouping
EXPLAIN (COSTS OFF)
SELECT * FROM (SELECT DISTINCT t FROM cit) d
WHERE (CASE t WHEN JSON_OBJECT('a': 'b' RETURNING text)
THEN 1 ELSE 0 END) = 1;

Nice catch. I did not realize CaseTestExpr can be used in a JSON
constructor's coercion expression. I've fixed that and then pushed
the patch.

(Interestingly, eval_const_expressions also mishandles CaseTestExpr in
a JSON constructor's coercion expression, and thus has the same bug.
See [1]/messages/by-id/CAMbWs48A=VCFbteTkuCoknO1_0-Cu0aMBT0M07dm7vj1QyixDg@mail.gmail.com.)

[1]: /messages/by-id/CAMbWs48A=VCFbteTkuCoknO1_0-Cu0aMBT0M07dm7vj1QyixDg@mail.gmail.com

- Richard