Skip to content

Commit 540bcea

Browse files
iskakaushikharshil-goel
authored andcommitted
feat(shadow-stream): walsender connection, backfill and queue metrics
1 parent 0a8fae2 commit 540bcea

5 files changed

Lines changed: 159 additions & 45 deletions

File tree

‎src/bin/stream/metrics_publish.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ pub(crate) struct ShadowMetricsView {
2727
/// yet, so the gauges keep their last value
2828
pub(crate) apply_lag: Option<(u64, f64)>,
2929
pub(crate) active_connections: u64,
30-
pub(crate) dropped_total: u64,
30+
pub(crate) accepted_total: u64,
31+
pub(crate) disconnects_total: [u64; walshadow::shadow_stream::Disconnect::COUNT],
32+
pub(crate) backfill_bytes_total: u64,
33+
pub(crate) send_queue_bytes: u64,
3134
}
3235

3336
/// Apply lag against the source head. A zero `shadow_replay` means no walreceiver
@@ -312,7 +315,10 @@ pub(crate) async fn populate_metrics(
312315
shadow_apply_lag_bytes: apply_lag_bytes,
313316
shadow_apply_lag_seconds: apply_lag_seconds,
314317
shadow_stream_active_connections: shadow_view.active_connections,
315-
shadow_stream_dropped_connections_total: shadow_view.dropped_total,
318+
shadow_stream_connections_total: shadow_view.accepted_total,
319+
shadow_stream_disconnects_total_by_reason: shadow_view.disconnects_total,
320+
shadow_stream_backfill_bytes_total: shadow_view.backfill_bytes_total,
321+
shadow_stream_send_queue_bytes: shadow_view.send_queue_bytes,
316322
..registry.snapshot().await
317323
};
318324
populate_pipeline_metrics(

‎src/bin/stream/session.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2289,7 +2289,10 @@ async fn session_body(
22892289
ShadowMetricsView {
22902290
apply_lag,
22912291
active_connections: shadow_agg.active_connections as u64,
2292-
dropped_total: shadow_agg.dropped_total,
2292+
accepted_total: shadow_agg.accepted_total,
2293+
disconnects_total: shadow_agg.disconnects_total,
2294+
backfill_bytes_total: shadow_agg.backfill_bytes_total,
2295+
send_queue_bytes: shadow_agg.send_queue_bytes,
22932296
},
22942297
&boundary_hold_stats,
22952298
metrics_dbs.iter().map(DbMetricSources::series).collect(),

‎src/ops/metrics.rs‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ use crate::catalog::pending::DegradeReason;
3737
use crate::decode::heap_decoder::HEAP_OP_LABELS;
3838
use crate::ops::bridge::{OP_COUNT, OP_LABELS};
3939
use crate::pos::{Drain, EmitterAck, FilterDispatched, Floor, Pos, ShadowReplay, SourceReceived};
40+
use crate::source::shadow_stream::Disconnect;
4041
use crate::source::transition::SWITCH_FAILURE_REASONS;
4142

4243
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -558,9 +559,15 @@ snapshot! {
558559
"Estimated seconds shadow trails source, by source byte rate over last 30s.",
559560
gauge shadow_stream_active_connections: u64 =
560561
"Currently-attached walreceiver connections to walshadow's walsender.",
561-
/// Cumulative connections dropped by `slow_threshold` overflow
562-
counter shadow_stream_dropped_connections_total: u64 =
563-
"Connections dropped by slow-client cutoff since daemon start.",
562+
counter shadow_stream_connections_total: u64 =
563+
"Sockets accepted by walshadow's walsender, including ones that never reach START_REPLICATION.",
564+
counter shadow_stream_disconnects_total_by_reason: [u64; Disconnect::COUNT]
565+
["reason" = Disconnect::LABELS] =
566+
"Walsender sockets ended, by reason: slow_client (send queue cap), client_closed, error (I/O, handshake, refused START_REPLICATION).",
567+
counter shadow_stream_backfill_bytes_total: u64 =
568+
"WAL bytes replayed from the retained wire buffer to reconnecting walreceivers.",
569+
gauge shadow_stream_send_queue_bytes: u64 =
570+
"Largest unsent walsender queue across connections; compare to the slow-client cap.",
564571
counter catalog_boundary_holds_total: u64 =
565572
"Publication holds released at catalog-mutating commit boundaries.",
566573
counter catalog_boundary_hold_failures_total: u64 =
@@ -1569,7 +1576,10 @@ mod tests {
15691576
shadow_apply_lag_bytes: 12345,
15701577
shadow_apply_lag_seconds: 1.23456,
15711578
shadow_stream_active_connections: 2,
1572-
shadow_stream_dropped_connections_total: 5,
1579+
shadow_stream_connections_total: 9,
1580+
shadow_stream_disconnects_total_by_reason: [5, 3, 1],
1581+
shadow_stream_backfill_bytes_total: 4096,
1582+
shadow_stream_send_queue_bytes: 777,
15731583
..MetricsSnapshot::default()
15741584
};
15751585
let body = render(snap);
@@ -1582,9 +1592,18 @@ mod tests {
15821592
assert!(body.contains("# HELP walshadow_shadow_stream_active_connections"));
15831593
assert!(body.contains("# TYPE walshadow_shadow_stream_active_connections gauge"));
15841594
assert!(body.contains("walshadow_shadow_stream_active_connections 2"));
1585-
assert!(body.contains("# HELP walshadow_shadow_stream_dropped_connections"));
1586-
assert!(body.contains("# TYPE walshadow_shadow_stream_dropped_connections counter"));
1587-
assert!(body.contains("walshadow_shadow_stream_dropped_connections_total 5"));
1595+
assert!(!body.contains("walshadow_shadow_stream_dropped_connections"));
1596+
assert!(body.contains("walshadow_shadow_stream_connections_total 9"));
1597+
assert!(
1598+
body.contains("walshadow_shadow_stream_disconnects_total{reason=\"slow_client\"} 5")
1599+
);
1600+
assert!(
1601+
body.contains("walshadow_shadow_stream_disconnects_total{reason=\"client_closed\"} 3")
1602+
);
1603+
assert!(body.contains("walshadow_shadow_stream_disconnects_total{reason=\"error\"} 1"));
1604+
assert!(body.contains("walshadow_shadow_stream_backfill_bytes_total 4096"));
1605+
assert!(!body.contains("walshadow_shadow_stream_start_before_buffer"));
1606+
assert!(body.contains("walshadow_shadow_stream_send_queue_bytes 777"));
15881607
}
15891608

15901609
/// Unknown rate stays infinite on the wire. prometheus-client spells it

‎src/source/shadow_stream.rs‎

Lines changed: 117 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,14 @@ pub struct AggregateLsn {
147147
/// `active_connections` means a client is connected but stalled before
148148
/// `START_REPLICATION`, which reads as "nothing attached" otherwise.
149149
pub accepted_total: u64,
150-
/// Monotonic count of connections dropped by `slow_threshold`
151-
/// overflow since process start.
152-
pub dropped_total: u64,
150+
/// Monotonic count of sockets that ended, indexed by [`Disconnect`]
151+
pub disconnects_total: [u64; Disconnect::COUNT],
152+
/// Monotonic count of `START_REPLICATION` bytes replayed from the retained
153+
/// wire buffer to reconnecting clients
154+
pub backfill_bytes_total: u64,
155+
/// Largest unsent send queue across connections, to read against
156+
/// `slow_threshold`
157+
pub send_queue_bytes: u64,
153158
/// Oldest branch an attached client is still reading: a historic
154159
/// connection is pinned to the branch its `ends_at` names, the rest to the
155160
/// served one. `None` with nothing attached. Beside the apply LSN it is
@@ -186,6 +191,23 @@ impl Refused {
186191
}
187192
}
188193

194+
/// Why a walsender socket ended; the `reason=` label of
195+
/// `walshadow_shadow_stream_disconnects_total`
196+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197+
pub enum Disconnect {
198+
/// Dropped for overflowing `slow_threshold`
199+
SlowClient,
200+
/// Client hung up cleanly
201+
ClientClosed,
202+
/// Handshake, I/O, protocol failure, or a refused `START_REPLICATION`
203+
Error,
204+
}
205+
206+
impl Disconnect {
207+
pub const COUNT: usize = 3;
208+
pub const LABELS: [&'static str; Self::COUNT] = ["slow_client", "client_closed", "error"];
209+
}
210+
189211
#[derive(Debug, Error)]
190212
pub enum ShadowStreamError {
191213
#[error("io: {0}")]
@@ -219,10 +241,9 @@ pub struct ShadowStreamState {
219241
pub slow_threshold: usize,
220242
/// Populates `'w'`/`'k'` frame headers.
221243
pub server_wal_end: Pos<SourceReceived>,
222-
/// Surfaced via [`AggregateLsn::dropped_total`] for the
223-
/// `walshadow_shadow_stream_dropped_connections_total` gauge.
224-
dropped_total: u64,
225244
accepted_total: u64,
245+
disconnects_total: [u64; Disconnect::COUNT],
246+
backfill_bytes_total: u64,
226247
/// Wire bytes `[wire_buf_start, server_wal_end]` not yet on disk, used to
227248
/// backfill a reconnect behind the live head (else it gets an unappliable
228249
/// gap and strands at segment boundaries). Spans up to two segments while
@@ -257,8 +278,9 @@ impl ShadowStreamState {
257278
send_queues: HashMap::new(),
258279
slow_threshold,
259280
server_wal_end: Pos::new(current_lsn),
260-
dropped_total: 0,
261281
accepted_total: 0,
282+
disconnects_total: [0; Disconnect::COUNT],
283+
backfill_bytes_total: 0,
262284
wire_buf: Vec::new(),
263285
wire_buf_start: current_lsn,
264286
queued: Monotone::default(),
@@ -304,7 +326,9 @@ impl ShadowStreamState {
304326
min_apply_lsn: (active > 0).then_some(min_apply),
305327
active_connections: active,
306328
accepted_total: self.accepted_total,
307-
dropped_total: self.dropped_total,
329+
disconnects_total: self.disconnects_total,
330+
backfill_bytes_total: self.backfill_bytes_total,
331+
send_queue_bytes: self.send_queues.values().map(Vec::len).max().unwrap_or(0) as u64,
308332
replay_timeline: (active > 0).then_some(branch),
309333
}
310334
}
@@ -317,6 +341,11 @@ impl ShadowStreamState {
317341
self.accepted_total += 1;
318342
}
319343

344+
/// Count a socket ending, once per socket.
345+
pub fn note_disconnect(&mut self, reason: Disconnect) {
346+
self.disconnects_total[reason as usize] += 1;
347+
}
348+
320349
/// Refuse a `START_REPLICATION` this walsender cannot serve gap-free
321350
///
322351
/// `ends_at` comes from the handshake, which resolved the request against
@@ -332,6 +361,12 @@ impl ShadowStreamState {
332361
return Err(Refused::Timeline(timeline));
333362
}
334363
if start_lsn < self.wire_buf_start {
364+
tracing::warn!(
365+
target: "walshadow::shadow_stream",
366+
start_lsn = %format_pg_lsn(start_lsn),
367+
retained_from = %format_pg_lsn(self.wire_buf_start),
368+
"START_REPLICATION below the retained wire buffer; the walreceiver takes that range from restore_command",
369+
);
335370
return Err(Refused::Archived {
336371
start: start_lsn,
337372
retained: self.wire_buf_start,
@@ -551,6 +586,7 @@ impl ShadowStreamState {
551586
if let Some(c) = self.connections.get_mut(&id) {
552587
c.backfill_queued = self.send_queues.get(&id).map_or(0, Vec::len);
553588
}
589+
self.backfill_bytes_total += backfill.len() as u64;
554590
self.advance_dispatched(id, Pos::new(server_wal_end));
555591
}
556592

@@ -615,10 +651,8 @@ impl ShadowStreamState {
615651
pub fn enqueue(&mut self, id: u64, framed: Vec<u8>) -> bool {
616652
let q = self.send_queues.entry(id).or_default();
617653
if q.len() + framed.len() > self.slow_threshold {
618-
if let Some(c) = self.connections.get_mut(&id)
619-
&& c.phase.close()
620-
{
621-
self.dropped_total += 1;
654+
if let Some(c) = self.connections.get_mut(&id) {
655+
c.phase.close();
622656
}
623657
self.send_queues.remove(&id);
624658
return false;
@@ -650,10 +684,8 @@ impl ShadowStreamState {
650684
&& envelope_start.saturating_sub(backfill) + 1 + payload_len > cap
651685
{
652686
q.truncate(envelope_start);
653-
if let Some(c) = self.connections.get_mut(&id)
654-
&& c.phase.close()
655-
{
656-
self.dropped_total += 1;
687+
if let Some(c) = self.connections.get_mut(&id) {
688+
c.phase.close();
657689
}
658690
self.send_queues.remove(&id);
659691
return false;
@@ -852,10 +884,26 @@ async fn handle_tcp_connection(
852884

853885
/// Generic over the socket transport so unix + TCP share the logic.
854886
async fn drive_connection<S>(
855-
mut sock: S,
887+
sock: S,
856888
state: Arc<Mutex<ShadowStreamState>>,
857889
flush_interval: Duration,
858890
) -> Result<(), ShadowStreamError>
891+
where
892+
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
893+
{
894+
let ended = serve_connection(sock, state.clone(), flush_interval).await;
895+
state.lock().await.note_disconnect(match &ended {
896+
Ok(reason) => *reason,
897+
Err(_) => Disconnect::Error,
898+
});
899+
ended.map(|_| ())
900+
}
901+
902+
async fn serve_connection<S>(
903+
mut sock: S,
904+
state: Arc<Mutex<ShadowStreamState>>,
905+
flush_interval: Duration,
906+
) -> Result<Disconnect, ShadowStreamError>
859907
where
860908
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
861909
{
@@ -889,7 +937,7 @@ where
889937
let mut err = bytes::BytesMut::new();
890938
server::encode_error_response(&mut err, refused.sqlstate(), &refused.to_string());
891939
conn.write_framed(&err).await?;
892-
return Ok(());
940+
return Ok(Disconnect::Error);
893941
}
894942
};
895943
tracing::info!(
@@ -903,7 +951,8 @@ where
903951
let outcome = run_connection_loop(&mut conn, state.clone(), id, flush_interval).await;
904952
state.lock().await.drop_connection(id);
905953
match outcome? {
906-
StreamOutcome::Closed => return Ok(()),
954+
StreamOutcome::Closed => return Ok(Disconnect::ClientClosed),
955+
StreamOutcome::Slow => return Ok(Disconnect::SlowClient),
907956
StreamOutcome::TimelineEnded(switch) => {
908957
conn.end_timeline(switch).await?;
909958
let identity = state.lock().await.identity();
@@ -915,8 +964,10 @@ where
915964

916965
/// How one stream on a walsender connection finished.
917966
enum StreamOutcome {
918-
/// Client gone, or the connection dropped for slowness
967+
/// Client gone
919968
Closed,
969+
/// Dropped for overflowing `slow_threshold`
970+
Slow,
920971
/// Served through a historic branch's switchpoint; the client is owed the
921972
/// next-timeline result
922973
TimelineEnded(TimelineSwitch),
@@ -1009,7 +1060,7 @@ where
10091060
return Ok(StreamOutcome::TimelineEnded(switch));
10101061
}
10111062
if closing {
1012-
return Ok(StreamOutcome::Closed);
1063+
return Ok(StreamOutcome::Slow);
10131064
}
10141065
}
10151066
}
@@ -1275,7 +1326,6 @@ mod tests {
12751326
assert!(!s.enqueue(id, vec![0u8; 64]));
12761327
assert!(s.connections[&id].phase.is_closing());
12771328
assert!(!s.send_queues.contains_key(&id));
1278-
assert_eq!(s.aggregate().dropped_total, 1);
12791329
}
12801330

12811331
#[test]
@@ -1295,16 +1345,6 @@ mod tests {
12951345
assert_eq!(s.timeline_ended_for(id), Some(switch));
12961346
}
12971347

1298-
#[test]
1299-
fn dropped_total_increments_once_per_connection() {
1300-
let mut s = ShadowStreamState::new(1, "x".into(), 0, 64);
1301-
let id = s.register_connection(0, 1, None).expect("current timeline");
1302-
assert!(!s.enqueue(id, vec![0u8; 128]));
1303-
// second overflow on the closing slot must not double-count
1304-
assert!(!s.enqueue(id, vec![0u8; 128]));
1305-
assert_eq!(s.aggregate().dropped_total, 1);
1306-
}
1307-
13081348
#[tokio::test(flavor = "current_thread")]
13091349
async fn sink_dispatches_one_wire_chunk_per_active_connection() {
13101350
let state = Arc::new(Mutex::new(fresh_state()));
@@ -1405,6 +1445,49 @@ mod tests {
14051445
}
14061446
}
14071447

1448+
#[tokio::test(flavor = "current_thread")]
1449+
async fn backfill_is_counted_and_starts_below_the_buffer_are_refused() {
1450+
let state = Arc::new(Mutex::new(fresh_state()));
1451+
let mut sink = ShadowStreamSink::new(state.clone());
1452+
sink.on_wire_chunk(0x1000, b"AAAA").await.unwrap();
1453+
sink.on_segment_retired(0x1004).await.unwrap();
1454+
sink.on_wire_chunk(0x1004, b"CCCC").await.unwrap();
1455+
let mut s = state.lock().await;
1456+
s.register_connection(0x1008, 1, None).unwrap();
1457+
assert_eq!(s.aggregate().backfill_bytes_total, 0);
1458+
s.register_connection(0x1004, 1, None).unwrap();
1459+
assert_eq!(s.aggregate().backfill_bytes_total, 4);
1460+
assert!(matches!(
1461+
s.register_connection(0x1000, 1, None),
1462+
Err(Refused::Archived { .. })
1463+
));
1464+
assert_eq!(s.aggregate().backfill_bytes_total, 4);
1465+
}
1466+
1467+
/// A rebuilt `WalStream` replays its segment over retained bytes, which
1468+
/// keeps `wire_buf_start` and the backfill gap-free
1469+
#[test]
1470+
fn send_queue_bytes_is_the_largest_queue() {
1471+
let mut s = ShadowStreamState::new(1, "x".into(), 0, 64);
1472+
let a = s.register_connection(0, 1, None).unwrap();
1473+
let b = s.register_connection(0, 1, None).unwrap();
1474+
assert!(s.enqueue(a, vec![0u8; 10]));
1475+
assert!(s.enqueue(b, vec![0u8; 30]));
1476+
assert_eq!(s.aggregate().send_queue_bytes, 30);
1477+
s.drain_send_queue(b);
1478+
assert_eq!(s.aggregate().send_queue_bytes, 10);
1479+
}
1480+
1481+
#[test]
1482+
fn disconnects_count_per_reason() {
1483+
let mut s = fresh_state();
1484+
s.note_disconnect(Disconnect::SlowClient);
1485+
s.note_disconnect(Disconnect::ClientClosed);
1486+
s.note_disconnect(Disconnect::ClientClosed);
1487+
s.note_disconnect(Disconnect::Error);
1488+
assert_eq!(s.aggregate().disconnects_total, [1, 2, 1]);
1489+
}
1490+
14081491
/// A rebuilt `WalStream` replays its segment over retained bytes, which
14091492
/// keeps `wire_buf_start` and the backfill gap-free
14101493
#[tokio::test(flavor = "current_thread")]
@@ -1428,9 +1511,9 @@ mod tests {
14281511
s.dispatch_wire(16, b"EEEEEEEE");
14291512
s.swap_send_queue(id, &mut Vec::new());
14301513
s.dispatch_wire(24, b"FFFFFFFF");
1431-
assert_eq!(s.aggregate().dropped_total, 0);
1514+
assert!(!s.connections[&id].phase.is_closing());
14321515
s.dispatch_wire(32, b"GGGGGGGG");
1433-
assert_eq!(s.aggregate().dropped_total, 1);
1516+
assert!(s.connections[&id].phase.is_closing());
14341517
}
14351518

14361519
#[tokio::test(flavor = "current_thread")]

‎tests/bin_stream_e2e.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,10 @@ async fn bin_stream_replicates_segments_and_serves_metrics() {
366366
"walshadow_shadow_apply_lag_bytes",
367367
"walshadow_shadow_apply_lag_seconds",
368368
"walshadow_shadow_stream_active_connections",
369-
"walshadow_shadow_stream_dropped_connections_total",
369+
"walshadow_shadow_stream_connections_total",
370+
"walshadow_shadow_stream_disconnects_total",
371+
"walshadow_shadow_stream_backfill_bytes_total",
372+
"walshadow_shadow_stream_send_queue_bytes",
370373
] {
371374
assert!(
372375
body.contains(name),

0 commit comments

Comments
 (0)