Re: Speed up tuplestore_seek() by starting from the nearest known position

From: Henson Choi <assam258(at)gmail(dot)com>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Cc: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Subject: Re: Speed up tuplestore_seek() by starting from the nearest known position
Date: 2026-12-02 02:52:59
Message-ID: CAAAe_zD+iUTaUdT8VydhGJjchHWebknc48gFGbgnV1TYWH5Anw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi hackers,

There have been no comments on v1 [1] yet, but here is v2, as it
goes further. v1 can jump only to the start and the end of a spilled
tuplestore's file, so a seek into the middle of the file still walks
one record at a time. v2 removes that walking.

At first I thought of a complex structure spanning disk and memory to
get rid of that walking [2]. But that was closer to a habit formed
over many years of DBMS development, going back to when disk and
memory were scarce. With SSDs and ample memory common today, the
temp file is usually in the OS cache or on an SSD, and what remains
is the CPU time spent walking records, so such a structure is too
much [3].

Also, once a tuplestore spills to disk, the work_mem budget that held
its tuples in memory becomes free. Using that space for the index
means the index need not go on disk, which removes that complexity.
The tuplestore went to disk because work_mem was full anyway, so an
index that uses up to work_mem is no problem.

The core idea is to keep the index at the finest precision memory
allows. It remembers the file position of every N-th row, with N as
small as the work_mem budget permits. When more rows outgrow the
budget, it halves the precision instead, so it always covers the
whole file.

The index is one array, set up when the tuplestore spills:

posindex[k] file position where row rowstrimmed + k * N starts

- Row numbers follow from the entries, so they are not stored. N is
a power of two. Each entry holds the temp file number (1GB
segment) and the offset in it, in 32 bits each. An offset is at
most 1GB plus one buffer into its segment, so 32 bits are enough,
and an entry takes 8 bytes, the same as a pointer in memtuples.

- N starts at one, and the array starts with room for every row the
dump writes.

- posindex is charged to work_mem. The array doubles while the
budget allows; after that it keeps every other entry and doubles N.

array full, budget spent: [0]=r0 [1]=r4 [2]=r8 [3]=r12 N = 4
keep every other entry: [0]=r0 [1]=r8 N = 8

- Only the rows that get an entry look up their file position as they
are written; every other row pays one mask test.

- One cost to point out: the index is allocated before the dump frees
the tuples, so while the dump runs the store holds up to 16 bytes
per row on top of work_mem. For 100-byte rows that is about 10%,
and only rows with no columns at all get near 50%. It has to be
that way round, since entries for the rows being dumped cannot be
added after the fact, and once the dump finishes the index lives in
the space the tuples gave back.

A seek works as follows:

N = 4

temp file | r0 r1 r2 r3 | r4 r5 r6 r7 | r8 r9 ...
^ ^ ^
posindex [0] [1] [2]

seek to r7: jump to [1] (r4), walk r4 -> r5 -> r6 -> r7
or, with length words, jump to [2] (r8),
walk back r8 -> r7

- One shift finds the entry at or before the target. The seek jumps
there with BufFileSeek and walks forward to the target.

- If the file has the length words for backward scans, it jumps to
the next entry instead when walking back from it takes fewer steps.
The write position stands in for an entry past the last one, so
reaching the end needs no walk either way.

- Counting the jump as one step, it walks from where the read pointer
already is when that takes no more steps. A backward walk loses a
tie, as its steps cost more. v1's jumps to the start and the end
of the file become special cases of this.

- So a seek walks fewer than N rows, or about N/2 with the length
words, however far it goes.

How small N stays depends on how many entries the budget holds.
After the spill the index gets about 4096 entries at work_mem = 64kB
and about 256k at the default 4MB. Even a 100GB store of 100-byte
rows, about 930 million rows, then has N = 4096 at 4MB: a seek walks
fewer than 4096 rows, about 440kB of the file, or half that with the
length words, while master walks the whole distance for every seek.
A larger work_mem shrinks N in proportion: at work_mem = 64MB the
index gets about 4M entries in 32MB, and the same store has N = 256,
a walk of under 30kB.

The design stays within tuplestore.c and changes neither the file
format nor the API.

Timings on release builds, work_mem = 64kB, median of three runs, in
ms (the first row is the example from v1):

ROWS frame, 4000 rows master v1 v2
max 2000 PRECEDING, CURRENT ROW 1697 151 147
max 2000 PRECEDING, 2000 FOLLOWING 2535 223 214
max CURRENT ROW, 2000 FOLLOWING 2470 947 210
max CURRENT ROW, UNBOUNDED FOLLOWING 3262 1022 276
max 1 FOLLOWING, UNBOUNDED FOLLOWING 3303 1023 275
max 400 FOLLOWING, UNBOUNDED FOLLOWING 2675 999 229
sum 2000 PRECEDING, CURRENT ROW 1443 771 3
lag(1000) + lead(1000) 8 8 8

moving sum(), 16000 rows master v1 v2
sum 2000 PRECEDING, CURRENT ROW 10136 9720 21
sum 8000 PRECEDING, CURRENT ROW 25150 12707 16

The FOLLOWING frames read ahead of the rows v1 could reach. An
aggregate that moves both ends of its frame, like sum(), goes back
and forth by the frame width in the middle of the file for every
row, so master and v1 walk in proportion to the width, while v2
walks fewer than N rows whatever the width. All results were the
same with and without the patch.

0001 implements this design. The existing regression tests reach
only some of the ways a seek can start; 0003 goes through all of
them.

0002 makes MOVE, and FETCH ABSOLUTE or RELATIVE on their way to the
requested row, skip the rows of a held cursor with
tuplestore_skiptuples() instead of fetching each one and throwing it
away. That helps an in-memory store too, but a spilled store needs
0001 for the skip to be faster than a walk. It adds a small
regression test for moving a held cursor past either end. Timings
for a held SCROLL cursor over 1M rows, in ms:

in memory spilled, work_mem = 4MB
master v2 master 0001 v2
FETCH ABSOLUTE 900000 9.0 0.1 25.1 24.8 0.1
FETCH RELATIVE 200000 1.2 0.1 5.6 5.5 0.1
FETCH RELATIVE -200000 1.2 0.1 170.4 169.2 0.1
MOVE FORWARD ALL 2.5 0.1 10.8 11.1 0.1

0003 is a test-only patch, not meant for commit, for reviewers to
run. It compares a range of window frames over a spilled buffer with
the same frames in memory, repositions a spilled holdable SCROLL
cursor at commit, and spills a buffer large enough for the index to
grow and then thin out. It needs far more rows than the regular
suite should spend.

I would like to hear what you think of this approach.

[1]
https://postgr.es/m/CAAAe_zD5Ti_C-8LEK6=v3QDUu9YYWMmM%2By1CBk3pOyYEm=jZSw@mail.gmail.com
[2]
https://postgr.es/m/CAAAe_zBmyjM1QgB-cE8XLrXOj4hm=-WTJTc%2BZFoha3%2B2kO4Ajw@mail.gmail.com
[3] https://postgr.es/m/1016045.1795541071@sss.pgh.pa.us

Best regards,
Henson

Attachment Content-Type Size
v2-0001-Index-tuple-positions-in-a-spilled-tuplestore-for.patch application/octet-stream 15.2 KB
v2-0002-Skip-rows-without-fetching-them-when-moving-a-hel.patch application/octet-stream 4.9 KB
v2-0003-XXX-Volume-tests-for-the-tuplestore-position-inde.patch application/octet-stream 6.6 KB

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Hayato Kuroda (Fujitsu) 2026-12-02 03:06:52 RE: [PATCH] Reuse slot helpers in pg_get_replication_slots and slot copy
Previous Message Ideriha, Takeshi 2026-12-02 02:44:42 Re: [PATCH] pgcrypto: Fix sha-crypt rounds= values that do not fit in int (BUG #19743)