pg.ddx.io pgsql-bugs@postgresql.org mailing list archive
help / color / mirror / Atom feedBUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry
4+ messages / 3 participants
[nested] [flat]
Commits from this thread:
2026-11-20 e22173e29b fba1717d5a 5844022a27 0e7dabc852 0f8e93fab9 d27418375d Fix SEARCH/CYCLE when the recursive term has resjunk columns.
* BUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry
@ 2026-11-19 03:27 PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 4+ messages in thread
From: PG Bug reporting form @ 2026-11-19 03:27 UTC (permalink / raw)
To: pgsql-bugs@lists.postgresql.org; +Cc: tharakan@gmail.com
The following bug has been logged on the website:
Bug reference: 19922
Logged by: Robins Tharakan
Email address: tharakan@gmail.com
PostgreSQL version: Unsupported/Unknown
Operating system: Unsupported/Unknown
Description:
A recursive query with a CYCLE or SEARCH clause fails when its
recursive term has a resjunk column, such as a window function's
ORDER BY column.
With CYCLE, builds without assertions, and assert-enabled builds
of 17 and older, raise
ERROR: XX000: could not find replacement targetlist entry for attno 2
LOCATION: ReplaceVarFromTargetList, rewriteManip.c:1903
and assert-enabled builds of 18 and later fail an assertion before
that:
TRAP: failed Assert("OidIsValid(eqop)"), File: "allpaths.c",
Line: 4602
With SEARCH in place of CYCLE, the same recursive term fails on every
branch, with or without assertions:
ERROR: 42804: attribute 2 of type record has wrong type
DETAIL: Table has type integer, but query expects record[].
LOCATION: CheckVarSlotCompatibility, execExprInterp.c:2429
Commit
======
Master: 8303f2e13c5 (2026-11-18) affected
Also affects: REL_14_STABLE through REL_19_STABLE
Built with --enable-cassert --enable-debug at -O0, and master also
without --enable-cassert at -O2 (gcc 14.2.0, glibc 2.41, Debian 13,
x86_64).
Error Log
========
master (8303f2e13c5), query 1:
TRAP: failed Assert("OidIsValid(eqop)"), File: "allpaths.c", Line: 4602,
PID: 1176274
LOG: client backend (PID 1176274) was terminated by signal 6: Aborted
master without assertions, and REL_17_STABLE (6c8717359a4), query 1:
ERROR: could not find replacement targetlist entry for attno 2
Backtrace
========
The assertion on master, query 1:
#0 ExceptionalCondition (conditionName="OidIsValid(eqop)", ...)
#1 pushdown_var_grouping_eqop (...) at allpaths.c:4602
#2 grouping_conflict_walker (...) at clauses.c:6576
#5 grouping_conflict_walker (...) at clauses.c:6710
#6 expression_has_grouping_conflict (...) at clauses.c:6533
#7 qual_is_pushdown_safe (...) at allpaths.c:4569
#8 set_subquery_pathlist (...) at allpaths.c:2774
#9 set_rel_size (...) at allpaths.c:472
#14 subquery_planner (...) at planner.c:1368
#15 recurse_set_operations (...) at prepunion.c:252
#16 generate_recursion_path (...) at prepunion.c:405
SQL
===
-- 1. CYCLE, with the window's ORDER BY column in the recursive term.
-- Builds without assertions, and 17 and older:
-- ERROR: could not find replacement targetlist entry for attno 2
-- Assert-enabled builds of 18 and later end the session at
-- TRAP: failed Assert("OidIsValid(eqop)"), File: "allpaths.c"
-- It should return (1, f, {(1)}) and (1, t, {(1),(1)}).
WITH RECURSIVE t(x) AS (
SELECT 1
UNION ALL
SELECT max(x) OVER (ORDER BY x) FROM t
) CYCLE x SET m USING p
SELECT * FROM t;
-- 2. The same recursive term with SEARCH, on every branch:
-- ERROR: attribute 2 of type record has wrong type
-- It should return what the term without the window does:
-- 1 | {(1)}
-- 2 | {(1),(2)}
-- 3 | {(1),(2),(3)}
WITH RECURSIVE t(x) AS (
SELECT 1
UNION ALL
SELECT max(x) OVER (ORDER BY x) + 1 FROM t WHERE x < 3
) SEARCH DEPTH FIRST BY x SET o
SELECT * FROM t;
-- 3. Both clauses, on every branch, with or without assertions:
-- ERROR: could not find replacement targetlist entry for attno 4
-- It should return one empty row.
WITH RECURSIVE a AS (
SELECT NULL b, NULL ~ NULL c
UNION
SELECT NULL, NULL ~ max(NULL) OVER (PARTITION BY 0 ORDER BY 1) FROM a
) SEARCH BREADTH FIRST BY b SET d CYCLE c SET e USING f,
g AS (SELECT FROM a)
SELECT;
All three queries fail on master and every supported branch
(and on 14.25). A release build of master (no --enable-cassert, -O2)
raises the XX000 and 42804 errors.
A recursive term with DISTINCT fails the same assertion on 18 and
later, for a different reason: a regression of 44fb59fc605. I'm
reporting that separately.
Found using SQLsmith, SQLReduce and Claude.
-
Robins Tharakan
Databricks
^ permalink raw reply [nested|flat] 4+ messages in thread
* Re: BUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry
@ 2026-11-19 21:47 Tom Lane <tgl@sss.pgh.pa.us>
parent: PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 4+ messages in thread
From: Tom Lane @ 2026-11-19 21:47 UTC (permalink / raw)
To: tharakan@gmail.com; +Cc: pgsql-bugs@lists.postgresql.org, Peter Eisentraut <peter@eisentraut.org>
PG Bug reporting form <noreply@postgresql.org> writes:
> A recursive query with a CYCLE or SEARCH clause fails when its
> recursive term has a resjunk column, such as a window function's
> ORDER BY column.
Yeah; you can make it fail with a resjunk GROUP BY term too, such as
WITH RECURSIVE t(x) AS (
SELECT 1
UNION ALL
SELECT x+1 FROM t WHERE x < 3 GROUP BY x
) SEARCH DEPTH FIRST BY x SET o
SELECT * FROM t;
ERROR: attribute 2 of type record has wrong type
DETAIL: Table has type integer, but query expects record[].
I think the problem is that rewriteSearchAndCycle() is appending extra
items to the right subquery's tlist without regard for the possibility
that there are resjunk items in it. This goes against our general
expectation that resjunk entries come last, and in particular it
breaks the correspondence between the subquery's column name lists and
their corresponding tlist entries. The names that are meant to refer
to the added extra items instead refer to resjunk entries, causing
all sorts of jolliness later.
There may be a similar problem with the left subquery too, not sure.
I think the way to fix this is to inject the added columns before any
resjunk columns (renumbering the latter). I've got a hard stop coming
up shortly, but can look at this tomorrow if no one beats me to it.
regards, tom lane
^ permalink raw reply [nested|flat] 4+ messages in thread
* Re: BUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry
@ 2026-11-20 10:52 Nitin Motiani <nitinmotiani@google.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 4+ messages in thread
From: Nitin Motiani @ 2026-11-20 10:52 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: tharakan@gmail.com, pgsql-bugs@lists.postgresql.org, Peter Eisentraut <peter@eisentraut.org>
Hi,
I looked into this following Tom's suggestion.
On Fri, Nov 20, 2026 at 3:17 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I think the problem is that rewriteSearchAndCycle() is appending extra
> items to the right subquery's tlist without regard for the possibility
> that there are resjunk items in it. This goes against our general
> expectation that resjunk entries come last, and in particular it
> breaks the correspondence between the subquery's column name lists and
> their corresponding tlist entries. The names that are meant to refer
> to the added extra items instead refer to resjunk entries, causing
> all sorts of jolliness later.
>
Thanks for the idea. I checked this and it indeed seemed to be the case.
I'm attaching a patch with the fix in this area. It detaches any resjunk
entries from the recursive term's tlist, adds the SEARCH/CYCLE columns,
then re-attaches the resjunk entries with new resnos, the same way
rewriteTargetListIU() handles junk entries.
> There may be a similar problem with the left subquery too, not sure.
>
I checked this using LLM and the left side seems fine.
rewriteSearchAndCycle() wraps the non-recursive term in a new subquery
without touching its tlist, and the outer query only references columns
1..n of it. Here is one example I tested that was working fine on master.
WITH RECURSIVE t(x) AS (
SELECT max(n) OVER (ORDER BY s) FROM (VALUES (1, 'a')) v(n, s)
UNION ALL
SELECT x+1 FROM t WHERE x < 3
) SEARCH DEPTH FIRST BY x SET o CYCLE x SET m USING p
SELECT * FROM t;
x | o | m | p
---+---------------+---+---------------
1 | {(1)} | f | {(1)}
2 | {(1),(2)} | f | {(1),(2)}
3 | {(1),(2),(3)} | f | {(1),(2),(3)}
Thanks & Regards,
Nitin Motiani
Google
Attachments:
v1-0001-Fix-SEARCH-CYCLE-when-the-recursive-term-has-resj.patch (application/x-patch, 6.5K) download
From e2232a89c7735f3fdffd8efff2355a4c68cec5dd Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Fri, 20 Nov 2026 06:32:40 +0000
Subject: [PATCH v1] Fix SEARCH/CYCLE when the recursive term has resjunk
columns.
rewriteSearchAndCycle() appended the extra SEARCH/CYCLE columns to
the end of the recursive term's targetlist. If that targetlist had
resjunk entries, for example a window function's ORDER BY column or a
GROUP BY column that is not selected, the new columns landed after
them. That breaks the expectation that resjunk entries come last, and
the column names given to the wrapping subquery then pointed at the
wrong entries. Depending on the query, this caused errors such as
"could not find replacement targetlist entry" or "attribute N of type
record has wrong type", an assertion failure in assert-enabled builds,
or silently wrong results.
Fix by detaching any resjunk entries before adding the new columns and
re-attaching them afterwards with renumbered resnos. Sort/group
clauses reference targetlist entries via ressortgroupref, not resno,
so renumbering them is safe.
The non-recursive term is not affected, since it is wrapped in a new
subquery without modifying its targetlist.
Reported-by: Robins Tharakan <tharakan@gmail.com>
Diagnosed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19922-a0d338245d361a4c@postgresql.org
Backpatch-through: 14
---
src/backend/rewrite/rewriteSearchCycle.c | 25 ++++++++++-
src/test/regress/expected/with.out | 55 ++++++++++++++++++++++++
src/test/regress/sql/with.sql | 32 ++++++++++++++
3 files changed, 111 insertions(+), 1 deletion(-)
diff --git a/src/backend/rewrite/rewriteSearchCycle.c b/src/backend/rewrite/rewriteSearchCycle.c
index 7594307281..fee56a9a4e 100644
--- a/src/backend/rewrite/rewriteSearchCycle.c
+++ b/src/backend/rewrite/rewriteSearchCycle.c
@@ -221,6 +221,8 @@ rewriteSearchAndCycle(CommonTableExpr *cte)
RowExpr *cycle_col_rowexpr = NULL;
RowExpr *search_col_rowexpr = NULL;
List *ewcl;
+ List *junk_tles;
+ ListCell *lc;
int cte_rtindex = -1;
Assert(cte->search_clause || cte->cycle_clause);
@@ -414,8 +416,21 @@ rewriteSearchAndCycle(CommonTableExpr *cte)
IncrementVarSublevelsUp((Node *) newsubquery, 1, 1);
/*
- * Add extra columns to target list of subquery of right subquery
+ * Add extra columns to target list of subquery of right subquery.
+ *
+ * The subquery's targetlist might contain resjunk entries, such as sort
+ * or grouping columns that are not part of its output. Those must stay
+ * after all the non-resjunk entries, and the column names we assigned to
+ * the wrapping subquery above assume that the added columns immediately
+ * follow the original output columns. So detach any resjunk entries
+ * before adding the new columns, and re-attach them afterwards with new
+ * resnos.
*/
+ junk_tles = list_copy_tail(newsubquery->targetList,
+ list_length(cte->ctecolnames));
+ newsubquery->targetList = list_truncate(newsubquery->targetList,
+ list_length(cte->ctecolnames));
+
if (cte->search_clause)
{
Var *var;
@@ -454,6 +469,14 @@ rewriteSearchAndCycle(CommonTableExpr *cte)
newsubquery->targetList = lappend(newsubquery->targetList, tle);
}
+ /* Re-attach the resjunk entries, if any, after the new columns */
+ foreach(lc, junk_tles)
+ {
+ tle = lfirst_node(TargetEntry, lc);
+ tle->resno = list_length(newsubquery->targetList) + 1;
+ newsubquery->targetList = lappend(newsubquery->targetList, tle);
+ }
+
newrte->subquery = newsubquery;
newrte->inFromCl = true;
newq2->rtable = list_make1(newrte);
diff --git a/src/test/regress/expected/with.out b/src/test/regress/expected/with.out
index addb24896b..2da1cd669a 100644
--- a/src/test/regress/expected/with.out
+++ b/src/test/regress/expected/with.out
@@ -1501,6 +1501,61 @@ select * from search_graph;
2 | 3 | arc 2 -> 3 | (4,2,3) | f | {"(1,4)","(4,5)","(5,1)","(1,2)","(2,3)"}
(25 rows)
+-- resjunk columns in the recursive term (from window functions or GROUP BY)
+with recursive t(x) as (
+ select 1
+ union all
+ select max(x) over (order by x) from t
+) cycle x set m using p
+select * from t;
+ x | m | p
+---+---+-----------
+ 1 | f | {(1)}
+ 1 | t | {(1),(1)}
+(2 rows)
+
+with recursive t(x) as (
+ select 1
+ union all
+ select max(x) over (order by x) + 1 from t where x < 3
+) search depth first by x set o
+select * from t;
+ x | o
+---+---------------
+ 1 | {(1)}
+ 2 | {(1),(2)}
+ 3 | {(1),(2),(3)}
+(3 rows)
+
+with recursive t(x) as (
+ select 1
+ union all
+ select x + 1 from t where x < 3 group by x
+) search breadth first by x set o
+ cycle x set m using p
+select * from t;
+ x | o | m | p
+---+-------+---+---------------
+ 1 | (0,1) | f | {(1)}
+ 2 | (1,2) | f | {(1),(2)}
+ 3 | (2,3) | f | {(1),(2),(3)}
+(3 rows)
+
+with recursive t(x) as (
+ select 1
+ union all
+ select (rank() over (partition by x % 2 order by x))::int + x
+ from t where x < 3
+) search depth first by x set o
+ cycle x set m using p
+select * from t;
+ x | o | m | p
+---+---------------+---+---------------
+ 1 | {(1)} | f | {(1)}
+ 2 | {(1),(2)} | f | {(1),(2)}
+ 3 | {(1),(2),(3)} | f | {(1),(2),(3)}
+(3 rows)
+
-- various syntax errors
with recursive search_graph(f, t, label) as (
select * from graph g
diff --git a/src/test/regress/sql/with.sql b/src/test/regress/sql/with.sql
index 0cb26312e2..d3c6860e14 100644
--- a/src/test/regress/sql/with.sql
+++ b/src/test/regress/sql/with.sql
@@ -715,6 +715,38 @@ with recursive search_graph(f, t, label) as (
cycle f, t set is_cycle using path
select * from search_graph;
+-- resjunk columns in the recursive term (from window functions or GROUP BY)
+with recursive t(x) as (
+ select 1
+ union all
+ select max(x) over (order by x) from t
+) cycle x set m using p
+select * from t;
+
+with recursive t(x) as (
+ select 1
+ union all
+ select max(x) over (order by x) + 1 from t where x < 3
+) search depth first by x set o
+select * from t;
+
+with recursive t(x) as (
+ select 1
+ union all
+ select x + 1 from t where x < 3 group by x
+) search breadth first by x set o
+ cycle x set m using p
+select * from t;
+
+with recursive t(x) as (
+ select 1
+ union all
+ select (rank() over (partition by x % 2 order by x))::int + x
+ from t where x < 3
+) search depth first by x set o
+ cycle x set m using p
+select * from t;
+
-- various syntax errors
with recursive search_graph(f, t, label) as (
select * from graph g
--
^ permalink raw reply [nested|flat] 4+ messages in thread
* Re: BUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry
@ 2026-11-20 16:57 Tom Lane <tgl@sss.pgh.pa.us>
parent: Nitin Motiani <nitinmotiani@google.com>
0 siblings, 0 replies; 4+ messages in thread
From: Tom Lane @ 2026-11-20 16:57 UTC (permalink / raw)
To: Nitin Motiani <nitinmotiani@google.com>; +Cc: tharakan@gmail.com, pgsql-bugs@lists.postgresql.org, Peter Eisentraut <peter@eisentraut.org>
Nitin Motiani <nitinmotiani@google.com> writes:
> On Fri, Nov 20, 2026 at 3:17 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> I think the problem is that rewriteSearchAndCycle() is appending extra
>> items to the right subquery's tlist without regard for the possibility
>> that there are resjunk items in it.
> Thanks for the idea. I checked this and it indeed seemed to be the case.
> I'm attaching a patch with the fix in this area.
Thanks for doing the legwork. I pushed this after rewriting the
initial hunk a little: I didn't like just assuming that we know the
number of non-resjunk columns. rewriteTargetListIU() splits the
tlist using explicit checks on the resjunk flags, and I think this
code should do the same. We can assert that the result matches the
CTE column list afterwards.
regards, tom lane
^ permalink raw reply [nested|flat] 4+ messages in thread
end of thread, other threads:[~2026-11-20 16:57 UTC | newest]
Thread overview: 4+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-11-19 03:27 BUG #19922: CYCLE/SEARCH with a window in the recursive term: could not find replacement targetlist entry PG Bug reporting form <noreply@postgresql.org>
2026-11-19 21:47 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-11-20 10:52 ` Nitin Motiani <nitinmotiani@google.com>
2026-11-20 16:57 ` Tom Lane <tgl@sss.pgh.pa.us>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox