pg.ddx.io pgsql-bugs@postgresql.org mailing list archive
help / color / mirror / Atom feedBUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
6+ messages / 3 participants
[nested] [flat]
* BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
@ 2026-11-17 13:18 PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
0 siblings, 1 reply; 6+ messages in thread
From: PG Bug reporting form @ 2026-11-17 13:18 UTC (permalink / raw)
To: pgsql-bugs@lists.postgresql.org; +Cc: tharakan@gmail.com
The following bug has been logged on the website:
Bug reference: 19911
Logged by: Robins Tharakan
Email address: tharakan@gmail.com
PostgreSQL version: Unsupported/Unknown
Operating system: Debian 13 (x86_64)
Description:
A window aggregate whose ROWS frame starts at an offset FOLLOWING fails
with an internal error when the rows before the frame's start don't fit
in work_mem:
ERROR: XX000: unexpected end of tuplestore
LOCATION: window_gettupleslot, nodeWindowAgg.c:3358
The query should return its rows: with work_mem large enough for the
partition (4MB for the first query below), it does. It fails the same
way for max(), sum() and count(*), with or without PARTITION BY or
ORDER BY. first_value() and nth_value(), RANGE and GROUPS frames, and
frames starting at an offset PRECEDING give the same rows at 64kB as at
64MB. A Valgrind run didn't report much else interesting.
SQL
===
SET work_mem = '64kB';
SELECT count(x), max(x)
FROM (SELECT max(g) OVER (ROWS BETWEEN 2000 FOLLOWING
AND UNBOUNDED FOLLOWING) AS x
FROM generate_series(1, 2002) g) s;
-- expected: 2 | 2002 (as with work_mem = '4MB')
-- got: ERROR: XX000: unexpected end of tuplestore
Commit
======
Reproduces on master (11591f273e6) and on every supported branch,
including v14 (853b35f35b1). A release build (no assertions, -O2)
raises the same error.
Error Log
=======
ERROR: unexpected end of tuplestore
STATEMENT: SELECT count(x), max(x)
FROM (SELECT max(g) OVER (ROWS BETWEEN 2000 FOLLOWING
AND UNBOUNDED FOLLOWING) AS x
FROM generate_series(1, 2002) g) s;
Backtrace
========
#0 window_gettupleslot (winobj=..., pos=2001, slot=...)
at nodeWindowAgg.c:3358
#1 eval_windowaggregates (winstate=...) at nodeWindowAgg.c:982
#2 ExecWindowAgg (pstate=...) at nodeWindowAgg.c:2431
#3 ExecProcNodeFirst (node=...) at execProcnode.c:469
#4 ExecProcNode (node=...) at executor.h:327
#5 fetch_input_tuple (aggstate=...) at nodeAgg.c:564
#6 agg_retrieve_direct (aggstate=...) at nodeAgg.c:2464
#7 ExecAgg (pstate=...) at nodeAgg.c:2279
At #0, for the first output row (currentpos 0, frameheadpos 2000): the
fetch of row 2000 has just returned g = 2002, and the read pointer is
at EOF with seekpos 2000.
Found using SQLsmith, SQLReduce, creduce and Claude.
-
Robins Tharakan
Databricks
^ permalink raw reply [nested|flat] 6+ messages in thread
* Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
@ 2026-11-18 01:05 ` Henson Choi <assam258@gmail.com>
2026-11-18 02:03 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 6+ messages in thread
From: Henson Choi @ 2026-11-18 01:05 UTC (permalink / raw)
To: tharakan@gmail.com; pgsql-bugs@lists.postgresql.org
Subject: Re: BUG #19911: Window aggregate over ROWS n FOLLOWING:
"unexpected end of tuplestore" after spill
Hi Robins,
Thanks for the report. I can reproduce it on master, and the attached
patch fixes it. Below are the cause and fix, why this kind of bug
keeps turning up in WindowAgg, and two follow-up ideas for master.
1. Cause and fix
On the first row, WindowAgg reads rows up to the frame head, 2000 rows
ahead. The tuplestore spills to disk partway through, but the read
still stops there, so the frame head is the next row, not yet stored.
Moving the aggregate's mark to the frame head then leaves its read
pointer at the end of the stored rows, and still selected.
The next fetch first reads the rest of the partition, as it always
does once the store has spilled. A selected pointer at the end moves
along with the rows being written, so the pointer ends up two rows
further on, while the row WindowAgg remembers for it stays the same.
The next move is computed from that stale row and runs off the end.
The patch takes the pointer's row from the number of stored rows
whenever the pointer is at the end, before computing the move.
2. Why this keeps happening, and a mitigation
tuplestore has many users besides WindowAgg: Material, CTE scan,
recursive union and worktable scan, function and table function scans,
SRFs in materialize mode (SQL functions, PL/pgSQL RETURN NEXT, PL/Perl
and PL/Tcl return_next), portals and holdable cursors, trigger
transition tables, hash join and walreceiver queries, among others.
Its read pointers only move relative to where they are (forward or
back, skip, rewind); nothing fetches row N directly.
A window clause also needs random access: row N of the frame, a mark
that moves ahead. WindowAgg emulates it by remembering which row each
window function's and aggregate's pointer is on, while rows are added
to the store on demand from many places, both before reads and in
checks that only ask whether a row exists. Adding rows moves the
selected pointer sitting at the end, but neither side knows about the
other, which is what broke here. This makes the current approach
fragile to maintain.
As a mitigation, the code that manages these positions and limits
could move into a layer between the WindowAgg executor and tuplestore
that offers, in effect, seek by row number on top of the relative
moves: fetch a row, check whether row N or the end of the partition
exists, set a mark, make sure rows up to N are stored, and drop rows
no longer needed, plus pointer setup and partition reset. It would
sit on the existing tuplestore and is meant to behave the same. With
the bookkeeping in one place, including keeping positions right while
rows are added, this kind of defect should be easier to avoid.
3. Performance
Once the layer exists, the storage under it can change without
touching the executor. It could become a store dedicated to the
WindowAgg executor, in which each of several read pointers keeps its
own window of rows in memory and blocks are indexed by row number.
Today, after a spill every read pointer shares one temporary file with
a one-block buffer, and old rows are only dropped while the store is
in memory. Tuples are written to the file one after another with
varying lengths, and nothing maps a row number to a file offset, so
the only way to reach a row N rows away is to read every tuple in
between. When reads jump between distant positions, each row can mean
re-reading the file between them. Cases that do this:
- an aggregate over a long moving frame, whose read pointer walks back
to the frame head for every row
- a frame that starts at an offset FOLLOWING, as in this report
- lead() or lag() with a large offset
- first_value() or nth_value() over a long frame, whose pointer sits
at the frame head while the current row is read at the tail
With blocks indexed by row number, a jump becomes a direct read
instead of a walk, and with a window per pointer, alternating pointers
stop evicting each other's block. In memory, the store would keep
only those windows rather than everything from the oldest pointer to
the end.
The row pattern recognition patch under review adds navigation
operations in DEFINE that read rows near the row being tested (PREV,
NEXT, LAST) or near the match start (FIRST), which can sit far from
the row being tested. They add a read pointer whose fetches jump
between rows far apart, so they would gain from the same store.
The patch is for all supported branches. The ideas in sections 2 and
3 are master-only, and I would start a separate -hackers thread for
them if there is interest.
Regards,
Henson
Attachments:
v1-0001-Fix-stale-read-position-in-window_gettupleslot-af.patch (application/x-patch, 3.3K) download
From 3bc70d4a9e4d5e0fce8633c84385982098c78432 Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Wed, 18 Nov 2026 08:21:59 +0900
Subject: [PATCH v1] Fix stale read position in window_gettupleslot() after
tuplestore spill
If the tuplestore spills to disk while spooling rows up to a frame
head at an offset FOLLOWING, moving the aggregate's mark there can
leave its read pointer active at EOF.
The next spool then appends the rest of the partition, the pointer
follows the write position, and WindowObject's seekpos goes stale,
so a later fetch fails with "unexpected end of tuplestore".
Fix by resyncing seekpos to spooled_rows when the read pointer is at
EOF.
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 14
---
src/backend/executor/nodeWindowAgg.c | 7 +++++++
src/test/regress/expected/window.out | 12 ++++++++++++
src/test/regress/sql/window.sql | 8 ++++++++
3 files changed, 27 insertions(+)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 8d80f2cc023..9d08d372b5f 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -3306,6 +3306,13 @@ window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
+ /*
+ * A read pointer left at EOF follows the write position while rows are
+ * spooled, so seekpos may be stale. Resync it.
+ */
+ if (tuplestore_ateof(winstate->buffer))
+ winobj->seekpos = winstate->spooled_rows;
+
/*
* Advance or rewind until we are within one tuple of the one we want.
*/
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index 112551c350b..521b734d47d 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -1452,6 +1452,18 @@ FROM tenk1 WHERE unique1 < 10;
| 7 | 3
(10 rows)
+-- frame head past the spooled rows when the tuplestore spills to disk
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+ count | sum
+-------+------
+ 2002 | 6005
+(1 row)
+
+RESET work_mem;
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
unique1, four
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index e848557174b..e9f415929be 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -356,6 +356,14 @@ SELECT sum(unique1) over (ORDER BY four groups between 9223372036854775807 follo
unique1, four
FROM tenk1 WHERE unique1 < 10;
+-- frame head past the spooled rows when the tuplestore spills to disk
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+RESET work_mem;
+
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 6+ messages in thread
* Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
@ 2026-11-18 02:03 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-11-18 03:51 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
0 siblings, 1 reply; 6+ messages in thread
From: Tom Lane @ 2026-11-18 02:03 UTC (permalink / raw)
To: assam258@gmail.com; +Cc: tharakan@gmail.com; pgsql-bugs@lists.postgresql.org
Henson Choi <assam258@gmail.com> writes:
> Thanks for the report. I can reproduce it on master, and the attached
> patch fixes it. Below are the cause and fix, why this kind of bug
> keeps turning up in WindowAgg, and two follow-up ideas for master.
I've spent the last little while poking at this problem too.
I concur with your root-cause diagnosis: WindowAgg's dead reckoning
about where the tuplestore read pointers are positioned is getting
out of sync with their actual positions. I've got very little faith
in your proposed patch though. WindowAgg maintains a bunch of
read pointers and is less than consistent about which one is the
"active" one when it calls tuplestore_puttupleslot(), so I suspect
that there are more places than this one that would need resync logic
if we follow this fix approach.
I experimented with some alternative fix ideas, but couldn't come
up with anything very workable. I think what we need to do is
what you called a mitigation but seems to me to be a full fix:
get rid of WindowAgg's local tracking of tuplestore positions
in favor of extending the tuplestore API with some more-appropriate
operations. In particular, if tuplestore had an API call to the
effect of "set the read pointer to absolute tuple number N", we
could get rid of a lot of silliness in WindowAgg. Having a call
to read out the position as an absolute tuple number might help
too, but I'm not sure we'd even need it if we had the first one.
The reason that tuplestore hasn't got that already is long obsolete:
I think it's mainly that we wanted to support tuplestores with more
than 4G tuples on machines without int64 arithmetic, so dealing in
absolute rather than relative tuple numbers didn't work. There are
some fine points to be dealt with, like compensating for
"tuplestore_trim" operations, but I think it's not going to be too
complicated. And fortunately we never exposed the tuplestore state
structs in any header, so there's no ABI breakage risk to worry about
from adding or expanding fields.
I would not bother with the intermediate management layer that you
talked about; that seems like it's just adding bureaucracy.
regards, tom lane
^ permalink raw reply [nested|flat] 6+ messages in thread
* Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
2026-11-18 02:03 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-11-18 03:51 ` Henson Choi <assam258@gmail.com>
2026-11-19 07:22 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
0 siblings, 1 reply; 6+ messages in thread
From: Henson Choi @ 2026-11-18 03:51 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: tharakan@gmail.com; pgsql-bugs@lists.postgresql.org
Tom Lane <tgl@sss.pgh.pa.us> writes:
> I've got very little faith in your proposed patch though. WindowAgg
> maintains a bunch of read pointers and is less than consistent about
> which one is the "active" one when it calls tuplestore_puttupleslot(),
> so I suspect that there are more places than this one that would need
> resync logic if we follow this fix approach.
Agreed, v1 depended on that. tuplestore does need improving, and
once row pattern recognition has settled, I'd like to rework it,
together with the performance side, so that several positions can be
read at once through multiple read buffers. For the problem at hand,
though, I'd like to propose a simpler fix that, unlike v1, does not
create the EOF state at all.
WinSetMarkPosition() skipped the aggregate's read pointer past the
end of the stored rows. A skip past the end leaves the pointer at
EOF. While it is at EOF and still the active pointer, it moves along
as the spool adds rows, but seekpos does not, so the two no longer
agree.
v2 limits the skip so that it cannot reach EOF: the read pointer
stops on the last stored row. Since the read pointer can never reach
EOF, seekpos and the pointer can no longer disagree.
An assertion in window_gettupleslot() checks that the pointer it uses
is not at EOF.
This does not depend on which pointer is active. On a write,
tuplestore moves a read pointer only if it is at EOF; a pointer
anywhere else stays where it is, active or not. The skip above is the
only way a WindowObject's read pointer reaches EOF. The frame head,
frame tail, group tail and current-row pointers keep no seekpos, and
reach EOF only at the real end of the partition, after which no more
rows are written.
To check this, I made spool_tuples() report any WindowObject read
pointer at EOF before it writes. On 2900 window queries and a set of
random ones at work_mem = 64kB, it found the active aggregate pointer
at EOF thousands of times with v1, and never with v2.
The regression test is the same as in v1. With assertions enabled,
it fails without the fix and passes with it on master and on REL_14
to REL_19.
> I think what we need to do is what you called a mitigation but seems
> to me to be a full fix: get rid of WindowAgg's local tracking of
> tuplestore positions in favor of extending the tuplestore API with
> some more-appropriate operations.
I agree that the tuplestore API is the right direction, and I'll
include it, without the extra layer, when I rework tuplestore as
mentioned above. As that is likely to take quite a while, would you
consider v2 first, as a small fix without side effects?
Regards,
Henson
Attachments:
v2-0001-Don-t-move-a-window-read-pointer-past-the-stored-.patch (application/octet-stream, 4.4K) download
From e7fdc06f43a8a0233d9a97d17883eb64b92343f9 Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Wed, 18 Nov 2026 08:21:59 +0900
Subject: [PATCH v2] Don't move a window read pointer past the stored rows
When the frame head of a window aggregate is the next row, not yet
stored, WinSetMarkPosition() moved the aggregate's read pointer past
the stored rows and left it at EOF.
A read pointer at EOF follows the rows written while it is active.
Once the tuplestore has spilled to disk, the next spool reads the rest
of the partition, so the pointer ended up at its end while seekpos
stayed put, and a later fetch failed with "unexpected end of
tuplestore".
Fix by moving the read pointer no further than the last stored row,
where it stays put as rows are added, and assert that a WindowObject's
read pointer is never at EOF when it is used.
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 14
---
src/backend/executor/nodeWindowAgg.c | 24 ++++++++++++++++++++----
src/test/regress/expected/window.out | 12 ++++++++++++
src/test/regress/sql/window.sql | 8 ++++++++
3 files changed, 40 insertions(+), 4 deletions(-)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 8d80f2cc023..a5508d20005 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -3306,6 +3306,9 @@ window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
+ /* seekpos is only valid for a pointer not at EOF; see WinSetMarkPosition */
+ Assert(!tuplestore_ateof(winstate->buffer));
+
/*
* Advance or rewind until we are within one tuple of the one we want.
*/
@@ -3790,13 +3793,26 @@ WinSetMarkPosition(WindowObject winobj, int64 markpos)
true);
winobj->markpos = markpos;
}
+
+ /*
+ * Bring the read pointer up to the mark, but don't skip it past the rows
+ * stored so far: a pointer at EOF follows the rows written while it is
+ * active, which seekpos would not reflect. Stopped on the last stored
+ * row, it stays put. The mark pointer is never active while rows are
+ * written, so if it reaches EOF it is just held one row back.
+ */
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
if (markpos > winobj->seekpos)
{
- tuplestore_skiptuples(winstate->buffer,
- markpos - winobj->seekpos,
- true);
- winobj->seekpos = markpos;
+ int64 target = Min(markpos, winstate->spooled_rows - 1);
+
+ if (target > winobj->seekpos)
+ {
+ tuplestore_skiptuples(winstate->buffer,
+ target - winobj->seekpos,
+ true);
+ winobj->seekpos = target;
+ }
}
}
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index 112551c350b..061caa685d7 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -1452,6 +1452,18 @@ FROM tenk1 WHERE unique1 < 10;
| 7 | 3
(10 rows)
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+ count | sum
+-------+------
+ 2002 | 6005
+(1 row)
+
+RESET work_mem;
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
unique1, four
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index e848557174b..c4ff185d815 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -356,6 +356,14 @@ SELECT sum(unique1) over (ORDER BY four groups between 9223372036854775807 follo
unique1, four
FROM tenk1 WHERE unique1 < 10;
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+RESET work_mem;
+
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 6+ messages in thread
* Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
2026-11-18 02:03 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Tom Lane <tgl@sss.pgh.pa.us>
2026-11-18 03:51 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
@ 2026-11-19 07:22 ` Henson Choi <assam258@gmail.com>
2026-11-23 01:06 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 6+ messages in thread
From: Henson Choi @ 2026-11-19 07:22 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: tharakan@gmail.com; pgsql-bugs@lists.postgresql.org
Hi Tom,
> In particular, if tuplestore had an API call to the
> effect of "set the read pointer to absolute tuple number N", we
> could get rid of a lot of silliness in WindowAgg. Having a call
> to read out the position as an absolute tuple number might help
> too, but I'm not sure we'd even need it if we had the first one.
v3 follows that direction. There are four patches.
0001 removes needless complexity unrelated to this bug: only the
heap tuple kind exists, so the tuple-kind callbacks become direct
calls. It can be dropped if you prefer.
0002 gives each read pointer an absolute row number, counted from 0
since creation or the last tuplestore_clear(). Assert-enabled builds
check it against the array position while the store is in memory.
0003 adds tuplestore_tell() and tuplestore_seek(). tell returns the
number of the row the next forward fetch would return, or the number
of rows stored at EOF. seek clears the EOF state, as fseek() does.
In memory it computes the array position; on disk it steps over the
records by their length words without reading the tuples, so the
cost is still proportional to the distance.
I also added tell. As the counterpart of seek it is likely to find
uses, and WinSetMarkPosition() already uses it to move the read
pointer only forward.
0004 removes seekpos from WindowAgg. window_gettupleslot() positions
the pointer with tell and seek, and WinSetMarkPosition() never seeks
past the stored rows, so a WindowObject's pointer never reaches EOF.
Asserts check that in both places. The regression test is the same
as in v1 and v2.
> There are
> some fine points to be dealt with, like compensating for
> "tuplestore_trim" operations
The row numbers are not affected by trim. Trim does not change the
total row count tuplestore keeps, and the in-memory array position is
derived from that count. A seek to a trimmed row returns false.
v3 is for master. For the back branches, I'd like your view on
whether to use this series or v2. It applies to REL_19 as is; 14 to
18 need small context adjustments.
Best regards,
Henson
Attachments: download all (4 files, .tar.gz)
v3-0001-Remove-tuple-kind-callback-indirection-from-tuple.patch (application/octet-stream, 9.1K) download
From c14798ead54e6f4ec8239254fccb31ee22e87aaa Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Thu, 19 Nov 2026 13:06:40 +0900
Subject: [PATCH v3 1/4] Remove tuple-kind callback indirection from tuplestore
Only heap tuples have ever been stored, so call copytup_heap(),
writetup_heap() and readtup_heap() directly instead of through
function pointers.
---
src/backend/utils/sort/tuplestore.c | 86 ++++++++++-------------------
src/include/utils/tuplestore.h | 5 --
2 files changed, 29 insertions(+), 62 deletions(-)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index 610ddf00532..2da19b97356 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -117,39 +117,6 @@ struct Tuplestorestate
MemoryContext context; /* memory context for holding tuples */
ResourceOwner resowner; /* resowner for holding temp files */
- /*
- * These function pointers decouple the routines that must know what kind
- * of tuple we are handling from the routines that don't need to know it.
- * They are set up by the tuplestore_begin_xxx routines.
- *
- * (Although tuplestore.c currently only supports heap tuples, I've copied
- * this part of tuplesort.c so that extension to other kinds of objects
- * will be easy if it's ever needed.)
- *
- * Function to copy a supplied input tuple into palloc'd space. (NB: we
- * assume that a single pfree() is enough to release the tuple later, so
- * the representation must be "flat" in one palloc chunk.) state->availMem
- * must be decreased by the amount of space used.
- */
- void *(*copytup) (Tuplestorestate *state, void *tup);
-
- /*
- * Function to write a stored tuple onto tape. The representation of the
- * tuple on tape need not be the same as it is in memory; requirements on
- * the tape representation are given below. After writing the tuple,
- * pfree() it, and increase state->availMem by the amount of memory space
- * thereby released.
- */
- void (*writetup) (Tuplestorestate *state, void *tup);
-
- /*
- * Function to read a stored tuple from tape back into memory. 'len' is
- * the already-read length of the stored tuple. Create and return a
- * palloc'd copy, and decrease state->availMem by the amount of memory
- * space consumed.
- */
- void *(*readtup) (Tuplestorestate *state, unsigned int len);
-
/*
* This array holds pointers to tuples in memory if we are in state INMEM.
* In states WRITEFILE and READFILE it's not used.
@@ -183,9 +150,6 @@ struct Tuplestorestate
pgoff_t writepos_offset; /* offset (valid if READFILE state) */
};
-#define COPYTUP(state,tup) ((*(state)->copytup) (state, tup))
-#define WRITETUP(state,tup) ((*(state)->writetup) (state, tup))
-#define READTUP(state,len) ((*(state)->readtup) (state, len))
#define LACKMEM(state) ((state)->availMem < 0)
#define USEMEM(state,amt) ((state)->availMem -= (amt))
#define FREEMEM(state,amt) ((state)->availMem += (amt))
@@ -198,7 +162,7 @@ struct Tuplestorestate
* on-tape of the tuple, including itself (so it is never zero).
* The remainder of the stored tuple
* may or may not match the in-memory representation of the tuple ---
- * any conversion needed is the job of the writetup and readtup routines.
+ * any conversion needed is the job of writetup_heap and readtup_heap.
*
* If state->backward is true, then the stored representation of
* the tuple must be followed by another "unsigned int" that is a copy of the
@@ -207,16 +171,16 @@ struct Tuplestorestate
* state->backward is not set, the write/read routines may omit the extra
* length word.
*
- * writetup is expected to write both length words as well as the tuple
- * data. When readtup is called, the tape is positioned just after the
- * front length word; readtup must read the tuple data and advance past
+ * writetup_heap is expected to write both length words as well as the tuple
+ * data. When readtup_heap is called, the tape is positioned just after the
+ * front length word; readtup_heap must read the tuple data and advance past
* the back length word (if present).
*
* The write/read routines can make use of the tuple description data
* stored in the Tuplestorestate record, if needed. They are also expected
* to adjust state->availMem by the amount of memory space (not tape space!)
- * released or consumed. There is no error return from either writetup
- * or readtup; they should ereport() on failure.
+ * released or consumed. There is no error return from either writetup_heap
+ * or readtup_heap; they should ereport() on failure.
*
*
* NOTES about memory consumption calculations:
@@ -342,10 +306,6 @@ tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
state = tuplestore_begin_common(eflags, interXact, maxKBytes);
- state->copytup = copytup_heap;
- state->writetup = writetup_heap;
- state->readtup = readtup_heap;
-
return state;
}
@@ -766,9 +726,9 @@ tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
/*
* Copy the tuple. (Must do this even in WRITEFILE case. Note that
- * COPYTUP includes USEMEM, so we needn't do that here.)
+ * copytup_heap includes USEMEM, so we needn't do that here.)
*/
- tuple = COPYTUP(state, tuple);
+ tuple = copytup_heap(state, tuple);
tuplestore_puttuple_common(state, tuple);
@@ -901,7 +861,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
}
}
- WRITETUP(state, tuple);
+ writetup_heap(state, tuple);
break;
case TSS_READFILE:
@@ -934,7 +894,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
}
}
- WRITETUP(state, tuple);
+ writetup_heap(state, tuple);
break;
default:
elog(ERROR, "invalid tuplestore state");
@@ -1031,7 +991,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
{
if ((tuplen = getlen(state, true)) != 0)
{
- tup = READTUP(state, tuplen);
+ tup = readtup_heap(state, tuplen);
return tup;
}
else
@@ -1094,7 +1054,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
/*
* Now we have the length of the prior tuple, back up and read it.
- * Note: READTUP expects we are positioned after the initial
+ * Note: readtup_heap expects we are positioned after the initial
* length word of the tuple, so back up to that point.
*/
if (BufFileSeek(state->myfile, 0,
@@ -1103,7 +1063,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not seek in tuplestore temporary file")));
- tup = READTUP(state, tuplen);
+ tup = readtup_heap(state, tuplen);
return tup;
default:
@@ -1303,14 +1263,14 @@ dumptuples(Tuplestorestate *state)
}
if (i >= state->memtupcount)
break;
- WRITETUP(state, state->memtuples[i]);
+ writetup_heap(state, state->memtuples[i]);
/*
* Increase memtupdeleted to track the fact that we just deleted that
* tuple. Think not to remove this on the grounds that we'll reset
* memtupdeleted to zero below. We might not reach that if some later
- * WRITETUP fails (e.g. due to overrunning temp_file_limit). If so,
- * we'd error out leaving an effectively-corrupt tuplestore, which
+ * writetup_heap fails (e.g. due to overrunning temp_file_limit). If
+ * so, we'd error out leaving an effectively-corrupt tuplestore, which
* would be quite bad if it's a persistent data structure such as a
* Portal's holdStore.
*/
@@ -1619,12 +1579,16 @@ getlen(Tuplestorestate *state, bool eofOK)
* Routines specialized for HeapTuple case
*
* The stored form is actually a MinimalTuple, but for largely historical
- * reasons we allow COPYTUP to work from a HeapTuple.
+ * reasons we allow copytup_heap to work from a HeapTuple.
*
* Since MinimalTuple already has length in its first word, we don't need
* to write that separately.
*/
+/*
+ * Copy a HeapTuple into one palloc'd MinimalTuple, so that a single pfree()
+ * releases it, and charge its space to availMem.
+ */
static void *
copytup_heap(Tuplestorestate *state, void *tup)
{
@@ -1635,6 +1599,10 @@ copytup_heap(Tuplestorestate *state, void *tup)
return tuple;
}
+/*
+ * Write a stored tuple to the temp file, then pfree() it and return its space
+ * to availMem.
+ */
static void
writetup_heap(Tuplestorestate *state, void *tup)
{
@@ -1656,6 +1624,10 @@ writetup_heap(Tuplestorestate *state, void *tup)
heap_free_minimal_tuple(tuple);
}
+/*
+ * Read a stored tuple, whose length word 'len' has already been read, into a
+ * palloc'd copy.
+ */
static void *
readtup_heap(Tuplestorestate *state, unsigned int len)
{
diff --git a/src/include/utils/tuplestore.h b/src/include/utils/tuplestore.h
index 12dc51b81d2..d540d575153 100644
--- a/src/include/utils/tuplestore.h
+++ b/src/include/utils/tuplestore.h
@@ -40,11 +40,6 @@
*/
typedef struct Tuplestorestate Tuplestorestate;
-/*
- * Currently we only need to store MinimalTuples, but it would be easy
- * to support the same behavior for IndexTuples and/or bare Datums.
- */
-
extern Tuplestorestate *tuplestore_begin_heap(bool randomAccess,
bool interXact,
int maxKBytes);
--
2.54.0 (Apple Git-157)
v3-0002-Track-absolute-row-numbers-in-tuplestore-read-poi.patch (application/octet-stream, 8.5K) download
From 3ab24124bd79ce0416ed34dac6ff1daddd12cd04 Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Thu, 19 Nov 2026 13:30:33 +0900
Subject: [PATCH v3 2/4] Track absolute row numbers in tuplestore read pointers
Each read pointer now records the absolute number of the next tuple
it would return, counted from 0 since creation or the last
tuplestore_clear(). Trimming does not change these numbers.
Assert-enabled builds check them against the array position while
the store is in memory.
---
src/backend/utils/sort/tuplestore.c | 68 +++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index 2da19b97356..dabd86d46e7 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -88,12 +88,17 @@ typedef enum
* implicitly equal to the write position, and current/file/offset aren't
* maintained. This way we need not update all the read pointers each time
* we write.
+ *
+ * "row" is the absolute number of the tuple just after the last one returned,
+ * counting from 0 since creation or the last tuplestore_clear(). Like the
+ * other position fields, it is not maintained while eof_reached is true.
*/
typedef struct
{
int eflags; /* capability flags */
bool eof_reached; /* read has reached EOF */
int current; /* next array index to read */
+ int64 row; /* absolute row number of the position */
int file; /* temp file# */
pgoff_t offset; /* byte offset in file */
} TSReadPointer;
@@ -154,6 +159,12 @@ struct Tuplestorestate
#define USEMEM(state,amt) ((state)->availMem -= (amt))
#define FREEMEM(state,amt) ((state)->availMem += (amt))
+#ifdef USE_ASSERT_CHECKING
+static void check_read_pointer_rows(Tuplestorestate *state);
+#else
+#define check_read_pointer_rows(state) ((void) 0)
+#endif
+
/*--------------------
*
* NOTES about on-tape representation of tuples:
@@ -267,6 +278,7 @@ tuplestore_begin_common(int eflags, bool interXact, int maxKBytes)
state->readptrs[0].eflags = eflags;
state->readptrs[0].eof_reached = false;
state->readptrs[0].current = 0;
+ state->readptrs[0].row = 0;
return state;
}
@@ -439,6 +451,7 @@ tuplestore_clear(Tuplestorestate *state)
{
readptr->eof_reached = false;
readptr->current = 0;
+ readptr->row = 0;
}
}
@@ -470,6 +483,8 @@ tuplestore_select_read_pointer(Tuplestorestate *state, int ptr)
Assert(ptr >= 0 && ptr < state->readptrcount);
+ check_read_pointer_rows(state);
+
/* No work if already active */
if (ptr == state->activeptr)
return;
@@ -762,6 +777,8 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
ResourceOwner oldowner;
MemoryContext oldcxt;
+ check_read_pointer_rows(state);
+
state->tuples++;
switch (state->status)
@@ -778,6 +795,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
{
readptr->eof_reached = false;
readptr->current = state->memtupcount;
+ readptr->row = state->tuples - 1;
}
}
@@ -858,6 +876,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
BufFileTell(state->myfile,
&readptr->file,
&readptr->offset);
+ readptr->row = state->tuples - 1;
}
}
@@ -891,6 +910,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
readptr->eof_reached = false;
readptr->file = state->writepos_file;
readptr->offset = state->writepos_offset;
+ readptr->row = state->tuples - 1;
}
}
@@ -920,6 +940,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD));
+ check_read_pointer_rows(state);
+
switch (state->status)
{
case TSS_INMEM:
@@ -931,6 +953,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->current < state->memtupcount)
{
/* We have another tuple, so return it */
+ readptr->row++;
return state->memtuples[readptr->current++];
}
readptr->eof_reached = true;
@@ -945,6 +968,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->eof_reached)
{
readptr->current = state->memtupcount;
+ readptr->row = state->tuples;
readptr->eof_reached = false;
}
else
@@ -955,6 +979,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
return NULL;
}
readptr->current--; /* last returned tuple */
+ readptr->row--;
}
if (readptr->current <= state->memtupdeleted)
{
@@ -992,6 +1017,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if ((tuplen = getlen(state, true)) != 0)
{
tup = readtup_heap(state, tuplen);
+ readptr->row++;
return tup;
}
else
@@ -1015,6 +1041,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
{
/* even a failed backwards fetch gets you out of eof state */
readptr->eof_reached = false;
+ readptr->row = 0;
Assert(!state->truncated);
return NULL;
}
@@ -1023,6 +1050,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->eof_reached)
{
readptr->eof_reached = false;
+ readptr->row = state->tuples;
/* We will return the tuple returned before returning NULL */
}
else
@@ -1046,10 +1074,12 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not seek in tuplestore temporary file")));
+ readptr->row = 0;
Assert(!state->truncated);
return NULL;
}
tuplen = getlen(state, false);
+ readptr->row--;
}
/*
@@ -1184,6 +1214,8 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
if (ntuples <= 0)
return true;
+ check_read_pointer_rows(state);
+
switch (state->status)
{
case TSS_INMEM:
@@ -1194,9 +1226,11 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
if (state->memtupcount - readptr->current >= ntuples)
{
readptr->current += ntuples;
+ readptr->row += ntuples;
return true;
}
readptr->current = state->memtupcount;
+ readptr->row = state->tuples;
readptr->eof_reached = true;
return false;
}
@@ -1205,15 +1239,18 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
if (readptr->eof_reached)
{
readptr->current = state->memtupcount;
+ readptr->row = state->tuples;
readptr->eof_reached = false;
ntuples--;
}
if (readptr->current - state->memtupdeleted > ntuples)
{
readptr->current -= ntuples;
+ readptr->row -= ntuples;
return true;
}
Assert(!state->truncated);
+ readptr->row -= readptr->current - state->memtupdeleted;
readptr->current = state->memtupdeleted;
return false;
}
@@ -1292,6 +1329,8 @@ tuplestore_rescan(Tuplestorestate *state)
Assert(readptr->eflags & EXEC_FLAG_REWIND);
Assert(!state->truncated);
+ readptr->row = 0;
+
switch (state->status)
{
case TSS_INMEM:
@@ -1329,6 +1368,8 @@ tuplestore_copy_read_pointer(Tuplestorestate *state,
Assert(srcptr >= 0 && srcptr < state->readptrcount);
Assert(destptr >= 0 && destptr < state->readptrcount);
+ check_read_pointer_rows(state);
+
/* Assigning to self is a no-op */
if (srcptr == destptr)
return;
@@ -1425,6 +1466,8 @@ tuplestore_trim(Tuplestorestate *state)
if (state->eflags & EXEC_FLAG_REWIND)
return;
+ check_read_pointer_rows(state);
+
/*
* We don't bother trimming temp files since it usually would mean more
* work than just letting them sit in kernel buffers until they age out.
@@ -1502,6 +1545,8 @@ tuplestore_trim(Tuplestorestate *state)
if (!state->readptrs[i].eof_reached)
state->readptrs[i].current -= nremove;
}
+
+ check_read_pointer_rows(state);
}
/*
@@ -1575,6 +1620,29 @@ getlen(Tuplestorestate *state, bool eofOK)
}
+#ifdef USE_ASSERT_CHECKING
+/*
+ * Cross-check each read pointer's absolute row number against its in-memory
+ * array index. The file states keep no index to compare with.
+ */
+static void
+check_read_pointer_rows(Tuplestorestate *state)
+{
+ int64 base = state->tuples - state->memtupcount;
+
+ for (int i = 0; i < state->readptrcount; i++)
+ {
+ TSReadPointer *readptr = &state->readptrs[i];
+
+ if (readptr->eof_reached)
+ continue;
+ Assert(readptr->row >= 0 && readptr->row <= state->tuples);
+ if (state->status == TSS_INMEM)
+ Assert(readptr->row == base + readptr->current);
+ }
+}
+#endif
+
/*
* Routines specialized for HeapTuple case
*
--
2.54.0 (Apple Git-157)
v3-0003-Add-tuplestore_tell-and-tuplestore_seek.patch (application/octet-stream, 7.6K) download
From 7d3fb6dd5640d9f409b9a25a18479fe2b5b7fc25 Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Thu, 19 Nov 2026 13:30:33 +0900
Subject: [PATCH v3 3/4] Add tuplestore_tell and tuplestore_seek
tuplestore_tell() returns the absolute number of the row the next
forward fetch would return, or the number of rows stored at EOF.
tuplestore_seek() moves the active read pointer to an absolute row
number and clears its EOF state. On disk we step over records by
their length words without reading the tuples, so the cost is still
proportional to the distance.
---
src/backend/utils/sort/tuplestore.c | 175 +++++++++++++++++++++++++---
src/include/utils/tuplestore.h | 4 +
2 files changed, 165 insertions(+), 14 deletions(-)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index dabd86d46e7..fe77eab3b09 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -24,7 +24,9 @@
*
* Upon creation, a tuplestore supports a single read pointer, numbered 0.
* Additional read pointers can be created using tuplestore_alloc_read_pointer.
- * Mark/restore behavior is supported by copying read pointers.
+ * Mark/restore behavior is supported by copying read pointers. Each read
+ * pointer also knows the absolute number of its next tuple, so a caller can
+ * reposition it with tuplestore_seek instead of counting relative moves.
*
* When the caller requests backward-scan capability, we write the temp file
* in a format that allows either forward or backward scan. Otherwise, only
@@ -216,6 +218,9 @@ static Tuplestorestate *tuplestore_begin_common(int eflags,
int maxKBytes);
static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple);
static void dumptuples(Tuplestorestate *state);
+static void switch_to_readfile(Tuplestorestate *state);
+static void step_record_forward(Tuplestorestate *state);
+static bool step_record_backward(Tuplestorestate *state);
static void tuplestore_updatemax(Tuplestorestate *state);
static unsigned int getlen(Tuplestorestate *state, bool eofOK);
static void *copytup_heap(Tuplestorestate *state, void *tup);
@@ -995,19 +1000,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->eof_reached && forward)
return NULL;
- /*
- * Switch from writing to reading.
- */
- BufFileTell(state->myfile,
- &state->writepos_file, &state->writepos_offset);
- if (!readptr->eof_reached)
- if (BufFileSeek(state->myfile,
- readptr->file, readptr->offset,
- SEEK_SET) != 0)
- ereport(ERROR,
- (errcode_for_file_access(),
- errmsg("could not seek in tuplestore temporary file")));
- state->status = TSS_READFILE;
+ switch_to_readfile(state);
pg_fallthrough;
case TSS_READFILE:
@@ -1275,6 +1268,160 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
}
}
+/*
+ * switch_to_readfile - switch from TSS_WRITEFILE to TSS_READFILE
+ *
+ * Save the write position and seek to the active read pointer's position.
+ */
+static void
+switch_to_readfile(Tuplestorestate *state)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+
+ Assert(state->status == TSS_WRITEFILE);
+
+ BufFileTell(state->myfile,
+ &state->writepos_file, &state->writepos_offset);
+ if (!readptr->eof_reached)
+ if (BufFileSeek(state->myfile,
+ readptr->file, readptr->offset,
+ SEEK_SET) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ state->status = TSS_READFILE;
+}
+
+/*
+ * step_record_forward - move the file position past the next record
+ *
+ * Only the length word is read, not the tuple. The caller must know that
+ * a record is there.
+ */
+static void
+step_record_forward(Tuplestorestate *state)
+{
+ unsigned int tuplen = getlen(state, false);
+ pgoff_t rest = tuplen - sizeof(unsigned int);
+
+ if (state->backward)
+ rest += sizeof(unsigned int);
+ if (BufFileSeek(state->myfile, 0, rest, SEEK_CUR) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+}
+
+/*
+ * step_record_backward - move the file position to the start of the
+ * previous record, using its trailing length word
+ *
+ * Returns false, without moving, at the start of the file.
+ */
+static bool
+step_record_backward(Tuplestorestate *state)
+{
+ unsigned int tuplen;
+
+ Assert(state->backward);
+
+ if (BufFileSeek(state->myfile, 0, -(pgoff_t) sizeof(unsigned int),
+ SEEK_CUR) != 0)
+ return false;
+ tuplen = getlen(state, false);
+ if (BufFileSeek(state->myfile, 0,
+ -(pgoff_t) (tuplen + sizeof(unsigned int)),
+ SEEK_CUR) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ return true;
+}
+
+/*
+ * tuplestore_tell - return the active read pointer's absolute row number
+ *
+ * This is the number of the row that the next forward fetch would return;
+ * at EOF it is the number of rows stored so far.
+ */
+int64
+tuplestore_tell(Tuplestorestate *state)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+
+ return readptr->eof_reached ? state->tuples : readptr->row;
+}
+
+/*
+ * tuplestore_seek - move the active read pointer to an absolute row number
+ *
+ * Afterwards the next forward fetch returns row "row". Seeking to the number
+ * of rows stored so far positions the pointer at the end. Returns false if
+ * the row is out of range or has been trimmed away; on disk the pointer may
+ * then have moved toward it. Moving backward requires EXEC_FLAG_BACKWARD.
+ */
+bool
+tuplestore_seek(Tuplestorestate *state, int64 row)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+ int64 cur;
+
+ check_read_pointer_rows(state);
+
+ if (row < 0 || row > state->tuples)
+ return false;
+ cur = tuplestore_tell(state);
+ if (row == cur && !readptr->eof_reached)
+ return true;
+ Assert(row >= cur || (readptr->eflags & EXEC_FLAG_BACKWARD));
+
+ switch (state->status)
+ {
+ case TSS_INMEM:
+ {
+ int64 base = state->tuples - state->memtupcount;
+
+ if (row < base + state->memtupdeleted)
+ return false;
+ readptr->eof_reached = false;
+ readptr->current = (int) (row - base);
+ readptr->row = row;
+ return true;
+ }
+
+ case TSS_WRITEFILE:
+ switch_to_readfile(state);
+ pg_fallthrough;
+
+ case TSS_READFILE:
+ /* at EOF, the file is already positioned at the write position */
+ if (readptr->eof_reached)
+ {
+ readptr->eof_reached = false;
+ readptr->row = state->tuples;
+ }
+
+ while (readptr->row < row)
+ {
+ step_record_forward(state);
+ readptr->row++;
+ CHECK_FOR_INTERRUPTS();
+ }
+ while (readptr->row > row)
+ {
+ if (!step_record_backward(state))
+ return false;
+ readptr->row--;
+ CHECK_FOR_INTERRUPTS();
+ }
+ return true;
+
+ default:
+ elog(ERROR, "invalid tuplestore state");
+ return false; /* keep compiler quiet */
+ }
+}
+
/*
* dumptuples - remove tuples from memory and write to tape
*
diff --git a/src/include/utils/tuplestore.h b/src/include/utils/tuplestore.h
index d540d575153..e08646dc648 100644
--- a/src/include/utils/tuplestore.h
+++ b/src/include/utils/tuplestore.h
@@ -77,6 +77,10 @@ extern bool tuplestore_advance(Tuplestorestate *state, bool forward);
extern bool tuplestore_skiptuples(Tuplestorestate *state,
int64 ntuples, bool forward);
+extern int64 tuplestore_tell(Tuplestorestate *state);
+
+extern bool tuplestore_seek(Tuplestorestate *state, int64 row);
+
extern int64 tuplestore_tuple_count(Tuplestorestate *state);
extern bool tuplestore_ateof(Tuplestorestate *state);
--
2.54.0 (Apple Git-157)
v3-0004-Use-absolute-tuplestore-positions-in-WindowAgg.patch (application/octet-stream, 8.1K) download
From 23b053eef59e8e48c356d0d38aa75a71398d822b Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Thu, 19 Nov 2026 13:30:33 +0900
Subject: [PATCH v3 4/4] Use absolute tuplestore positions in WindowAgg
WindowAgg kept its own idea of where each read pointer was (seekpos)
and moved the pointers by relative skips. WinSetMarkPosition() could
skip the read pointer past the stored rows, leaving it at EOF. An
active pointer at EOF follows later writes while seekpos does not, so
window_gettupleslot() then failed with "unexpected end of tuplestore".
Remove seekpos and position the pointers with tuplestore_tell() and
tuplestore_seek(). WinSetMarkPosition() never seeks past the stored
rows, so a WindowObject's pointer never reaches EOF.
Bug: #19911
Reported-by: Robins Tharakan <tharakan@gmail.com>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
---
src/backend/executor/nodeWindowAgg.c | 94 +++++++++-------------------
src/test/regress/expected/window.out | 12 ++++
src/test/regress/sql/window.sql | 8 +++
3 files changed, 48 insertions(+), 66 deletions(-)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 8d80f2cc023..fa204cb6313 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -70,8 +70,7 @@ typedef struct WindowObjectData
void *localmem; /* WinGetPartitionLocalMemory's chunk */
int markptr; /* tuplestore mark pointer for this fn */
int readptr; /* tuplestore read pointer for this fn */
- int64 markpos; /* row that markptr is positioned on */
- int64 seekpos; /* row that readptr is positioned on */
+ int64 markpos; /* oldest row fn may still fetch */
uint8 **notnull_info; /* not null info for each func args */
int64 *num_notnull_info; /* track size (number of tuples in
* partition) of the notnull_info array
@@ -1304,16 +1303,15 @@ begin_partition(WindowAggState *winstate)
{
WindowObject agg_winobj = winstate->agg_winobj;
- /* reset mark and see positions for aggregate functions */
+ /* reset mark position for aggregate functions */
agg_winobj->markpos = -1;
- agg_winobj->seekpos = -1;
/* Also reset the row counters for aggregates */
winstate->aggregatedbase = 0;
winstate->aggregatedupto = 0;
}
- /* reset mark and seek positions for each real window function */
+ /* reset mark position for each real window function */
for (int i = 0; i < numfuncs; i++)
{
WindowStatePerFunc perfuncstate = &(winstate->perfunc[i]);
@@ -1323,7 +1321,6 @@ begin_partition(WindowAggState *winstate)
WindowObject winobj = perfuncstate->winobj;
winobj->markpos = -1;
- winobj->seekpos = -1;
/* reset null map */
if (winobj->ignore_nulls == IGNORE_NULLS ||
@@ -3307,59 +3304,21 @@ window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
/*
- * Advance or rewind until we are within one tuple of the one we want.
+ * Position the read pointer on the wanted row by its absolute number; the
+ * partition's rows are numbered from 0 in the tuplestore.
*/
- if (winobj->seekpos < pos - 1)
- {
- if (!tuplestore_skiptuples(winstate->buffer,
- pos - 1 - winobj->seekpos,
- true))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos = pos - 1;
- }
- else if (winobj->seekpos > pos + 1)
- {
- if (!tuplestore_skiptuples(winstate->buffer,
- winobj->seekpos - (pos + 1),
- false))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos = pos + 1;
- }
- else if (winobj->seekpos == pos)
- {
- /*
- * There's no API to refetch the tuple at the current position. We
- * have to move one tuple forward, and then one backward. (We don't
- * do it the other way because we might try to fetch the row before
- * our mark, which isn't allowed.) XXX this case could stand to be
- * optimized.
- */
- tuplestore_advance(winstate->buffer, true);
- winobj->seekpos++;
- }
+ if (tuplestore_tell(winstate->buffer) != pos &&
+ !tuplestore_seek(winstate->buffer, pos))
+ elog(ERROR, "unexpected end of tuplestore");
+ Assert(!tuplestore_ateof(winstate->buffer));
/*
- * Now we should be on the tuple immediately before or after the one we
- * want, so just fetch forwards or backwards as appropriate.
- *
* Notice that we tell tuplestore_gettupleslot to make a physical copy of
* the fetched tuple. This ensures that the slot's contents remain valid
* through manipulations of the tuplestore, which some callers depend on.
*/
- if (winobj->seekpos > pos)
- {
- if (!tuplestore_gettupleslot(winstate->buffer, false, true, slot))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos--;
- }
- else
- {
- if (!tuplestore_gettupleslot(winstate->buffer, true, true, slot))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos++;
- }
-
- Assert(winobj->seekpos == pos);
+ if (!tuplestore_gettupleslot(winstate->buffer, true, true, slot))
+ elog(ERROR, "unexpected end of tuplestore");
MemoryContextSwitchTo(oldcontext);
@@ -3776,28 +3735,31 @@ void
WinSetMarkPosition(WindowObject winobj, int64 markpos)
{
WindowAggState *winstate;
+ int64 target;
Assert(WindowObjectIsValid(winobj));
winstate = winobj->winstate;
if (markpos < winobj->markpos)
elog(ERROR, "cannot move WindowObject's mark position backward");
+ winobj->markpos = markpos;
+
+ /*
+ * Leave each pointer just after the mark row, so that tuplestore_trim
+ * keeps it. Don't go past the rows stored so far; a pointer left behind
+ * only keeps a few more rows.
+ */
+ target = Min(markpos + 1, tuplestore_tuple_count(winstate->buffer));
tuplestore_select_read_pointer(winstate->buffer, winobj->markptr);
- if (markpos > winobj->markpos)
- {
- tuplestore_skiptuples(winstate->buffer,
- markpos - winobj->markpos,
- true);
- winobj->markpos = markpos;
- }
+ Assert(tuplestore_tell(winstate->buffer) <= target);
+ if (!tuplestore_seek(winstate->buffer, target))
+ elog(ERROR, "unexpected end of tuplestore");
+ Assert(!tuplestore_ateof(winstate->buffer));
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
- if (markpos > winobj->seekpos)
- {
- tuplestore_skiptuples(winstate->buffer,
- markpos - winobj->seekpos,
- true);
- winobj->seekpos = markpos;
- }
+ if (tuplestore_tell(winstate->buffer) < target &&
+ !tuplestore_seek(winstate->buffer, target))
+ elog(ERROR, "unexpected end of tuplestore");
+ Assert(!tuplestore_ateof(winstate->buffer));
}
/*
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index 112551c350b..061caa685d7 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -1452,6 +1452,18 @@ FROM tenk1 WHERE unique1 < 10;
| 7 | 3
(10 rows)
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+ count | sum
+-------+------
+ 2002 | 6005
+(1 row)
+
+RESET work_mem;
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
unique1, four
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index e848557174b..c4ff185d815 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -356,6 +356,14 @@ SELECT sum(unique1) over (ORDER BY four groups between 9223372036854775807 follo
unique1, four
FROM tenk1 WHERE unique1 < 10;
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+RESET work_mem;
+
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 6+ messages in thread
* Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
2026-11-18 02:03 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Tom Lane <tgl@sss.pgh.pa.us>
2026-11-18 03:51 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
2026-11-19 07:22 ` Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill Henson Choi <assam258@gmail.com>
@ 2026-11-23 01:06 ` Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 0 replies; 6+ messages in thread
From: Tom Lane @ 2026-11-23 01:06 UTC (permalink / raw)
To: assam258@gmail.com; +Cc: tharakan@gmail.com; pgsql-bugs@lists.postgresql.org
Henson Choi <assam258@gmail.com> writes:
>> In particular, if tuplestore had an API call to the
>> effect of "set the read pointer to absolute tuple number N", we
>> could get rid of a lot of silliness in WindowAgg. Having a call
>> to read out the position as an absolute tuple number might help
>> too, but I'm not sure we'd even need it if we had the first one.
> v3 follows that direction. There are four patches.
I looked this over and did some more work with it.
I don't like your 0001. Just because we haven't found a need for
a tuplestore holding non-heap tuples doesn't mean we never will.
Even if we wanted to go in that direction, a bug fix requiring
back-patching is not the place to do it. So I want to drop that.
Attached v4-0001 corresponds to your 0002. I did a little bit of
cosmetic work, such as rearranging the fields into what seemed to
me a more sensible order. But the main change is to add a
"rowstrimmed" field to track how many rows we've thrown away.
You were right that we could get away without that so far as
the INMEM state is concerned, but if we trim some rows and then
switch to file-based operations, your code would have misnumbered
the surviving rows. Having it also simplifies some boundary checks
in tuplestore_seek.
v4-0002 corresponds to your 0003. I redefined the APIs a bit
to allow distinguishing between the "past the last tuple" and
"eof_reached" states.
v4-0003 is new work to reimplement tuplestore_advance() and
tuplestore_skiptuples() on top of tuplestore_seek(). The
main reasons to do this are to shorten the code and provide
additional test coverage for tuplestore_seek, but I think that
this should also make these operations a bit cheaper in file mode,
since we'll avoid creating/pfreeing tuples.
v4-0004 corresponds to your 0004, and is only slightly different.
One point I didn't like is having WindowAgg know about the fact
that tuplestore keeps an additional tuple before what it's told
it can trim off. That's not documented as part of its API and
it's something we might well change.
> v3 is for master. For the back branches, I'd like your view on
> whether to use this series or v2. It applies to REL_19 as is; 14 to
> 18 need small context adjustments.
I'm inclined to keep the code the same in all branches.
regards, tom lane
Attachments: download all (4 files, .tar.gz)
v4-0001-Track-absolute-row-numbers-in-tuplestore-read-poi.patch (text/x-diff, 15.2K) download
From 6c4c4e151a7667dd7d1ec1c7b240f0d8292a2799 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sun, 22 Nov 2026 11:28:06 -0500
Subject: [PATCH v4 1/4] Track absolute row numbers in tuplestore read
pointers.
Each read pointer now records the absolute number of the next tuple
it would return, counted from 0 since creation or the last
tuplestore_clear(). tuplestore_trim() does not change row numbers.
This is infrastructure work leading to a fix for the cited bug.
Bug: #19911
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 15
---
src/backend/utils/sort/tuplestore.c | 143 +++++++++++++++++++++++++---
1 file changed, 128 insertions(+), 15 deletions(-)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index 610ddf00532..4f0d3571abb 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -78,22 +78,39 @@ typedef enum
} TupStoreStatus;
/*
- * State for a single read pointer. If we are in state INMEM then all the
- * read pointers' "current" fields denote the read positions. In state
- * WRITEFILE, the file/offset fields denote the read positions. In state
- * READFILE, inactive read pointers have valid file/offset, but the active
- * read pointer implicitly has position equal to the temp file's seek position.
+ * State for a single read pointer.
*
- * Special case: if eof_reached is true, then the pointer's read position is
- * implicitly equal to the write position, and current/file/offset aren't
- * maintained. This way we need not update all the read pointers each time
- * we write.
+ * eflags shows the capability flags required for this pointer (which can
+ * be different from one pointer to another).
+ *
+ * eof_reached is set true when a forward read fails due to reaching EOF.
+ * While it is true, the pointer's read position is implicitly equal to the
+ * write position, and we do not maintain row/current/file/offset. This
+ * rule saves us from having to update read pointers each time we write.
+ *
+ * row is the absolute row number of the next record to be read by this
+ * pointer, counting from 0 as the first record inserted after tuplestore
+ * creation or tuplestore_clear(). (Note that tuplestore_trim() does not
+ * renumber rows, though it does make earlier rows inaccessible.)
+ *
+ * current is valid only in state INMEM: it is the pointer's current read
+ * position as an index into the in-memory array.
+ *
+ * file/offset are valid in the non-INMEM states: they denote the pointer's
+ * current read position in the underlying BufFile. In state WRITEFILE,
+ * all the file/offset fields are valid. In state READFILE, inactive read
+ * pointers have valid file/offset, but the active read pointer implicitly
+ * has position equal to the temp file's seek position.
*/
typedef struct
{
int eflags; /* capability flags */
bool eof_reached; /* read has reached EOF */
+ /* remaining fields are only valid when !eof_reached */
+ int64 row; /* next absolute row number to read */
+ /* fields only valid in INMEM state: */
int current; /* next array index to read */
+ /* fields only valid in WRITEFILE/READFILE state: */
int file; /* temp file# */
pgoff_t offset; /* byte offset in file */
} TSReadPointer;
@@ -158,7 +175,7 @@ struct Tuplestorestate
* released due to a tuplestore_trim() operation, but we haven't expended
* the effort to slide the remaining pointers down. These unused pointers
* are set to NULL to catch any invalid accesses. Note that memtupcount
- * includes the deleted pointers.
+ * includes these deleted pointers.
*/
void **memtuples; /* array of pointers to palloc'd tuples */
int memtupdeleted; /* the first N slots are currently unused */
@@ -166,6 +183,17 @@ struct Tuplestorestate
int memtupsize; /* allocated length of memtuples array */
bool growmemtuples; /* memtuples' growth still underway? */
+ /*
+ * rowstrimmed is the absolute row number of memtuples[0] while we're in
+ * INMEM state; when we switch to file state, it becomes the absolute row
+ * number of the first row in the file. This is redundant information
+ * while we're in INMEM state, because state->tuples is always the total
+ * number of tuples inserted into the tuplestore, so that the last valid
+ * array entry always has absolute row number state->tuples - 1. However,
+ * once we switch to a file state it's not redundant.
+ */
+ int64 rowstrimmed; /* reference point for tuple row numbers */
+
/*
* These variables are used to keep track of the current positions.
*
@@ -241,6 +269,11 @@ static Tuplestorestate *tuplestore_begin_common(int eflags,
int maxKBytes);
static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple);
static void dumptuples(Tuplestorestate *state);
+#ifdef USE_ASSERT_CHECKING
+static void check_read_pointer_rows(Tuplestorestate *state);
+#else
+#define check_read_pointer_rows(state) ((void) 0)
+#endif
static void tuplestore_updatemax(Tuplestorestate *state);
static unsigned int getlen(Tuplestorestate *state, bool eofOK);
static void *copytup_heap(Tuplestorestate *state, void *tup);
@@ -281,6 +314,7 @@ tuplestore_begin_common(int eflags, bool interXact, int maxKBytes)
state->memtupdeleted = 0;
state->memtupcount = 0;
+ state->rowstrimmed = 0;
state->tuples = 0;
/*
@@ -302,6 +336,7 @@ tuplestore_begin_common(int eflags, bool interXact, int maxKBytes)
state->readptrs[0].eflags = eflags;
state->readptrs[0].eof_reached = false;
+ state->readptrs[0].row = 0;
state->readptrs[0].current = 0;
return state;
@@ -422,8 +457,8 @@ tuplestore_alloc_read_pointer(Tuplestorestate *state, int eflags)
/*
* tuplestore_clear
*
- * Delete all the contents of a tuplestore, and reset its read pointers
- * to the start.
+ * Delete all the contents of a tuplestore, reset its read pointers
+ * to the start, and reset absolute row numbers to start at zero.
*/
void
tuplestore_clear(Tuplestorestate *state)
@@ -473,11 +508,13 @@ tuplestore_clear(Tuplestorestate *state)
state->truncated = false;
state->memtupdeleted = 0;
state->memtupcount = 0;
+ state->rowstrimmed = 0;
state->tuples = 0;
readptr = state->readptrs;
for (i = 0; i < state->readptrcount; readptr++, i++)
{
readptr->eof_reached = false;
+ readptr->row = 0;
readptr->current = 0;
}
}
@@ -510,6 +547,8 @@ tuplestore_select_read_pointer(Tuplestorestate *state, int ptr)
Assert(ptr >= 0 && ptr < state->readptrcount);
+ check_read_pointer_rows(state);
+
/* No work if already active */
if (ptr == state->activeptr)
return;
@@ -802,7 +841,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
ResourceOwner oldowner;
MemoryContext oldcxt;
- state->tuples++;
+ check_read_pointer_rows(state);
switch (state->status)
{
@@ -817,6 +856,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
if (readptr->eof_reached && i != state->activeptr)
{
readptr->eof_reached = false;
+ readptr->row = state->tuples;
readptr->current = state->memtupcount;
}
}
@@ -835,6 +875,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
/* Stash the tuple in the in-memory array */
state->memtuples[state->memtupcount++] = tuple;
+ state->tuples++;
/*
* Done if we still fit in available memory and have array slots.
@@ -895,6 +936,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
if (readptr->eof_reached && i != state->activeptr)
{
readptr->eof_reached = false;
+ readptr->row = state->tuples;
BufFileTell(state->myfile,
&readptr->file,
&readptr->offset);
@@ -902,6 +944,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
}
WRITETUP(state, tuple);
+ state->tuples++;
break;
case TSS_READFILE:
@@ -929,12 +972,14 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
if (readptr->eof_reached && i != state->activeptr)
{
readptr->eof_reached = false;
+ readptr->row = state->tuples;
readptr->file = state->writepos_file;
readptr->offset = state->writepos_offset;
}
}
WRITETUP(state, tuple);
+ state->tuples++;
break;
default:
elog(ERROR, "invalid tuplestore state");
@@ -960,6 +1005,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD));
+ check_read_pointer_rows(state);
+
switch (state->status)
{
case TSS_INMEM:
@@ -971,6 +1018,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->current < state->memtupcount)
{
/* We have another tuple, so return it */
+ readptr->row++;
return state->memtuples[readptr->current++];
}
readptr->eof_reached = true;
@@ -984,6 +1032,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
*/
if (readptr->eof_reached)
{
+ readptr->row = state->tuples;
readptr->current = state->memtupcount;
readptr->eof_reached = false;
}
@@ -994,7 +1043,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
Assert(!state->truncated);
return NULL;
}
- readptr->current--; /* last returned tuple */
+ readptr->row--; /* last returned tuple */
+ readptr->current--;
}
if (readptr->current <= state->memtupdeleted)
{
@@ -1032,6 +1082,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if ((tuplen = getlen(state, true)) != 0)
{
tup = READTUP(state, tuplen);
+ readptr->row++;
return tup;
}
else
@@ -1055,6 +1106,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
{
/* even a failed backwards fetch gets you out of eof state */
readptr->eof_reached = false;
+ readptr->row = state->rowstrimmed;
Assert(!state->truncated);
return NULL;
}
@@ -1063,6 +1115,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
if (readptr->eof_reached)
{
readptr->eof_reached = false;
+ readptr->row = state->tuples;
/* We will return the tuple returned before returning NULL */
}
else
@@ -1086,10 +1139,12 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not seek in tuplestore temporary file")));
+ readptr->row = state->rowstrimmed;
Assert(!state->truncated);
return NULL;
}
tuplen = getlen(state, false);
+ readptr->row--;
}
/*
@@ -1221,6 +1276,8 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD));
+ check_read_pointer_rows(state);
+
if (ntuples <= 0)
return true;
@@ -1233,9 +1290,11 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
return false;
if (state->memtupcount - readptr->current >= ntuples)
{
+ readptr->row += ntuples;
readptr->current += ntuples;
return true;
}
+ readptr->row = state->tuples;
readptr->current = state->memtupcount;
readptr->eof_reached = true;
return false;
@@ -1244,16 +1303,19 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
{
if (readptr->eof_reached)
{
+ readptr->row = state->tuples;
readptr->current = state->memtupcount;
readptr->eof_reached = false;
ntuples--;
}
if (readptr->current - state->memtupdeleted > ntuples)
{
+ readptr->row -= ntuples;
readptr->current -= ntuples;
return true;
}
Assert(!state->truncated);
+ readptr->row -= readptr->current - state->memtupdeleted;
readptr->current = state->memtupdeleted;
return false;
}
@@ -1290,6 +1352,9 @@ dumptuples(Tuplestorestate *state)
{
int i;
+ /* Make rowstrimmed = row number of the oldest tuple we still have */
+ state->rowstrimmed += state->memtupdeleted;
+
for (i = state->memtupdeleted;; i++)
{
TSReadPointer *readptr = state->readptrs;
@@ -1330,21 +1395,26 @@ tuplestore_rescan(Tuplestorestate *state)
TSReadPointer *readptr = &state->readptrs[state->activeptr];
Assert(readptr->eflags & EXEC_FLAG_REWIND);
+ /* REWIND should have prevented trimming any tuples */
Assert(!state->truncated);
+ Assert(state->rowstrimmed == 0);
switch (state->status)
{
case TSS_INMEM:
readptr->eof_reached = false;
+ readptr->row = 0;
readptr->current = 0;
break;
case TSS_WRITEFILE:
readptr->eof_reached = false;
+ readptr->row = 0;
readptr->file = 0;
readptr->offset = 0;
break;
case TSS_READFILE:
readptr->eof_reached = false;
+ readptr->row = 0;
if (BufFileSeek(state->myfile, 0, 0, SEEK_SET) != 0)
ereport(ERROR,
(errcode_for_file_access(),
@@ -1373,6 +1443,8 @@ tuplestore_copy_read_pointer(Tuplestorestate *state,
if (srcptr == destptr)
return;
+ check_read_pointer_rows(state);
+
if (dptr->eflags != sptr->eflags)
{
/* Possible change of overall eflags, so copy and then recompute */
@@ -1444,7 +1516,8 @@ tuplestore_copy_read_pointer(Tuplestorestate *state,
*
* Calling this function authorizes the tuplestore to delete all tuples
* before the oldest read pointer, if no read pointer is marked as requiring
- * REWIND capability.
+ * REWIND capability. However, such deletion doesn't change the absolute
+ * row numbers associated with tuples or read pointer positions.
*
* Note: this is obviously safe if no pointer has BACKWARD capability either.
* If a pointer is marked as BACKWARD but not REWIND capable, it means that
@@ -1472,6 +1545,8 @@ tuplestore_trim(Tuplestorestate *state)
if (state->status != TSS_INMEM)
return;
+ check_read_pointer_rows(state);
+
/* Find the oldest read pointer */
oldest = state->memtupcount;
for (i = 0; i < state->readptrcount; i++)
@@ -1537,12 +1612,50 @@ tuplestore_trim(Tuplestorestate *state)
state->memtupdeleted = 0;
state->memtupcount -= nremove;
+ state->rowstrimmed += nremove;
for (i = 0; i < state->readptrcount; i++)
{
if (!state->readptrs[i].eof_reached)
state->readptrs[i].current -= nremove;
}
+
+ check_read_pointer_rows(state);
+}
+
+/*
+ * Validate each read pointer's absolute row number against other state.
+ */
+#ifdef USE_ASSERT_CHECKING
+static void
+check_read_pointer_rows(Tuplestorestate *state)
+{
+ /* base is the row number of memtuples[0], if we're in INMEM state */
+ int64 base = state->tuples - state->memtupcount;
+ int64 oldest;
+
+ /* calculate row number of oldest still-accessible tuple */
+ if (state->status == TSS_INMEM)
+ {
+ Assert(base == state->rowstrimmed);
+ oldest = base + state->memtupdeleted;
+ }
+ else
+ oldest = state->rowstrimmed;
+
+ for (int i = 0; i < state->readptrcount; i++)
+ {
+ TSReadPointer *readptr = &state->readptrs[i];
+
+ if (readptr->eof_reached)
+ continue; /* row is not valid in eof_reached state */
+ /* row mustn't be before oldest tuple, nor beyond the EOF point */
+ Assert(readptr->row >= oldest && readptr->row <= state->tuples);
+ if (state->status == TSS_INMEM)
+ Assert(readptr->row == base + readptr->current);
+ /* in the file states there's no equivalently simple check */
+ }
}
+#endif
/*
* tuplestore_updatemax
--
2.52.0
v4-0002-Add-tuplestore_tell-and-tuplestore_seek.patch (text/x-diff, 9.7K) download
From a39dedce3b05b0fa5c90b4b8f97e222bd6b563aa Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sun, 22 Nov 2026 17:50:28 -0500
Subject: [PATCH v4 2/4] Add tuplestore_tell() and tuplestore_seek().
tuplestore_tell() returns the absolute number of the row the next
forward fetch would return, or nrows+1 if already at EOF.
tuplestore_seek() moves the active read pointer to an absolute row
number in 0..nrows, or sets it to EOF if passed nrows+1.
This is infrastructure work leading to a fix for the cited bug.
Bug: #19911
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 15
---
src/backend/utils/sort/tuplestore.c | 230 +++++++++++++++++++++++-----
src/include/utils/tuplestore.h | 4 +
2 files changed, 195 insertions(+), 39 deletions(-)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index 4f0d3571abb..aacab4d0116 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -269,6 +269,9 @@ static Tuplestorestate *tuplestore_begin_common(int eflags,
int maxKBytes);
static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple);
static void dumptuples(Tuplestorestate *state);
+static void switch_to_readfile(Tuplestorestate *state);
+static bool step_record_forward(Tuplestorestate *state);
+static bool step_record_backward(Tuplestorestate *state);
#ifdef USE_ASSERT_CHECKING
static void check_read_pointer_rows(Tuplestorestate *state);
#else
@@ -923,29 +926,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
state->status = TSS_WRITEFILE;
dumptuples(state);
break;
- case TSS_WRITEFILE:
- /*
- * Update read pointers as needed; see API spec above. Note:
- * BufFileTell is quite cheap, so not worth trying to avoid
- * multiple calls.
- */
- readptr = state->readptrs;
- for (i = 0; i < state->readptrcount; readptr++, i++)
- {
- if (readptr->eof_reached && i != state->activeptr)
- {
- readptr->eof_reached = false;
- readptr->row = state->tuples;
- BufFileTell(state->myfile,
- &readptr->file,
- &readptr->offset);
- }
- }
-
- WRITETUP(state, tuple);
- state->tuples++;
- break;
case TSS_READFILE:
/*
@@ -962,9 +943,14 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
(errcode_for_file_access(),
errmsg("could not seek in tuplestore temporary file")));
state->status = TSS_WRITEFILE;
+ pg_fallthrough;
+
+ case TSS_WRITEFILE:
/*
- * Update read pointers as needed; see API spec above.
+ * Update read pointers as needed; see API spec above. Note:
+ * BufFileTell is quite cheap, so not worth trying to avoid
+ * multiple calls.
*/
readptr = state->readptrs;
for (i = 0; i < state->readptrcount; readptr++, i++)
@@ -973,8 +959,9 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
{
readptr->eof_reached = false;
readptr->row = state->tuples;
- readptr->file = state->writepos_file;
- readptr->offset = state->writepos_offset;
+ BufFileTell(state->myfile,
+ &readptr->file,
+ &readptr->offset);
}
}
@@ -1059,20 +1046,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forward,
/* Skip state change if we'll just return NULL */
if (readptr->eof_reached && forward)
return NULL;
-
- /*
- * Switch from writing to reading.
- */
- BufFileTell(state->myfile,
- &state->writepos_file, &state->writepos_offset);
- if (!readptr->eof_reached)
- if (BufFileSeek(state->myfile,
- readptr->file, readptr->offset,
- SEEK_SET) != 0)
- ereport(ERROR,
- (errcode_for_file_access(),
- errmsg("could not seek in tuplestore temporary file")));
- state->status = TSS_READFILE;
+ switch_to_readfile(state);
pg_fallthrough;
case TSS_READFILE:
@@ -1340,6 +1314,113 @@ tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
}
}
+/*
+ * tuplestore_tell - return the active read pointer's absolute row number
+ *
+ * If the read pointer is "at EOF" then the result is state->tuples + 1;
+ * otherwise it is in the range 0..state->tuples.
+ */
+int64
+tuplestore_tell(Tuplestorestate *state)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+
+ return readptr->eof_reached ? (state->tuples + 1) : readptr->row;
+}
+
+/*
+ * tuplestore_seek - move the active read pointer to an absolute row number
+ *
+ * The argument is interpreted as per tuplestore_tell(); in particular,
+ * row = state->tuples + 1 causes the pointer to be set "at EOF", while
+ * row = state->tuples causes the pointer to be set after the last stored
+ * row but not "at EOF".
+ *
+ * Returns true if successful, false if the argument is out of range
+ * (including pointing to a trimmed-away tuple); the tuplestore state
+ * is unchanged in the latter case.
+ *
+ * Moving backward requires EXEC_FLAG_BACKWARD.
+ */
+bool
+tuplestore_seek(Tuplestorestate *state, int64 row)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+ int64 cur;
+
+ check_read_pointer_rows(state);
+
+ /* Quick exit if row is obviously bogus */
+ if (row < state->rowstrimmed || row > state->tuples + 1)
+ return false;
+ /* Quick exit for no-op requests */
+ cur = tuplestore_tell(state);
+ if (row == cur)
+ return true;
+ Assert(row > cur || (readptr->eflags & EXEC_FLAG_BACKWARD));
+
+ switch (state->status)
+ {
+ case TSS_INMEM:
+ {
+ int64 base = state->tuples - state->memtupcount;
+
+ if (row < base + state->memtupdeleted)
+ return false;
+ if (row > state->tuples)
+ readptr->eof_reached = true;
+ else
+ {
+ readptr->eof_reached = false;
+ readptr->row = row;
+ readptr->current = (int) (row - base);
+ }
+ return true;
+ }
+
+ case TSS_WRITEFILE:
+ switch_to_readfile(state);
+ pg_fallthrough;
+
+ case TSS_READFILE:
+ /* We must seek the file to the correct tuple */
+ if (readptr->eof_reached)
+ {
+ /* Return to the state of being just past the last tuple */
+ readptr->eof_reached = false;
+ readptr->row = state->tuples;
+ }
+
+ while (readptr->row < row)
+ {
+ /* This should fail only when we're advancing to "at EOF" */
+ if (!step_record_forward(state))
+ {
+ Assert(readptr->row == state->tuples);
+ readptr->eof_reached = true;
+ return true;
+ }
+ readptr->row++;
+ CHECK_FOR_INTERRUPTS();
+ }
+ while (readptr->row > row)
+ {
+ /* This should not fail given prior test against rowstrimmed */
+ if (!step_record_backward(state))
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ readptr->row--;
+ CHECK_FOR_INTERRUPTS();
+ }
+ return true;
+
+ default:
+ elog(ERROR, "invalid tuplestore state");
+ return false; /* keep compiler quiet */
+ }
+}
+
/*
* dumptuples - remove tuples from memory and write to tape
*
@@ -1386,6 +1467,77 @@ dumptuples(Tuplestorestate *state)
state->memtupcount = 0;
}
+/*
+ * switch_to_readfile - switch from state TSS_WRITEFILE to TSS_READFILE
+ *
+ * Save the write position and seek to the active read pointer's position.
+ */
+static void
+switch_to_readfile(Tuplestorestate *state)
+{
+ TSReadPointer *readptr = &state->readptrs[state->activeptr];
+
+ Assert(state->status == TSS_WRITEFILE);
+ BufFileTell(state->myfile,
+ &state->writepos_file, &state->writepos_offset);
+ if (!readptr->eof_reached)
+ if (BufFileSeek(state->myfile,
+ readptr->file, readptr->offset,
+ SEEK_SET) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ state->status = TSS_READFILE;
+}
+
+/*
+ * step_record_forward - move the temp file position forward by one tuple
+ *
+ * Returns false, without moving, at the end of the file.
+ */
+static bool
+step_record_forward(Tuplestorestate *state)
+{
+ unsigned int tuplen = getlen(state, true);
+ pgoff_t rest;
+
+ if (tuplen == 0)
+ return false;
+ if (state->backward)
+ rest = tuplen;
+ else
+ rest = tuplen - sizeof(unsigned int);
+ if (BufFileSeek(state->myfile, 0, rest, SEEK_CUR) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ return true;
+}
+
+/*
+ * step_record_backward - move the temp file position backward by one tuple
+ *
+ * Returns false, without moving, at the start of the file.
+ */
+static bool
+step_record_backward(Tuplestorestate *state)
+{
+ unsigned int tuplen;
+
+ Assert(state->backward);
+ if (BufFileSeek(state->myfile, 0, -(pgoff_t) sizeof(unsigned int),
+ SEEK_CUR) != 0)
+ return false;
+ tuplen = getlen(state, false);
+ if (BufFileSeek(state->myfile, 0,
+ -(pgoff_t) (tuplen + sizeof(unsigned int)),
+ SEEK_CUR) != 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not seek in tuplestore temporary file")));
+ return true;
+}
+
/*
* tuplestore_rescan - rewind the active read pointer to start
*/
diff --git a/src/include/utils/tuplestore.h b/src/include/utils/tuplestore.h
index 12dc51b81d2..c0a447f46dc 100644
--- a/src/include/utils/tuplestore.h
+++ b/src/include/utils/tuplestore.h
@@ -82,6 +82,10 @@ extern bool tuplestore_advance(Tuplestorestate *state, bool forward);
extern bool tuplestore_skiptuples(Tuplestorestate *state,
int64 ntuples, bool forward);
+extern int64 tuplestore_tell(Tuplestorestate *state);
+
+extern bool tuplestore_seek(Tuplestorestate *state, int64 row);
+
extern int64 tuplestore_tuple_count(Tuplestorestate *state);
extern bool tuplestore_ateof(Tuplestorestate *state);
--
2.52.0
v4-0003-Reimplement-tuplestore_advance-and-tuplestore_ski.patch (text/x-diff, 4.2K) download
From 345f34593fbb90a2faeb59b6320b516eae14c808 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sun, 22 Nov 2026 17:55:55 -0500
Subject: [PATCH v4 3/4] Reimplement tuplestore_advance() and
tuplestore_skiptuples().
We can now turn these into thin wrappers around tuplestore_seek().
This gives some small performance improvement because it removes
the overhead of forming and deleting tuples, but the main point
is just to have a localized way of testing tuplestore_seek().
This is infrastructure work leading to a fix for the cited bug.
Bug: #19911
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 15
---
src/backend/utils/sort/tuplestore.c | 104 ++++++++--------------------
1 file changed, 29 insertions(+), 75 deletions(-)
diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c
index aacab4d0116..2602278e6ce 100644
--- a/src/backend/utils/sort/tuplestore.c
+++ b/src/backend/utils/sort/tuplestore.c
@@ -1215,27 +1215,12 @@ tuplestore_gettupleslot_force(Tuplestorestate *state, bool forward,
/*
* tuplestore_advance - exported function to adjust position without fetching
*
- * We could optimize this case to avoid palloc/pfree overhead, but for the
- * moment it doesn't seem worthwhile.
+ * Returns true if able to advance over a tuple, false if not.
*/
bool
tuplestore_advance(Tuplestorestate *state, bool forward)
{
- void *tuple;
- bool should_free;
-
- tuple = tuplestore_gettuple(state, forward, &should_free);
-
- if (tuple)
- {
- if (should_free)
- pfree(tuple);
- return true;
- }
- else
- {
- return false;
- }
+ return tuplestore_skiptuples(state, 1, forward);
}
/*
@@ -1247,70 +1232,39 @@ bool
tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
{
TSReadPointer *readptr = &state->readptrs[state->activeptr];
-
- Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD));
-
- check_read_pointer_rows(state);
+ int64 limit;
if (ntuples <= 0)
return true;
- switch (state->status)
+ if (forward)
{
- case TSS_INMEM:
- if (forward)
- {
- if (readptr->eof_reached)
- return false;
- if (state->memtupcount - readptr->current >= ntuples)
- {
- readptr->row += ntuples;
- readptr->current += ntuples;
- return true;
- }
- readptr->row = state->tuples;
- readptr->current = state->memtupcount;
- readptr->eof_reached = true;
- return false;
- }
- else
- {
- if (readptr->eof_reached)
- {
- readptr->row = state->tuples;
- readptr->current = state->memtupcount;
- readptr->eof_reached = false;
- ntuples--;
- }
- if (readptr->current - state->memtupdeleted > ntuples)
- {
- readptr->row -= ntuples;
- readptr->current -= ntuples;
- return true;
- }
- Assert(!state->truncated);
- readptr->row -= readptr->current - state->memtupdeleted;
- readptr->current = state->memtupdeleted;
+ if (readptr->eof_reached)
+ return false;
+ else
+ {
+ limit = state->tuples - readptr->row + 1;
+ /* If ntuples > limit, return false after advancing to EOF */
+ if (!tuplestore_seek(state, readptr->row + Min(limit, ntuples)))
return false;
- }
- break;
-
- default:
- /* We don't currently try hard to optimize other cases */
- while (ntuples-- > 0)
- {
- void *tuple;
- bool should_free;
-
- tuple = tuplestore_gettuple(state, forward, &should_free);
-
- if (tuple == NULL)
- return false;
- if (should_free)
- pfree(tuple);
- CHECK_FOR_INTERRUPTS();
- }
- return true;
+ return (ntuples <= limit);
+ }
+ }
+ else
+ {
+ if (readptr->eof_reached)
+ {
+ /* Return to the state of being just past the last tuple */
+ readptr->eof_reached = false;
+ readptr->row = state->tuples;
+ }
+ limit = readptr->row - state->rowstrimmed;
+ if (state->status == TSS_INMEM)
+ limit -= state->memtupdeleted;
+ /* If ntuples > limit, return false after moving to start */
+ if (!tuplestore_seek(state, readptr->row - Min(limit, ntuples)))
+ return false;
+ return (ntuples <= limit);
}
}
--
2.52.0
v4-0004-Use-absolute-tuplestore-positions-in-WindowAgg.patch (text/x-diff, 8.5K) download
From 12df4c5961b6940733a5ef7feb72808f2585c390 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sun, 22 Nov 2026 18:54:52 -0500
Subject: [PATCH v4 4/4] Use absolute tuplestore positions in WindowAgg.
WindowAgg kept its own idea of where each read pointer was (seekpos)
and moved the pointers by relative skips. However, its tracking was
inaccurate. WinSetMarkPosition() could advance the read pointer past
the stored rows, leaving it at EOF. An active pointer at EOF follows
later writes while seekpos does not, so window_gettupleslot() then
failed with "unexpected end of tuplestore".
Rather than trying to fix up that logic, let's remove seekpos and
position the pointers with tuplestore_tell() and tuplestore_seek().
Bug: #19911
Reported-by: Robins Tharakan <tharakan@gmail.com>
Author: Henson Choi <assam258@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org
Backpatch-through: 15
---
src/backend/executor/nodeWindowAgg.c | 100 +++++++++------------------
src/test/regress/expected/window.out | 12 ++++
src/test/regress/sql/window.sql | 8 +++
3 files changed, 51 insertions(+), 69 deletions(-)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 8d80f2cc023..1b2b008ec9d 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -70,8 +70,7 @@ typedef struct WindowObjectData
void *localmem; /* WinGetPartitionLocalMemory's chunk */
int markptr; /* tuplestore mark pointer for this fn */
int readptr; /* tuplestore read pointer for this fn */
- int64 markpos; /* row that markptr is positioned on */
- int64 seekpos; /* row that readptr is positioned on */
+ int64 markpos; /* oldest row this fn may still fetch */
uint8 **notnull_info; /* not null info for each func args */
int64 *num_notnull_info; /* track size (number of tuples in
* partition) of the notnull_info array
@@ -1294,9 +1293,15 @@ begin_partition(WindowAggState *winstate)
}
}
- /* Create new tuplestore if not done already. */
+ /*
+ * Create new tuplestore if not done already. If we do have one, check
+ * that it was cleared by release_partition; this is important since we
+ * depend on absolute row numbering within the tuplestore.
+ */
if (unlikely(winstate->buffer == NULL))
prepare_tuplestore(winstate);
+ else
+ Assert(tuplestore_tuple_count(winstate->buffer) == 0);
winstate->next_partition = false;
@@ -1304,16 +1309,15 @@ begin_partition(WindowAggState *winstate)
{
WindowObject agg_winobj = winstate->agg_winobj;
- /* reset mark and see positions for aggregate functions */
- agg_winobj->markpos = -1;
- agg_winobj->seekpos = -1;
+ /* Reset mark position for aggregate functions */
+ agg_winobj->markpos = 0;
/* Also reset the row counters for aggregates */
winstate->aggregatedbase = 0;
winstate->aggregatedupto = 0;
}
- /* reset mark and seek positions for each real window function */
+ /* Reset mark position for each real window function */
for (int i = 0; i < numfuncs; i++)
{
WindowStatePerFunc perfuncstate = &(winstate->perfunc[i]);
@@ -1322,8 +1326,7 @@ begin_partition(WindowAggState *winstate)
{
WindowObject winobj = perfuncstate->winobj;
- winobj->markpos = -1;
- winobj->seekpos = -1;
+ winobj->markpos = 0;
/* reset null map */
if (winobj->ignore_nulls == IGNORE_NULLS ||
@@ -3307,59 +3310,19 @@ window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
/*
- * Advance or rewind until we are within one tuple of the one we want.
+ * Position the read pointer on the wanted row by its absolute number; the
+ * partition's rows are numbered from 0 in the tuplestore.
*/
- if (winobj->seekpos < pos - 1)
- {
- if (!tuplestore_skiptuples(winstate->buffer,
- pos - 1 - winobj->seekpos,
- true))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos = pos - 1;
- }
- else if (winobj->seekpos > pos + 1)
- {
- if (!tuplestore_skiptuples(winstate->buffer,
- winobj->seekpos - (pos + 1),
- false))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos = pos + 1;
- }
- else if (winobj->seekpos == pos)
- {
- /*
- * There's no API to refetch the tuple at the current position. We
- * have to move one tuple forward, and then one backward. (We don't
- * do it the other way because we might try to fetch the row before
- * our mark, which isn't allowed.) XXX this case could stand to be
- * optimized.
- */
- tuplestore_advance(winstate->buffer, true);
- winobj->seekpos++;
- }
+ if (!tuplestore_seek(winstate->buffer, pos))
+ elog(ERROR, "unexpected end of tuplestore");
/*
- * Now we should be on the tuple immediately before or after the one we
- * want, so just fetch forwards or backwards as appropriate.
- *
* Notice that we tell tuplestore_gettupleslot to make a physical copy of
* the fetched tuple. This ensures that the slot's contents remain valid
* through manipulations of the tuplestore, which some callers depend on.
*/
- if (winobj->seekpos > pos)
- {
- if (!tuplestore_gettupleslot(winstate->buffer, false, true, slot))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos--;
- }
- else
- {
- if (!tuplestore_gettupleslot(winstate->buffer, true, true, slot))
- elog(ERROR, "unexpected end of tuplestore");
- winobj->seekpos++;
- }
-
- Assert(winobj->seekpos == pos);
+ if (!tuplestore_gettupleslot(winstate->buffer, true, true, slot))
+ elog(ERROR, "unexpected end of tuplestore");
MemoryContextSwitchTo(oldcontext);
@@ -3776,28 +3739,27 @@ void
WinSetMarkPosition(WindowObject winobj, int64 markpos)
{
WindowAggState *winstate;
+ int64 target;
Assert(WindowObjectIsValid(winobj));
winstate = winobj->winstate;
if (markpos < winobj->markpos)
elog(ERROR, "cannot move WindowObject's mark position backward");
+ winobj->markpos = markpos;
+ /* Don't try to move the mark pointer past current EOF */
+ target = tuplestore_tuple_count(winstate->buffer);
+ target = Min(markpos, target);
tuplestore_select_read_pointer(winstate->buffer, winobj->markptr);
- if (markpos > winobj->markpos)
- {
- tuplestore_skiptuples(winstate->buffer,
- markpos - winobj->markpos,
- true);
- winobj->markpos = markpos;
- }
+ Assert(tuplestore_tell(winstate->buffer) <= target);
+ if (!tuplestore_seek(winstate->buffer, target))
+ elog(ERROR, "unexpected end of tuplestore");
+ Assert(!tuplestore_ateof(winstate->buffer));
tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
- if (markpos > winobj->seekpos)
- {
- tuplestore_skiptuples(winstate->buffer,
- markpos - winobj->seekpos,
- true);
- winobj->seekpos = markpos;
- }
+ if (tuplestore_tell(winstate->buffer) < target &&
+ !tuplestore_seek(winstate->buffer, target))
+ elog(ERROR, "unexpected end of tuplestore");
+ Assert(!tuplestore_ateof(winstate->buffer));
}
/*
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index 112551c350b..061caa685d7 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -1452,6 +1452,18 @@ FROM tenk1 WHERE unique1 < 10;
| 7 | 3
(10 rows)
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+ count | sum
+-------+------
+ 2002 | 6005
+(1 row)
+
+RESET work_mem;
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
unique1, four
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index e848557174b..c4ff185d815 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -356,6 +356,14 @@ SELECT sum(unique1) over (ORDER BY four groups between 9223372036854775807 follo
unique1, four
FROM tenk1 WHERE unique1 < 10;
+-- frame head on the next row, not yet stored, when the tuplestore spills
+SET work_mem = '64kB';
+SELECT count(*), sum(s) FROM
+ (SELECT sum(i) OVER (ORDER BY i ROWS BETWEEN 2000 FOLLOWING
+ AND UNBOUNDED FOLLOWING) s
+ FROM generate_series(1, 2002) i) t;
+RESET work_mem;
+
-- RANGE offset PRECEDING/FOLLOWING tests
SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding),
--
2.52.0
^ permalink raw reply [nested|flat] 6+ messages in thread
end of thread, other threads:[~2026-11-23 01:06 UTC | newest]
Thread overview: 6+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-11-17 13:18 BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill PG Bug reporting form <noreply@postgresql.org>
2026-11-18 01:05 ` Henson Choi <assam258@gmail.com>
2026-11-18 02:03 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-11-18 03:51 ` Henson Choi <assam258@gmail.com>
2026-11-19 07:22 ` Henson Choi <assam258@gmail.com>
2026-11-23 01:06 ` 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