|
| 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 | +} |
0 commit comments