[PATCH] Fix grouping-set nulling of variable-free grouping expressions
Hi Hackers,
I found a wrong-result issue with grouping sets when a grouping
expression is reduced to a constant during planning.
For example:
CREATE TABLE t (a int NOT NULL);
INSERT INTO t VALUES (1);
SELECT CASE WHEN a IS NOT NULL THEN 'yes' ELSE 'no' END,
GROUPING(a IS NOT NULL), count(*)
FROM t
GROUP BY ROLLUP (a IS NOT NULL)
ORDER BY 2;
PostgreSQL 18 returns:
yes | 0 | 1
no | 1 | 1
PostgreSQL 19 instead returns:
yes | 0 | 1
yes | 1 | 1
The grand-total row should contain 'no', since the grouping expression
is NULL in that grouping set.
This regression was exposed by commit e2debb64380, which allows
"a IS NOT NULL" to be folded to true based on the column's NOT NULL
constraint. The folding itself is valid for the grouping input.
The underlying issue predates this change. For example:
SELECT (1 + 1) * 10
FROM generate_series(1, 10)
GROUP BY ROLLUP (1 + 1);
PostgreSQL 18 already returns 20 for the grand-total row, where the
result should be NULL.
The problem is that flatten_group_exprs() substitutes the preprocessed
grouping expression for an RTE_GROUP reference. For variable-free
expressions, mark_nullable_by_grouping() wraps the expression in a
PlaceHolderVar, but creates a new PHV ID for each reference to the
same grouping output.
Consequently, setrefs may fail to match an upper reference to the
actual grouping column. The expression is then evaluated separately,
bypassing the NULL inserted for the corresponding grouping set.
The attached patch caches one PHV ID per RTE_GROUP attribute in
PlannerInfo, so references to the same grouping output share an ID.
Different grouping attributes retain distinct IDs, even when their
expressions are folded to the same constant.
This fixes both the PostgreSQL 19 regression and the pre-existing
variable-free grouping-expression issue, without restricting constant
folding or changing the aggregate executor.
The patch has been tested on master and REL_19_STABLE with assertions
enabled. Core regression, isolation, and relevant TAP tests pass.
Regression tests cover ROLLUP, CUBE, GROUPING SETS, HAVING, LATERAL,
and distinct grouping expressions folded to identical constants.
Given the wrong-result regression in PostgreSQL 19, I'd appreciate
review of whether this fix is appropriate for REL_19_STABLE.
The underlying issue also affects PostgreSQL 18. Backpatching there
would require some branch-specific adaptation and testing.
Comments and review are welcome.
Thanks,
Haibo
On Fri, Oct 9, 2026 at 11:10 PM Haibo Yan <tristan.yim@gmail.com> wrote:
Hi Hackers,
I found a wrong-result issue with grouping sets when a grouping
expression is reduced to a constant during planning.For example:
CREATE TABLE t (a int NOT NULL);
INSERT INTO t VALUES (1);SELECT CASE WHEN a IS NOT NULL THEN 'yes' ELSE 'no' END,
GROUPING(a IS NOT NULL), count(*)
FROM t
GROUP BY ROLLUP (a IS NOT NULL)
ORDER BY 2;PostgreSQL 18 returns:
yes | 0 | 1
no | 1 | 1PostgreSQL 19 instead returns:
yes | 0 | 1
yes | 1 | 1The grand-total row should contain 'no', since the grouping expression
is NULL in that grouping set.This regression was exposed by commit e2debb64380, which allows
"a IS NOT NULL" to be folded to true based on the column's NOT NULL
constraint. The folding itself is valid for the grouping input.The underlying issue predates this change. For example:
SELECT (1 + 1) * 10
FROM generate_series(1, 10)
GROUP BY ROLLUP (1 + 1);PostgreSQL 18 already returns 20 for the grand-total row, where the
result should be NULL.The problem is that flatten_group_exprs() substitutes the preprocessed
grouping expression for an RTE_GROUP reference. For variable-free
expressions, mark_nullable_by_grouping() wraps the expression in a
PlaceHolderVar, but creates a new PHV ID for each reference to the
same grouping output.Consequently, setrefs may fail to match an upper reference to the
actual grouping column. The expression is then evaluated separately,
bypassing the NULL inserted for the corresponding grouping set.The attached patch caches one PHV ID per RTE_GROUP attribute in
PlannerInfo, so references to the same grouping output share an ID.
Different grouping attributes retain distinct IDs, even when their
expressions are folded to the same constant.This fixes both the PostgreSQL 19 regression and the pre-existing
variable-free grouping-expression issue, without restricting constant
folding or changing the aggregate executor.The patch has been tested on master and REL_19_STABLE with assertions
enabled. Core regression, isolation, and relevant TAP tests pass.
Regression tests cover ROLLUP, CUBE, GROUPING SETS, HAVING, LATERAL,
and distinct grouping expressions folded to identical constants.Given the wrong-result regression in PostgreSQL 19, I'd appreciate
review of whether this fix is appropriate for REL_19_STABLE.The underlying issue also affects PostgreSQL 18. Backpatching there
would require some branch-specific adaptation and testing.Comments and review are welcome.
Thanks,
Haibo
Hi,
Attached is v2, updated to current master.
There are no changes to the implementation or regression tests
from v1. The patch applies cleanly to both master and
REL_19_STABLE.
I also added the following contributor credit:
Reported-by: Shihao Zhong <zhong950419@gmail.com>
The patch has been independently tested on both branches with
assertions enabled. Core regression (239/239), isolation
(134/134), and the relevant postgres_fdw tests all pass.
Thanks,
Haibo
Attachments:
0002-Fix-preexisting-grouping-expression-bug.patchapplication/octet-stream; name=0002-Fix-preexisting-grouping-expression-bug.patchDownload+200-6
Hi Haibo,
I reviewed v1 and it looks correct to me.
Both of your queries give the right rows on master and 19, and the
new tests fail without the fix. I asked Claude to try about 80 more
queries, in HAVING, ORDER BY, window functions, sublinks and LATERAL.
All give the rows I expect.
The code applies to 18 too, only two hunks of expected output differ.
The file sent as v2 is not the same patch though. It does not apply
to master, its test hunks need a gs_users test that is not in the
tree. The code is different, the NOT NULL test is gone, and it has no
Reported-by line. Was it the wrong file?
The first query is right on 18 and wrong on 19, so I hope this can go
in before 19 is out.
Thanks,
Shihao
On Sun, Oct 11, 2026 at 7:11 PM shihao zhong <zhong950419@gmail.com> wrote:
Hi Haibo,
I reviewed v1 and it looks correct to me.
Both of your queries give the right rows on master and 19, and the
new tests fail without the fix. I asked Claude to try about 80 more
queries, in HAVING, ORDER BY, window functions, sublinks and LATERAL.
All give the rows I expect.The code applies to 18 too, only two hunks of expected output differ.
The file sent as v2 is not the same patch though. It does not apply
to master, its test hunks need a gs_users test that is not in the
tree. The code is different, the NOT NULL test is gone, and it has no
Reported-by line. Was it the wrong file?The first query is right on 18 and wrong on 19, so I hope this can go
in before 19 is out.Thanks,
Shihao
Hi Shihao,
Thanks for reviewing v1 and for the additional testing.
You're right. I accidentally attached an earlier experimental patch
instead of the correct v2. Sorry for the confusion.
Attached is the corrected v3. The implementation and regression tests
are identical to v1, with no functional changes. The patch applies
cleanly to current master and REL_19_STABLE.
I've also added the following trailer to the commit message:
Reported-by: Shihao Zhong <zhong950419@gmail.com>
Thanks,
Haibo
Hi Haibo,
Thanks for your v3. I think it breaks some thing that is right today.
On master with v3:
SELECT 1 AS one, 1 AS uno GROUP BY ROLLUP(one);
gives uno = NULL in the grand-total row. Master, 17 and 18 give 1.
The parser turns the second 1 into the group Var, and with the shared
phid it now gets nulled. Andrey Rachitskiy's patch for bug 19752 stops
that [1]/messages/by-id/CAB8bMiv2JLSxs1aYF42G4887y5LdY=1-E8FLj_wGmKFooqWocQ@mail.gmail.com Thanks, Shihao.
With his patch, v3 is supposed to be ok. So that created some dependency
on submission.
[1]: /messages/by-id/CAB8bMiv2JLSxs1aYF42G4887y5LdY=1-E8FLj_wGmKFooqWocQ@mail.gmail.com Thanks, Shihao
/messages/by-id/CAB8bMiv2JLSxs1aYF42G4887y5LdY=1-E8FLj_wGmKFooqWocQ@mail.gmail.com
Thanks,
Shihao
On Fri, Oct 16, 2026 at 8:23 PM shihao zhong <zhong950419@gmail.com> wrote:
Hi Haibo,
Thanks for your v3. I think it breaks some thing that is right today.
On master with v3:
SELECT 1 AS one, 1 AS uno GROUP BY ROLLUP(one);
gives uno = NULL in the grand-total row. Master, 17 and 18 give 1.
The parser turns the second 1 into the group Var, and with the shared
phid it now gets nulled. Andrey Rachitskiy's patch for bug 19752 stops
that [1].With his patch, v3 is supposed to be ok. So that created some dependency
on submission.[1] /messages/by-id/CAB8bMiv2JLSxs1aYF42G4887y5LdY=1-E8FLj_wGmKFooqWocQ@mail.gmail.com
Thanks,
Shihao
Hi hackers,
After Shihao's report about v3, I investigated the interaction
between grouping-expression matching in parse_agg.c and PHV identity
in the planner.
I agree that v3 is not safe as submitted. Sharing a PHV ID by
RTE_GROUP attribute is only correct if the parser has identified
genuine references to the same grouping output. Currently, equal()
can replace independently written expressions with the same group Var.
This seems closely related to Tom's suggestions in the discussion
of bug #19752:
/messages/by-id/2530849.1791487908@sss.pgh.pa.us
/messages/by-id/2533535.1791490239@sss.pgh.pa.us
I would like to confirm whether the following matching rules are
reasonable:
A target entry explicitly identified as a grouping item should
reference its own RTE_GROUP attribute, selected by ressortgroupref,
rather than the first structurally equal grouping item.
Other subexpressions should be matched structurally only against
grouping items containing a Var of the current query level.
Grouping items without such a Var would only be referenced through
their explicitly identified target entries.
The second rule would leave independent constants, stable expressions,
Params, and outer-only correlated expressions untouched, while still
allowing expressions involving current-level Vars to be recognized
as grouping references.
For example, consider:
CREATE TABLE t (a int NOT NULL);
INSERT INTO t VALUES (1);
SELECT DISTINCT a IS NOT NULL AS c1,
a IS NOT NULL AS c2
FROM t
GROUP BY CUBE(c1, c2)
ORDER BY 1 NULLS LAST, 2 NULLS LAST;
The two grouping outputs have different ressortgrouprefs, even
though their expressions are equal. They should remain distinct.
The query returns four rows on current master, but only two with v3.
There is also a query-level question:
SELECT s.c1, s.c2
FROM t,
LATERAL (
SELECT t.a + 1 AS c1,
ARRAY[t.a + 1] AS c2
FROM (VALUES (1)) v(x)
GROUP BY ROLLUP(c1)
) s
ORDER BY s.c1 NULLS LAST;
Current master retains {2} in c2 for the grand-total row. I think
this is appropriate because c2 is an independently written expression
depending only on the outer query. It should not become a reference
to the inner grouping output merely because a subtree is equal.
I have experimented with the two parser rules above together with
v3's PHV-sharing mechanism. The results are encouraging: the
original PG19 wrong result, the independent-expression cases, and
the CUBE example behave as expected. Core and isolation regression
tests pass on master and REL_19_STABLE.
Before preparing another patch revision, I'd appreciate opinions on
whether these two matching rules reflect the intended semantics,
particularly the level-zero-Var criterion.
The parser changes also overlap with Andrey's work on bug #19752,
so I would like to resolve the intended behavior before deciding how
best to separate or coordinate the fixes.
Tom, your suggestion in the bug #19752 discussion about restricting
structural matching to grouping items containing a level-zero Var seems
relevant here. Do you think that rule, together with matching explicitly
identified target entries by ressortgroupref, would be the right direction?
Thanks,
Haibo
Hi Haibo,
I agree with both rules. On your CUBE example, 17 and 18 also give 2 rows,
so master's 4 is right.
v3 alone has one more problem. SELECT 1 AS x GROUP BY ROLLUP(x) HAVING 1
IS NOT NULL returns 2 rows on master but 1 with v3. The parser turns the
1 in HAVING into a GROUP Var.
A question on (b). SELECT now() IS NULL AS n GROUP BY ROLLUP(now())
gives f and t on 17 and with v3, but f and f on 18 and master. (b)
should keep f and f, which seems fine to me.
Thanks,
Shihao
Hi Shihao,
Thanks for confirming, and for the additional examples.
The HAVING case is another good demonstration of why structural
matching should exclude grouping items without a level-zero Var.
The constant in HAVING is independent of the grouped target entry,
so it should not be replaced by a group Var.
I also agree that the now() example should retain the PG18/master
behavior (f, f). The independently written now() expression does
not reference the grouping output merely because it is structurally
equal.
I've tested a prototype combining the two parser rules with v3's
PHV-sharing change, with encouraging results so far. I'll verify
these two examples explicitly and add them to the regression tests
before posting a revision.
I'd still like to hear Tom's thoughts on the level-zero-Var rule,
since that determines the intended semantics of these cases.
Thanks,
Haibo
Show quoted text
On Tue, Oct 20, 2026 at 5:48 PM shihao zhong <zhong950419@gmail.com> wrote:
Hi Haibo,
I agree with both rules. On your CUBE example, 17 and 18 also give 2 rows,
so master's 4 is right.v3 alone has one more problem. SELECT 1 AS x GROUP BY ROLLUP(x) HAVING 1
IS NOT NULL returns 2 rows on master but 1 with v3. The parser turns the
1 in HAVING into a GROUP Var.A question on (b). SELECT now() IS NULL AS n GROUP BY ROLLUP(now())
gives f and t on 17 and with v3, but f and f on 18 and master. (b)
should keep f and f, which seems fine to me.Thanks,
Shihao