From 3894642f0226c92bbb505395962f43ef65bb8467 Mon Sep 17 00:00:00 2001 From: Henson Choi Date: Mon, 23 Nov 2026 18:23:25 +0900 Subject: [PATCH v6 4/8] Do not let tuplestore_seek() land on the tuple kept by a trim. tuplestore_trim() keeps the tuple just before the oldest read pointer, because a caller may still have it in a slot. That tuple is not a position, in memory or after a spill: no read pointer is meant to move back onto it. A backward read stops there with Assert(!state->truncated), and the next trim can fail Assert(nremove >= memtupdeleted), but tuplestore_seek() accepted it and returned true. Treat it as trimmed and return false. Once the store spills, the kept tuple is the first one in the file, at rowstrimmed. Before any trim there is no kept tuple; it would be row -1, so the lowest position stays 0. No caller seeks there today, but tuplestore_seek() is new and exported. Bug: #19911 Author: Henson Choi Discussion: https://postgr.es/m/19911-991c431cc0ba50d1@postgresql.org Backpatch-through: 15 --- src/backend/utils/sort/tuplestore.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index c2738827fca..412705fcd36 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -1344,8 +1344,8 @@ tuplestore_tell(Tuplestorestate *state) * 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. + * (including pointing to a trimmed-away tuple or the tuple a trim kept + * for a slot); the tuplestore state is unchanged in the latter case. * * Moving backward requires EXEC_FLAG_BACKWARD. */ @@ -1354,11 +1354,19 @@ tuplestore_seek(Tuplestorestate *state, int64 row) { TSReadPointer *readptr = &state->readptrs[state->activeptr]; int64 cur; + int64 lowest; check_read_pointer_rows(state); + /* Lowest position; after a trim, the tuple kept for a slot is not one */ + lowest = state->rowstrimmed; + if (state->status == TSS_INMEM) + lowest += state->memtupdeleted; + if (state->truncated) + lowest++; + /* Quick exit if row is obviously bogus */ - if (row < state->rowstrimmed || row > state->tuples + 1) + if (row < lowest || row > state->tuples + 1) return false; /* Quick exit for no-op requests */ cur = tuplestore_tell(state); @@ -1372,8 +1380,6 @@ tuplestore_seek(Tuplestorestate *state, int64 row) { int64 base = state->tuples - state->memtupcount; - if (row < base + state->memtupdeleted) - return false; if (row > state->tuples) readptr->eof_reached = true; else @@ -1745,7 +1751,7 @@ tuplestore_trim(Tuplestorestate *state) } Assert(state->memtupdeleted == nremove); - /* mark tuplestore as truncated (used for Assert crosschecks only) */ + /* mark tuplestore as truncated; tuplestore_seek() relies on this */ state->truncated = true; /* -- 2.54.0 (Apple Git-157)