Repository navigation
Read shadow TOAST before polling replay - #230
Conversation
8eb5f5a to
7e4048a
Compare
|
|
||
| /// 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) { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| // 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 { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| let turn = self.polling.try_lock(); | ||
| let polled = match turn { | ||
| Ok(_) => bridge.replay_lsn().await, | ||
| Err(_) => Ok(at), |
There was a problem hiding this comment.
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"
There was a problem hiding this comment.
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.
| return Ok(through); | ||
| } | ||
| // One waiter polls, the rest follow its answers | ||
| let turn = self.polling.try_lock(); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| 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 => { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
|
Simpler alternative: the worker already refuses a floor above replay, so skip the cache and always try the read at 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)
Retrying the slow-path read on refusal the same way would also close the existing race of a restart between |
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>
7e4048a to
87d9953
Compare
Adopted in 87d9953, with a retry on the slow path too:
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 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. |
Based on
mainwith #222 merged (97f9305, same tree asharshil/perf91efc4d, 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: firstreplay_lsn, thenfetch_toast. In a production profile on 0.1.5, the two ops run paired 1:1 at ~4.6k/s, 124 µs forfetch_toastplus 60 µs forreplay_lsnper 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 withoutEmitErrorReport, so the shadow log stays quiet.ShadowToastStore::fetch_manynow leans on that check instead of asking first:await_replay) and read again only when the read is refused (BridgeError::Remote) or the shadow is unreachable (BridgeError::Io).read_valueskeeps theBridgeErrorfor that; protocol, version and size errors return on the first attempt.replay_lsnandfetch_toast, which today fails the read. A third refusal returns its error.The store keeps no replay position and no state shared between callers.
Results
bench/ceramicfrom #229, on a dev VM whose TOAST read cost matches production: c_fetch is 126 µs onharshil/perfagainst production's ~115 µs (45 µs on the box that harness was calibrated on), and shadow data, source WAL andout/share one EBS volume as in production. The golden is built withharshil/perf. The daemon is pinned to 8 physical cores, with source and ClickHouse on their own cores. 4 interleaved runs per side:harshil/perf91efc4dreplay_lsnperfetch_toastcallfetch_toastper callwalshadow-queueCPU / recAbout 300k
fetch_toastcalls per run see ~3replay_lsnpolls 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 whenreplay_lsnis 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=1the 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 andfetch_toastcosts ~190-200 µs. 4 interleaved runs per side:harshil/perf91efc4dfetch_toast/ callreplay_lsnperfetch_toastcallwalshadow-queueCPU / recTests
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 pollsreplay_lsnonce 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_writesreads through a real primary at boundu64::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".cargo nextest run --workspace --all-targets --lockedagainst PG 17 withWALSHADOW_REQUIRE_TOOLS=1,cargo fmt --check,cargo clippy --all-targets -- -D warnings.🤖 Generated with Claude Code