Skip to content

Batch shadow TOAST read-ahead across rows - #348

Open
harshil-goel wants to merge 1 commit into
mainfrom
harshil/batch-shadow-toast-reads
Open

harshil-goel wants to merge 1 commit into
mainfrom
harshil/batch-shadow-toast-reads

Conversation

@harshil-goel

@harshil-goel harshil-goel commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

@harshil-goel

Copy link
Copy Markdown
Contributor Author

Benchmarks

Setup: one m8g.xlarge (4 vCPU Graviton, 16 GB), walshadow state on io2, Postgres 18 source, ClickHouse and walshadow on the same box, [toast] mode = "shadow", 4 bridge workers. Eight tables of 50K rows, one row in seven carrying a 4 KB EXTERNAL text column.

Workload: 16 pgbench clients running UPDATE t SET status = 'bulk', updated_at = now() WHERE id BETWEEN :a AND :a + 700 AND doc IS NOT NULL, which leaves the TOAST column unchanged (about 520 WAL records per commit).

build records/s under load records/s draining TOAST values/s values per round trip pump blocked_out
main 117-150K ~170K 22.7K 1 0.94
main + queue cap only 92-130K 166-170K 17.6-25K 1 0.91-0.96
batching only 161K not measured 31.0K 3.5 0.93
batching + several referrers per value 164K not measured 30.9K 3.8 0.89
this PR 270K 560K 51-54K (105-108K draining) ~58 0.5-0.6

Notes:

  • On main with read_ahead = false the queue worker is busy 0.999 s/s, of which 0.95 s/s is bridge round trips (10.5K fetches/s at 89 µs, 0.31 cores).
  • Batching alone left about a quarter of values on single foreground fetches because the read-ahead queue (4,096) filled. The queue cap alone changes nothing because every read is still one value per round trip.
  • Several referrers per value made no measurable difference on this workload.
  • The apply-progress wake made no measurable difference here (22.7K values/s before and after); this shadow never trails its readers, so that path is not exercised.
  • Under load Postgres, ClickHouse and walshadow share 4 cores, so the under-load numbers are depressed by contention.

Checks after all runs:

  • Row count, TOAST document count, total document length, distinct document hashes, payload length and status counts match between Postgres and ClickHouse (FINAL, _is_deleted = 0) on all eight tables.
  • toast_fetch_miss_total and every toast_values_filled_*_total counter stayed at 0.
  • New-TOAST inserts and a mixed insert/update workload (8.4K commits/s) kept up with no backlog.
  • Peak resident_payload_peak_bytes 584 MB, against 322 MB with the queue cap only.

Not run: the Postgres-backed integration tests.

@serprex

serprex commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

I reproduced the reclamation race on PostgreSQL 19. An older value read successfully on its own. The mixed batch was refused until replay reached the newer member. By then, replay had applied VACUUM and the older value came back missing. Streaming can emit NULL or a column default in that case. PostgreSQL’s snapshot conflict checks only protect snapshots old enough to conflict with pruning.

I’d batch across WAL positions only when replay already covers every member, and let planning bypass speculative reads that are still queued. That removes the extra replay dependency. Shadow TOAST still needs a reclamation fence for a retention guarantee.

gpt5.2sol
import 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')

@harshil-goel
harshil-goel force-pushed the harshil/batch-shadow-toast-reads branch 2 times, most recently from 7642ffa to 057624f Compare November 24, 2026 20:12
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.
@harshil-goel
harshil-goel force-pushed the harshil/batch-shadow-toast-reads branch from 057624f to c0a2580 Compare November 24, 2026 20:13
@serprex

serprex commented Nov 24, 2026 •

Copy link
Copy Markdown
Member
opus found another race The race that survives 7642ffa: later rows take the newest read

PendingReads::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:

  • main: the planner for the L2 row takes E1, which already holds v, so the row is correct.
  • PR: the planner takes E2, which comes back missing. The foreground fetch at L2 also misses, so the column becomes NULL and toast_values_filled_superseded goes up. E1 sits unused until a clear or reclaim drops it.

To make it repeatable:

  1. Run the aborted update and wait for E1 to finish.
  2. Pause shadow replay below L2 with pg_wal_replay_pause().
  3. Run the committed UPDATE, then DELETE and VACUUM.
  4. Resume replay.

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.

@serprex

serprex commented Nov 24, 2026 •

Copy link
Copy Markdown
Member
New in this version
  • Extra bridge round trip per batch. Every pass through the batch loop calls replayed_through, which sends a replay_lsn request before the batch's fetch, so a batch of one now costs two round trips. Replay only moves forward (apart from restarts, which read_at already retries), so two cheaper options work:
    • Cache the last value and only re-query when a queued member is above it.
    • Use the walsender aggregate's min_apply_lsn instead. It lags actual replay, which only makes the cutoff stricter.
  • Dead queue entries. When a not-yet-started read is dropped, its AheadRequest stays in AheadFetch.queued with a closed sender. It is only cleared by the next take for that same (db, toastrelid), so a relation that is never read again keeps its dead entries. A drop guard that calls withdraw(key, token) would clear them.
  • Commit message and docs are now wrong. The commit message says "values no longer fall back to single foreground fetches", but with the new started rule they do. Neither the commit message nor docs/configuration.md mentions the replay cutoff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants