Skip to content

Commit ad35a88

Browse files
committed
Protect TOAST values needed by shadow replication
PostgreSQL can vacuum TOAST values before walshadow reads them. Hold back source cleanup while replication still needs those values. Check once a second so cleanup can resume promptly, and improve read-ahead so fewer writes wait for TOAST reads.
1 parent 096469a commit ad35a88

25 files changed

Lines changed: 1648 additions & 107 deletions

‎Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,10 @@ harness = false
122122
name = "jsonb"
123123
harness = false
124124

125+
[[bench]]
126+
name = "shadow_toast_horizon"
127+
harness = false
128+
125129
[dev-dependencies]
126130
walshadow = { path = ".", features = ["test-support"] }
127131
# Pre-main tracing subscriber for tests

‎architecture/shadow-toast.md‎

Lines changed: 71 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,82 @@ read-only from resolver perspective; decoded chunk writes never go back into
3434
PostgreSQL
3535

3636
Bounded speculative reads fetch and decompress values ahead of commit planning.
37-
Planning consumes matching results or resolves values normally. Chunk births
38-
and schema barriers invalidate speculative reads; these reads do not prevent
39-
shadow reclamation
37+
Planning consumes matching results or resolves values normally. Schema barriers
38+
invalidate speculative reads, and planning a commit that births chunks drops
39+
reads of those IDs reserved before that commit. Prescan skips only values born
40+
in referring transaction, whose chunks resolve from its own WAL. These reads do
41+
not prevent shadow reclamation
4042

4143
Reads select database-specific bridge using referring row’s database OID.
4244
Batched bootstrap lookups include database OID in value keys, so identical
4345
TOAST relation and value IDs across databases stay separate
4446

45-
PostgreSQL can reclaim chunks through prune, vacuum, truncate, drop, or rewrite
46-
before slower ClickHouse work reads them. Current mode reports such values as
47-
superseded and emits NULL or column default. To detect reused value IDs,
48-
extension reports newest chunk xmin and daemon compares it with highest xid
49-
assigned at referring record. Newer chunks indicate a replacement, whether
50-
complete or partial. A short run with an older xmin still indicates partial
51-
reclamation of original value.
52-
Planned work prevents source reclamation where possible and saves values before
53-
shadow reclaims them, see [safe reclamation plan](../plans/shadow_toast.md)
47+
PostgreSQL can remove TOAST chunks before walshadow reads them for ClickHouse.
48+
If chunks are gone or belong to a replacement value, walshadow reports the
49+
value as superseded and writes NULL or the column default. To spot a reused
50+
value ID, compare the newest chunk's `xmin` with the highest transaction ID
51+
assigned when the row's WAL record was written. A newer chunk belongs to a
52+
replacement. If some chunks are missing and the rest are older, PostgreSQL
53+
removed part of the original value.
54+
55+
See how walshadow could save values before shadow removes them in the
56+
[safe reclamation plan](../plans/shadow_toast.md)
57+
58+
## Source horizon pin
59+
60+
With `[toast] source_horizon_pin`, walshadow uses hot standby feedback to tell
61+
source PostgreSQL which deleted row versions to keep. This keeps pruning and
62+
vacuum from removing TOAST chunks walshadow may still need. Shadow only removes
63+
chunks when it replays WAL from source.
64+
65+
The resolved floor is the WAL position walshadow can safely restart from. It
66+
stays at or before the first record of any open transaction. Walshadow picks
67+
the latest transaction ID sample taken at or before that position. Any
68+
transaction that marks chunks as deleted at or after the sample's WAL
69+
position has an ID at least as high as the sample, so PostgreSQL keeps those
70+
chunks.
71+
72+
PostgreSQL logs the oldest running transaction ID (`oldestRunningXid`) about
73+
every 15 seconds while busy. On a primary, walshadow also uses a separate SQL
74+
connection to read a snapshot's `xmin`, then `pg_current_wal_insert_lsn()`,
75+
once a second. A transaction writing at or after that WAL position was running
76+
when PostgreSQL took the snapshot or started later. Walshadow orders samples
77+
by WAL position because the SQL connection can sample WAL ahead of the stream.
78+
A new source connection may follow another timeline, so walshadow drops
79+
samples ahead of the WAL it has consumed. It warns once when sampling fails
80+
and falls back to `oldestRunningXid` until sampling recovers.
81+
82+
Walshadow sends feedback only when the `xmin` changes, apart from standby
83+
status, because PostgreSQL keeps the last value it received.
84+
85+
PostgreSQL checks the transaction ID's epoch in feedback to reject IDs from
86+
outside the recent past. Walshadow uses the source's next full transaction ID
87+
to work out the epoch for each 32-bit ID from WAL. With a physical replication
88+
slot, PostgreSQL keeps the slot's `xmin` when walshadow disconnects and can
89+
only advance or clear it.
90+
91+
Walshadow saves the `xmin` for the resolved floor in the resume manifest. At
92+
startup it uses the slot's `xmin` if it has one, and warns when that is ahead
93+
of the saved `xmin`. Otherwise it uses the saved `xmin` or the source's oldest
94+
running transaction ID, whichever is older, and never goes below the oldest
95+
`datfrozenxid`. Without a slot, nothing holds `xmin` while walshadow is
96+
disconnected, and a slot can lose its `xmin` when the source crashes before a
97+
checkpoint. Restoring the saved `xmin` only protects chunks that vacuum has
98+
not yet removed. Connecting with the pin disabled clears any `xmin` held by
99+
an earlier session.
100+
101+
The pin also prevents reuse of a value ID while any of its chunks remain.
102+
PostgreSQL checks the TOAST index with `SnapshotAny`, which includes chunks
103+
that ordinary queries cannot see. `TRUNCATE`, `DROP TABLE`, `VACUUM FULL`,
104+
`CLUSTER`, and `ALTER TABLE` rewrites can still remove or replace whole files.
105+
Slot invalidation and promotion can lose the pin, and bootstrap runs before
106+
it starts. A standby source forwards feedback upstream only with
107+
`hot_standby_feedback = on`, and walshadow warns at startup when it is off.
108+
109+
Even when walshadow keeps up, the pin advances only as ClickHouse acknowledges
110+
writes, walshadow saves its progress, and the floor reaches the next WAL
111+
segment boundary. Keeping old versions of frequently updated rows reduces
112+
source throughput in the [churn benchmark](../benches/shadow_toast_horizon.rs).
54113

55114
## Implementation
56115

‎benches/shadow_toast_horizon.rs‎

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
//! Shadow-TOAST cost under pgbench churn of pointer-only updates and value
2+
//! replacements on toasted rows. Daemon is release-built under `cargo bench`
3+
//!
4+
//! Live mode streams while pgbench runs. Reports source throughput, how far
5+
//! horizon pin trails source head, dead row versions VACUUM keeps right after
6+
//! churn, and values lost to reclamation
7+
//!
8+
//! Drain mode builds a backlog of `--drain` transactions while daemon is down,
9+
//! then times catch-up into ClickHouse with pin on. Steady rate excludes
10+
//! daemon startup. `--metrics` prints worker, TOAST and bridge counters
11+
//!
12+
//! ```text
13+
//! cargo bench --bench shadow_toast_horizon -- --secs 10 --reps 3 --pin both
14+
//! cargo bench --bench shadow_toast_horizon -- --drain 160000 --read-ahead off
15+
//! ```
16+
//!
17+
//! Needs PostgreSQL tools, pgbench and ClickHouse on PATH, plus
18+
//! `pgext/walshadow.so` built against that major
19+
//!
20+
//! `harness = false`, so nextest lists it by answering `--list`
21+
22+
#[path = "../tests/common/horizon_fixture.rs"]
23+
mod hz;
24+
25+
use std::fs;
26+
use std::path::Path;
27+
use std::process::{Command, Stdio};
28+
use std::time::{Duration, Instant};
29+
30+
use anyhow::{Context, Result, ensure};
31+
use hz::{ROWS, Rig, SCHEMA, fx, slot_lag, toast_dead_tuples};
32+
33+
const USAGE: &str = "usage: shadow_toast_horizon [--secs N] [--reps N] [--pin on|off|both] \
34+
[--read-ahead on|off] [--drain TXNS] [--metrics]";
35+
36+
struct Opts {
37+
secs: u32,
38+
reps: u32,
39+
pins: Vec<bool>,
40+
read_ahead: bool,
41+
drain: Option<u32>,
42+
metrics: bool,
43+
}
44+
45+
/// Pointer-only update then value replacement per transaction, 8 KB of
46+
/// uncompressed chunks each
47+
fn churn_script(path: &Path) -> Result<()> {
48+
let sql = format!(
49+
"\\set k random(1, {ROWS})\n\
50+
UPDATE {SCHEMA}.t SET meta = 'p' || :k WHERE id = :k;\n\
51+
UPDATE {SCHEMA}.t SET body = repeat(md5(random()::text), 250) WHERE id = :k;\n"
52+
);
53+
Ok(fs::write(path, sql)?)
54+
}
55+
56+
/// pgbench over churn script, `limit` is `-T` seconds or `-t` transactions
57+
fn pgbench(rig: &Rig, limit: [&str; 2]) -> Result<Command> {
58+
let script = rig.tmp.path().join("churn.sql");
59+
churn_script(&script)?;
60+
let cfg = rig.source.config();
61+
let mut cmd = Command::new("pgbench");
62+
cmd.args(["-h", cfg.socket_dir.to_str().unwrap(), "-p"])
63+
.arg(cfg.port.to_string())
64+
.args(["-U", &cfg.user, "-n", "-c", "4"])
65+
.args(limit)
66+
.arg("-f")
67+
.arg(&script)
68+
.arg(&cfg.dbname);
69+
Ok(cmd)
70+
}
71+
72+
fn rig(pin: bool, read_ahead: bool) -> Option<Rig> {
73+
let rig = Rig::new(pin)?;
74+
let cfg = fs::read_to_string(&rig.config).unwrap();
75+
let cfg = cfg.replace("read_ahead = false", &format!("read_ahead = {read_ahead}"));
76+
fs::write(&rig.config, cfg).unwrap();
77+
Some(rig)
78+
}
79+
80+
/// Prints figures, asserts only that pinned values survive
81+
fn churn(o: &Opts, pin: bool) {
82+
let Some(rig) = rig(pin, o.read_ahead) else {
83+
return;
84+
};
85+
let guard = fx::ChildGuard::new(rig.spawn().expect("spawn walshadow-stream"));
86+
let result = (|| -> Result<()> {
87+
rig.wait_bootstrapped()?;
88+
let mut bench = pgbench(&rig, ["-T", &o.secs.to_string()])?
89+
.stdout(Stdio::piped())
90+
.spawn()
91+
.context("spawn pgbench")?;
92+
let (mut ages, mut wal_max) = (Vec::new(), 0);
93+
while bench.try_wait()?.is_none() {
94+
let (age, wal) = slot_lag(&rig.source)?;
95+
ages.push(age);
96+
wal_max = wal_max.max(wal);
97+
std::thread::sleep(Duration::from_millis(250));
98+
}
99+
let out = bench.wait_with_output()?;
100+
ensure!(out.status.success(), "pgbench failed");
101+
let report = String::from_utf8_lossy(&out.stdout);
102+
let txns: u64 = report
103+
.lines()
104+
.find_map(|l| l.strip_prefix("number of transactions actually processed: "))
105+
.and_then(|n| n.split('/').next())
106+
.context("pgbench transaction count")?
107+
.parse()?;
108+
rig.source.psql_one(&format!("VACUUM {SCHEMA}.t"))?;
109+
let toast_dead = toast_dead_tuples(&rig.source)?;
110+
fx::wait_for_ch_value(
111+
&rig.ch,
112+
"SELECT count() FROM default.t",
113+
&(u64::from(ROWS) + 2 * txns).to_string(),
114+
Duration::from_secs(60),
115+
)?;
116+
let superseded = rig.superseded()?;
117+
ages.sort_unstable();
118+
let p50 = ages.get(ages.len() / 2).copied().unwrap_or(0);
119+
let max = ages.last().copied().unwrap_or(0);
120+
eprintln!(
121+
"pin={pin} read_ahead={} xacts={txns} xid/s={} pin_age_xids p50={p50} max={max} \
122+
slot_wal_max={wal_max} toast_dead_after_vacuum={toast_dead} superseded={superseded}",
123+
o.read_ahead,
124+
txns / u64::from(o.secs),
125+
);
126+
report_metrics(&rig, o.metrics)?;
127+
ensure!(!pin || superseded == 0, "pinned values lost: {superseded}");
128+
Ok(())
129+
})();
130+
fx::finish_daemon(guard, &rig.daemon, result);
131+
}
132+
133+
fn drain(o: &Opts, txns: u32) {
134+
let Some(rig) = rig(true, o.read_ahead) else {
135+
return;
136+
};
137+
let mut guard = fx::ChildGuard::new(rig.spawn().expect("spawn walshadow-stream"));
138+
let result = (|| -> Result<()> {
139+
rig.wait_bootstrapped()?;
140+
if let Some(mut first) = guard.child.take() {
141+
fx::tools::stop_gracefully(&mut first);
142+
}
143+
let per_client = txns / 4;
144+
let st = pgbench(&rig, ["-t", &per_client.to_string()])?
145+
.stdout(Stdio::null())
146+
.status()?;
147+
ensure!(st.success(), "pgbench failed");
148+
let wal: u64 = rig
149+
.source
150+
.psql_one(&format!(
151+
"SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)::bigint \
152+
FROM pg_replication_slots WHERE slot_name = '{}'",
153+
hz::SLOT
154+
))?
155+
.trim()
156+
.parse()?;
157+
let want = u64::from(ROWS) + 2 * 4 * u64::from(per_client);
158+
let t0 = Instant::now();
159+
guard.child = Some(rig.spawn()?);
160+
// First rows past bootstrap mark end of daemon startup
161+
let mut first = None;
162+
loop {
163+
let n: u64 = rig
164+
.ch
165+
.query("SELECT count() FROM default.t")
166+
.ok()
167+
.and_then(|n| n.parse().ok())
168+
.unwrap_or(0);
169+
if first.is_none() && n > u64::from(ROWS) {
170+
first = Some((t0.elapsed().as_secs_f64(), n));
171+
}
172+
if n >= want {
173+
break;
174+
}
175+
ensure!(
176+
t0.elapsed() < Duration::from_secs(300),
177+
"drain stuck at {n}/{want}"
178+
);
179+
std::thread::sleep(Duration::from_millis(100));
180+
}
181+
let secs = t0.elapsed().as_secs_f64();
182+
let (start, at_start) = first.context("no rows drained")?;
183+
eprintln!(
184+
"drain read_ahead={} rows={want} wal_mb={} secs={secs:.2} start={start:.2} \
185+
steady_rows/s={:.0} superseded={}",
186+
o.read_ahead,
187+
wal >> 20,
188+
(want - at_start) as f64 / (secs - start),
189+
rig.superseded()?,
190+
);
191+
report_metrics(&rig, o.metrics)
192+
})();
193+
fx::finish_daemon(guard, &rig.daemon, result);
194+
}
195+
196+
fn report_metrics(rig: &Rig, on: bool) -> Result<()> {
197+
if !on {
198+
return Ok(());
199+
}
200+
let metrics = fx::http_get(rig.daemon.metrics_addr, "/metrics")?;
201+
let shown = [
202+
"worker_seconds_total",
203+
"toast_value",
204+
"bridge_request",
205+
"bridge_errors",
206+
];
207+
for l in metrics.lines().filter(|l| {
208+
!l.starts_with('#') && shown.iter().any(|s| l.contains(s)) && !l.ends_with(" 0")
209+
}) {
210+
eprintln!(" {l}");
211+
}
212+
Ok(())
213+
}
214+
215+
fn on_off(v: &str) -> bool {
216+
match v {
217+
"on" => true,
218+
"off" => false,
219+
_ => panic!("{USAGE}"),
220+
}
221+
}
222+
223+
fn main() {
224+
let argv: Vec<String> = std::env::args().skip(1).collect();
225+
// nextest --all-targets lists benches by running them with --list
226+
if argv.iter().any(|a| a == "--list") {
227+
println!("shadow_toast_horizon: benchmark");
228+
return;
229+
}
230+
let mut o = Opts {
231+
secs: 10,
232+
reps: 1,
233+
pins: vec![true, false],
234+
read_ahead: true,
235+
drain: None,
236+
metrics: false,
237+
};
238+
let mut args = argv.iter().filter(|a| *a != "--bench");
239+
while let Some(flag) = args.next() {
240+
if flag == "--metrics" {
241+
o.metrics = true;
242+
continue;
243+
}
244+
let value = args.next().map(String::as_str).expect(USAGE);
245+
let n = || value.parse().expect(USAGE);
246+
match flag.as_str() {
247+
"--secs" => o.secs = n(),
248+
"--reps" => o.reps = n(),
249+
"--drain" => o.drain = Some(n()),
250+
"--read-ahead" => o.read_ahead = on_off(value),
251+
"--pin" if value == "both" => o.pins = vec![true, false],
252+
"--pin" => o.pins = vec![on_off(value)],
253+
_ => panic!("{USAGE}"),
254+
}
255+
}
256+
for _ in 0..o.reps {
257+
if let Some(txns) = o.drain {
258+
drain(&o, txns);
259+
continue;
260+
}
261+
for &pin in &o.pins {
262+
churn(&o, pin);
263+
}
264+
}
265+
}

‎docs/configuration.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ Tune chunk-store buffering independently of inserter count, restart daemon to ap
222222
| `put_batch_bytes` | 67,108,864 | Seal chunk INSERT after this many body bytes |
223223
| `connections` | `ch.inserter_pool_size` | Limit concurrent chunk-store connections |
224224
| `read_ahead` | `true` | Fetch and decode external values ahead of planning |
225+
| `source_horizon_pin` | `true` | In `shadow` mode, hold source vacuum horizon for values still pending |
225226

226227
Both seals apply to bootstrap and WAL chunk writes. Each bootstrap drain holds
227228
its own batch, so more lanes can multiply buffered chunk bodies. A byte seal
@@ -278,6 +279,13 @@ ClickHouse. Choose it only when limits below are acceptable
278279
- Shadow can remove a value before ClickHouse writes its row during heavy lag,
279280
table maintenance, truncate, drop, or restart. Affected destination value
280281
becomes NULL, or column default when destination column is not Nullable
282+
- `source_horizon_pin` stops source VACUUM from removing values pending rows
283+
still reference, by reporting an xmin as hot-standby feedback. It samples
284+
source snapshot every second over one more SQL connection. It holds back
285+
cleanup of every table in source cluster while ClickHouse lags. Set
286+
`[source] slot` so pin holds while walshadow is disconnected, and watch
287+
`SELECT age(xmin) FROM pg_replication_slots` against
288+
`autovacuum_freeze_max_age`. Setting it `false` releases xmin slot holds
281289
- Buffering settings above have no effect because this mode writes no chunks
282290
- Changing mode requires a fresh bootstrap
283291
- Only default tablespace is supported. Bootstrap refuses a mapped table whose

0 commit comments

Comments
 (0)