Repository navigation
Batch shadow TOAST read-ahead across rows - #348
harshil-goel wants to merge 1 commit 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') |
7642ffa to
057624f
Compare
Rows carrying an unchanged external value cost one bridge round trip each, so bulk updates of such rows saturate the serial queue worker. Queued read-ahead requests for one TOAST relation now share a round trip, up to 256 values, with each value judged against its own referrer's xid ceiling. Shadow mode queues up to 65,536 requests so values no longer fall back to single foreground fetches, and several pending referrers of one value each hold a read. Replay waits wake on the walsender's apply-progress gate, keeping the 20 ms poll as fallback.
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
|
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.