Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ harness = false
name = "jsonb"
harness = false

[[bench]]
name = "shadow_toast_horizon"
harness = false

[dev-dependencies]
walshadow = { path = ".", features = ["test-support"] }
# Pre-main tracing subscriber for tests
Expand Down
83 changes: 71 additions & 12 deletions architecture/shadow-toast.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,82 @@ read-only from resolver perspective; decoded chunk writes never go back into
PostgreSQL

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

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

PostgreSQL can reclaim chunks through prune, vacuum, truncate, drop, or rewrite
before slower ClickHouse work reads them. Current mode reports such values as
superseded and emits NULL or column default. To detect reused value IDs,
extension reports newest chunk xmin and daemon compares it with highest xid
assigned at referring record. Newer chunks indicate a replacement, whether
complete or partial. A short run with an older xmin still indicates partial
reclamation of original value.
Planned work prevents source reclamation where possible and saves values before
shadow reclaims them, see [safe reclamation plan](../plans/shadow_toast.md)
PostgreSQL can remove TOAST chunks before walshadow reads them for ClickHouse.
If chunks are gone or belong to a replacement value, walshadow reports the
value as superseded and writes NULL or the column default. To spot a reused
value ID, compare the newest chunk's `xmin` with the highest transaction ID
assigned when the row's WAL record was written. A newer chunk belongs to a
replacement. If some chunks are missing and the rest are older, PostgreSQL
removed part of the original value.

See how walshadow could save values before shadow removes them in the
[safe reclamation plan](../plans/shadow_toast.md)

## Source horizon pin

With `[toast] source_horizon_pin`, walshadow uses hot standby feedback to tell
source PostgreSQL which deleted row versions to keep. This keeps pruning and
vacuum from removing TOAST chunks walshadow may still need. Shadow only removes
chunks when it replays WAL from source.

The resolved floor is the WAL position walshadow can safely restart from. It
stays at or before the first record of any open transaction. Walshadow picks
the latest transaction ID sample taken at or before that position. Any
transaction that marks chunks as deleted at or after the sample's WAL
position has an ID at least as high as the sample, so PostgreSQL keeps those
chunks.

PostgreSQL logs the oldest running transaction ID (`oldestRunningXid`) about
every 15 seconds while busy. On a primary, walshadow also uses a separate SQL
connection to read a snapshot's `xmin`, then `pg_current_wal_insert_lsn()`,
once a second. A transaction writing at or after that WAL position was running
when PostgreSQL took the snapshot or started later. Walshadow orders samples
by WAL position because the SQL connection can sample WAL ahead of the stream.
A new source connection may follow another timeline, so walshadow drops
samples ahead of the WAL it has consumed. It warns once when sampling fails
and falls back to `oldestRunningXid` until sampling recovers.

Walshadow sends feedback only when the `xmin` changes, apart from standby
status, because PostgreSQL keeps the last value it received.

PostgreSQL checks the transaction ID's epoch in feedback to reject IDs from
outside the recent past. Walshadow uses the source's next full transaction ID
to work out the epoch for each 32-bit ID from WAL. With a physical replication
slot, PostgreSQL keeps the slot's `xmin` when walshadow disconnects and can
only advance or clear it.

Walshadow saves the `xmin` for the resolved floor in the resume manifest. At
startup it uses the slot's `xmin` if it has one, and warns when that is ahead
of the saved `xmin`. Otherwise it uses the saved `xmin` or the source's oldest
running transaction ID, whichever is older, and never goes below the oldest
`datfrozenxid`. Without a slot, nothing holds `xmin` while walshadow is
disconnected, and a slot can lose its `xmin` when the source crashes before a
checkpoint. Restoring the saved `xmin` only protects chunks that vacuum has
not yet removed. Connecting with the pin disabled clears any `xmin` held by
an earlier session.

The pin also prevents reuse of a value ID while any of its chunks remain.
PostgreSQL checks the TOAST index with `SnapshotAny`, which includes chunks
that ordinary queries cannot see. `TRUNCATE`, `DROP TABLE`, `VACUUM FULL`,
`CLUSTER`, and `ALTER TABLE` rewrites can still remove or replace whole files.
Slot invalidation and promotion can lose the pin, and bootstrap runs before
it starts. A standby source forwards feedback upstream only with
`hot_standby_feedback = on`, and walshadow warns at startup when it is off.

Even when walshadow keeps up, the pin advances only as ClickHouse acknowledges
writes, walshadow saves its progress, and the floor reaches the next WAL
segment boundary. Keeping old versions of frequently updated rows reduces
source throughput in the [churn benchmark](../benches/shadow_toast_horizon.rs).

## Implementation

Expand Down
265 changes: 265 additions & 0 deletions benches/shadow_toast_horizon.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
//! Shadow-TOAST cost under pgbench churn of pointer-only updates and value
//! replacements on toasted rows. Daemon is release-built under `cargo bench`
//!
//! Live mode streams while pgbench runs. Reports source throughput, how far
//! horizon pin trails source head, dead row versions VACUUM keeps right after
//! churn, and values lost to reclamation
//!
//! Drain mode builds a backlog of `--drain` transactions while daemon is down,
//! then times catch-up into ClickHouse with pin on. Steady rate excludes
//! daemon startup. `--metrics` prints worker, TOAST and bridge counters
//!
//! ```text
//! cargo bench --bench shadow_toast_horizon -- --secs 10 --reps 3 --pin both
//! cargo bench --bench shadow_toast_horizon -- --drain 160000 --read-ahead off
//! ```
//!
//! Needs PostgreSQL tools, pgbench and ClickHouse on PATH, plus
//! `pgext/walshadow.so` built against that major
//!
//! `harness = false`, so nextest lists it by answering `--list`

#[path = "../tests/common/horizon_fixture.rs"]
mod hz;

use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, ensure};
use hz::{ROWS, Rig, SCHEMA, fx, slot_lag, toast_dead_tuples};

const USAGE: &str = "usage: shadow_toast_horizon [--secs N] [--reps N] [--pin on|off|both] \
[--read-ahead on|off] [--drain TXNS] [--metrics]";

struct Opts {
secs: u32,
reps: u32,
pins: Vec<bool>,
read_ahead: bool,
drain: Option<u32>,
metrics: bool,
}

/// Pointer-only update then value replacement per transaction, 8 KB of
/// uncompressed chunks each
fn churn_script(path: &Path) -> Result<()> {
let sql = format!(
"\\set k random(1, {ROWS})\n\
UPDATE {SCHEMA}.t SET meta = 'p' || :k WHERE id = :k;\n\
UPDATE {SCHEMA}.t SET body = repeat(md5(random()::text), 250) WHERE id = :k;\n"
);
Ok(fs::write(path, sql)?)
}

/// pgbench over churn script, `limit` is `-T` seconds or `-t` transactions
fn pgbench(rig: &Rig, limit: [&str; 2]) -> Result<Command> {
let script = rig.tmp.path().join("churn.sql");
churn_script(&script)?;
let cfg = rig.source.config();
let mut cmd = Command::new("pgbench");
cmd.args(["-h", cfg.socket_dir.to_str().unwrap(), "-p"])
.arg(cfg.port.to_string())
.args(["-U", &cfg.user, "-n", "-c", "4"])
.args(limit)
.arg("-f")
.arg(&script)
.arg(&cfg.dbname);
Ok(cmd)
}

fn rig(pin: bool, read_ahead: bool) -> Option<Rig> {
let rig = Rig::new(pin)?;
let cfg = fs::read_to_string(&rig.config).unwrap();
let cfg = cfg.replace("read_ahead = false", &format!("read_ahead = {read_ahead}"));
fs::write(&rig.config, cfg).unwrap();
Some(rig)
}

/// Prints figures, asserts only that pinned values survive
fn churn(o: &Opts, pin: bool) {
let Some(rig) = rig(pin, o.read_ahead) else {
return;
};
let guard = fx::ChildGuard::new(rig.spawn().expect("spawn walshadow-stream"));
let result = (|| -> Result<()> {
rig.wait_bootstrapped()?;
let mut bench = pgbench(&rig, ["-T", &o.secs.to_string()])?
.stdout(Stdio::piped())
.spawn()
.context("spawn pgbench")?;
let (mut ages, mut wal_max) = (Vec::new(), 0);
while bench.try_wait()?.is_none() {
let (age, wal) = slot_lag(&rig.source)?;
ages.push(age);
wal_max = wal_max.max(wal);
std::thread::sleep(Duration::from_millis(250));
}
let out = bench.wait_with_output()?;
ensure!(out.status.success(), "pgbench failed");
let report = String::from_utf8_lossy(&out.stdout);
let txns: u64 = report
.lines()
.find_map(|l| l.strip_prefix("number of transactions actually processed: "))
.and_then(|n| n.split('/').next())
.context("pgbench transaction count")?
.parse()?;
rig.source.psql_one(&format!("VACUUM {SCHEMA}.t"))?;
let toast_dead = toast_dead_tuples(&rig.source)?;
fx::wait_for_ch_value(
&rig.ch,
"SELECT count() FROM default.t",
&(u64::from(ROWS) + 2 * txns).to_string(),
Duration::from_secs(60),
)?;
let superseded = rig.superseded()?;
ages.sort_unstable();
let p50 = ages.get(ages.len() / 2).copied().unwrap_or(0);
let max = ages.last().copied().unwrap_or(0);
eprintln!(
"pin={pin} read_ahead={} xacts={txns} xid/s={} pin_age_xids p50={p50} max={max} \
slot_wal_max={wal_max} toast_dead_after_vacuum={toast_dead} superseded={superseded}",
o.read_ahead,
txns / u64::from(o.secs),
);
report_metrics(&rig, o.metrics)?;
ensure!(!pin || superseded == 0, "pinned values lost: {superseded}");
Ok(())
})();
fx::finish_daemon(guard, &rig.daemon, result);
}

fn drain(o: &Opts, txns: u32) {
let Some(rig) = rig(true, o.read_ahead) else {
return;
};
let mut guard = fx::ChildGuard::new(rig.spawn().expect("spawn walshadow-stream"));
let result = (|| -> Result<()> {
rig.wait_bootstrapped()?;
if let Some(mut first) = guard.child.take() {
fx::tools::stop_gracefully(&mut first);
}
let per_client = txns / 4;
let st = pgbench(&rig, ["-t", &per_client.to_string()])?
.stdout(Stdio::null())
.status()?;
ensure!(st.success(), "pgbench failed");
let wal: u64 = rig
.source
.psql_one(&format!(
"SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)::bigint \
FROM pg_replication_slots WHERE slot_name = '{}'",
hz::SLOT
))?
.trim()
.parse()?;
let want = u64::from(ROWS) + 2 * 4 * u64::from(per_client);
let t0 = Instant::now();
guard.child = Some(rig.spawn()?);
// First rows past bootstrap mark end of daemon startup
let mut first = None;
loop {
let n: u64 = rig
.ch
.query("SELECT count() FROM default.t")
.ok()
.and_then(|n| n.parse().ok())
.unwrap_or(0);
if first.is_none() && n > u64::from(ROWS) {
first = Some((t0.elapsed().as_secs_f64(), n));
}
if n >= want {
break;
}
ensure!(
t0.elapsed() < Duration::from_secs(300),
"drain stuck at {n}/{want}"
);
std::thread::sleep(Duration::from_millis(100));
}
let secs = t0.elapsed().as_secs_f64();
let (start, at_start) = first.context("no rows drained")?;
eprintln!(
"drain read_ahead={} rows={want} wal_mb={} secs={secs:.2} start={start:.2} \
steady_rows/s={:.0} superseded={}",
o.read_ahead,
wal >> 20,
(want - at_start) as f64 / (secs - start),
rig.superseded()?,
);
report_metrics(&rig, o.metrics)
})();
fx::finish_daemon(guard, &rig.daemon, result);
}

fn report_metrics(rig: &Rig, on: bool) -> Result<()> {
if !on {
return Ok(());
}
let metrics = fx::http_get(rig.daemon.metrics_addr, "/metrics")?;
let shown = [
"worker_seconds_total",
"toast_value",
"bridge_request",
"bridge_errors",
];
for l in metrics.lines().filter(|l| {
!l.starts_with('#') && shown.iter().any(|s| l.contains(s)) && !l.ends_with(" 0")
}) {
eprintln!(" {l}");
}
Ok(())
}

fn on_off(v: &str) -> bool {
match v {
"on" => true,
"off" => false,
_ => panic!("{USAGE}"),
}
}

fn main() {
let argv: Vec<String> = std::env::args().skip(1).collect();
// nextest --all-targets lists benches by running them with --list
if argv.iter().any(|a| a == "--list") {
println!("shadow_toast_horizon: benchmark");
return;
}
let mut o = Opts {
secs: 10,
reps: 1,
pins: vec![true, false],
read_ahead: true,
drain: None,
metrics: false,
};
let mut args = argv.iter().filter(|a| *a != "--bench");
while let Some(flag) = args.next() {
if flag == "--metrics" {
o.metrics = true;
continue;
}
let value = args.next().map(String::as_str).expect(USAGE);
let n = || value.parse().expect(USAGE);
match flag.as_str() {
"--secs" => o.secs = n(),
"--reps" => o.reps = n(),
"--drain" => o.drain = Some(n()),
"--read-ahead" => o.read_ahead = on_off(value),
"--pin" if value == "both" => o.pins = vec![true, false],
"--pin" => o.pins = vec![on_off(value)],
_ => panic!("{USAGE}"),
}
}
for _ in 0..o.reps {
if let Some(txns) = o.drain {
drain(&o, txns);
continue;
}
for &pin in &o.pins {
churn(&o, pin);
}
}
}
8 changes: 8 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ Tune chunk-store buffering independently of inserter count, restart daemon to ap
| `put_batch_bytes` | 67,108,864 | Seal chunk INSERT after this many body bytes |
| `connections` | `ch.inserter_pool_size` | Limit concurrent chunk-store connections |
| `read_ahead` | `true` | Fetch and decode external values ahead of planning |
| `source_horizon_pin` | `true` | In `shadow` mode, hold source vacuum horizon for values still pending |

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