From: Tom Lane <tgl@sss.pgh.pa.us>
To: assam258@gmail.com
Cc: tharakan@gmail.com
Cc: pgsql-bugs@lists.postgresql.org
Subject: Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
Date: Sun, 22 Nov 2026 20:06:02 -0500
Message-ID: <742405.1795395962@sss.pgh.pa.us> (raw)
In-Reply-To: <CAAAe_zBzVHBabZeD3GMSQsEKAe7CZAw_LZHrf3bgPR3bdtKY5Q@mail.gmail.com>
References: <19911-991c431cc0ba50d1@postgresql.org>
<CAAAe_zCRzOjsr2y_WG149sY52xusNo2KuLQGgw0vta0uMvVpmw@mail.gmail.com>
<601850.1794967393@sss.pgh.pa.us>
<CAAAe_zC=2KN_seGKj+G6s7S5-33b6tZ9s_VhA_4PusAdD3bhCw@mail.gmail.com>
<CAAAe_zBzVHBabZeD3GMSQsEKAe7CZAw_LZHrf3bgPR3bdtKY5Q@mail.gmail.com>
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.cindex 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.cindex 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.hindex 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.cindex 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.cindex 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.outindex 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.sqlindex 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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-bugs@postgresql.org
Cc: tgl@sss.pgh.pa.us, assam258@gmail.com, tharakan@gmail.com
Subject: Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
In-Reply-To: <742405.1795395962@sss.pgh.pa.us>
References: <19911-991c431cc0ba50d1@postgresql.org> <CAAAe_zCRzOjsr2y_WG149sY52xusNo2KuLQGgw0vta0uMvVpmw@mail.gmail.com> <601850.1794967393@sss.pgh.pa.us> <CAAAe_zC=2KN_seGKj+G6s7S5-33b6tZ9s_VhA_4PusAdD3bhCw@mail.gmail.com> <CAAAe_zBzVHBabZeD3GMSQsEKAe7CZAw_LZHrf3bgPR3bdtKY5Q@mail.gmail.com> <742405.1795395962@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
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