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
15 changes: 15 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions plans/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
3 changes: 3 additions & 0 deletions src/bin/stream/metrics_publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 3 additions & 0 deletions src/emit/ch_emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ColumnBuf> {
Expand Down Expand Up @@ -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,
Expand Down
68 changes: 66 additions & 2 deletions src/emit/pipeline/ack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use tokio::sync::{mpsc, watch};
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;
Expand Down Expand Up @@ -165,6 +167,15 @@ pub struct AckState {
probe_tx: watch::Sender<AckSnapshot>,
/// Tripped on first protocol fault so barrier waits fail instead of hanging
fatal: Fatal,
stats: Option<Arc<EmitterStats>>,
}

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 {
Expand All @@ -173,6 +184,7 @@ impl AckState {
frontier_cell: Monotone<AckFrontier>,
probe_tx: watch::Sender<AckSnapshot>,
fatal: Fatal,
stats: Option<Arc<EmitterStats>>,
) -> Self {
Self {
map: BTreeMap::new(),
Expand All @@ -187,6 +199,7 @@ impl AckState {
late: 0,
probe_tx,
fatal,
stats,
}
}

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<Monotone<EmitterAck>>, fatal: Fatal) -> (AckHandle, JoinHandle<()>) {
spawn_observed(emitter_ack, fatal, None)
}

pub fn spawn_observed(
emitter_ack: Arc<Monotone<EmitterAck>>,
fatal: Fatal,
stats: Option<Arc<EmitterStats>>,
) -> (AckHandle, JoinHandle<()>) {
let (tx, mut rx) = mpsc::unbounded_channel::<AckEvent>();
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);
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion src/emit/pipeline/tail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ pub async fn spawn_with_config(
) -> Result<(mpsc::Sender<BatcherMsg>, 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
Expand Down
2 changes: 2 additions & 0 deletions src/ops/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down