Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xVIVZ-00000001TTg-2xTX for pgsql-bugs@arkaria.postgresql.org; Mon, 23 Nov 2026 01:06:15 +0000 Received: from localhost ([127.0.0.1]:47850 helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.98.2) (envelope-from ) id 1xVIVX-00000000oj8-2tLg for pgsql-bugs@arkaria.postgresql.org; Mon, 23 Nov 2026 01:06:11 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]:48948) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xVIVW-00000000oj0-2iMI for pgsql-bugs@lists.postgresql.org; Mon, 23 Nov 2026 01:06:11 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xVIVS-000000012fJ-1370 for pgsql-bugs@lists.postgresql.org; Mon, 23 Nov 2026 01:06:09 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.18.1/8.18.1) with ESMTP id 6AN162kM742406; Sun, 22 Nov 2026 20:06:02 -0500 DKIM-Filter: OpenDKIM Filter v2.11.0 sss.pgh.pa.us 6AN162kM742406 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sss.pgh.pa.us; s=default; t=1795395962; bh=1M3XmaRbUBIlZwkGrWvLYmofmLfbdz9kf4/2Lag63pk=; h=From:To:cc:Subject:In-reply-to:References:Date:From; b=hprXvCKE3MugSH3c1CSDY21f/HrFzy7PQAPgX5p6PeGYdfs11suY7aR42susL8wsv nNkp5M2RJKHaAKsyksfir+2r95lTZ6WHo+dbPWsXv+nhN9CBHVaIMW6BHxU9S2eA3o f0iVJToz69L1010tT4OqfQv9z68nYo0Jm6f5tQ5A= From: Tom Lane To: assam258@gmail.com cc: tharakan@gmail.com, pgsql-bugs@lists.postgresql.org Subject: Re: BUG #19911: Window aggregate over ROWS n FOLLOWING: "unexpected end of tuplestore" after spill In-reply-to: References: <19911-991c431cc0ba50d1@postgresql.org> <601850.1794967393@sss.pgh.pa.us> Comments: In-reply-to Henson Choi message dated "Thu, 19 Nov 2026 16:22:28 +0900" MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----- =_aaaaaaaaaa0" Content-ID: <742397.1795395959.0@sss.pgh.pa.us> Date: Sun, 22 Nov 2026 20:06:02 -0500 Message-ID: <742405.1795395962@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk ------- =_aaaaaaaaaa0 Content-Type: text/plain; charset="us-ascii" Content-ID: <742397.1795395959.1@sss.pgh.pa.us> Henson Choi 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 ------- =_aaaaaaaaaa0 Content-Type: text/x-diff; name*0="v4-0001-Track-absolute-row-numbers-in-tuplestore-read-poi.p"; name*1="atch"; charset="us-ascii" Content-ID: <742397.1795395959.2@sss.pgh.pa.us> Content-Description: v4-0001-Track-absolute-row-numbers-in-tuplestore-read-poi.patch Content-Transfer-Encoding: quoted-printable =46rom 6c4c4e151a7667dd7d1ec1c7b240f0d8292a2799 Mon Sep 17 00:00:00 2001 From: Tom Lane 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 Author: Henson Choi Reviewed-by: Tom Lane 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 th= e - * 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 activ= e - * read pointer implicitly has position equal to the temp file's seek pos= ition. + * 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 ti= me - * 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 t= he + * 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 rea= d + * pointers have valid file/offset, but the active read pointer implicitl= y + * 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 expende= d * the effort to slide the remaining pointers down. These unused pointe= rs * 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 ro= w + * 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. Howeve= r, + * 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 e= flags, int maxKBytes); static void tuplestore_puttuple_common(Tuplestorestate *state, void *tupl= e); 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, in= t maxKBytes) = state->memtupdeleted =3D 0; state->memtupcount =3D 0; + state->rowstrimmed =3D 0; state->tuples =3D 0; = /* @@ -302,6 +336,7 @@ tuplestore_begin_common(int eflags, bool interXact, in= t maxKBytes) = state->readptrs[0].eflags =3D eflags; state->readptrs[0].eof_reached =3D false; + state->readptrs[0].row =3D 0; state->readptrs[0].current =3D 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 =3D false; state->memtupdeleted =3D 0; state->memtupcount =3D 0; + state->rowstrimmed =3D 0; state->tuples =3D 0; readptr =3D state->readptrs; for (i =3D 0; i < state->readptrcount; readptr++, i++) { readptr->eof_reached =3D false; + readptr->row =3D 0; readptr->current =3D 0; } } @@ -510,6 +547,8 @@ tuplestore_select_read_pointer(Tuplestorestate *state,= int ptr) = Assert(ptr >=3D 0 && ptr < state->readptrcount); = + check_read_pointer_rows(state); + /* No work if already active */ if (ptr =3D=3D state->activeptr) return; @@ -802,7 +841,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) ResourceOwner oldowner; MemoryContext oldcxt; = - state->tuples++; + check_read_pointer_rows(state); = switch (state->status) { @@ -817,6 +856,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) if (readptr->eof_reached && i !=3D state->activeptr) { readptr->eof_reached =3D false; + readptr->row =3D state->tuples; readptr->current =3D state->memtupcount; } } @@ -835,6 +875,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) = /* Stash the tuple in the in-memory array */ state->memtuples[state->memtupcount++] =3D tuple; + state->tuples++; = /* * Done if we still fit in available memory and have array slots. @@ -895,6 +936,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) if (readptr->eof_reached && i !=3D state->activeptr) { readptr->eof_reached =3D false; + readptr->row =3D state->tuples; BufFileTell(state->myfile, &readptr->file, &readptr->offset); @@ -902,6 +944,7 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) } = WRITETUP(state, tuple); + state->tuples++; break; case TSS_READFILE: = @@ -929,12 +972,14 @@ tuplestore_puttuple_common(Tuplestorestate *state, v= oid *tuple) if (readptr->eof_reached && i !=3D state->activeptr) { readptr->eof_reached =3D false; + readptr->row =3D state->tuples; readptr->file =3D state->writepos_file; readptr->offset =3D state->writepos_offset; } } = WRITETUP(state, tuple); + state->tuples++; break; default: elog(ERROR, "invalid tuplestore state"); @@ -960,6 +1005,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forw= ard, = 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 forw= ard, if (readptr->current < state->memtupcount) { /* We have another tuple, so return it */ + readptr->row++; return state->memtuples[readptr->current++]; } readptr->eof_reached =3D true; @@ -984,6 +1032,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool forw= ard, */ if (readptr->eof_reached) { + readptr->row =3D state->tuples; readptr->current =3D state->memtupcount; readptr->eof_reached =3D false; } @@ -994,7 +1043,8 @@ tuplestore_gettuple(Tuplestorestate *state, bool forw= ard, Assert(!state->truncated); return NULL; } - readptr->current--; /* last returned tuple */ + readptr->row--; /* last returned tuple */ + readptr->current--; } if (readptr->current <=3D state->memtupdeleted) { @@ -1032,6 +1082,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool for= ward, if ((tuplen =3D getlen(state, true)) !=3D 0) { tup =3D READTUP(state, tuplen); + readptr->row++; return tup; } else @@ -1055,6 +1106,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool for= ward, { /* even a failed backwards fetch gets you out of eof state */ readptr->eof_reached =3D false; + readptr->row =3D state->rowstrimmed; Assert(!state->truncated); return NULL; } @@ -1063,6 +1115,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool for= ward, if (readptr->eof_reached) { readptr->eof_reached =3D false; + readptr->row =3D state->tuples; /* We will return the tuple returned before returning NULL */ } else @@ -1086,10 +1139,12 @@ tuplestore_gettuple(Tuplestorestate *state, bool f= orward, ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file"))); + readptr->row =3D state->rowstrimmed; Assert(!state->truncated); return NULL; } tuplen =3D 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 <=3D 0) return true; = @@ -1233,9 +1290,11 @@ tuplestore_skiptuples(Tuplestorestate *state, int64= ntuples, bool forward) return false; if (state->memtupcount - readptr->current >=3D ntuples) { + readptr->row +=3D ntuples; readptr->current +=3D ntuples; return true; } + readptr->row =3D state->tuples; readptr->current =3D state->memtupcount; readptr->eof_reached =3D true; return false; @@ -1244,16 +1303,19 @@ tuplestore_skiptuples(Tuplestorestate *state, int6= 4 ntuples, bool forward) { if (readptr->eof_reached) { + readptr->row =3D state->tuples; readptr->current =3D state->memtupcount; readptr->eof_reached =3D false; ntuples--; } if (readptr->current - state->memtupdeleted > ntuples) { + readptr->row -=3D ntuples; readptr->current -=3D ntuples; return true; } Assert(!state->truncated); + readptr->row -=3D readptr->current - state->memtupdeleted; readptr->current =3D state->memtupdeleted; return false; } @@ -1290,6 +1352,9 @@ dumptuples(Tuplestorestate *state) { int i; = + /* Make rowstrimmed =3D row number of the oldest tuple we still have */ + state->rowstrimmed +=3D state->memtupdeleted; + for (i =3D state->memtupdeleted;; i++) { TSReadPointer *readptr =3D state->readptrs; @@ -1330,21 +1395,26 @@ tuplestore_rescan(Tuplestorestate *state) TSReadPointer *readptr =3D &state->readptrs[state->activeptr]; = Assert(readptr->eflags & EXEC_FLAG_REWIND); + /* REWIND should have prevented trimming any tuples */ Assert(!state->truncated); + Assert(state->rowstrimmed =3D=3D 0); = switch (state->status) { case TSS_INMEM: readptr->eof_reached =3D false; + readptr->row =3D 0; readptr->current =3D 0; break; case TSS_WRITEFILE: readptr->eof_reached =3D false; + readptr->row =3D 0; readptr->file =3D 0; readptr->offset =3D 0; break; case TSS_READFILE: readptr->eof_reached =3D false; + readptr->row =3D 0; if (BufFileSeek(state->myfile, 0, 0, SEEK_SET) !=3D 0) ereport(ERROR, (errcode_for_file_access(), @@ -1373,6 +1443,8 @@ tuplestore_copy_read_pointer(Tuplestorestate *state, if (srcptr =3D=3D destptr) return; = + check_read_pointer_rows(state); + if (dptr->eflags !=3D 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 requir= ing - * 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 eit= her. * If a pointer is marked as BACKWARD but not REWIND capable, it means th= at @@ -1472,6 +1545,8 @@ tuplestore_trim(Tuplestorestate *state) if (state->status !=3D TSS_INMEM) return; = + check_read_pointer_rows(state); + /* Find the oldest read pointer */ oldest =3D state->memtupcount; for (i =3D 0; i < state->readptrcount; i++) @@ -1537,12 +1612,50 @@ tuplestore_trim(Tuplestorestate *state) = state->memtupdeleted =3D 0; state->memtupcount -=3D nremove; + state->rowstrimmed +=3D nremove; for (i =3D 0; i < state->readptrcount; i++) { if (!state->readptrs[i].eof_reached) state->readptrs[i].current -=3D 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 =3D state->tuples - state->memtupcount; + int64 oldest; + + /* calculate row number of oldest still-accessible tuple */ + if (state->status =3D=3D TSS_INMEM) + { + Assert(base =3D=3D state->rowstrimmed); + oldest =3D base + state->memtupdeleted; + } + else + oldest =3D state->rowstrimmed; + + for (int i =3D 0; i < state->readptrcount; i++) + { + TSReadPointer *readptr =3D &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 >=3D oldest && readptr->row <=3D state->tuples); + if (state->status =3D=3D TSS_INMEM) + Assert(readptr->row =3D=3D base + readptr->current); + /* in the file states there's no equivalently simple check */ + } } +#endif = /* * tuplestore_updatemax -- = 2.52.0 ------- =_aaaaaaaaaa0 Content-Type: text/x-diff; name="v4-0002-Add-tuplestore_tell-and-tuplestore_seek.patch"; charset="us-ascii" Content-ID: <742397.1795395959.3@sss.pgh.pa.us> Content-Description: v4-0002-Add-tuplestore_tell-and-tuplestore_seek.patch Content-Transfer-Encoding: quoted-printable =46rom a39dedce3b05b0fa5c90b4b8f97e222bd6b563aa Mon Sep 17 00:00:00 2001 From: Tom Lane 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 Author: Henson Choi Reviewed-by: Tom Lane 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 ef= lags, int maxKBytes); static void tuplestore_puttuple_common(Tuplestorestate *state, void *tupl= e); 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, vo= id *tuple) state->status =3D 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 =3D state->readptrs; - for (i =3D 0; i < state->readptrcount; readptr++, i++) - { - if (readptr->eof_reached && i !=3D state->activeptr) - { - readptr->eof_reached =3D false; - readptr->row =3D 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, vo= id *tuple) (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file"))); state->status =3D 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 =3D state->readptrs; for (i =3D 0; i < state->readptrcount; readptr++, i++) @@ -973,8 +959,9 @@ tuplestore_puttuple_common(Tuplestorestate *state, voi= d *tuple) { readptr->eof_reached =3D false; readptr->row =3D state->tuples; - readptr->file =3D state->writepos_file; - readptr->offset =3D state->writepos_offset; + BufFileTell(state->myfile, + &readptr->file, + &readptr->offset); } } = @@ -1059,20 +1046,7 @@ tuplestore_gettuple(Tuplestorestate *state, bool fo= rward, /* 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) !=3D 0) - ereport(ERROR, - (errcode_for_file_access(), - errmsg("could not seek in tuplestore temporary file"))); - state->status =3D TSS_READFILE; + switch_to_readfile(state); pg_fallthrough; = case TSS_READFILE: @@ -1340,6 +1314,113 @@ tuplestore_skiptuples(Tuplestorestate *state, int6= 4 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 =3D &state->readptrs[state->activeptr]; + + return readptr->eof_reached ? (state->tuples + 1) : readptr->row; +} + +/* + * tuplestore_seek - move the active read pointer to an absolute row numb= er + * + * The argument is interpreted as per tuplestore_tell(); in particular, + * row =3D state->tuples + 1 causes the pointer to be set "at EOF", while + * row =3D state->tuples causes the pointer to be set after the last stor= ed + * 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 =3D &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 =3D tuplestore_tell(state); + if (row =3D=3D cur) + return true; + Assert(row > cur || (readptr->eflags & EXEC_FLAG_BACKWARD)); + + switch (state->status) + { + case TSS_INMEM: + { + int64 base =3D state->tuples - state->memtupcount; + + if (row < base + state->memtupdeleted) + return false; + if (row > state->tuples) + readptr->eof_reached =3D true; + else + { + readptr->eof_reached =3D false; + readptr->row =3D row; + readptr->current =3D (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 =3D false; + readptr->row =3D 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 =3D=3D state->tuples); + readptr->eof_reached =3D 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 =3D 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 =3D &state->readptrs[state->activeptr]; + + Assert(state->status =3D=3D 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) !=3D 0) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not seek in tuplestore temporary file"))); + state->status =3D 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 =3D getlen(state, true); + pgoff_t rest; + + if (tuplen =3D=3D 0) + return false; + if (state->backward) + rest =3D tuplen; + else + rest =3D tuplen - sizeof(unsigned int); + if (BufFileSeek(state->myfile, 0, rest, SEEK_CUR) !=3D 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 tup= le + * + * 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) !=3D 0) + return false; + tuplen =3D getlen(state, false); + if (BufFileSeek(state->myfile, 0, + -(pgoff_t) (tuplen + sizeof(unsigned int)), + SEEK_CUR) !=3D 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 ------- =_aaaaaaaaaa0 Content-Type: text/x-diff; name*0="v4-0003-Reimplement-tuplestore_advance-and-tuplestore_ski.p"; name*1="atch"; charset="us-ascii" Content-ID: <742397.1795395959.4@sss.pgh.pa.us> Content-Description: v4-0003-Reimplement-tuplestore_advance-and-tuplestore_ski.patch Content-Transfer-Encoding: quoted-printable =46rom 345f34593fbb90a2faeb59b6320b516eae14c808 Mon Sep 17 00:00:00 2001 From: Tom Lane 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 Author: Henson Choi Reviewed-by: Tom Lane 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 *sta= te, bool forward, /* * tuplestore_advance - exported function to adjust position without fetc= hing * - * We could optimize this case to avoid palloc/pfree overhead, but for th= e - * 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 =3D 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 =3D &state->readptrs[state->activeptr]; - - Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD)); - - check_read_pointer_rows(state); + int64 limit; = if (ntuples <=3D 0) return true; = - switch (state->status) + if (forward) { - case TSS_INMEM: - if (forward) - { - if (readptr->eof_reached) - return false; - if (state->memtupcount - readptr->current >=3D ntuples) - { - readptr->row +=3D ntuples; - readptr->current +=3D ntuples; - return true; - } - readptr->row =3D state->tuples; - readptr->current =3D state->memtupcount; - readptr->eof_reached =3D true; - return false; - } - else - { - if (readptr->eof_reached) - { - readptr->row =3D state->tuples; - readptr->current =3D state->memtupcount; - readptr->eof_reached =3D false; - ntuples--; - } - if (readptr->current - state->memtupdeleted > ntuples) - { - readptr->row -=3D ntuples; - readptr->current -=3D ntuples; - return true; - } - Assert(!state->truncated); - readptr->row -=3D readptr->current - state->memtupdeleted; - readptr->current =3D state->memtupdeleted; + if (readptr->eof_reached) + return false; + else + { + limit =3D 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 =3D tuplestore_gettuple(state, forward, &should_free); - - if (tuple =3D=3D NULL) - return false; - if (should_free) - pfree(tuple); - CHECK_FOR_INTERRUPTS(); - } - return true; + return (ntuples <=3D limit); + } + } + else + { + if (readptr->eof_reached) + { + /* Return to the state of being just past the last tuple */ + readptr->eof_reached =3D false; + readptr->row =3D state->tuples; + } + limit =3D readptr->row - state->rowstrimmed; + if (state->status =3D=3D TSS_INMEM) + limit -=3D state->memtupdeleted; + /* If ntuples > limit, return false after moving to start */ + if (!tuplestore_seek(state, readptr->row - Min(limit, ntuples))) + return false; + return (ntuples <=3D limit); } } = -- = 2.52.0 ------- =_aaaaaaaaaa0 Content-Type: text/x-diff; name*0="v4-0004-Use-absolute-tuplestore-positions-in-WindowAgg.patc"; name*1="h"; charset="us-ascii" Content-ID: <742397.1795395959.5@sss.pgh.pa.us> Content-Description: v4-0004-Use-absolute-tuplestore-positions-in-WindowAgg.patch Content-Transfer-Encoding: quoted-printable =46rom 12df4c5961b6940733a5ef7feb72808f2585c390 Mon Sep 17 00:00:00 2001 From: Tom Lane 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 Author: Henson Choi Reviewed-by: Tom Lane 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/n= odeWindowAgg.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 =3D=3D NULL)) prepare_tuplestore(winstate); + else + Assert(tuplestore_tuple_count(winstate->buffer) =3D=3D 0); = winstate->next_partition =3D false; = @@ -1304,16 +1309,15 @@ begin_partition(WindowAggState *winstate) { WindowObject agg_winobj =3D winstate->agg_winobj; = - /* reset mark and see positions for aggregate functions */ - agg_winobj->markpos =3D -1; - agg_winobj->seekpos =3D -1; + /* Reset mark position for aggregate functions */ + agg_winobj->markpos =3D 0; = /* Also reset the row counters for aggregates */ winstate->aggregatedbase =3D 0; winstate->aggregatedupto =3D 0; } = - /* reset mark and seek positions for each real window function */ + /* Reset mark position for each real window function */ for (int i =3D 0; i < numfuncs; i++) { WindowStatePerFunc perfuncstate =3D &(winstate->perfunc[i]); @@ -1322,8 +1326,7 @@ begin_partition(WindowAggState *winstate) { WindowObject winobj =3D perfuncstate->winobj; = - winobj->markpos =3D -1; - winobj->seekpos =3D -1; + winobj->markpos =3D 0; = /* reset null map */ if (winobj->ignore_nulls =3D=3D 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; t= he + * 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 =3D 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 =3D pos + 1; - } - else if (winobj->seekpos =3D=3D 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 o= f * the fetched tuple. This ensures that the slot's contents remain vali= d * 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 =3D=3D 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 =3D winobj->winstate; = if (markpos < winobj->markpos) elog(ERROR, "cannot move WindowObject's mark position backward"); + winobj->markpos =3D markpos; + /* Don't try to move the mark pointer past current EOF */ + target =3D tuplestore_tuple_count(winstate->buffer); + target =3D 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 =3D markpos; - } + Assert(tuplestore_tell(winstate->buffer) <=3D 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 =3D 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/expec= ted/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 =3D '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 a= nd 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 betwee= n 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 =3D '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 a= nd 1::int2 preceding), -- = 2.52.0 ------- =_aaaaaaaaaa0--