Re: BUG #19055: Server crash at ExecInterpExpr

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: dllggyx(at)outlook(dot)com
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #19055: Server crash at ExecInterpExpr
Date: 2025-09-17 18:02:09
Message-ID: 1652186.1758132129@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

PG Bug reporting form <noreply(at)postgresql(dot)org> writes:
> PoC:
> SELECT FROM ( SELECT generate_series ( 1 , '31' ) x ) GROUP BY ( x ) WINDOW
> w AS ( ORDER BY ( WITH x AS ( WITH x AS ( SELECT sum ( x ) ) SELECT DISTINCT
> * FROM x ) ( SELECT ( count ( ( SELECT x FROM x ) ) ) ) ) )

Interesting example. De-obfuscating a little bit, we have

SELECT 1 FROM ( SELECT generate_series ( 1 , '31' ) gs ) ss
GROUP BY ( gs )
WINDOW w AS ( ORDER BY (
WITH x1 AS -- MATERIALIZED
( WITH x2 AS ( SELECT sum ( gs ) )
SELECT DISTINCT * FROM x2 )
SELECT ( count ( ( SELECT gs FROM x1 ) ) )
) );

If you stick in MATERIALIZED where I show, then instead of an
executor assertion failure you get
ERROR: could not find CTE "x1"
which is also what happens in branches pre-dating default inlining
of CTEs.

The problem appears to be that the count() aggregate is assigned the
wrong agglevelsup: it's labeled with agglevelsup = 1, implying that
it belongs to the outer query level (which is where its "gs" input
comes from). Then when we try to pull it up to the outer level,
the contained reference to the x1 CTE becomes dangling --- the planner
can't find any x1 in that level. Or, if we don't say MATERIALIZED,
the planner tries to inline x1 and just botches things entirely.
I suspect it's getting confused about which level "sum(gs)"
belongs to, but I didn't bother running down the details.

In any case, this is the parser's fault. Because the count()
references x1, it should not be given an agglevelsup higher than
where x1 is. The attached seems to fix it. I need to think
of a test case with less extraneous crud, though...

Thanks for the report!

regards, tom lane

Attachment Content-Type Size
fix-agglevelsup-calculation-with-CTEs.patch text/x-diff 1.5 KB

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message David Rowley 2025-09-17 21:43:19 Re: BUG #19056: ExecInitPartitionExecPruning segfault due to NULL es_part_prune_infos
Previous Message Vik Fearing 2025-09-17 17:57:14 Re: BUG #19055: Server crash at ExecInterpExpr