diff --git a/docs/operations.md b/docs/operations.md index dd6adb23..49ad30af 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -75,6 +75,21 @@ under-reports during archive catch-up or a restart catch-up. source idleness as lag. The two views answer different questions: bytes say how much WAL is still to process, seconds say how stale the destination is. +`walshadow_replication_latency_seconds` is a histogram of the delay of each +transaction: the time from its commit on the source to ClickHouse confirming +it, observed once per confirmed commit. Read it as quantiles: + +```promql +histogram_quantile(0.99, sum by (le) (rate(walshadow_replication_latency_seconds_bucket[5m]))) +``` + +Buckets run from 1 ms doubling to 131 s. The commit time comes from the +source's clock and the confirmation time from the walshadow host's, so clock +skew between the two shifts every sample by the same amount. Commits delivered +during an archive catch-up are counted at their true delay, which lands in the +top buckets. Initial loads and table backfills are not counted. It has no +samples while the source commits nothing. + Set `--metrics-bind` to expose OpenMetrics text metrics, which Prometheus scrapes directly. Counter series carry `_total`. Docker deployment uses port 9484 and includes optional provisioned dashboard diff --git a/plans/observability.md b/plans/observability.md index 9c408d94..d4b3a17c 100644 --- a/plans/observability.md +++ b/plans/observability.md @@ -43,6 +43,7 @@ expected siblings is too narrow. |---|---|---|---| | `position_lsn` | `at` | source_head, received, filter, decoder_commit, ack, shadow_replay, floor, pause_consumed, pause_received, promotion_target_replay, promotion_target_receive, timeline_switch, catalog_boundary_stalled | complete | | `commit_timestamp_seconds` | `at` | source, ack | shadow_replay once the pump keeps an LSN→commit-time ring | +| `replication_latency_seconds` | none | histogram of commit-to-confirmation delay, one sample per confirmed live commit | complete | | `source_mode` | `mode` | the six one-hot states, `initial_load` included | complete | | `stage_active`, `stage_seconds_total`, `stage_completed_total`, `stage_interrupted_total` | `stage`, `title`, `order` | ten stages | copy and publish phases as the table backfill grows | | `stage_progress` | `stage`, `title`, `order`, `measure` | work_total, work_done, rows | complete | diff --git a/src/bin/stream/metrics_publish.rs b/src/bin/stream/metrics_publish.rs index 547f4f55..0a0b3293 100644 --- a/src/bin/stream/metrics_publish.rs +++ b/src/bin/stream/metrics_publish.rs @@ -606,6 +606,9 @@ pub(crate) fn stage_gauges_on(v: &StageCounters<'_>, base: MetricsSnapshot) -> M toast_values_per_fetch: v.emitter.map_or_else(HistogramSnapshot::default, |s| { s.toast_values_per_fetch.snapshot(1.0) }), + replication_latency_seconds: v.emitter.map_or_else(HistogramSnapshot::default, |s| { + s.replication_latency.snapshot(1e6) + }), toast_image_rows_mirrored_total: emitter(|s| &s.toast_image_rows_mirrored), toast_values_filled_superseded_total: emitter(|s| &s.toast_values_filled_superseded), toast_values_filled_mismatch_total: emitter(|s| &s.toast_values_filled_mismatch), diff --git a/src/emit/ch_emitter.rs b/src/emit/ch_emitter.rs index 5a1844d4..30b0a291 100644 --- a/src/emit/ch_emitter.rs +++ b/src/emit/ch_emitter.rs @@ -3327,6 +3327,8 @@ fn oracle_cell( /// and the top is past a typical deferred-resolution batch pub type ValuesPerFetch = crate::ops::metrics::Histogram<1, 9>; +pub type ReplicationLatency = crate::ops::metrics::Histogram<1_000, 18>; + /// Default of `att` encoded for a one-row `ch_inner` column; `None` without /// a fast default or when the column can't hold it locally pub(crate) fn encode_default(att: &RelAttr, ch_inner: &str) -> Option { @@ -3403,6 +3405,7 @@ crate::atomic_stats! { pub toast_value_wait_nanos, /// Values requested per store fetch pub toast_values_per_fetch: ValuesPerFetch, + pub replication_latency: ReplicationLatency, /// Toasted values NULL/default-filled because no store could rebuild /// them (disabled mode). Surfaced, never silent pub toast_values_filled_default, diff --git a/src/emit/pipeline/ack.rs b/src/emit/pipeline/ack.rs index dcca982c..b0f95e36 100644 --- a/src/emit/pipeline/ack.rs +++ b/src/emit/pipeline/ack.rs @@ -21,6 +21,7 @@ use std::collections::BTreeMap; use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; use tokio::sync::{mpsc, watch}; use tokio::task::JoinHandle; @@ -28,6 +29,7 @@ use tokio::task::JoinHandle; use crate::ch::EndOfStream; #[cfg(feature = "test-support")] use crate::crash_test; +use crate::emit::ch_emitter::EmitterStats; use crate::emit::pipeline::Fatal; use crate::pos::{AckFrontier, EmitterAck, Gate, GateClosed, Monotone, Pos}; use crate::record::SinkError; @@ -165,6 +167,15 @@ pub struct AckState { probe_tx: watch::Sender, /// Tripped on first protocol fault so barrier waits fail instead of hanging fatal: Fatal, + stats: Option>, +} + +fn micros_since_commit(commit_ts: i64) -> u64 { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_micros() as i64); + let committed = commit_ts.saturating_add(walrus::pg::replication::PG_EPOCH_USEC); + now.saturating_sub(committed).max(0) as u64 } impl AckState { @@ -173,6 +184,7 @@ impl AckState { frontier_cell: Monotone, probe_tx: watch::Sender, fatal: Fatal, + stats: Option>, ) -> Self { Self { map: BTreeMap::new(), @@ -187,6 +199,7 @@ impl AckState { late: 0, probe_tx, fatal, + stats, } } @@ -282,6 +295,13 @@ impl AckState { if publish { self.watermark = self.watermark.max(commit_lsn); self.watermark_ts = self.watermark_ts.max(commit_ts); + if let Some(stats) = &self.stats + && let Some(commit_ts) = commit_ts + { + stats + .replication_latency + .observe(micros_since_commit(commit_ts)); + } } self.frontier += 1; } @@ -508,11 +528,19 @@ impl OpenSeq { /// Spawn the collector actor. When all [`AckHandle`] clones drop it drains /// and exits, completing the [`JoinHandle`]. A protocol fault sets `fatal` pub fn spawn(emitter_ack: Arc>, fatal: Fatal) -> (AckHandle, JoinHandle<()>) { + spawn_observed(emitter_ack, fatal, None) +} + +pub fn spawn_observed( + emitter_ack: Arc>, + fatal: Fatal, + stats: Option>, +) -> (AckHandle, JoinHandle<()>) { let (tx, mut rx) = mpsc::unbounded_channel::(); let frontier_cell = Monotone::default(); let frontier = frontier_cell.watch(); let (probe_tx, probe) = watch::channel(AckSnapshot::default()); - let mut state = AckState::new(emitter_ack, frontier_cell, probe_tx, fatal); + let mut state = AckState::new(emitter_ack, frontier_cell, probe_tx, fatal, stats); let handle = tokio::spawn(async move { while let Some(ev) = rx.recv().await { state.apply(ev); @@ -562,11 +590,47 @@ mod tests { let ack = Arc::new(Monotone::default()); let (probe_tx, _probe) = watch::channel(AckSnapshot::default()); ( - AckState::new(ack.clone(), Monotone::default(), probe_tx, Fatal::new()), + AckState::new( + ack.clone(), + Monotone::default(), + probe_tx, + Fatal::new(), + None, + ), ack, ) } + #[test] + fn confirmed_commits_record_their_latency() { + let (probe_tx, _probe) = watch::channel(AckSnapshot::default()); + let stats = Arc::new(EmitterStats::default()); + let mut s = AckState::new( + Arc::new(Monotone::default()), + Monotone::default(), + probe_tx, + Fatal::new(), + Some(stats.clone()), + ); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_micros() as i64 + - walrus::pg::replication::PG_EPOCH_USEC; + s.register(0, 100, Some(now - 5_000_000), true); + s.register(1, 200, Some(now + 60_000_000), true); + s.register(2, 300, Some(now), false); + s.register(3, 400, None, true); + for seq in 0..4 { + s.placed(seq, 1); + s.acked(seq, 1); + } + let latency = stats.replication_latency.snapshot(1e6); + assert_eq!(latency.count, 2); + assert!((5.0..65.0).contains(&latency.sum), "{}", latency.sum); + assert_eq!(latency.buckets[0].1, 1); + } + /// Guard against O(N²) placement scan when placement runs ahead of acks #[test] fn placed_far_ahead_of_acked_stays_linear() { diff --git a/src/emit/pipeline/tail.rs b/src/emit/pipeline/tail.rs index d1f63f5a..e2167ecd 100644 --- a/src/emit/pipeline/tail.rs +++ b/src/emit/pipeline/tail.rs @@ -318,7 +318,7 @@ pub async fn spawn_with_config( ) -> Result<(mpsc::Sender, AckHandle, TailParts), EmitterError> { let n = inserter_pool_size.max(1); - let (ack, collector) = ack::spawn(emitter_ack, fatal.clone()); + let (ack, collector) = ack::spawn_observed(emitter_ack, fatal.clone(), Some(stats.clone())); let collector = AbortOnDropHandle::new(collector); // Rows and FlushAll share one FIFO channel so a flush can't overtake rows diff --git a/src/ops/metrics.rs b/src/ops/metrics.rs index c0290da4..ac509ab6 100644 --- a/src/ops/metrics.rs +++ b/src/ops/metrics.rs @@ -478,6 +478,8 @@ snapshot! { "Cumulative wall-clock planning spent waiting on values read ahead of it, apart from the store time those reads count in toast_value_fetch_seconds.", histogram toast_values_per_fetch: HistogramSnapshot = "Values requested per chunk-store fetch round trip; the distribution behind the batching factor toast_values_fetched_total / toast_value_fetch_batches_total.", + histogram replication_latency_seconds: HistogramSnapshot = + "Seconds from a transaction's commit on the source to ClickHouse confirming it, one observation per confirmed commit: 1ms doubling to 131s. The commit time is the source's clock and the confirmation time is this host's, so clock skew between them shifts every sample. Commits delivered during an archive catch-up are counted at their true, large delay. Initial loads and table backfills are not counted.", counter toast_image_rows_mirrored_total: u64 = "Chunk rows mirrored from restored page images during a backup window; non-zero means the backup copied TOAST pages mid-write.", counter toast_values_filled_superseded_total: u64 =