pgsql: Don't allow CTEs to determine semantic levels of aggregates.

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Don't allow CTEs to determine semantic levels of aggregates.
Date: 2025-11-18 17:57:16
Message-ID: E1vLPx5-000BIN-1w@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Don't allow CTEs to determine semantic levels of aggregates.

The fix for bug #19055 (commit b0cc0a71e) allowed CTE references in
sub-selects within aggregate functions to affect the semantic levels
assigned to such aggregates. It turns out this broke some related
cases, leading to assertion failures or strange planner errors such
as "unexpected outer reference in CTE query". After experimenting
with some alternative rules for assigning the semantic level in
such cases, we've come to the conclusion that changing the level
is more likely to break things than be helpful.

Therefore, this patch undoes what b0cc0a71e changed, and instead
installs logic to throw an error if there is any reference to a
CTE that's below the semantic level that standard SQL rules would
assign to the aggregate based on its contained Var and Aggref nodes.
(The SQL standard disallows sub-selects within aggregate functions,
so it can't reach the troublesome case and hence has no rule for
what to do.)

Perhaps someone will come along with a legitimate query that this
logic rejects, and if so probably the example will help us craft
a level-adjustment rule that works better than what b0cc0a71e did.
I'm not holding my breath for that though, because the previous
logic had been there for a very long time before bug #19055 without
complaints, and that bug report sure looks to have originated from
fuzzing not from real usage.

Like b0cc0a71e, back-patch to all supported branches, though
sadly that no longer includes v13.

Bug: #19106
Reported-by: Kamil Monicz <kamil(at)monicz(dot)dev>
Author: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Discussion: https://postgr.es/m/19106-9dd3668a0734cd72@postgresql.org
Backpatch-through: 14

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/35b5c62c3ad9a28ca145691219d889c638c82e37

Modified Files
--------------
src/backend/parser/parse_agg.c | 49 ++++++++++++++++++++++++--------
src/test/regress/expected/with.out | 58 ++++++++++++++++++++++----------------
src/test/regress/sql/with.sql | 22 +++++++++++----
3 files changed, 87 insertions(+), 42 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Álvaro Herrera 2025-11-18 18:31:54 pgsql: Fix typo
Previous Message Nathan Bossart 2025-11-18 16:32:42 pgsql: Add commit f63ae72bbc to .git-blame-ignore-revs.