pgsql: Fix infinite loop in first_value()/nth_value() with IGNORE NULLS

Started by Tatsuo Ishii18 days ago3 messagescommitters
Jump to latest
#1Tatsuo Ishii
ishii@postgresql.org

Fix infinite loop in first_value()/nth_value() with IGNORE NULLS.

ignorenulls_getfuncarginframe() walks the frame row by row looking for
the n-th non-null value. It calls row_is_in_frame() on each position
without first checking that the position is inside the partition,
although row_is_in_frame() requires its caller to have done so ("The
caller must have already determined that the row is in the
partition"). When the frame ends at UNBOUNDED FOLLOWING,
row_is_in_frame() has no end-of-frame test, and with EXCLUDE GROUP (or
EXCLUDE TIES, for rows other than the current one) and no ORDER BY it
returns 0 ("excluded") for every position, including positions past
the last row. The loop then never calls window_gettupleslot(), which
is what would have noticed the end of the partition, and it advances
abs_pos forever. The fix checks the partition end before calling
row_is_in_frame(), the same way window_gettupleslot() does
(spool_tuples(), then compare with spooled_rows). It also adds
CHECK_FOR_INTERRUPTS() at the top of the loop: the loop can pass over
many excluded or known-NULL rows without fetching any tuple, and
window_gettupleslot() is where the interrupt check normally happens.

Author: BHUVAN CHILUKUTI <c.bhuvan@iitg.ac.in>
Reviewed-by: shihao zhong <zhong950419@gmail.com>
Reviewed-by: Tatsuo Ishii <ishii@postgresql.org>
Discussion: /messages/by-id/PN0P287MB09038F3BD9921EBACF5646F6A7632@PN0P287MB0903.INDP287.PROD.OUTLOOK.COM
Backpatch-through: 19

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/69b20fdd20de68b0f0eaa855669a6657c65c8533

Modified Files
--------------
src/backend/executor/nodeWindowAgg.c | 15 ++++++++++++++
src/test/regress/expected/window.out | 40 ++++++++++++++++++++++++++++++++++++
src/test/regress/sql/window.sql | 20 ++++++++++++++++++
3 files changed, 75 insertions(+)

#2Richard Guo
guofenglinux@gmail.com
In reply to: Tatsuo Ishii (#1)
Re: pgsql: Fix infinite loop in first_value()/nth_value() with IGNORE NULLS

On Fri, Nov 6, 2026 at 9:04 AM Tatsuo Ishii <ishii@postgresql.org> wrote:

Fix infinite loop in first_value()/nth_value() with IGNORE NULLS.

This commit needs a pgindent.

- Richard

#3Tatsuo Ishii
ishii@postgresql.org
In reply to: Richard Guo (#2)
Re: pgsql: Fix infinite loop in first_value()/nth_value() with IGNORE NULLS

On Fri, Nov 6, 2026 at 9:04 AM Tatsuo Ishii <ishii@postgresql.org> wrote:

Fix infinite loop in first_value()/nth_value() with IGNORE NULLS.

This commit needs a pgindent.

Thanks for letting me know. Fixed.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp