Skip to content

Read shadow TOAST before polling replay - #230

Merged
serprex merged 1 commit into
mainfrom
toast-replay-skip
Oct 20, 2026
Merged

serprex merged 1 commit into
mainfrom
toast-replay-skip

Conversation

@iskakaushik

@iskakaushik iskakaushik commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Based on main with #222 merged (97f9305, same tree as harshil/perf 91efc4d, which the numbers below were measured against).

Problem

With [toast] mode = "shadow", every value the planner reads from the store costs two serial bridge round trips on the queue worker: first replay_lsn, then fetch_toast. In a production profile on 0.1.5, the two ops run paired 1:1 at ~4.6k/s, 124 µs for fetch_toast plus 60 µs for replay_lsn per fetch, with 1.2 values per batch. TOAST takes ~85% of the serial worker's wall time, the queue thread is 44% on-CPU, and most of the 8 bridge backends sit idle.

The worker runs far behind a shadow that replays only a few MB behind the pump, so replay nearly always covers the bound already.

Change

The bridge worker already refuses a floor above its replay position (ws_handle_fetch_toast). It samples replay before it opens the relation, so a refusal takes no lock, and the worker reports it without EmitErrorReport, so the shadow log stays quiet. ShadowToastStore::fetch_many now leans on that check instead of asking first:

  • On a standby, read at the bound straight away. Wait for replay (await_replay) and read again only when the read is refused (BridgeError::Remote) or the shadow is unreachable (BridgeError::Io). read_values keeps the BridgeError for that; protocol, version and size errors return on the first attempt.
  • A read refused after the wait waits and reads once more. That covers a restart that rewinds replay between replay_lsn and fetch_toast, which today fails the read. A third refusal returns its error.
  • A primary reads at floor 0, as before: its replay position stays where crash recovery ended.

The store keeps no replay position and no state shared between callers.

Results

bench/ceramic from #229, on a dev VM whose TOAST read cost matches production: c_fetch is 126 µs on harshil/perf against production's ~115 µs (45 µs on the box that harness was calibrated on), and shadow data, source WAL and out/ share one EBS volume as in production. The golden is built with harshil/perf. The daemon is pinned to 8 physical cores, with source and ClickHouse on their own cores. 4 interleaved runs per side:

harshil/perf 91efc4d this PR B/A
rec/s 121,822 ± 659 167,634 ± 299 1.376
drain 47.9 s 35.0 s 0.731
f (fetches/rec) 0.0516 0.0516 1.000
c_fetch 126 µs 80.8 µs 0.643
replay_lsn per fetch_toast call 1 0.00001
refused fetch_toast per call 0 0.000003
fetch s/s 0.79 0.70
pump wait s/s 0.80 0.75
walshadow-queue CPU / rec 3,350 ns 2,662 ns 0.795
daemon cores 0.97 1.13

About 300k fetch_toast calls per run see ~3 replay_lsn polls and ~1 refusal. In model terms (rec/s = 1/(c_rec + f·c_fetch)): c_rec stays ~1.8 µs and f·c_fetch drops from 6.5 to 4.2 µs per record. The production share is smaller when replay_lsn is fast, and larger when it is slow (60 µs on 0.1.5).

Shadow reads from disk

Production's shadow is far larger than memory, while ceramic's toast relation fits in page cache. With COLD_SHADOW=1 the harness evicts the shadow's files from page cache after the restore (posix_fadvise(DONTNEED)), so its first read of each page goes to EBS and fetch_toast costs ~190-200 µs. 4 interleaved runs per side:

harshil/perf 91efc4d this PR B/A
rec/s 68,804 ± 120 81,532 ± 268 1.185
drain 83.2 s 70.6 s 0.849
c_fetch 247 µs 202 µs 0.817
bridge fetch_toast / call 187 µs 201 µs
replay_lsn per fetch_toast call 1 < 0.000001
walshadow-queue CPU / rec 3,299 ns 2,612 ns 0.792
daemon cores 0.55 0.56

Tests

  • refused_read_waits_for_replay_and_retries: a standby scripted on the bridge's own fake worker (ops::bridge::tests, whose response builders are now shared) refuses 0 to 3 times. Each read polls replay_lsn once per refusal and never before its first read. Up to two refusals end in the value, a third returns the refusal.
  • shadow_store_reads_and_refuses_writes reads through a real primary at bound u64::MAX. The primary's worker refuses any floor past its recovery end, so this passes only while a primary reads at floor 0.
  • shadow_store_read_survives_worker_restart: its stand-in worker now refuses a floor above replay, as the real one does. A read refused while replay lags, held while the worker is down, completes once the worker returns with replay past the bound; a worker that stays down fails with "shadow unreachable".
  • Full cargo nextest run --workspace --all-targets --locked against PG 17 with WALSHADOW_REQUIRE_TOOLS=1, cargo fmt --check, cargo clippy --all-targets -- -D warnings.

🤖 Generated with Claude Code

Base automatically changed from harshil/perf to main October 20, 2026 02:48
Comment thread src/toast/shadow_store.rs Outdated

/// Replay position known since the bridge last redialled
fn known_replay(&self, bridge: &Bridge, (at, dials): (u64, u64)) -> u64 {
if dials == bridge.stats.reconnects.load(Ordering::Relaxed) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reconnects is a metrics counter, bumped by a transport error on any of the 8 slots for any op. As an epoch it is also late: after a shadow restart nothing bumps it until some call hits a dead socket, so the fast path still sends a read to a rewound shadow and only recovers because ws_handle_fetch_toast refuses the floor. Correctness rests entirely on that worker check, so this epoch buys nothing for safety

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in 87d9953. The store keeps no replay state, and there is no epoch. Safety rests on the worker refusing a floor above replay, as it already did.

Comment thread src/toast/shadow_store.rs Outdated
// below the remembered position, so a failed read waits and retries
let known = *self.replayed.borrow();
if max_lsn != 0 && self.known_replay(bridge, known) >= max_lsn {
if let Ok(got) = read_values(bridge, toast_relid, values, max_lsn, ceiling).await {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This catches every error, not only the floor refusal. Protocol, Version and RequestTooLarge pay a second attempt after await_replay, and the first error is discarded. Fallback should match BridgeError::Remote (refusal) and Io (restart) only, which needs read_values to return BridgeError instead of stringifying it

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. read_values now returns BridgeError, and only Remote or Io fall back to await_replay and a retry. Protocol, Version and RequestTooLarge return on the first attempt with their own error.

Comment thread src/toast/shadow_store.rs Outdated
let turn = self.polling.try_lock();
let polled = match turn {
Ok(_) => bridge.replay_lsn().await,
Err(_) => Ok(at),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Followers turn the shared value into Ok(at), so they never see Err(Io). While the poller backs off on an unreachable shadow, followers time out with "replay stuck at X" instead of "shadow unreachable"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The follower path is gone. Each read that needs to wait goes through await_replay itself, so an unreachable shadow reports "shadow unreachable" again; shadow_store_read_survives_worker_restart checks that message.

Comment thread src/toast/shadow_store.rs Outdated
return Ok(through);
}
// One waiter polls, the rest follow its answers
let turn = self.polling.try_lock();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Who are the concurrent waiters? Both fetch_values call sites, xact_buffer.rs and resolve_batch in bootstrap.rs, loop and await serially, and the description calls the queue worker serial. Unless bootstrap's deferred drain and live tail share one store concurrently, the watch + mutex never engage

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this PR alone, nobody on the hot path. In live CDC the planner is the only caller of its store, and bootstrap and backfill build their own. The only sharing is greenfield bootstrap, where the window leg and the drain share one resolver, so at most two waiters. The watch and mutex were there for the read-ahead in #232, which no longer needs them, so they are gone.

Comment thread src/toast/shadow_store.rs Outdated
shadow.polls.fetch_add(1, Ordering::SeqCst);
body.extend(at.to_be_bytes());
}
_ if u64::from_be_bytes(req[1..9].try_into().unwrap()) > at => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fake worker hand-rolls the wire format: literal op codes 1/4, req[1..9], req[13..17], fixed fetch response bytes. It duplicates fake_worker framing in bridge.rs and can drift from the real protocol without failing. "Served at or above bound" is enforced by this fake itself, so what the test checks is the fallback and the poll count

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced. The test now scripts ops::bridge::tests::fake_worker, whose builders are shared as pub(crate) with new lsn_body / remote_body / fetch_body, and it checks the exact replay_lsn and fetch_toast counts for 0-3 refusals. The primary half runs against a real PG primary at bound u64::MAX. The stand-in worker in tests/bridge.rs now also refuses a floor above replay; shadow_store_read_survives_worker_restart failed without that.

@serprex

serprex commented Oct 20, 2026

Copy link
Copy Markdown
Member

Simpler alternative: the worker already refuses a floor above replay, so skip the cache and always try the read at max_lsn while in recovery, falling back to await_replay on refusal. Untested sketch, with read_values returning BridgeError:

let bridge = self.bridge().await?;
let ceiling = self.read.ceiling.at(max_lsn);
// Worker refuses a floor above replay, so read before polling it
if max_lsn != 0 && bridge.info().in_recovery {
    match read_values(bridge, toast_relid, values, max_lsn, ceiling).await {
        Err(BridgeError::Remote(_) | BridgeError::Io(_)) => {}
        got => return got.map_err(shadow_err),
    }
}
let floor = self.await_replay(bridge, max_lsn).await?;
read_values(bridge, toast_relid, values, floor, ceiling)
    .await
    .map_err(shadow_err)
  • Hit rate is at least this PR's: it hits whenever actual replay covers the bound, not only when the last polled position does
  • A miss costs one refused round trip. The worker samples replay before try_table_open, takes no lock, and FlushErrorState without EmitErrorReport keeps the shadow log quiet. On a miss the read waits on replay at 20 ms polls anyway
  • Drops the replayed watch, the polling mutex, known_replay, the poller/follower split and the reliance on reconnects; replay_lsn polls go to ~0 on the bench workload
  • The in_recovery guard keeps primaries at floor 0, since a primary's GetXLogReplayRecPtr is frozen at end of crash recovery
  • Test shrinks to: refusal, wait, retry succeeds; primary never sends a nonzero floor

Retrying the slow-path read on refusal the same way would also close the existing race of a restart between replay_lsn and fetch_toast

Every shadow TOAST fetch on a standby asked the bridge for the replay
position before reading the chunks, so each value cost two serial round
trips on the queue worker. A production profile shows replay_lsn and
fetch_toast paired 1:1, 60 us on top of 124 us per value, while the
shadow replays a few MB behind the pump and far ahead of the worker.

The worker already refuses a floor above its replay position, and
samples replay before it opens the relation, so a refusal takes no lock
and leaves the shadow log quiet. Read at the bound first, and wait for
replay only once the read is refused or the shadow is unreachable.
Protocol, version and size errors return as they are.

A restart can rewind replay between the wait and the read, so a read
refused after the wait waits and reads once more before it fails.

A primary's replay position stays where crash recovery ended, so a
primary keeps reading at floor 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@iskakaushik iskakaushik changed the title Skip shadow replay polls a known position covers Read shadow TOAST before polling replay Oct 20, 2026
@iskakaushik

Copy link
Copy Markdown
Contributor Author

Simpler alternative: the worker already refuses a floor above replay, so skip the cache and always try the read at max_lsn while in recovery, falling back to await_replay on refusal.

Adopted in 87d9953, with a retry on the slow path too:

  • While the shadow is in recovery, fetch_many reads at the bound right away.
  • A Remote or Io error leads to await_replay and another read, at most three reads in all, then the error is returned.
  • A primary reads at floor 0.

I capped the slow-path retry instead of retrying until the wait budget runs out. Replay already covers the bound by then, so a persistent non-refusal Remote error would otherwise hot-loop.

On ceramic at 8 CPUs it matches the cached-position version: 167.6k against 168.4k rec/s, with about 3 polls and 1 refusal per ~300k calls.

@serprex
serprex merged commit f12de2b into main Oct 20, 2026
6 checks passed
@serprex
serprex deleted the toast-replay-skip branch October 20, 2026 17:19
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