From 61f296b5aa4fd626f17b04ad983deda3a309e4e4 Mon Sep 17 00:00:00 2001 From: Henson Choi Date: Mon, 30 Nov 2026 14:06:36 +0900 Subject: [PATCH v7 7/9] Hold the tuple kept by tuplestore_trim() outside the store. tuplestore_trim() keeps the tuple just before the oldest read pointer, because tuplestore_gettuple() returns a pointer to its internal copy in INMEM state and a caller may still have that tuple in a slot. The tuple stayed in memtuples[], and was written to the file by a later dumptuples(), so it remained a position that read pointers could move to: a backward read could return it, and tuplestore_seek() accepted it although the next trim might free it. Making seek and skiptuples reject that one tuple needed special cases that depended on whether a trim had happened. Remove that tuple from the store like the others, and keep it in a separate field, heldtuple, until a later trim releases more tuples, dumptuples() switches to a file, or the store is cleared or ended. That is no shorter than its lifetime before: dumptuples() used to free it when writing it out, and a later trim when removing it. In file states gettuple returns a palloc'd copy owned by the caller, so there is nothing to keep. The lowest position is now the oldest row still stored, in every state. A backward read that reaches it returns NULL as it does at the start of an untrimmed store. The assertions there that no trim had happened now also catch a caller trying to read the held tuple, which is past the truncation point that tuplestore_set_eflags() documents. WindowAgg relied on reaching the kept tuple before it switched to absolute positions, which is why this comes after that change; no other core caller moves back past the oldest read pointer. Since a trim can now leave the store empty, tuplestore_set_eflags() and tuplestore_alloc_read_pointer() check tuples instead of memtupcount for whether data has been inserted. --- src/backend/utils/sort/tuplestore.c | 82 +++++++++++++++++++--------- src/test/regress/expected/window.out | 12 ++++ src/test/regress/sql/window.sql | 8 +++ 3 files changed, 76 insertions(+), 26 deletions(-) diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index a1609f67b38..7f2fb167217 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -184,6 +184,14 @@ struct Tuplestorestate int memtupsize; /* allocated length of memtuples array */ bool growmemtuples; /* memtuples' growth still underway? */ + /* + * heldtuple is the last tuple released by tuplestore_trim(), if any. It + * is no longer in the store, but a caller may still have it in a slot, so + * we free it only at the next trim that releases more tuples, or when the + * tuples are dumped to a file or the store is cleared or ended. + */ + void *heldtuple; + /* * 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 @@ -270,6 +278,7 @@ 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 release_heldtuple(Tuplestorestate *state); static void switch_to_readfile(Tuplestorestate *state); static bool step_record_forward(Tuplestorestate *state); static bool step_record_backward(Tuplestorestate *state); @@ -301,6 +310,7 @@ tuplestore_begin_common(int eflags, bool interXact, int maxKBytes) state->eflags = eflags; state->interXact = interXact; state->truncated = false; + state->heldtuple = NULL; state->usedDisk = false; state->maxSpace = 0; state->allowedMem = maxKBytes * (int64) 1024; @@ -411,7 +421,7 @@ tuplestore_set_eflags(Tuplestorestate *state, int eflags) { int i; - if (state->status != TSS_INMEM || state->memtupcount != 0) + if (state->status != TSS_INMEM || state->tuples != 0) elog(ERROR, "too late to call tuplestore_set_eflags"); state->readptrs[0].eflags = eflags; @@ -434,7 +444,7 @@ int tuplestore_alloc_read_pointer(Tuplestorestate *state, int eflags) { /* Check for possible increase of requirements */ - if (state->status != TSS_INMEM || state->memtupcount != 0) + if (state->status != TSS_INMEM || state->tuples != 0) { if ((state->eflags | eflags) != state->eflags) elog(ERROR, "too late to require new tuplestore eflags"); @@ -503,6 +513,8 @@ tuplestore_clear(Tuplestorestate *state) */ for (i = state->memtupdeleted; i < state->memtupcount; i++) availMem += GetMemoryChunkSpace(state->memtuples[i]); + if (state->heldtuple) + availMem += GetMemoryChunkSpace(state->heldtuple); availMem += GetMemoryChunkSpace(state->memtuples); @@ -522,6 +534,7 @@ tuplestore_clear(Tuplestorestate *state) state->status = TSS_INMEM; state->truncated = false; + state->heldtuple = NULL; state->memtupdeleted = 0; state->memtupcount = 0; state->rowstrimmed = 0; @@ -1399,6 +1412,9 @@ dumptuples(Tuplestorestate *state) { int i; + /* Writing to the file invalidates slots anyway, so drop the held tuple */ + release_heldtuple(state); + /* Make rowstrimmed = row number of the oldest tuple we still have */ state->rowstrimmed += state->memtupdeleted; @@ -1504,6 +1520,19 @@ step_record_backward(Tuplestorestate *state) return true; } +/* + * release_heldtuple - free the tuple held for a slot by tuplestore_trim() + */ +static void +release_heldtuple(Tuplestorestate *state) +{ + if (state->heldtuple == NULL) + return; + FREEMEM(state, GetMemoryChunkSpace(state->heldtuple)); + pfree(state->heldtuple); + state->heldtuple = NULL; +} + /* * tuplestore_rescan - rewind the active read pointer to start */ @@ -1674,27 +1703,31 @@ tuplestore_trim(Tuplestorestate *state) } /* - * Note: you might think we could remove all the tuples before the oldest - * "current", since that one is the next to be returned. However, since - * tuplestore_gettuple returns a direct pointer to our internal copy of - * the tuple, it's likely that the caller has still got the tuple just - * before "current" referenced in a slot. So we keep one extra tuple - * before the oldest "current". (Strictly speaking, we could require such - * callers to use the "copy" flag to tuplestore_gettupleslot, but for - * efficiency we allow this one case to not use "copy".) + * Note: you might think we could simply free all the tuples before the + * oldest "current", since that one is the next to be returned. However, + * since tuplestore_gettuple returns a direct pointer to our internal copy + * of the tuple, it's likely that the caller has still got the tuple just + * before "current" referenced in a slot. So we remove that tuple from + * the store like the others, but keep it in heldtuple instead of freeing + * it. It is then no longer a position any read pointer can move to. + * (Strictly speaking, we could require such callers to use the "copy" + * flag to tuplestore_gettupleslot, but for efficiency we allow this one + * case to not use "copy".) */ - nremove = oldest - 1; - if (nremove <= 0) + nremove = oldest; + if (nremove <= state->memtupdeleted) return; /* nothing to do */ - Assert(nremove >= state->memtupdeleted); Assert(nremove <= state->memtupcount); /* before freeing any memory, update the statistics */ tuplestore_updatemax(state); - /* Release no-longer-needed tuples */ - for (i = state->memtupdeleted; i < nremove; i++) + /* The tuple held by an earlier trim is older still, so free it now */ + release_heldtuple(state); + + /* Release no-longer-needed tuples, except the last one */ + for (i = state->memtupdeleted; i < nremove - 1; i++) { FREEMEM(state, GetMemoryChunkSpace(state->memtuples[i])); pfree(state->memtuples[i]); @@ -1702,6 +1735,11 @@ tuplestore_trim(Tuplestorestate *state) /* As in dumptuples(), increment memtupdeleted synchronously */ state->memtupdeleted++; } + + /* Hold the last one instead, as a caller may still have it in a slot */ + state->heldtuple = state->memtuples[i]; + state->memtuples[i] = NULL; + state->memtupdeleted++; Assert(state->memtupdeleted == nremove); /* mark tuplestore as truncated (used for Assert crosschecks only) */ @@ -1716,17 +1754,9 @@ tuplestore_trim(Tuplestorestate *state) if (nremove < state->memtupcount / 8) return; - /* - * Slide the array down and readjust pointers. - * - * In mergejoin's current usage, it's demonstrable that there will always - * be exactly one non-removed tuple; so optimize that case. - */ - if (nremove + 1 == state->memtupcount) - state->memtuples[0] = state->memtuples[nremove]; - else - memmove(state->memtuples, state->memtuples + nremove, - (state->memtupcount - nremove) * sizeof(void *)); + /* Slide the array down and readjust pointers */ + memmove(state->memtuples, state->memtuples + nremove, + (state->memtupcount - nremove) * sizeof(void *)); state->memtupdeleted = 0; state->memtupcount -= nremove; diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out index 061caa685d7..19f56c80fef 100644 --- a/src/test/regress/expected/window.out +++ b/src/test/regress/expected/window.out @@ -1463,6 +1463,18 @@ SELECT count(*), sum(s) FROM 2002 | 6005 (1 row) +RESET work_mem; +-- trim before the tuplestore spills to a file +SET work_mem = '64kB'; +SELECT count(*), sum(c) FROM + (SELECT count(*) OVER (ORDER BY g RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c + FROM (SELECT CASE WHEN i <= 100 THEN i ELSE 101 END g + FROM generate_series(1, 3100) i) s) t; + count | sum +-------+--------- + 3100 | 9000100 +(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), diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql index c4ff185d815..f62f73e36b1 100644 --- a/src/test/regress/sql/window.sql +++ b/src/test/regress/sql/window.sql @@ -364,6 +364,14 @@ SELECT count(*), sum(s) FROM FROM generate_series(1, 2002) i) t; RESET work_mem; +-- trim before the tuplestore spills to a file +SET work_mem = '64kB'; +SELECT count(*), sum(c) FROM + (SELECT count(*) OVER (ORDER BY g RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c + FROM (SELECT CASE WHEN i <= 100 THEN i ELSE 101 END g + FROM generate_series(1, 3100) i) s) 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),