[PG19] Wrong results from NOT NULL-based expression simplification
Hi hackers,
I used Opus to analyze the new features in PG19, and it found five
queries that work on 18 and break on 19 and master. Each item has a
script and a patch with its number.
I manually verified these issues and
1. coalesce(b, '') on a NOT NULL column is simplified to plain b, in
the index and in ON CONFLICT. Only the ON CONFLICT side counts it as a
plain column, so they do not match.
create table oc (b text not null);
create unique index on oc (coalesce(b, ''));
insert into oc values ('x') on conflict (coalesce(b, '')) do nothing;
18 inserts the row. 19 gives "there is no unique or exclusion
constraint matching the ON CONFLICT specification". 0001 counts the
index expression as a plain column too.
2. With a join as the MERGE source, only Vars of the join RTE are
marked nullable for NOT MATCHED BY SOURCE, not Vars of the tables
under it.
create table mt (id int);
create table sa (id int not null);
create table sb (id int);
insert into mt values (1);
merge into mt using (sa join sb on sa.id = sb.id) on mt.id = sa.id
when not matched by source then delete
returning sa.id is null;
18 returns t, 19 returns f. 0002 marks them all.
The marking comes from 259a0a99fe3, the fix for bug #18634, which is
also in 17 and 18. It covers a source that is one table, but not a
join. On 18 that does not give wrong values, but planning can fail
with "wrong varnullingrels", the error from that bug. So I think 0002
should be back-patched to 17.
create view mv as select * from mt where exists (select 1 from mt);
merge into mv using (sa join sb on sa.id = sb.id) on mv.id = sa.id
when not matched by source then delete
returning sa.id is null;
wrong varnullingrels (b) (expected (b 6)) for Var 2/1
3. COALESCE on a NOT NULL column is replaced by the column, which can
have another collation.
create collation ci (provider = icu, locale = 'und-u-ks-level2',
deterministic = false);
create table co (t text not null, u text);
insert into co values ('a'), ('A');
select count(*) from
(select coalesce(t, u collate ci) from co group by 1) s;
18 returns 1, 19 returns 2. 0003 adds a RelabelType.
4. NOT IN becomes an anti join when the sub-select's output is NOT
NULL. For a virtual generated column the check runs before the column
is expanded, and a partition can have another expression.
create table p (a int,
v int generated always as (nullif(a, 0)) virtual not null)
partition by list (a);
create table p1 partition of p
(v generated always as (a + 1) virtual) for values in (0);
insert into p values (0);
create table o (id int not null);
insert into o values (1);
select * from o where id not in (select v from p);
18 returns no rows, 19 returns one. 0004 does not trust NOT NULL
there.
5. Two grouping expressions can be simplified to the same Var, and
expressions above the grouping step cannot tell them apart.
create table g (a int not null);
insert into g values (1);
select a, coalesce(a, 0) as ca, coalesce(a, 0) is null as ca_is_null
from g group by grouping sets ((a), (coalesce(a, 0))) order by 1;
ca_is_null is t, f on 18 and f, t on 19. 18 does the same with CASE
WHEN true THEN a END. 0005 wraps the duplicate in a PlaceHolderVar.
Each patch has a test. All five work on 18, so I think they are open
items.
I am less sure about 0005. It is more like a workaround for now. The
grouping nullingrel goes on the Vars inside an expression, not on the
expression, so two equal expressions look the same. Maybe that is
what should change.
I did not try other ways, but I see three. One is to wrap every
grouping expression, so that the mark is on the expression itself.
That looks more correct, but it touches every grouping sets query.
Another is to keep the references to grouping columns as Vars until
setrefs.c, so they are not matched by equal(). That is a bigger
change. The smallest is to stop using NOT NULL to simplify grouping
expressions when there are grouping sets. But then the CASE example
stays wrong.
Thanks,
Shihao
Attachments:
t254078_1v1-0001-Fix-ON-CONFLICT-inference-for-simplified-index-ex.patchapplication/octet-stream; name=v1-0001-Fix-ON-CONFLICT-inference-for-simplified-index-ex.patchDownload+82-20
v1-0003-Keep-typmod-and-collation-when-simplifying-COALES.patchapplication/octet-stream; name=v1-0003-Keep-typmod-and-collation-when-simplifying-COALES.patchDownload+49-5
v1-0004-Don-t-trust-NOT-NULL-on-virtual-generated-columns.patchapplication/octet-stream; name=v1-0004-Don-t-trust-NOT-NULL-on-virtual-generated-columns.patchDownload+34-1
v1-0002-Mark-all-source-rels-nullable-for-MERGE-NOT-MATCH.patchapplication/octet-stream; name=v1-0002-Mark-all-source-rels-nullable-for-MERGE-NOT-MATCH.patchDownload+28-5
v1-0005-Keep-duplicate-grouping-expressions-apart-with-gr.patchapplication/octet-stream; name=v1-0005-Keep-duplicate-grouping-expressions-apart-with-gr.patchDownload+226-1
On Mon, Oct 5, 2026 at 11:28 PM shihao zhong <zhong950419@gmail.com> wrote:
I used Opus to analyze the new features in PG19, and it found five
queries that work on 18 and break on 19 and master. Each item has a
script and a patch with its number.
Seems like there are a number of issues in this thread but so far I
see only one open item for the whole thing. Should there be more than
one open item?
- Melanie
Hi Melanie,
Yes, I agree this should be 5 open items. I don't have wiki edit access yet
and
I'm applying for it now.
Could you or someone else add it for now?
I will take over once I have access.
Thanks,
Shihao
On Tue, Oct 6, 2026 at 11:28 AM shihao zhong <zhong950419@gmail.com> wrote:
Hi hackers,
I used Opus to analyze the new features in PG19, and it found five
queries that work on 18 and break on 19 and master. Each item has a
script and a patch with its number.I manually verified these issues and
1. coalesce(b, '') on a NOT NULL column is simplified to plain b, in
the index and in ON CONFLICT. Only the ON CONFLICT side counts it as a
plain column, so they do not match.
create table oc (b text not null);
create unique index on oc (coalesce(b, ''));
insert into oc values ('x') on conflict (coalesce(b, '')) do nothing;
18 inserts the row. 19 gives "there is no unique or exclusion
constraint matching the ON CONFLICT specification". 0001 counts the
index expression as a plain column too.
/*
* Now that all inference elements were matched, ensure that the
* expression elements from inference clause are not missing any
* cataloged expressions. This does the right thing when unique
* indexes redundantly repeat the same attribute, or if attributes
* redundantly appear multiple times within an inference clause.
*/
if (list_difference(idxOtherExprs, inferElems) != NIL)
continue;
The above comments also need to change?
While at it, we can replace 0 with InvalidAttrNumber, as shown in the
attachment.
Other than that, V1 looks good to me.
Attachments:
minor_change_on_conflict.txttext/plain; charset=US-ASCII; name=minor_change_on_conflict.txtDownload+3-3
On Thu, Oct 8, 2026 at 12:41 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
On Mon, Oct 5, 2026 at 11:28 PM shihao zhong <zhong950419@gmail.com> wrote:
I used Opus to analyze the new features in PG19, and it found five
queries that work on 18 and break on 19 and master. Each item has a
script and a patch with its number.
Seems like there are a number of issues in this thread but so far I
see only one open item for the whole thing. Should there be more than
one open item?
I've pushed fixes for #1, #3 and #4, after makeing cosmetic tweaks.
Regarding #1, nothing more to add.
Regarding #2, this is a bug in v17 and later, not a v19 regression, so
I don't think it should be a v19 open item. And it's in the MERGE
code, so I think Dean is the right person to look at it, not me.
Regarding #3, it is not limited to COALESCE. CASE and NULLIF have the
same problem when they are reduced to one of their inputs, and those
date back to older branches. Even for COALESCE, the first commit that
has this problem is 931766aae, not the NOT NULL-based simplification.
The fix covers all three, but I only back-patched it to v19, since
there are no field reports and it changes the typmod exposed by a
reduced CASE expression.
Regarding #4, the fix is to not trust NOT NULL on a virtual generated
column of a partitioned table. But I don't like this fix at all. I
think the real problem is that a partition is allowed to have a
different virtual generation expression than its parent. The
constraint is enforced with the partition's expression, while a query
on the parent computes the column with the parent's expression. So
even on v18, a NOT NULL column can read as NULL through the parent,
and the same goes for CHECK constraints. That seems fragile to me,
and I suspect it will bite us again. CC'ing Peter here.
Regarding #5, it is not specific to v19 either. You get the same
wrong result with CASE WHEN true THEN a END in place of COALESCE(a, 0),
which has nothing to do with the new simplification. So I don't think
it should be a v19 open item.
- Richard
On Fri, Oct 9, 2026 at 5:53 PM Richard Guo <guofenglinux@gmail.com> wrote:
On Thu, Oct 8, 2026 at 12:41 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:On Mon, Oct 5, 2026 at 11:28 PM shihao zhong <zhong950419@gmail.com> wrote:
I used Opus to analyze the new features in PG19, and it found five
queries that work on 18 and break on 19 and master. Each item has a
script and a patch with its number.Seems like there are a number of issues in this thread but so far I
see only one open item for the whole thing. Should there be more than
one open item?I've pushed fixes for #1, #3 and #4, after makeing cosmetic tweaks.
Regarding #1, nothing more to add.
Regarding #2, this is a bug in v17 and later, not a v19 regression, so
I don't think it should be a v19 open item. And it's in the MERGE
code, so I think Dean is the right person to look at it, not me.Regarding #3, it is not limited to COALESCE. CASE and NULLIF have the
same problem when they are reduced to one of their inputs, and those
date back to older branches. Even for COALESCE, the first commit that
has this problem is 931766aae, not the NOT NULL-based simplification.
The fix covers all three, but I only back-patched it to v19, since
there are no field reports and it changes the typmod exposed by a
reduced CASE expression.Regarding #4, the fix is to not trust NOT NULL on a virtual generated
column of a partitioned table. But I don't like this fix at all. I
think the real problem is that a partition is allowed to have a
different virtual generation expression than its parent. The
constraint is enforced with the partition's expression, while a query
on the parent computes the column with the parent's expression. So
even on v18, a NOT NULL column can read as NULL through the parent,
and the same goes for CHECK constraints. That seems fragile to me,
and I suspect it will bite us again. CC'ing Peter here.Regarding #5, it is not specific to v19 either. You get the same
wrong result with CASE WHEN true THEN a END in place of COALESCE(a, 0),
which has nothing to do with the new simplification. So I don't think
it should be a v19 open item.- Richard
Hi Shihao, Richard,
Thanks, Shihao, for bringing the grouping-set issue to my attention.
I investigated a related problem and posted a separate patch in [1]/messages/by-id/CABXr29FSih8YtLCEe6Swquu_c=YvFiLVoH-ejvk2jVge9EMEMQ@mail.gmail.com.
I also tested it against Shihao's 0005 patch.
The two patches address different identity problems.
My patch fixes the case where multiple references to the same
variable-free grouping expression receive different PHV IDs.
It reuses one PHV ID per RTE_GROUP attribute.
Patch 0005 addresses a different case, where distinct grouping
expressions simplify to the same expression containing Vars, causing
their references to become indistinguishable.
Neither patch fixes the other's reproducer. Both can be applied
together without conflicts in the C code.
However, I found a potential wrong-result regression in 0005
involving volatile expressions:
CREATE TABLE t (id int PRIMARY KEY, a int NOT NULL);
CREATE TABLE s (x int);
INSERT INTO t VALUES (1, 1), (2, 2), (3, 3);
INSERT INTO s VALUES (10), (20);
SELECT count(*)
FROM (
SELECT 1
FROM t JOIN s ON true
GROUP BY GROUPING SETS (
(t.a + random()),
(coalesce(t.a, 0) + random())
)
) ss;
Without 0005, this returned 12 rows, as expected.
With 0005, it returned 9.
The PHV introduced by 0005 appears to cause the volatile expression
to be evaluated at the scan of t rather than once per joined row.
Its value is then reused across multiple join output rows.
I also found that 0005 does not resolve some duplicate grouping
expressions involving argument-free SRFs.
These seem worth investigating separately. I suggest keeping
the two fixes independent for now.
[1]: /messages/by-id/CABXr29FSih8YtLCEe6Swquu_c=YvFiLVoH-ejvk2jVge9EMEMQ@mail.gmail.com
Thanks,
Haibo
On Sat, Oct 10, 2026 at 9:53 AM Richard Guo <guofenglinux@gmail.com> wrote:
The fix covers all three, but I only back-patched it to v19, since
there are no field reports and it changes the typmod exposed by a
reduced CASE expression.
Codex reported that commit d8ce0050a6c causes the following INSERT to fail,
and I confirmed it. Is this a bug?
---------------------------------
CREATE TABLE t (a varchar(20) NOT NULL, b varchar(20));
CREATE UNIQUE INDEX t_idx ON t ((COALESCE(NULL::varchar, a, b)));
INSERT INTO t VALUES ('x', 'y')
ON CONFLICT ((COALESCE(NULL::varchar, a, b))) DO NOTHING;
ERROR: there is no unique or exclusion constraint matching the ON
CONFLICT specification
---------------------------------
Regards,
--
Fujii Masao
On Sun, Oct 11, 2026 at 12:37 AM Fujii Masao <masao.fujii@gmail.com> wrote:
Codex reported that commit d8ce0050a6c causes the following INSERT to fail,
and I confirmed it. Is this a bug?
Thanks for the report. Yes, it is a bug.
A COALESCE's typmod is derived from its arguments, so dropping the
NULL constant changes it from -1 to that of varchar(20). The index
expression is simplified twice (in the relcache, then in
infer_arbiter_indexes), while the ON CONFLICT expression is simplified
once, so only the latter gets the RelabelType added by d8ce0050a, and
the two no longer match.
The attached patch preserves the typmod for a partially reduced
COALESCE or CASE as well.
While at it, I noticed that an all-null COALESCE is reduced to a null
constant with typmod -1, which can cause the same failure. That code
dates back to 2005, but before v19 it only affects the typmod the
expression exposes. The patch fixes it too.
I plan to back-patch this to v19 only, after rc1.
- Richard
On Sun, Oct 11, 2026 at 9:36 AM Richard Guo <guofenglinux@gmail.com> wrote:
I plan to back-patch this to v19 only, after rc1.
Thanks for the patch!
Codex reported that the following INSERT, which previously succeeded, still
fails with this patch. I confirmed the issue. Should we fix this as well?
------------------------------------------
CREATE FUNCTION f(numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS 'SELECT $1';
CREATE TABLE t (a numeric(10) NOT NULL);
CREATE UNIQUE INDEX ON t (
NULLIF(f(a), CASE WHEN a IS NULL THEN a END)
);
INSERT INTO t VALUES (1)
ON CONFLICT (NULLIF(f(a), CASE WHEN a IS NULL THEN a END))
DO NOTHING;
------------------------------------------
Regards,
--
Fujii Masao
Hi,
Richard, thanks for committing my fix and drafting the quick fix
for the first case.
Regarding #2, this is a bug in v17 and later, not a v19 regression, so
I don't think it should be a v19 open item. And it's in the MERGE
code, so I think Dean is the right person to look at it, not me.
On #2, I agree the root cause is in 17. But the wrong result is new
in 19. The MERGE in my first mail returns t on 17 and 18, and f on
19. So I would like to keep it on the list.
Fujii, thanks for reviewing the fix.
Codex reported that the following INSERT, which previously succeeded,
still
fails with this patch. I confirmed the issue. Should we fix this as well?
I see this too. It works on 18 and on 62e46c00c65, and fails from
d8ce0050a on, with or without Richard's v1.
The NULLIF branch labels its result with the typmod the NULLIF had
before f(a) was inlined. The index expression was already inlined in
the relcache, so its NULLIF gets no label.
The attached patch goes on top of Richard's v1. It uses the typmod of
the simplified first argument.
Haibo, thanks for reviewing the 005.
Without 0005, this returned 12 rows, as expected.
With 0005, it returned 9.
I reproed that result too. But I agree with Richard
#5 is not a v19 item, I withdraw 0005 for now.
Let's finish the v19 open items first and have new thread to discuss that.
Thanks,
Shihao
Attachments:
nocfbot-0001-Use-the-simplified-argument-s-typmod-when-reducing-NULLIF.patchapplication/octet-stream; name=nocfbot-0001-Use-the-simplified-argument-s-typmod-when-reducing-NULLIF.patchDownload+34-3
On Sat, 10 Oct 2026, 01:52 Richard Guo, <guofenglinux@gmail.com> wrote:
Regarding #2, this is a bug in v17 and later, not a v19 regression, so
I don't think it should be a v19 open item. And it's in the MERGE
code, so I think Dean is the right person to look at it, not me.
I'm dealing with some life issues at the moment and I'll be mostly offline
this week. I'll try to get back to this next week.
Regards,
Dean
Show quoted text
On Sun, Oct 11, 2026 at 10:50 AM Fujii Masao <masao.fujii@gmail.com> wrote:
Codex reported that the following INSERT, which previously succeeded, still
fails with this patch. I confirmed the issue. Should we fix this as well?
Thanks for the report. This is the same problem, this time in NULLIF.
A NULLIF's typmod is that of its first argument, and inlining the SQL
function changes it from -1 to that of numeric(10). The index expr is
inlined in the first pass but reduced only in the second, so it gets
the new typmod, while the ON CONFLICT expression is inlined and
reduced in one pass and keeps -1.
v2-0001 extends v1 to relabel a rebuilt NULLIF to its original typmod
as well, and to use that typmod when a NULLIF is folded to a constant.
While testing, I found that relabeling a rebuilt COALESCE defeats
reconsider_full_join_clause(), which expects the merged column of a
FULL JOIN USING to be a bare COALESCE. So when the join inputs are
inlined SQL functions, a qual like "x = 1" on the merged column is no
longer pushed down to them. v2-0002 fixes that by looking through the
RelabelType there.
- Richard
Attachments:
t254078_12v2-0001-Preserve-typmod-when-reducing-CASE-COALESCE-and-N.patchapplication/octet-stream; name=v2-0001-Preserve-typmod-when-reducing-CASE-COALESCE-and-N.patchDownload+127-11
v2-0002-Look-through-RelabelType-when-matching-a-FULL-JOI.patchapplication/octet-stream; name=v2-0002-Look-through-RelabelType-when-matching-a-FULL-JOI.patchDownload+46-3
Hi,
On Fri, Oct 16, 2026 Richard Guo wrote:
v2-0001 extends v1 to relabel a rebuilt NULLIF to its original typmod
as well, [...] v2-0002 fixes that by looking through the RelabelType
there.
I ran a differential sweep of v2 on REL_19_STABLE against 18:
COALESCE/CASE/NULLIF shapes x 15 types (typmod, domain, array, ICU
nondeterministic) x inlining modes x ON CONFLICT sites, plus result
and FULL JOIN USING checks. v2 fixes every ON CONFLICT failure that
REL_19_STABLE has in that matrix and restores the FULL JOIN pushdown
that 0001 alone loses. No result differs from 18 except where 18 is
wrong.
One case still fails, on current REL_19_STABLE and with v2. Bisect
points at e2debb64380, "Reduce Var IS [NOT] NULL quals during constant
folding"; 18 accepts it:
CREATE FUNCTION f(varchar) RETURNS varchar
LANGUAGE sql IMMUTABLE AS 'SELECT $1';
CREATE TABLE t (a varchar(20) NOT NULL, b varchar(20));
CREATE UNIQUE INDEX ON t ((f((CASE WHEN a IS NULL THEN b END)::varchar(3))));
INSERT INTO t VALUES ('x', 'y')
ON CONFLICT ((f((CASE WHEN a IS NULL THEN b END)::varchar(3)))) DO NOTHING;
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
The NullTest fold added there runs only when eval_const_expressions()
has a PlannerInfo. RelationGetIndexExpressions() simplifies the index
expression with root = NULL, so the CASE is not reduced: f() is inlined
and the cast's typmod (3) stays visible, and infer_arbiter_indexes()
later folds it to a Const of typmod 3. The ON CONFLICT expression is
simplified once, with root, so its argument folds first and f() is
evaluated to a Const of typmod -1. equal() then sees typmod 3 vs -1.
A non-null constant and numeric fail the same way; a STABLE f() works,
since it is never pre-evaluated.
Comparing the two expressions in infer_arbiter_indexes() without
typmod-only decorations (a RelabelType that keeps type and collation,
and Const typmod) closes it, passes the regression tests, and changes
nothing else in the sweep; it sits on top of v2. I can post it if you
want it.
Regards,
Manu
Hi Richard,
With v2 this scans both partitions, on master only pc1.
CREATE FUNCTION pf(numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS 'SELECT $1';
CREATE TABLE pc (a numeric(10), b numeric(10))
PARTITION BY LIST ((COALESCE(pf(a), b)));
CREATE TABLE pc1 PARTITION OF pc FOR VALUES IN (1);
CREATE TABLE pc2 PARTITION OF pc FOR VALUES IN (2);
EXPLAIN (COSTS OFF) SELECT * FROM pc WHERE COALESCE(pf(a), b) = 1;
This is because the key is RelabelType, partprune.c shard it only from the
clause.
Thanks,
Shihao
Attachments:
nocfbot-0001-Shard-relabeling-from-the-partition-key-when-matching.patchapplication/octet-stream; name=nocfbot-0001-Shard-relabeling-from-the-partition-key-when-matching.patchDownload+33-0
On Tue, 6 Oct 2026 at 04:28, shihao zhong <zhong950419@gmail.com> wrote:
2. With a join as the MERGE source, only Vars of the join RTE are
marked nullable for NOT MATCHED BY SOURCE, not Vars of the tables
under it.
create table mt (id int);
create table sa (id int not null);
create table sb (id int);
insert into mt values (1);
merge into mt using (sa join sb on sa.id = sb.id) on mt.id = sa.id
when not matched by source then delete
returning sa.id is null;
18 returns t, 19 returns f. 0002 marks them all.The marking comes from 259a0a99fe3, the fix for bug #18634, which is
also in 17 and 18. It covers a source that is one table, but not a
join. On 18 that does not give wrong values, but planning can fail
with "wrong varnullingrels", the error from that bug. So I think 0002
should be back-patched to 17.
Thanks for the report. Your analysis and fix look correct.
I've pushed and back-patched the patch, with some cosmetic
adjustments, and I expanded the tests to cover both cases (wrong
results and "wrong varnullingrels" error).
Regards,
Dean