From 26042a69fd6eeeb8d345d80b9ff2db01606a60e4 Mon Sep 17 00:00:00 2001 From: Henson Choi Date: Mon, 23 Nov 2026 18:23:25 +0900 Subject: [PATCH v5 3/7] 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. In memory, that tuple is not a position: 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. 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 | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index aacab4d0116..fef1fc0c8e1 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -1364,8 +1364,12 @@ tuplestore_seek(Tuplestorestate *state, int64 row) case TSS_INMEM: { int64 base = state->tuples - state->memtupcount; + int64 lowest = base + state->memtupdeleted; - if (row < base + state->memtupdeleted) + /* After a trim, the tuple kept for a slot is not a position */ + if (state->truncated) + lowest++; + if (row < lowest) return false; if (row > state->tuples) readptr->eof_reached = true; @@ -1738,7 +1742,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)