From d3d6af9fa990a19b3a4136dd1770639cf5f7709d Mon Sep 17 00:00:00 2001 From: Henson Choi Date: Tue, 1 Dec 2026 21:54:51 +0900 Subject: [PATCH v2 1/3] Index tuple positions in a spilled tuplestore for faster seeks. Once a tuplestore spills to its temp file, tuplestore_seek() moves by stepping over records one at a time from the read pointer's current position, so reaching a row in the middle of the file costs a walk proportional to the distance. WindowAgg does this for every row when it re-reads the frame head of an aggregate, or moves both ends of a moving aggregate's frame, once the partition no longer fits in work_mem. Keep the file position of every N-th row in memory, with N as small as the work_mem budget allows. That budget is what the dump to disk has just freed, which a file-state tuplestore otherwise does not use. N is a power of two and starts at one, with room for every row the dump writes. The array doubles while the budget allows; after that it keeps every other entry and doubles N, so it always covers the whole file. Each entry holds the temp file segment number and the offset in it in 32 bits each, and only the rows that get an entry look up their position, so the write path adds one mask test per row. tuplestore_seek() then jumps to the index entry at or before the target, or to the next entry if walking back from it takes fewer steps, and walks from there. The write position stands in for an entry at the end, and walking back needs the length words for backward scans. It walks from the read pointer's current position instead when that takes no more steps, counting the jump as one step. A backward walk loses a tie, as its steps cost more. Discussion: https://postgr.es/m/CAAAe_zD5Ti_C-8LEK6=v3QDUu9YYWMmM+y1CBk3pOyYEm=jZSw@mail.gmail.com --- src/backend/utils/sort/tuplestore.c | 288 +++++++++++++++++++++++++++- src/tools/pgindent/typedefs.list | 1 + 2 files changed, 279 insertions(+), 10 deletions(-) diff --git a/src/backend/utils/sort/tuplestore.c b/src/backend/utils/sort/tuplestore.c index d8a4d669727..3a5819c5902 100644 --- a/src/backend/utils/sort/tuplestore.c +++ b/src/backend/utils/sort/tuplestore.c @@ -20,7 +20,9 @@ * in kilobytes by the caller. We absorb tuples and simply store them in an * in-memory array as long as we haven't exceeded maxKBytes. If we do exceed * maxKBytes, we dump all the tuples into a temp file and then read from that - * when needed. + * when needed. The space the dump frees then holds the file position of + * every Nth row, so that seeking can start from the nearest known position + * instead of walking the file from the read pointer. * * Upon creation, a tuplestore supports a single read pointer, numbered 0. * Additional read pointers can be created using tuplestore_alloc_read_pointer. @@ -61,6 +63,7 @@ #include "commands/tablespace.h" #include "executor/executor.h" #include "miscadmin.h" +#include "port/pg_bitutils.h" #include "storage/buffile.h" #include "utils/memutils.h" #include "utils/resowner.h" @@ -118,6 +121,17 @@ typedef struct pgoff_t offset; /* byte offset in file */ } TSReadPointer; +/* + * A position BufFileTell reports is at most 1GB plus one buffer into its + * segment, so 32 bits hold the offset of a posindex entry; note_tuple_pos + * checks it anyway. + */ +typedef struct +{ + int32 file; /* temp file# */ + uint32 offset; /* byte offset in file */ +} TSFilePos; + /* * Private state of a Tuplestore operation. */ @@ -219,8 +233,21 @@ struct Tuplestorestate int writepos_file; /* file# (valid if READFILE state) */ pgoff_t writepos_offset; /* offset (valid if READFILE state) */ + + /* + * In file states, posindex[idx] is the file position of absolute row + * rowstrimmed + (idx << posshift). Only entries for rows below tuples + * are valid. It is charged to availMem. + */ + TSFilePos *posindex; /* position of every (1 << posshift)'th row */ + int posindexsize; /* allocated length of posindex array */ + int posshift; /* log2 of rows between posindex entries */ }; +/* Does posindex keep the file position of this row? */ +#define TUPPOS_WANTED(state,row) \ + ((((row) - (state)->rowstrimmed) & (((int64) 1 << (state)->posshift) - 1)) == 0) + #define COPYTUP(state,tup) ((*(state)->copytup) (state, tup)) #define WRITETUP(state,tup) ((*(state)->writetup) (state, tup)) #define READTUP(state,len) ((*(state)->readtup) (state, len)) @@ -260,7 +287,7 @@ struct Tuplestorestate * NOTES about memory consumption calculations: * * We count space allocated for tuples against the maxKBytes limit, - * plus the space used by the variable-size array memtuples. + * plus the space used by the variable-size arrays memtuples and posindex. * Fixed-size space (primarily the BufFile I/O buffer) is not counted. * We don't worry about the size of the read pointer array, either. * @@ -279,6 +306,11 @@ 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 begin_posindex(Tuplestorestate *state); +static void end_posindex(Tuplestorestate *state); +static void grow_posindex(Tuplestorestate *state); +static void note_tuple_pos(Tuplestorestate *state, int64 row); +static void seek_nearest_known(Tuplestorestate *state, int64 row); static void release_heldtuple(Tuplestorestate *state); static void switch_to_readfile(Tuplestorestate *state); static bool step_record_forward(Tuplestorestate *state); @@ -499,6 +531,7 @@ tuplestore_clear(Tuplestorestate *state) if (state->myfile) BufFileClose(state->myfile); state->myfile = NULL; + end_posindex(state); #ifdef USE_ASSERT_CHECKING { @@ -558,6 +591,7 @@ tuplestore_end(Tuplestorestate *state) { if (state->myfile) BufFileClose(state->myfile); + end_posindex(state); MemoryContextDelete(state->context); pfree(state->memtuples); @@ -918,6 +952,17 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple) */ PrepareTempTablespaces(); + /* + * Update the maximum space used before dumping the tuples, and + * before begin_posindex charges the index to availMem. It's + * possible that more space will be used by the tuples in memory + * than the space that will be used on disk. + */ + tuplestore_updatemax(state); + + /* Allocate the index first, so failing leaves an in-memory store */ + begin_posindex(state); + /* associate the file with the store's resource owner */ oldowner = CurrentResourceOwner; CurrentResourceOwner = state->resowner; @@ -942,13 +987,6 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple) */ state->backward = (state->eflags & EXEC_FLAG_BACKWARD) != 0; - /* - * Update the maximum space used before dumping the tuples. It's - * possible that more space will be used by the tuples in memory - * than the space that will be used on disk. - */ - tuplestore_updatemax(state); - state->status = TSS_WRITEFILE; dumptuples(state); break; @@ -991,6 +1029,8 @@ tuplestore_puttuple_common(Tuplestorestate *state, void *tuple) } } + if (TUPPOS_WANTED(state, state->tuples)) + note_tuple_pos(state, state->tuples); WRITETUP(state, tuple); state->tuples++; break; @@ -1366,6 +1406,9 @@ tuplestore_seek(Tuplestorestate *state, int64 row) readptr->row = state->tuples; } + /* Jump to a known position if that saves steps, then walk */ + seek_nearest_known(state, row); + while (readptr->row < row) { /* This should fail only when we're advancing to "at EOF" */ @@ -1401,11 +1444,14 @@ tuplestore_seek(Tuplestorestate *state, int64 row) * * As a side effect, we must convert each read pointer's position from * "current" to file/offset format. But eof_reached pointers don't - * need to change state. + * need to change state. We also note the file positions of the rows + * posindex keeps. */ static void dumptuples(Tuplestorestate *state) { + /* absolute row number of memtuples[0], as in tuplestore_seek */ + int64 base = state->tuples - state->memtupcount; int i; /* Writing to the file invalidates slots anyway, so drop any held tuple */ @@ -1424,6 +1470,8 @@ dumptuples(Tuplestorestate *state) } if (i >= state->memtupcount) break; + if (TUPPOS_WANTED(state, base + i)) + note_tuple_pos(state, base + i); WRITETUP(state, state->memtuples[i]); /* @@ -1442,6 +1490,226 @@ dumptuples(Tuplestorestate *state) state->memtupcount = 0; } +/* + * begin_posindex - allocate the file position index before dumptuples() + * + * Start with an entry for every row, in an array that holds all the rows the + * dump writes, since availMem stays exhausted until the dump frees them. The + * size is a power of two, which keeps it even for thinning out entries, and + * as for memtuples it starts above ALLOCSET_SEPARATE_THRESHOLD. + */ +static void +begin_posindex(Tuplestorestate *state) +{ + MemoryContext cxt = state->context->parent; + int64 ntuples = state->memtupcount - state->memtupdeleted; + uint64 nentries; + int shift = 0; + TSFilePos *newindex; + + Assert(state->status == TSS_INMEM); + + /* Free any index left by an earlier spill that failed */ + end_posindex(state); + + nentries = pg_nextpower2_64(Max(ntuples, 16384 / sizeof(TSFilePos))); + + /* Stay within MaxAllocSize; only a huge work_mem gets near it */ + while (nentries > MaxAllocSize / sizeof(TSFilePos)) + { + nentries /= 2; + shift++; + } + + /* No more than memtuples and the tuples being dumped take now */ + Assert(nentries * sizeof(TSFilePos) <= + (uint64) (state->allowedMem - state->availMem)); + + newindex = MemoryContextAlloc(cxt, nentries * sizeof(TSFilePos)); + + state->posindex = newindex; + state->posindexsize = (int) nentries; + state->posshift = shift; + USEMEM(state, GetMemoryChunkSpace(newindex)); +} + +/* + * end_posindex - release the file position index + */ +static void +end_posindex(Tuplestorestate *state) +{ + if (state->posindex) + { + FREEMEM(state, GetMemoryChunkSpace(state->posindex)); + pfree(state->posindex); + state->posindex = NULL; + } + state->posindexsize = 0; + state->posshift = 0; +} + +/* + * grow_posindex - make room in the full file position index + * + * Double the array while work_mem allows; otherwise keep every other entry + * and double the spacing. + */ +static void +grow_posindex(Tuplestorestate *state) +{ + int64 addbytes = (int64) state->posindexsize * sizeof(TSFilePos); + + if (state->availMem >= addbytes && + 2 * addbytes <= (int64) MaxAllocSize) + { + int64 oldspace = GetMemoryChunkSpace(state->posindex); + TSFilePos *newindex; + + newindex = repalloc_array(state->posindex, TSFilePos, + state->posindexsize * 2); + state->posindex = newindex; + state->posindexsize *= 2; + FREEMEM(state, oldspace); + USEMEM(state, GetMemoryChunkSpace(newindex)); + } + else + { + for (int idx = 0; idx < state->posindexsize / 2; idx++) + state->posindex[idx] = state->posindex[2 * idx]; + state->posshift++; + } +} + +/* + * note_tuple_pos - record where the row about to be written will start + * + * Callers check TUPPOS_WANTED first. Lookups ignore entries for rows at or + * beyond state->tuples, so failing to append a row leaves no stale entry in + * use. + */ +static void +note_tuple_pos(Tuplestorestate *state, int64 row) +{ + int64 nrows = row - state->rowstrimmed; /* rows before it */ + int64 idx; + int file; + pgoff_t offset; + + Assert(TUPPOS_WANTED(state, row)); + + if ((nrows >> state->posshift) >= state->posindexsize) + { + grow_posindex(state); + /* the even size keeps the row on the doubled spacing */ + Assert(TUPPOS_WANTED(state, row)); + } + + /* + * This may be past the segment's end while the buffer straddles it; + * BufFileSeek normalizes such a position. + */ + BufFileTell(state->myfile, &file, &offset); + if (offset < 0 || offset > PG_UINT32_MAX) + elog(ERROR, "tuplestore temporary file offset %lld out of range", + (long long) offset); + + idx = nrows >> state->posshift; + Assert(idx < state->posindexsize); + state->posindex[idx].file = file; + state->posindex[idx].offset = (uint32) offset; +} + +/* + * seek_nearest_known - move the active read pointer to a known file + * position near "row" + * + * The known positions around "row" are the index entry at or before it and + * the next entry, with the write position standing for the end. Walking + * back from the later one needs the length words for backward scans, so it + * is used only with them, unless it is "row" itself, and only if it takes + * fewer steps. Counting the jump there as one step, walk from where the + * pointer is unless that takes more steps. A backward walk loses a tie, as + * its steps cost more. + */ +static void +seek_nearest_known(Tuplestorestate *state, int64 row) +{ + TSReadPointer *readptr = &state->readptrs[state->activeptr]; + int64 target = Min(row, state->tuples); /* caller walks to EOF */ + int64 prev; + int64 next; + int64 start; + int64 steps; + int file; + pgoff_t offset; + + /* + * Find the rows of the entry at or before target and of the next one. + * Both stay within the file, as the end stands in for an entry past it. + */ + prev = state->rowstrimmed + + (((target - state->rowstrimmed) >> state->posshift) << state->posshift); + next = Min(prev + ((int64) 1 << state->posshift), state->tuples); + + /* + * If we can walk backward and the next one is nearer, use it instead. + * Reaching target itself needs no backward walk. + */ + if ((next == target || state->backward) && next - target < target - prev) + start = next; + else + start = prev; + + /* + * Count the steps from start as one for the jump there, plus the walk to + * target, forward from prev or backward from next. + */ + steps = 1 + (start > target ? start - target : target - start); + + /* + * If the current position is nearer, fall back to walking from there. A + * backward walk loses a tie. + */ + if (target >= readptr->row) + { + if (target - readptr->row <= steps) + return; + } + else + { + /* tuplestore_seek moves back only with EXEC_FLAG_BACKWARD */ + Assert(state->backward); + if (readptr->row - target < steps) + return; + } + + /* + * Look up the file position of start. The end has no index entry, as no + * row starts there yet, so its position is the write position. + */ + if (start == state->tuples) + { + file = state->writepos_file; + offset = state->writepos_offset; + } + else + { + int64 idx = (start - state->rowstrimmed) >> state->posshift; + + Assert(idx < state->posindexsize); + file = state->posindex[idx].file; + offset = state->posindex[idx].offset; + } + + /* Jump to start, leaving the walk to the caller */ + if (BufFileSeek(state->myfile, file, offset, SEEK_SET) != 0) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not seek in tuplestore temporary file"))); + readptr->row = start; +} + /* * release_heldtuple - free the tuple held for a slot by tuplestore_trim() */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb469266..119d934933a 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -3105,6 +3105,7 @@ TSConfigInfo TSDictInfo TSDictionaryCacheEntry TSExecuteCallback +TSFilePos TSLexeme TSParserCacheEntry TSParserInfo -- 2.54.0 (Apple Git-157)