CYCLE over calculates windows functions

Started by Kirill Reshke4 days ago4 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1Kirill Reshke
reshkekirill@gmail.com

So, I was reviewing two recent bugs reports 19922/19923 [0]/messages/by-id/19922-a0d338245d361a4c@postgresql.org & [1]/messages/by-id/19923-24cef1e958fa2370@postgresql.org
and fix from [2]https://github.com/postgres/postgres/commit/d27418375d64663c920d81b0814d389a33d621db. And I learned how CTE with CYCLE clause is
implemented in PostgreSQL: it goes thru rewrite subsystem to make
classing CTE for cycle detection, just like doc says [3]https://www.postgresql.org/docs/current/queries-with.html. To better
understand how [2]https://github.com/postgres/postgres/commit/d27418375d64663c920d81b0814d389a33d621db and rewriteSearchAndCycle works I made this example
(from attached 0002 test):

create temp table cycle_window_edge (src int, dst int);
insert into cycle_window_edge values (1, 2), (2, 1), (2, 3), (3, 4);

with recursive walk(id, depth) as (

values (1, 0::bigint)
union all
select e.dst, w.depth + 1
from walk w join cycle_window_edge e on e.src = w.id

) cycle id set is_cycle using path
select depth, id, is_cycle from walk order by depth, id;

On master, rewriteSearchAndCycle will rewrite this to be efficiently
this (internally it will be AST not SQL, so SQL is just for
explanation)

WITH RECURSIVE walk(id, depth, n, is_cycle, path) AS (
VALUES (1, 0, 0::bigint, false, ARRAY[1]/messages/by-id/19923-24cef1e958fa2370@postgresql.org)

UNION ALL

SELECT c.id, c.depth, c.n, c.is_cycle, c.path
FROM (
SELECT e.dst AS id,
w.depth + 1 AS depth,
count(*) OVER () AS n,
e.dst = ANY(w.path) AS is_cycle,
w.path || e.dst AS path,
w.is_cycle AS parent_is_cycle
FROM walk w
JOIN cycle_window_edge e ON e.src = w.id
) AS c
WHERE c.parent_is_cycle <> true
)
SELECT depth, id, n, is_cycle
FROM walk
ORDER BY depth, id;

-- not correct result (last row n == 2, counted edge 1->2 and than
filtering out)

depth | id | n | is_cycle
-------+----+---+----------
0 | 1 | 0 | f
1 | 2 | 1 | f
2 | 1 | 2 | t
2 | 3 | 2 | f
3 | 4 | 2 | f
(5 rows)

So, our recursive step goes into subquery and we then do outer
filtering by parent_is_cycle var.
But turns out, this is not always correct rewriting, cause we first
collect all rows from subquery and only then filter. If we use window
function in recursive step, parent_is_cycle=true rows will be counted
in the window function column for surviving rows.

So, dont make subquery?

After 0001, rewrite would be like ths

WITH RECURSIVE walk(id, depth, n, is_cycle, path) AS (
VALUES (1, 0, 0::bigint, false, ARRAY[1]/messages/by-id/19923-24cef1e958fa2370@postgresql.org)

UNION ALL

SELECT e.dst,
w.depth + 1,
count(*) OVER () AS n,
e.dst = ANY(w.path) AS is_cycle,
w.path || e.dst AS path
FROM walk w
JOIN cycle_window_edge e ON e.src = w.id
WHERE w.is_cycle <> true
)
SELECT depth, id, n, is_cycle
FROM walk
ORDER BY depth, id;

-- correct result

depth | id | n | is_cycle
-------+----+---+----------
0 | 1 | 0 | f
1 | 2 | 1 | f
2 | 1 | 2 | t
2 | 3 | 2 | f
3 | 4 | 1 | f
(5 rows)

which will preserve window functions semantic

[0]: /messages/by-id/19922-a0d338245d361a4c@postgresql.org
[1]: /messages/by-id/19923-24cef1e958fa2370@postgresql.org
[2]: https://github.com/postgres/postgres/commit/d27418375d64663c920d81b0814d389a33d621db
[3]: https://www.postgresql.org/docs/current/queries-with.html

--
Best regards,
Kirill Reshke

Attachments:

0001-Fix-CYCLE-filtering-before-window-functions.patchapplication/octet-stream; name=0001-Fix-CYCLE-filtering-before-window-functions.patchDownload+18-17
0002-Test-CYCLE-filtering-before-window-functions.patchapplication/octet-stream; name=0002-Test-CYCLE-filtering-before-window-functions.patchDownload+34-1
#2Kirill Reshke
reshkekirill@gmail.com
In reply to: Kirill Reshke (#1)
Re: CYCLE over calculates windows functions

On Wed, 25 Nov 2026 at 14:13, Kirill Reshke <reshkekirill@gmail.com> wrote:

-- not correct result (last row n == 2, counted edge 1->2 and than
filtering out)

depth | id | n | is_cycle
-------+----+---+----------
0 | 1 | 0 | f
1 | 2 | 1 | f
2 | 1 | 2 | t
2 | 3 | 2 | f
3 | 4 | 2 | f
(5 rows)

There are more cases with wrong results (all because of subquery-style
query rewrite, all cures with 0001). Sorry for AI slop, tests just
FTWW

1) GROUP BY dst OFFSET 0

-- Each query is independent. cardinality(path) = 3 selects the second
-- recursive step. Only parents whose cycle mark is false may take that step.
-- 1. GROUP BY, no HAVING. Expected one row: 1.
WITH RECURSIVE w(id) AS (
VALUES (1), (2)
UNION ALL
(SELECT dst FROM w JOIN (VALUES (1,1), (2,3), (3,1)) e(src,dst) ON src = id
GROUP BY dst OFFSET 0)
) CYCLE id SET cyc USING path
SELECT id FROM w WHERE cardinality(path) = 3;
id
----
(0 rows)

2. GROUP BY with HAVING. The extra edge to 4 is rejected by HAVING.
-- Expected one row: 1.
WITH RECURSIVE w(id) AS (
VALUES (1), (2)
UNION ALL
(SELECT dst FROM w JOIN (VALUES (1,1), (2,3), (3,1), (2,4))
e(src,dst) ON src = id
GROUP BY dst HAVING dst < 4 OFFSET 0)
) CYCLE id SET cyc USING path
SELECT id FROM w WHERE cardinality(path) = 3;
id
----
(0 rows)

3. DISTINCT. Expected one row: 1.
WITH RECURSIVE w(id) AS (
VALUES (1), (2)
UNION ALL
SELECT DISTINCT dst FROM w JOIN (VALUES (1,1), (2,3), (3,1))
e(src,dst) ON src = id
) CYCLE id SET cyc USING path
SELECT id FROM w WHERE cardinality(path) = 3;
id
----
(0 rows)

4. DISTINCT ON. ORDER BY prefers the marked parent 1 over the live
-- parent 3 if both get to compete for dst = 1. Expected one row: 1.
WITH RECURSIVE w(id) AS (
VALUES (1), (2)
UNION ALL
(SELECT DISTINCT ON (dst) dst
FROM w JOIN (VALUES (1,1), (2,3), (3,1)) e(src,dst) ON src = id
ORDER BY dst, id)
) CYCLE id SET cyc USING path
SELECT id FROM w WHERE cardinality(path) = 3;
id
----
(0 rows)

5. LIMIT. At step 1 the two lowest destinations are 1 (cycle) and 3.
-- Only 3 may continue, via 3 -> 4. Expected one row: 4.
WITH RECURSIVE w(id) AS (
VALUES (1), (2)
UNION ALL
(SELECT dst FROM w JOIN (VALUES (1,1), (1,4), (2,3), (3,4))
e(src,dst) ON src = id
ORDER BY dst, id LIMIT 2)
) CYCLE id SET cyc USING path
SELECT id FROM w WHERE cardinality(path) = 3;
id
----
(0 rows)

6. Window count. Only the live parent 3 contributes to dst = 1.
-- Expected one row: 1.
WITH RECURSIVE w(id,n) AS (
VALUES (1,0::bigint), (2,0::bigint)
UNION ALL
SELECT dst, count(*) OVER (PARTITION BY dst)
FROM w JOIN (VALUES (1,1), (2,3), (3,1)) e(src,dst) ON src = id
) CYCLE id SET cyc USING path
SELECT n FROM w WHERE cardinality(path) = 3;
n
---
2
(1 row)

--
Best regards,
Kirill Reshke

#3Andrey Borodin
amborodin@acm.org
In reply to: Kirill Reshke (#2)
Re: CYCLE over calculates windows functions

Hi Kirill,

On 25 Nov 2026, Kirill Reshke wrote:

There are more cases with wrong results (all because of subquery-style
query rewrite, all cures with 0001).

The SQL draft I checked specifies this subquery rewrite: 7.18
"<search or cycle clause>", Syntax Rule 8, puts the cycle-mark filter
in the outer WHERE, as our current implementation does.

Also, 7.17 "<query expression>", SR 3)j)ix)5)C)II, prohibits window
functions in the recursive SELECT. Supporting them is our extension,
so the standard does not prescribe the window results in your example.

Could you clarify which semantics you want to propose for these extensions
before treating this as a bug fix?

Thank you!

Best regards, Andrey Borodin.

#4Kirill Reshke
reshkekirill@gmail.com
In reply to: Andrey Borodin (#3)
Re: CYCLE over calculates windows functions

On Fri, 27 Nov 2026 at 13:55, Andrey Borodin <x4mmm@yandex-team.ru> wrote:

Hi Kirill,

On 25 Nov 2026, Kirill Reshke wrote:

There are more cases with wrong results (all because of subquery-style
query rewrite, all cures with 0001).

The SQL draft I checked specifies this subquery rewrite: 7.18
"<search or cycle clause>", Syntax Rule 8, puts the cycle-mark filter
in the outer WHERE, as our current implementation does.

OK, should we follow this? Can we rewrite the query this way
preserving window func semantics?

Also, 7.17 "<query expression>", SR 3)j)ix)5)C)II, prohibits window
functions in the recursive SELECT. Supporting them is our extension,
so the standard does not prescribe the window results in your example.

(§7.17, Syntax Rule 5(c)(II)) prohibits windows functions in WITH
RECURSIVE even without CYCLE (at least from my reading). Also here was
previous diction about similar problems [0]/messages/by-id/17581.1230482868@sss.pgh.pa.us. At time, postgres didn't
forbid this case just because SQL standard says its disallowed.

....

Another issue found while luring SQL draft copy

WITH RECURSIVE t(n) AS (
VALUES (1)
UNION ALL
SELECT n + 1 FROM t WHERE n < 2
)
CYCLE n SET mark TO TRUE DEFAULT TRUE USING path
SELECT n, mark FROM t;

§7.18, Syntax Rule 6(c): ..CMV and CMD shall be literals and CMV shall
not be equal to CMD... - but postgres allows TO TRUE DEFAULT TRUE. We
can add this here or fix [1]https://wiki.postgresql.org/wiki/PostgreSQL_vs_SQL_Standard

[0]: /messages/by-id/17581.1230482868@sss.pgh.pa.us
[1]: https://wiki.postgresql.org/wiki/PostgreSQL_vs_SQL_Standard

--
Best regards,
Kirill Reshke