From: Henson Choi <assam258@gmail.com>
To: Tom Lane <tgl@sss.pgh.pa.us>
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: Thu, 19 Nov 2026 16:22:28 +0900
Message-ID: <CAAAe_zBzVHBabZeD3GMSQsEKAe7CZAw_LZHrf3bgPR3bdtKY5Q@mail.gmail.com> (raw)
In-Reply-To: <CAAAe_zC=2KN_seGKj+G6s7S5-33b6tZ9s_VhA_4PusAdD3bhCw@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>
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.cindex 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.hindex 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.cindex 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.cindex 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.hindex 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.cindex 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.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.54.0 (Apple Git-157)
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: assam258@gmail.com, tgl@sss.pgh.pa.us, tharakan@gmail.com
Subject: Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill
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>
* 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