Repository navigation
Batch shadow TOAST read-ahead across rows - #348
harshil-goel wants to merge 2 commits into
Conversation
BenchmarksSetup: one m8g.xlarge (4 vCPU Graviton, 16 GB), walshadow state on io2, Postgres 18 source, ClickHouse and walshadow on the same box, Workload: 16 pgbench clients running
Notes:
Checks after all runs:
Not run: the Postgres-backed integration tests. |
gpt5.2solimport pathlib
import socket
import struct
import subprocess
import tempfile
import time
pg_bin = pathlib.Path('/usr/lib/postgresql/19/bin')
pgext = pathlib.Path('/tmp/ws-toast-review.T7h9n8/pgext')
def pg(tool, *args):
result = subprocess.run([pg_bin / tool, *map(str, args)], capture_output=True, text=True, timeout=40)
if result.returncode:
raise RuntimeError(f'{tool}: {result.stdout}\n{result.stderr}')
return result.stdout.strip()
def config(cluster, text):
with (cluster / 'postgresql.conf').open('a') as conf:
conf.write('\n' + text + '\n')
def wait_for(probe):
deadline = time.monotonic() + 20
while not probe():
if time.monotonic() >= deadline:
raise RuntimeError('timed out')
time.sleep(0.02)
def lsn(pos):
high, low = pos.split('/')
return (int(high, 16) << 32) + int(low, 16)
def request(path, op, payload=b''):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
client.settimeout(5)
client.connect(str(path))
client.sendall(struct.pack('!IB', len(payload) + 1, op) + payload)
with client.makefile('rb') as stream:
size, = struct.unpack('!I', stream.read(4))
response = stream.read(size)
assert len(response) == size
return response
def fetch(path, floor, relation, values):
payload = struct.pack('!QII', lsn(floor), relation, len(values))
payload += b''.join(struct.pack('!II', *entry) for entry in values)
response = request(path, 5, payload)
if response[0] != 0:
return response[5:].decode()
count, = struct.unpack_from('!I', response, 1)
assert count == len(values)
offset = 5
found = []
for _ in range(count):
status, _, size = struct.unpack_from('!BII', response, offset)
offset += 9
if status == 0:
found.append(response[offset:offset + size])
offset += size
else:
found.append({1: 'missing', 2: 'mismatch'}[status])
assert offset == len(response)
return found
with tempfile.TemporaryDirectory(prefix='ws-replay.') as tmp:
root = pathlib.Path(tmp)
src, sb = root / 'src', root / 'sb'
src_sock, sb_sock, bridge = root / 's', root / 'b', root / 'bridge'
src_sock.mkdir()
sb_sock.mkdir()
def sql(sock, text):
return pg('psql', '-XAtq', '-v', 'ON_ERROR_STOP=1', '-h', sock, '-p', 55432, '-U', 'postgres', '-d', 'postgres', '-c', text)
def toast_entry(relation):
value, size = sql(src_sock, f'SELECT chunk_id, sum(length(chunk_data)) FROM pg_toast.{relation} GROUP BY chunk_id').split('|')
return int(value), int(size)
try:
pg('initdb', '-D', src, '-U', 'postgres', '-A', 'trust', '--no-sync')
config(src, f"listen_addresses = ''\nport = 55432\nunix_socket_directories = '{src_sock}'\nautovacuum = off\n")
pg('pg_ctl', '-D', src, '-l', root / 'src.log', '-w', 'start')
sql(src_sock, "CREATE TABLE t (id int, body text); ALTER TABLE t ALTER body SET STORAGE EXTERNAL; INSERT INTO t VALUES (1, repeat('a', 240000));")
relation, name = sql(src_sock, "SELECT c.oid, c.relname FROM pg_class c WHERE c.oid = (SELECT reltoastrelid FROM pg_class WHERE oid = 't'::regclass)").split('|')
old = toast_entry(name)
sql(src_sock, 'DELETE FROM t WHERE id = 1')
old_lsn = sql(src_sock, 'SELECT pg_current_wal_flush_lsn()')
pg('pg_basebackup', '-D', sb, '-X', 'stream', '-c', 'fast', '--no-sync', '-h', src_sock, '-p', 55432, '-U', 'postgres')
(sb / 'standby.signal').touch()
config(sb, f"unix_socket_directories = '{sb_sock}'\nprimary_conninfo = 'host={src_sock} port=55432 user=postgres'\ndynamic_library_path = '{pgext}:$libdir'\nshared_preload_libraries = 'walshadow'\nwalshadow.socket_path = '{bridge}'\nwalshadow.databases = 'postgres'\nwalshadow.bridge_workers = 1\n")
pg('pg_ctl', '-D', sb, '-l', root / 'sb.log', '-w', 'start')
wait_for(bridge.exists)
wait_for(lambda: sql(sb_sock, f"SELECT pg_last_wal_replay_lsn() >= '{old_lsn}'::pg_lsn") == 't')
sql(sb_sock, 'SELECT pg_wal_replay_pause()')
wait_for(lambda: sql(sb_sock, 'SELECT pg_get_wal_replay_pause_state()') == 'paused')
assert fetch(bridge, old_lsn, int(relation), [old]) == [b'a' * 240000]
print('Before replay: old value readable at its own LSN', flush=True)
sql(src_sock, 'VACUUM t')
sql(src_sock, "INSERT INTO t VALUES (2, repeat('b', 240000))")
new_lsn = sql(src_sock, 'SELECT pg_current_wal_flush_lsn()')
new = toast_entry(name)
both = [old, new]
waiting = fetch(bridge, new_lsn, int(relation), both)
assert isinstance(waiting, str) and 'below the requested' in waiting, waiting
print(f'Mixed batch refused while old value still readable: {waiting}', flush=True)
sql(sb_sock, 'SELECT pg_wal_replay_resume()')
wait_for(lambda: sql(sb_sock, f"SELECT pg_last_wal_replay_lsn() >= '{new_lsn}'::pg_lsn") == 't')
after = fetch(bridge, new_lsn, int(relation), both)
assert after == ['missing', b'b' * 240000], [x if isinstance(x, str) else len(x) for x in after]
print('After replay reaches batch floor: old value missing, new value readable', flush=True)
except Exception:
for log in ('src.log', 'sb.log'):
if (root / log).exists():
print((root / log).read_text()[-5000:], flush=True)
raise
finally:
for cluster in (sb, src):
if (cluster / 'postmaster.pid').exists():
pg('pg_ctl', '-D', cluster, '-m', 'immediate', '-w', 'stop') |
057624f to
c0a2580
Compare
opus found another raceThe race that survives 7642ffa: later rows take the newest readPendingReads::take now picks the entry with the highest LSN at or below the row's LSN. The PR's own test each_referrer_of_one_value_takes_its_own_read asserts this. Main kept one entry per value and handed the earliest read to any later referrer. -- t(id int, n int, doc text, doc SET STORAGE EXTERNAL); row 1 holds value v
BEGIN; UPDATE t SET n = n + 1 WHERE id = 1; ROLLBACK; -- L1: read-ahead E1 for v; the planner never consumes it
-- E1 finishes and holds v's bytes
UPDATE t SET n = n + 1 WHERE id = 1; -- L2: read-ahead E2 for v (main skips it because E1 exists)
DELETE FROM t WHERE id = 1; VACUUM t; -- Lv: chunks reclaimed (pruning alone also does it)E2 always runs after E1: it is reserved later, and a pool takes only one read per value, so E2 cannot join E1's pool. If replay passes Lv between the two reads:
To make it repeatable:
While replay is paused, E2 is ahead of replay, so it runs as a single read marked "started" and the planner waits on it. After resume, the first replay check (the 20 ms poll or an apply wake) will very likely already see replay past Lv. I have not run this. The aborted referrer can come from a rolled-back savepoint, a deadlock retry or a statement timeout, all common. The fix is small: drop AHEAD_REFERRERS, which the PR's benchmark showed gave no measurable gain, or make take prefer the oldest entry at or below the row's LSN. This kills the multi-reader part of the PR, not pooling. |
New in this version
|
6ce9524 to
1f6c04a
Compare
There was a problem hiding this comment.
Auto-approved by the AI review gate on 1f6c04a. Details in the approver's comment on this pull request.
AI review gate — auto-approved
History (latest 5 heads, newest first)
|
1f6c04a to
30116c4
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 30116c4. Configure here.
AI review gate — AI review passedClean review from: Cursor Bugbot. |
30116c4 to
7d8cfe2
Compare
There was a problem hiding this comment.
Auto-approved by the AI review gate on 7d8cfe2. Details in the approver's comment on this pull request.
Three controlled probes confirmed regressions.
will push commit |
Keep one pending read per TOAST value. Fit each batch into one request and hold its memory reservation until the fetch ends, even if a reader drops out. Read values individually when shadow replay is behind, the batch exceeds the memory budget, or a batch fetch fails. Save the transaction IDs used to detect reused TOAST IDs before fetching, since those records can expire during the read.
There was a problem hiding this comment.
Auto-approved by the AI review gate on 0afccb7. Details in the approver's comment on this pull request.

Shadow-mode TOAST read-ahead now shares one bridge round trip across queued rows (up to 256 values, per-value xid ceilings) and queues up to 65,536 requests, so bulk updates of TOAST-carrying rows stop saturating the serial queue worker.
Replay waits also wake on the walsender's apply-progress gate, with the 20 ms poll kept as fallback.
Note
Medium Risk
Touches WAL replay ordering, shadow bridge batching, and generation checks for TOAST values; incorrect batching or LSN/ceiling handling could return wrong or stale external values.
Overview
Shadow-mode TOAST read-ahead now coalesces queued fetches for the same TOAST relation into shared bridge round trips (up to 256 values or 64 MiB, 65,536 queue depth) when replay has already passed each read’s LSN; reads ahead of replay or that miss the batch still go alone, and planning does not block on reads that have not actually started.
The
ChunkStorepath gainsmixed_bounds, per-valuefetch_bounded, andreplayed_throughsoShadowToastStorecan judge generation per referring LSN in one batched call.PendingReads::batcheduses lazy “started” signaling so planning only waits on in-flight work.Replay waits for shadow values can wake on the stream’s apply-progress gate (
Oracle::with_replay_wake) instead of only polling, with the existing poll interval as fallback.Configuration docs describe the new shadow read-ahead batching rules.
Reviewed by Cursor Bugbot for commit 0afccb7. Bugbot is set up for automated code reviews on this repo. Configure here.