1use async_stream::stream;
13use mz_persist_types::stats::PartStatsMetrics;
14use std::collections::BTreeMap;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Mutex, Weak};
17use std::time::{Duration, Instant};
18use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};
19
20use async_trait::async_trait;
21use bytes::Bytes;
22use futures_util::StreamExt;
23use mz_dyncfg::ConfigSet;
24use mz_ore::bytes::SegmentedBytes;
25use mz_ore::cast::{CastFrom, CastLossy};
26use mz_ore::instrument;
27use mz_ore::metric;
28use mz_ore::metrics::aggregation::{AggregatedFamilies, AggregatedFamily, AggregationKey};
29use mz_ore::metrics::{
30 ComputedGauge, ComputedUIntGauge, Counter, DeleteOnDropCounter, DeleteOnDropGauge, IntCounter,
31 MakeCollector, MetricsRegistry, PrometheusOpts, UIntGauge, UIntGaugeVec, raw,
32};
33use mz_ore::stats::histogram_seconds_buckets;
34use mz_persist::location::{
35 Blob, BlobMetadata, CaSResult, Consensus, ExternalError, ResultStream, SeqNo, VersionedData,
36};
37use mz_persist::metrics::{BlobHedgeMetrics, ColumnarMetrics, S3BlobMetrics};
38use mz_persist::retry::RetryStream;
39use mz_persist_types::Codec64;
40use mz_postgres_client::metrics::PostgresClientMetrics;
41use prometheus::core::{AtomicI64, AtomicU64, Collector, Desc, GenericGauge};
42use prometheus::proto::MetricFamily;
43use prometheus::{CounterVec, Gauge, GaugeVec, Histogram, HistogramVec, IntCounterVec};
44use regex::Regex;
45use timely::progress::Antichain;
46use tokio_metrics::TaskMonitor;
47use tracing::{Instrument, debug, info, info_span, warn};
48
49use crate::batch::BlobDeleteStats;
50use crate::cfg::{
51 PER_SHARD_METRICS_ENABLE_REGEX, SHARD_INFO_METRIC, SHARD_METRICS, ShardMetricsExport,
52};
53use crate::fetch::{FETCH_SEMAPHORE_COST_ADJUSTMENT, FETCH_SEMAPHORE_PERMIT_ADJUSTMENT};
54use crate::internal::gc::GcCaller;
55use crate::internal::paths::BlobKey;
56use crate::{PersistConfig, ShardId};
57
58pub struct Metrics {
63 _vecs: MetricsVecs,
64 _uptime: ComputedGauge,
65
66 pub blob: BlobMetrics,
68 pub consensus: ConsensusMetrics,
70 pub cmds: CmdsMetrics,
72 pub retries: RetriesMetrics,
74 pub user: BatchWriteMetrics,
77 pub read: BatchPartReadMetrics,
79 pub compaction: CompactionMetrics,
81 pub gc: GcMetrics,
83 pub lease: LeaseMetrics,
85 pub codecs: CodecsMetrics,
87 pub state: StateMetrics,
89 pub shards: ShardsMetrics,
91 pub audit: UsageAuditMetrics,
93 pub locks: LocksMetrics,
95 pub watch: WatchMetrics,
97 pub pubsub_client: PubSubClientMetrics,
99 pub pushdown: PushdownMetrics,
101 pub consolidation: ConsolidationMetrics,
103 pub blob_cache_mem: BlobMemCache,
105 pub tasks: TasksMetrics,
107 pub columnar: ColumnarMetrics,
109 pub schema: SchemaMetrics,
111 pub inline: InlineMetrics,
113 pub(crate) semaphore: SemaphoreMetrics,
115
116 pub sink: SinkMetrics,
118 pub backpressure: BackpressureMetrics,
120
121 pub s3_blob: S3BlobMetrics,
123 pub blob_hedge: BlobHedgeMetrics,
125 pub postgres_consensus: PostgresClientMetrics,
127
128 #[allow(dead_code)]
129 pub(crate) registry: MetricsRegistry,
130}
131
132impl std::fmt::Debug for Metrics {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 f.debug_struct("Metrics").finish_non_exhaustive()
135 }
136}
137
138impl Metrics {
139 pub fn new(cfg: &PersistConfig, registry: &MetricsRegistry) -> Self {
141 let vecs = MetricsVecs::new(registry);
142 let start = Instant::now();
143 let uptime = registry.register_computed_gauge(
144 metric!(
145 name: "mz_persist_metadata_seconds",
146 help: "server uptime, labels are build metadata",
147 const_labels: {
148 "version" => cfg.build_version,
149 "build_type" => if cfg!(release) { "release" } else { "debug" }
150 },
151 ),
152 move || start.elapsed().as_secs_f64(),
153 );
154 let s3_blob = S3BlobMetrics::new(registry);
155 let columnar = ColumnarMetrics::new(registry);
156 let mut per_shard_filter = PerShardMetricsFilter {
157 configs: Arc::clone(&cfg.configs),
158 mode: (String::new(), ShardMetricsExport::default()),
159 invalid_mode: registry.register(metric!(
160 name: "mz_persist_shard_metrics_mode_invalid",
161 help: "count of metrics scrapes that found persist_shard_metrics unrecognized and so exported the default",
162 )),
163 allow: (String::new(), None),
164 invalid_regex: registry.register(metric!(
165 name: "mz_persist_per_shard_metrics_regex_invalid",
166 help: "count of metrics scrapes that found persist_per_shard_metrics_enable_regex invalid and so kept no per-shard series",
167 )),
168 };
169 registry.register_postprocessor(move |families| per_shard_filter.filter(families));
170 Metrics {
171 blob: vecs.blob_metrics(),
172 consensus: vecs.consensus_metrics(),
173 cmds: vecs.cmds_metrics(registry),
174 retries: vecs.retries_metrics(),
175 codecs: vecs.codecs_metrics(),
176 user: BatchWriteMetrics::new(registry, "user"),
177 read: vecs.batch_part_read_metrics(),
178 compaction: CompactionMetrics::new(registry),
179 gc: GcMetrics::new(registry),
180 lease: LeaseMetrics::new(registry),
181 state: StateMetrics::new(registry),
182 shards: ShardsMetrics::new(registry, Arc::clone(&cfg.configs)),
183 audit: UsageAuditMetrics::new(registry),
184 locks: vecs.locks_metrics(),
185 watch: WatchMetrics::new(registry),
186 pubsub_client: PubSubClientMetrics::new(registry),
187 pushdown: PushdownMetrics::new(registry),
188 consolidation: ConsolidationMetrics::new(registry),
189 blob_cache_mem: BlobMemCache::new(registry),
190 tasks: TasksMetrics::new(registry),
191 columnar,
192 schema: SchemaMetrics::new(registry),
193 inline: InlineMetrics::new(registry),
194 semaphore: SemaphoreMetrics::new(cfg.clone(), registry.clone()),
195 sink: SinkMetrics::new(registry),
196 backpressure: BackpressureMetrics::new(registry),
197 s3_blob,
198 blob_hedge: BlobHedgeMetrics::new(registry),
199 postgres_consensus: PostgresClientMetrics::new(registry, "mz_persist"),
200 _vecs: vecs,
201 _uptime: uptime,
202 registry: registry.clone(),
203 }
204 }
205
206 pub fn write_amplification(&self) -> f64 {
211 let total_written = self.blob.set.bytes.get();
214 let user_written = self.user.goodbytes.get();
215 #[allow(clippy::as_conversions)]
216 {
217 total_written as f64 / user_written as f64
218 }
219 }
220}
221
222#[derive(Debug)]
223struct MetricsVecs {
224 cmd_started: IntCounterVec,
225 cmd_cas_mismatch: IntCounterVec,
226 cmd_succeeded: IntCounterVec,
227 cmd_failed: IntCounterVec,
228 cmd_seconds: CounterVec,
229
230 external_op_started: IntCounterVec,
231 external_op_succeeded: IntCounterVec,
232 external_op_failed: IntCounterVec,
233 external_op_bytes: IntCounterVec,
234 external_op_seconds: CounterVec,
235 external_consensus_truncated_count: IntCounter,
236 external_blob_delete_noop_count: IntCounter,
237 external_blob_sizes: Histogram,
238 external_rtt_latency: GaugeVec,
239 external_op_latency: HistogramVec,
240
241 retry_started: IntCounterVec,
242 retry_finished: IntCounterVec,
243 retry_retries: IntCounterVec,
244 retry_sleep_seconds: CounterVec,
245
246 encode_count: IntCounterVec,
247 encode_seconds: CounterVec,
248 decode_count: IntCounterVec,
249 decode_seconds: CounterVec,
250
251 read_part_bytes: IntCounterVec,
252 read_part_goodbytes: IntCounterVec,
253 read_part_count: IntCounterVec,
254 read_part_seconds: CounterVec,
255 read_ts_rewrite: IntCounterVec,
256
257 lock_acquire_count: IntCounterVec,
258 lock_blocking_acquire_count: IntCounterVec,
259 lock_blocking_seconds: CounterVec,
260
261 alerts_metrics: Arc<AlertsMetrics>,
263}
264
265impl MetricsVecs {
266 fn new(registry: &MetricsRegistry) -> Self {
267 MetricsVecs {
268 cmd_started: registry.register(metric!(
269 name: "mz_persist_cmd_started_count",
270 help: "count of commands started",
271 var_labels: ["cmd"],
272 )),
273 cmd_cas_mismatch: registry.register(metric!(
274 name: "mz_persist_cmd_cas_mismatch_count",
275 help: "count of command retries from CaS mismatch",
276 var_labels: ["cmd"],
277 )),
278 cmd_succeeded: registry.register(metric!(
279 name: "mz_persist_cmd_succeeded_count",
280 help: "count of commands succeeded",
281 var_labels: ["cmd"],
282 )),
283 cmd_failed: registry.register(metric!(
284 name: "mz_persist_cmd_failed_count",
285 help: "count of commands failed",
286 var_labels: ["cmd"],
287 )),
288 cmd_seconds: registry.register(metric!(
289 name: "mz_persist_cmd_seconds",
290 help: "time spent applying commands",
291 var_labels: ["cmd"],
292 )),
293
294 external_op_started: registry.register(metric!(
295 name: "mz_persist_external_started_count",
296 help: "count of external service calls started",
297 var_labels: ["op"],
298 )),
299 external_op_succeeded: registry.register(metric!(
300 name: "mz_persist_external_succeeded_count",
301 help: "count of external service calls succeeded",
302 var_labels: ["op"],
303 )),
304 external_op_failed: registry.register(metric!(
305 name: "mz_persist_external_failed_count",
306 help: "count of external service calls failed",
307 var_labels: ["op"],
308 )),
309 external_op_bytes: registry.register(metric!(
310 name: "mz_persist_external_bytes_count",
311 help: "total size represented by external service calls",
312 var_labels: ["op"],
313 )),
314 external_op_seconds: registry.register(metric!(
315 name: "mz_persist_external_seconds",
316 help: "time spent in external service calls",
317 var_labels: ["op"],
318 )),
319 external_consensus_truncated_count: registry.register(metric!(
320 name: "mz_persist_external_consensus_truncated_count",
321 help: "count of versions deleted by consensus truncate calls",
322 )),
323 external_blob_delete_noop_count: registry.register(metric!(
324 name: "mz_persist_external_blob_delete_noop_count",
325 help: "count of blob delete calls that deleted a non-existent key",
326 )),
327 external_blob_sizes: registry.register(metric!(
328 name: "mz_persist_external_blob_sizes",
329 help: "histogram of blob sizes at put time",
330 buckets: mz_ore::stats::HISTOGRAM_BYTE_BUCKETS.to_vec(),
331 )),
332 external_rtt_latency: registry.register(metric!(
333 name: "mz_persist_external_rtt_latency",
334 help: "roundtrip-time to external service as seen by this process",
335 var_labels: ["external"],
336 )),
337 external_op_latency: registry.register(metric!(
338 name: "mz_persist_external_op_latency",
339 help: "rountrip latency observed by individual performance-critical operations",
340 var_labels: ["op"],
341 buckets: histogram_seconds_buckets(0.000_500, 32.0),
344 )),
345
346 retry_started: registry.register(metric!(
347 name: "mz_persist_retry_started_count",
348 help: "count of retry loops started",
349 var_labels: ["op"],
350 )),
351 retry_finished: registry.register(metric!(
352 name: "mz_persist_retry_finished_count",
353 help: "count of retry loops finished",
354 var_labels: ["op"],
355 )),
356 retry_retries: registry.register(metric!(
357 name: "mz_persist_retry_retries_count",
358 help: "count of total attempts by retry loops",
359 var_labels: ["op"],
360 )),
361 retry_sleep_seconds: registry.register(metric!(
362 name: "mz_persist_retry_sleep_seconds",
363 help: "time spent in retry loop backoff",
364 var_labels: ["op"],
365 )),
366
367 encode_count: registry.register(metric!(
368 name: "mz_persist_encode_count",
369 help: "count of op encodes",
370 var_labels: ["op"],
371 )),
372 encode_seconds: registry.register(metric!(
373 name: "mz_persist_encode_seconds",
374 help: "time spent in op encodes",
375 var_labels: ["op"],
376 )),
377 decode_count: registry.register(metric!(
378 name: "mz_persist_decode_count",
379 help: "count of op decodes",
380 var_labels: ["op"],
381 )),
382 decode_seconds: registry.register(metric!(
383 name: "mz_persist_decode_seconds",
384 help: "time spent in op decodes",
385 var_labels: ["op"],
386 )),
387
388 read_part_bytes: registry.register(metric!(
389 name: "mz_persist_read_batch_part_bytes",
390 help: "total encoded size of batch parts read",
391 var_labels: ["op"],
392 )),
393 read_part_goodbytes: registry.register(metric!(
394 name: "mz_persist_read_batch_part_goodbytes",
395 help: "total logical size of batch parts read",
396 var_labels: ["op"],
397 )),
398 read_part_count: registry.register(metric!(
399 name: "mz_persist_read_batch_part_count",
400 help: "count of batch parts read",
401 var_labels: ["op"],
402 )),
403 read_part_seconds: registry.register(metric!(
404 name: "mz_persist_read_batch_part_seconds",
405 help: "time spent reading batch parts",
406 var_labels: ["op"],
407 )),
408 read_ts_rewrite: registry.register(metric!(
409 name: "mz_persist_read_ts_rewite",
410 help: "count of updates read with rewritten ts",
411 var_labels: ["op"],
412 )),
413
414 lock_acquire_count: registry.register(metric!(
415 name: "mz_persist_lock_acquire_count",
416 help: "count of locks acquired",
417 var_labels: ["op"],
418 )),
419 lock_blocking_acquire_count: registry.register(metric!(
420 name: "mz_persist_lock_blocking_acquire_count",
421 help: "count of locks acquired that required blocking",
422 var_labels: ["op"],
423 )),
424 lock_blocking_seconds: registry.register(metric!(
425 name: "mz_persist_lock_blocking_seconds",
426 help: "time spent blocked for a lock",
427 var_labels: ["op"],
428 )),
429
430 alerts_metrics: Arc::new(AlertsMetrics::new(registry)),
431 }
432 }
433
434 fn cmds_metrics(&self, registry: &MetricsRegistry) -> CmdsMetrics {
435 CmdsMetrics {
436 init_state: self.cmd_metrics("init_state"),
437 add_rollup: self.cmd_metrics("add_rollup"),
438 remove_rollups: self.cmd_metrics("remove_rollups"),
439 upgrade_version: self.cmd_metrics("upgrade_version"),
440 register: self.cmd_metrics("register"),
441 compare_and_append: self.cmd_metrics("compare_and_append"),
442 compare_and_append_noop: registry.register(metric!(
443 name: "mz_persist_cmd_compare_and_append_noop",
444 help: "count of compare_and_append retries that were discoverd to have already committed",
445 )),
446 compare_and_downgrade_since: self.cmd_metrics("compare_and_downgrade_since"),
447 downgrade_since: self.cmd_metrics("downgrade_since"),
448 expire_reader: self.cmd_metrics("expire_reader"),
449 expire_writer: self.cmd_metrics("expire_writer"),
450 merge_res: self.cmd_metrics("merge_res"),
451 become_tombstone: self.cmd_metrics("become_tombstone"),
452 compare_and_evolve_schema: self.cmd_metrics("compare_and_evolve_schema"),
453 spine_exert: self.cmd_metrics("spine_exert"),
454 fetch_upper_count: registry.register(metric!(
455 name: "mz_persist_cmd_fetch_upper_count",
456 help: "count of fetch_upper calls",
457 ))
458 }
459 }
460
461 fn cmd_metrics(&self, cmd: &str) -> CmdMetrics {
462 CmdMetrics {
463 name: cmd.to_owned(),
464 started: self.cmd_started.with_label_values(&[cmd]),
465 succeeded: self.cmd_succeeded.with_label_values(&[cmd]),
466 cas_mismatch: self.cmd_cas_mismatch.with_label_values(&[cmd]),
467 failed: self.cmd_failed.with_label_values(&[cmd]),
468 seconds: self.cmd_seconds.with_label_values(&[cmd]),
469 }
470 }
471
472 fn retries_metrics(&self) -> RetriesMetrics {
473 RetriesMetrics {
474 determinate: RetryDeterminate {
475 apply_unbatched_cmd_cas: self.retry_metrics("apply_unbatched_cmd::cas"),
476 },
477 external: RetryExternal {
478 batch_delete: Arc::new(self.retry_metrics("batch::delete")),
479 batch_set: self.retry_metrics("batch::set"),
480 blob_open: self.retry_metrics("blob::open"),
481 compaction_noop_delete: Arc::new(self.retry_metrics("compaction_noop::delete")),
482 consensus_open: self.retry_metrics("consensus::open"),
483 fetch_batch_get: self.retry_metrics("fetch_batch::get"),
484 fetch_state_scan: self.retry_metrics("fetch_state::scan"),
485 gc_truncate: self.retry_metrics("gc::truncate"),
486 maybe_init_cas: self.retry_metrics("maybe_init::cas"),
487 rollup_delete: self.retry_metrics("rollup::delete"),
488 rollup_get: self.retry_metrics("rollup::get"),
489 rollup_set: self.retry_metrics("rollup::set"),
490 hollow_run_get: self.retry_metrics("hollow_run::get"),
491 hollow_run_set: self.retry_metrics("hollow_run::set"),
492 storage_usage_shard_size: self.retry_metrics("storage_usage::shard_size"),
493 },
494 compare_and_append_idempotent: self.retry_metrics("compare_and_append_idempotent"),
495 fetch_latest_state: self.retry_metrics("fetch_latest_state"),
496 fetch_live_states: self.retry_metrics("fetch_live_states"),
497 idempotent_cmd: self.retry_metrics("idempotent_cmd"),
498 next_listen_batch: self.retry_metrics("next_listen_batch"),
499 snapshot: self.retry_metrics("snapshot"),
500 }
501 }
502
503 fn retry_metrics(&self, name: &str) -> RetryMetrics {
504 RetryMetrics {
505 name: name.to_owned(),
506 started: self.retry_started.with_label_values(&[name]),
507 finished: self.retry_finished.with_label_values(&[name]),
508 retries: self.retry_retries.with_label_values(&[name]),
509 sleep_seconds: self.retry_sleep_seconds.with_label_values(&[name]),
510 }
511 }
512
513 fn codecs_metrics(&self) -> CodecsMetrics {
514 CodecsMetrics {
515 state: self.codec_metrics("state"),
516 state_diff: self.codec_metrics("state_diff"),
517 batch: self.codec_metrics("batch"),
518 key: self.codec_metrics("key"),
519 val: self.codec_metrics("val"),
520 }
521 }
522
523 fn codec_metrics(&self, op: &str) -> CodecMetrics {
524 CodecMetrics {
525 encode_count: self.encode_count.with_label_values(&[op]),
526 encode_seconds: self.encode_seconds.with_label_values(&[op]),
527 decode_count: self.decode_count.with_label_values(&[op]),
528 decode_seconds: self.decode_seconds.with_label_values(&[op]),
529 }
530 }
531
532 fn blob_metrics(&self) -> BlobMetrics {
533 BlobMetrics {
534 set: self.external_op_metrics("blob_set", true),
535 get: self.external_op_metrics("blob_get", true),
536 list_keys: self.external_op_metrics("blob_list_keys", false),
537 delete: self.external_op_metrics("blob_delete", false),
538 restore: self.external_op_metrics("restore", false),
539 delete_noop: self.external_blob_delete_noop_count.clone(),
540 blob_sizes: self.external_blob_sizes.clone(),
541 rtt_latency: self.external_rtt_latency.with_label_values(&["blob"]),
542 }
543 }
544
545 fn consensus_metrics(&self) -> ConsensusMetrics {
546 ConsensusMetrics {
547 list_keys: self.external_op_metrics("consensus_list_keys", false),
548 head: self.external_op_metrics("consensus_head", false),
549 compare_and_set: self.external_op_metrics("consensus_cas", true),
550 scan: self.external_op_metrics("consensus_scan", false),
551 truncate: self.external_op_metrics("consensus_truncate", false),
552 truncated_count: self.external_consensus_truncated_count.clone(),
553 rtt_latency: self.external_rtt_latency.with_label_values(&["consensus"]),
554 }
555 }
556
557 fn external_op_metrics(&self, op: &str, latency_histogram: bool) -> ExternalOpMetrics {
558 ExternalOpMetrics {
559 started: self.external_op_started.with_label_values(&[op]),
560 succeeded: self.external_op_succeeded.with_label_values(&[op]),
561 failed: self.external_op_failed.with_label_values(&[op]),
562 bytes: self.external_op_bytes.with_label_values(&[op]),
563 seconds: self.external_op_seconds.with_label_values(&[op]),
564 seconds_histogram: if latency_histogram {
565 Some(self.external_op_latency.with_label_values(&[op]))
566 } else {
567 None
568 },
569 alerts_metrics: Arc::clone(&self.alerts_metrics),
570 }
571 }
572
573 fn batch_part_read_metrics(&self) -> BatchPartReadMetrics {
574 BatchPartReadMetrics {
575 listen: self.read_metrics("listen"),
576 snapshot: self.read_metrics("snapshot"),
577 batch_fetcher: self.read_metrics("batch_fetcher"),
578 compaction: self.read_metrics("compaction"),
579 unindexed: self.read_metrics("unindexed"),
580 }
581 }
582
583 fn read_metrics(&self, op: &str) -> ReadMetrics {
584 ReadMetrics {
585 part_bytes: self.read_part_bytes.with_label_values(&[op]),
586 part_goodbytes: self.read_part_goodbytes.with_label_values(&[op]),
587 part_count: self.read_part_count.with_label_values(&[op]),
588 seconds: self.read_part_seconds.with_label_values(&[op]),
589 ts_rewrite: self.read_ts_rewrite.with_label_values(&[op]),
590 }
591 }
592
593 fn locks_metrics(&self) -> LocksMetrics {
594 LocksMetrics {
595 applier_read_cacheable: self.lock_metrics("applier_read_cacheable"),
596 applier_read_noncacheable: self.lock_metrics("applier_read_noncacheable"),
597 applier_write: self.lock_metrics("applier_write"),
598 watch: self.lock_metrics("watch"),
599 }
600 }
601
602 fn lock_metrics(&self, op: &str) -> LockMetrics {
603 LockMetrics {
604 acquire_count: self.lock_acquire_count.with_label_values(&[op]),
605 blocking_acquire_count: self.lock_blocking_acquire_count.with_label_values(&[op]),
606 blocking_seconds: self.lock_blocking_seconds.with_label_values(&[op]),
607 }
608 }
609}
610
611#[derive(Debug)]
612pub struct CmdMetrics {
613 pub(crate) name: String,
614 pub(crate) started: IntCounter,
615 pub(crate) cas_mismatch: IntCounter,
616 pub(crate) succeeded: IntCounter,
617 pub(crate) failed: IntCounter,
618 pub(crate) seconds: Counter,
619}
620
621impl CmdMetrics {
622 pub async fn run_cmd<R, E, F, CmdFn>(
623 &self,
624 shard_metrics: &ShardMetrics,
625 cmd_fn: CmdFn,
626 ) -> Result<R, E>
627 where
628 F: std::future::Future<Output = Result<R, E>>,
629 CmdFn: FnOnce() -> F,
630 {
631 self.started.inc();
632 let start = Instant::now();
633 let res = cmd_fn().await;
634 self.seconds.inc_by(start.elapsed().as_secs_f64());
635 match res.as_ref() {
636 Ok(_) => {
637 self.succeeded.inc();
638 shard_metrics.cmd_succeeded.inc();
639 }
640 Err(_) => self.failed.inc(),
641 };
642 res
643 }
644}
645
646#[derive(Debug)]
647pub struct CmdsMetrics {
648 pub(crate) init_state: CmdMetrics,
649 pub(crate) add_rollup: CmdMetrics,
650 pub(crate) remove_rollups: CmdMetrics,
651 pub(crate) upgrade_version: CmdMetrics,
652 pub(crate) register: CmdMetrics,
653 pub(crate) compare_and_append: CmdMetrics,
654 pub(crate) compare_and_append_noop: IntCounter,
655 pub(crate) compare_and_downgrade_since: CmdMetrics,
656 pub(crate) downgrade_since: CmdMetrics,
657 pub(crate) expire_reader: CmdMetrics,
658 pub(crate) expire_writer: CmdMetrics,
659 pub(crate) merge_res: CmdMetrics,
660 pub(crate) become_tombstone: CmdMetrics,
661 pub(crate) compare_and_evolve_schema: CmdMetrics,
662 pub(crate) spine_exert: CmdMetrics,
663 pub(crate) fetch_upper_count: IntCounter,
664}
665
666#[derive(Debug)]
667pub struct RetryMetrics {
668 pub(crate) name: String,
669 pub(crate) started: IntCounter,
670 pub(crate) finished: IntCounter,
671 pub(crate) retries: IntCounter,
672 pub(crate) sleep_seconds: Counter,
673}
674
675impl RetryMetrics {
676 pub(crate) fn stream(&self, retry: RetryStream) -> MetricsRetryStream {
677 MetricsRetryStream::new(retry, self)
678 }
679}
680
681#[derive(Debug)]
682pub struct RetryDeterminate {
683 pub(crate) apply_unbatched_cmd_cas: RetryMetrics,
684}
685
686#[derive(Debug)]
687pub struct RetryExternal {
688 pub(crate) batch_delete: Arc<RetryMetrics>,
689 pub(crate) batch_set: RetryMetrics,
690 pub(crate) blob_open: RetryMetrics,
691 pub(crate) compaction_noop_delete: Arc<RetryMetrics>,
692 pub(crate) consensus_open: RetryMetrics,
693 pub(crate) fetch_batch_get: RetryMetrics,
694 pub(crate) fetch_state_scan: RetryMetrics,
695 pub(crate) gc_truncate: RetryMetrics,
696 pub(crate) maybe_init_cas: RetryMetrics,
697 pub(crate) rollup_delete: RetryMetrics,
698 pub(crate) rollup_get: RetryMetrics,
699 pub(crate) rollup_set: RetryMetrics,
700 pub(crate) hollow_run_get: RetryMetrics,
701 pub(crate) hollow_run_set: RetryMetrics,
702 pub(crate) storage_usage_shard_size: RetryMetrics,
703}
704
705#[derive(Debug)]
706pub struct RetriesMetrics {
707 pub(crate) determinate: RetryDeterminate,
708 pub(crate) external: RetryExternal,
709
710 pub(crate) compare_and_append_idempotent: RetryMetrics,
711 pub(crate) fetch_latest_state: RetryMetrics,
712 pub(crate) fetch_live_states: RetryMetrics,
713 pub(crate) idempotent_cmd: RetryMetrics,
714 pub(crate) next_listen_batch: RetryMetrics,
715 pub(crate) snapshot: RetryMetrics,
716}
717
718#[derive(Debug)]
719pub struct BatchPartReadMetrics {
720 pub(crate) listen: ReadMetrics,
721 pub(crate) snapshot: ReadMetrics,
722 pub(crate) batch_fetcher: ReadMetrics,
723 pub(crate) compaction: ReadMetrics,
724 pub(crate) unindexed: ReadMetrics,
725}
726
727#[derive(Debug, Clone)]
728pub struct ReadMetrics {
729 pub(crate) part_bytes: IntCounter,
730 pub(crate) part_goodbytes: IntCounter,
731 pub(crate) part_count: IntCounter,
732 pub(crate) seconds: Counter,
733 pub(crate) ts_rewrite: IntCounter,
734}
735
736#[derive(Debug, Clone)]
739pub struct BatchWriteMetrics {
740 pub(crate) bytes: IntCounter,
741 pub(crate) goodbytes: IntCounter,
742 pub(crate) seconds: Counter,
743 pub(crate) write_stalls: IntCounter,
744 pub(crate) key_lower_too_big: IntCounter,
745
746 pub(crate) unordered: IntCounter,
747 pub(crate) codec_order: IntCounter,
748 pub(crate) structured_order: IntCounter,
749 _order_counts: IntCounterVec,
750
751 pub(crate) step_stats: Counter,
752 pub(crate) step_part_writing: Counter,
753 pub(crate) step_inline: Counter,
754}
755
756impl BatchWriteMetrics {
757 fn new(registry: &MetricsRegistry, name: &str) -> Self {
758 let order_counts: IntCounterVec = registry.register(metric!(
759 name: format!("mz_persist_{}_write_batch_order", name),
760 help: "count of batches by the data ordering",
761 var_labels: ["order"],
762 ));
763 let unordered = order_counts.with_label_values(&["unordered"]);
764 let codec_order = order_counts.with_label_values(&["codec"]);
765 let structured_order = order_counts.with_label_values(&["structured"]);
766
767 BatchWriteMetrics {
768 bytes: registry.register(metric!(
769 name: format!("mz_persist_{}_bytes", name),
770 help: format!("total encoded size of {} batches written", name),
771 )),
772 goodbytes: registry.register(metric!(
773 name: format!("mz_persist_{}_goodbytes", name),
774 help: format!("total logical size of {} batches written", name),
775 )),
776 seconds: registry.register(metric!(
777 name: format!("mz_persist_{}_write_batch_part_seconds", name),
778 help: format!("time spent writing {} batches", name),
779 )),
780 write_stalls: registry.register(metric!(
781 name: format!("mz_persist_{}_write_stall_count", name),
782 help: format!(
783 "count of {} writes stalling to await max outstanding reqs",
784 name
785 ),
786 )),
787 key_lower_too_big: registry.register(metric!(
788 name: format!("mz_persist_{}_key_lower_too_big", name),
789 help: format!(
790 "count of {} writes that were unable to write a key lower, because the size threshold was too low",
791 name
792 ),
793 )),
794 unordered,
795 codec_order,
796 structured_order,
797 _order_counts: order_counts,
798 step_stats: registry.register(metric!(
799 name: format!("mz_persist_{}_step_stats", name),
800 help: format!("time spent computing {} update stats", name),
801 )),
802 step_part_writing: registry.register(metric!(
803 name: format!("mz_persist_{}_step_part_writing", name),
804 help: format!("blocking time spent writing parts for {} updates", name),
805 )),
806 step_inline: registry.register(metric!(
807 name: format!("mz_persist_{}_step_inline", name),
808 help: format!("time spent encoding {} inline batches", name)
809 )),
810 }
811 }
812}
813
814#[derive(Debug)]
815pub struct CompactionMetrics {
816 pub(crate) requested: IntCounter,
817 pub(crate) dropped: IntCounter,
818 pub(crate) disabled: IntCounter,
819 pub(crate) skipped: IntCounter,
820 pub(crate) started: IntCounter,
821 pub(crate) applied: IntCounter,
822 pub(crate) timed_out: IntCounter,
823 pub(crate) failed: IntCounter,
824 pub(crate) noop: IntCounter,
825 pub(crate) seconds: Counter,
826 pub(crate) concurrency_waits: IntCounter,
827 pub(crate) queued_seconds: Counter,
828 pub(crate) memory_violations: IntCounter,
829 pub(crate) runs_compacted: IntCounter,
830 pub(crate) chunks_compacted: IntCounter,
831 pub(crate) not_all_prefetched: IntCounter,
832 pub(crate) parts_prefetched: IntCounter,
833 pub(crate) parts_waited: IntCounter,
834 pub(crate) fast_path_eligible: IntCounter,
835 pub(crate) admin_count: IntCounter,
836
837 pub(crate) applied_exact_match: IntCounter,
838 pub(crate) applied_subset_match: IntCounter,
839 pub(crate) not_applied_too_many_updates: IntCounter,
840
841 pub(crate) batch: BatchWriteMetrics,
842 pub(crate) steps: CompactionStepTimings,
843 pub(crate) schema_selection: CompactionSchemaSelection,
844
845 pub(crate) _steps_vec: CounterVec,
846}
847
848impl CompactionMetrics {
849 fn new(registry: &MetricsRegistry) -> Self {
850 let step_timings: CounterVec = registry.register(metric!(
851 name: "mz_persist_compaction_step_seconds",
852 help: "time spent on individual steps of compaction",
853 var_labels: ["step"],
854 ));
855 let schema_selection: CounterVec = registry.register(metric!(
856 name: "mz_persist_compaction_schema_selection",
857 help: "count of compactions and how we did schema selection",
858 var_labels: ["selection"],
859 ));
860
861 CompactionMetrics {
862 requested: registry.register(metric!(
863 name: "mz_persist_compaction_requested",
864 help: "count of total compaction requests",
865 )),
866 dropped: registry.register(metric!(
867 name: "mz_persist_compaction_dropped",
868 help: "count of total compaction requests dropped due to a full queue",
869 )),
870 disabled: registry.register(metric!(
871 name: "mz_persist_compaction_disabled",
872 help: "count of total compaction requests dropped because compaction was disabled",
873 )),
874 skipped: registry.register(metric!(
875 name: "mz_persist_compaction_skipped",
876 help: "count of compactions skipped due to heuristics",
877 )),
878 started: registry.register(metric!(
879 name: "mz_persist_compaction_started",
880 help: "count of compactions started",
881 )),
882 failed: registry.register(metric!(
883 name: "mz_persist_compaction_failed",
884 help: "count of compactions failed",
885 )),
886 applied: registry.register(metric!(
887 name: "mz_persist_compaction_applied",
888 help: "count of compactions applied to state",
889 )),
890 timed_out: registry.register(metric!(
891 name: "mz_persist_compaction_timed_out",
892 help: "count of compactions that timed out",
893 )),
894 noop: registry.register(metric!(
895 name: "mz_persist_compaction_noop",
896 help: "count of compactions discarded (obsolete)",
897 )),
898 seconds: registry.register(metric!(
899 name: "mz_persist_compaction_seconds",
900 help: "time spent in compaction",
901 )),
902 concurrency_waits: registry.register(metric!(
903 name: "mz_persist_compaction_concurrency_waits",
904 help: "count of compaction requests that ever blocked due to concurrency limit",
905 )),
906 queued_seconds: registry.register(metric!(
907 name: "mz_persist_compaction_queued_seconds",
908 help: "time that compaction requests spent queued",
909 )),
910 memory_violations: registry.register(metric!(
911 name: "mz_persist_compaction_memory_violations",
912 help: "count of compaction memory requirement violations",
913 )),
914 runs_compacted: registry.register(metric!(
915 name: "mz_persist_compaction_runs_compacted",
916 help: "count of runs compacted",
917 )),
918 chunks_compacted: registry.register(metric!(
919 name: "mz_persist_compaction_chunks_compacted",
920 help: "count of run chunks compacted",
921 )),
922 not_all_prefetched: registry.register(metric!(
923 name: "mz_persist_compaction_not_all_prefetched",
924 help: "count of compactions where not all inputs were prefetched",
925 )),
926 parts_prefetched: registry.register(metric!(
927 name: "mz_persist_compaction_parts_prefetched",
928 help: "count of compaction parts completely prefetched by the time they're needed",
929 )),
930 parts_waited: registry.register(metric!(
931 name: "mz_persist_compaction_parts_waited",
932 help: "count of compaction parts that had to be waited on",
933 )),
934 fast_path_eligible: registry.register(metric!(
935 name: "mz_persist_compaction_fast_path_eligible",
936 help: "count of compaction requests that could have used the fast-path optimization",
937 )),
938 admin_count: registry.register(metric!(
939 name: "mz_persist_compaction_admin_count",
940 help: "count of compaction requests that were performed by admin tooling",
941 )),
942 applied_exact_match: registry.register(metric!(
943 name: "mz_persist_compaction_applied_exact_match",
944 help: "count of merge results that exactly replaced a SpineBatch",
945 )),
946 applied_subset_match: registry.register(metric!(
947 name: "mz_persist_compaction_applied_subset_match",
948 help: "count of merge results that replaced a subset of a SpineBatch",
949 )),
950 not_applied_too_many_updates: registry.register(metric!(
951 name: "mz_persist_compaction_not_applied_too_many_updates",
952 help: "count of merge results that did not apply due to too many updates",
953 )),
954 batch: BatchWriteMetrics::new(registry, "compaction"),
955 steps: CompactionStepTimings::new(step_timings.clone()),
956 schema_selection: CompactionSchemaSelection::new(schema_selection.clone()),
957 _steps_vec: step_timings,
958 }
959 }
960}
961
962#[derive(Debug)]
963pub struct CompactionStepTimings {
964 pub(crate) part_fetch_seconds: Counter,
965 pub(crate) heap_population_seconds: Counter,
966}
967
968impl CompactionStepTimings {
969 fn new(step_timings: CounterVec) -> CompactionStepTimings {
970 CompactionStepTimings {
971 part_fetch_seconds: step_timings.with_label_values(&["part_fetch"]),
972 heap_population_seconds: step_timings.with_label_values(&["heap_population"]),
973 }
974 }
975}
976
977#[derive(Debug)]
978pub struct CompactionSchemaSelection {
979 pub(crate) recent_schema: Counter,
980 pub(crate) no_schema: Counter,
981}
982
983impl CompactionSchemaSelection {
984 fn new(schema_selection: CounterVec) -> CompactionSchemaSelection {
985 CompactionSchemaSelection {
986 recent_schema: schema_selection.with_label_values(&["recent"]),
987 no_schema: schema_selection.with_label_values(&["none"]),
988 }
989 }
990}
991
992#[derive(Debug)]
993pub struct GcMetrics {
994 pub(crate) noop: IntCounter,
995 pub(crate) started: IntCounter,
996 pub(crate) finished: IntCounter,
997 pub(crate) merged: IntCounter,
998 pub(crate) seconds: Counter,
999 pub(crate) steps: GcStepTimings,
1000 tombstone_deleted_blobs: IntCounterVec,
1001 tombstone_deleted_bytes: IntCounterVec,
1002}
1003
1004#[derive(Debug)]
1005pub struct GcStepTimings {
1006 pub(crate) find_removable_rollups: Counter,
1007 pub(crate) fetch_seconds: Counter,
1008 pub(crate) find_deletable_blobs_seconds: Counter,
1009 pub(crate) delete_rollup_seconds: Counter,
1010 pub(crate) delete_batch_part_seconds: Counter,
1011 pub(crate) truncate_diff_seconds: Counter,
1012 pub(crate) remove_rollups_from_state: Counter,
1013 pub(crate) post_gc_calculations_seconds: Counter,
1014}
1015
1016impl GcStepTimings {
1017 fn new(step_timings: CounterVec) -> Self {
1018 Self {
1019 find_removable_rollups: step_timings.with_label_values(&["find_removable_rollups"]),
1020 fetch_seconds: step_timings.with_label_values(&["fetch"]),
1021 find_deletable_blobs_seconds: step_timings.with_label_values(&["find_deletable_blobs"]),
1022 delete_rollup_seconds: step_timings.with_label_values(&["delete_rollup"]),
1023 delete_batch_part_seconds: step_timings.with_label_values(&["delete_batch_part"]),
1024 truncate_diff_seconds: step_timings.with_label_values(&["truncate_diff"]),
1025 remove_rollups_from_state: step_timings
1026 .with_label_values(&["remove_rollups_from_state"]),
1027 post_gc_calculations_seconds: step_timings.with_label_values(&["post_gc_calculations"]),
1028 }
1029 }
1030}
1031
1032impl GcMetrics {
1033 fn new(registry: &MetricsRegistry) -> Self {
1034 let step_timings: CounterVec = registry.register(metric!(
1035 name: "mz_persist_gc_step_seconds",
1036 help: "time spent on individual steps of gc",
1037 var_labels: ["step"],
1038 ));
1039 GcMetrics {
1040 noop: registry.register(metric!(
1041 name: "mz_persist_gc_noop",
1042 help: "count of garbage collections skipped because they were already done",
1043 )),
1044 started: registry.register(metric!(
1045 name: "mz_persist_gc_started",
1046 help: "count of garbage collections started",
1047 )),
1048 finished: registry.register(metric!(
1049 name: "mz_persist_gc_finished",
1050 help: "count of garbage collections finished",
1051 )),
1052 merged: registry.register(metric!(
1053 name: "mz_persist_gc_merged_reqs",
1054 help: "count of garbage collection requests merged",
1055 )),
1056 seconds: registry.register(metric!(
1057 name: "mz_persist_gc_seconds",
1058 help: "time spent in garbage collections",
1059 )),
1060 steps: GcStepTimings::new(step_timings),
1061 tombstone_deleted_blobs: registry.register(metric!(
1062 name: "mz_persist_gc_tombstone_deleted_blobs",
1063 help: "count of blobs GC deleted from dropped (tombstone) shards, by who requested the GC",
1064 var_labels: ["caller"],
1065 )),
1066 tombstone_deleted_bytes: registry.register(metric!(
1067 name: "mz_persist_gc_tombstone_deleted_bytes",
1068 help: "total size of blobs GC deleted from dropped (tombstone) shards, by who requested the GC",
1069 var_labels: ["caller"],
1070 )),
1071 }
1072 }
1073
1074 pub(crate) fn tombstone_deleted(&self, caller: GcCaller, deleted: BlobDeleteStats) {
1076 let caller = match caller {
1077 GcCaller::Maintenance => "maintenance",
1078 GcCaller::Finalize => "finalize",
1079 };
1080 self.tombstone_deleted_blobs
1081 .with_label_values(&[caller])
1082 .inc_by(u64::cast_from(deleted.count));
1083 self.tombstone_deleted_bytes
1084 .with_label_values(&[caller])
1085 .inc_by(u64::cast_from(deleted.bytes));
1086 }
1087
1088 #[cfg(test)]
1089 pub(crate) fn tombstone_deleted_blobs(&self, caller: &str) -> u64 {
1090 self.tombstone_deleted_blobs
1091 .with_label_values(&[caller])
1092 .get()
1093 }
1094}
1095
1096#[derive(Debug)]
1097pub struct LeaseMetrics {
1098 pub(crate) timeout_read: IntCounter,
1099 pub(crate) expired_live_read: IntCounter,
1102 pub(crate) dropped_part: IntCounter,
1103}
1104
1105impl LeaseMetrics {
1106 fn new(registry: &MetricsRegistry) -> Self {
1107 LeaseMetrics {
1108 timeout_read: registry.register(metric!(
1109 name: "mz_persist_lease_timeout_read",
1110 help: "count of readers whose lease timed out",
1111 )),
1112 expired_live_read: registry.register(metric!(
1113 name: "mz_persist_lease_expired_live_read",
1114 help: "count of fetches that found their reader's lease had timed out",
1115 )),
1116 dropped_part: registry.register(metric!(
1117 name: "mz_persist_lease_dropped_part",
1118 help: "count of LeasedBatchParts that were dropped without being politely returned",
1119 )),
1120 }
1121 }
1122}
1123
1124struct IncOnDrop(IntCounter);
1125
1126impl Drop for IncOnDrop {
1127 fn drop(&mut self) {
1128 self.0.inc()
1129 }
1130}
1131
1132pub struct MetricsRetryStream {
1133 retry: RetryStream,
1134 pub(crate) retries: IntCounter,
1135 sleep_seconds: Counter,
1136 _finished: IncOnDrop,
1137}
1138
1139impl MetricsRetryStream {
1140 pub fn new(retry: RetryStream, metrics: &RetryMetrics) -> Self {
1141 metrics.started.inc();
1142 MetricsRetryStream {
1143 retry,
1144 retries: metrics.retries.clone(),
1145 sleep_seconds: metrics.sleep_seconds.clone(),
1146 _finished: IncOnDrop(metrics.finished.clone()),
1147 }
1148 }
1149
1150 pub fn attempt(&self) -> usize {
1152 self.retry.attempt()
1153 }
1154
1155 pub fn next_sleep(&self) -> Duration {
1157 self.retry.next_sleep()
1158 }
1159
1160 pub async fn sleep(self) -> Self {
1165 self.retries.inc();
1166 self.sleep_seconds
1167 .inc_by(self.retry.next_sleep().as_secs_f64());
1168 let retry = self.retry.sleep().await;
1169 MetricsRetryStream {
1170 retry,
1171 retries: self.retries,
1172 sleep_seconds: self.sleep_seconds,
1173 _finished: self._finished,
1174 }
1175 }
1176}
1177
1178#[derive(Debug)]
1179pub struct CodecsMetrics {
1180 pub(crate) state: CodecMetrics,
1181 pub(crate) state_diff: CodecMetrics,
1182 pub(crate) batch: CodecMetrics,
1183 pub(crate) key: CodecMetrics,
1184 pub(crate) val: CodecMetrics,
1185 }
1188
1189#[derive(Debug)]
1190pub struct CodecMetrics {
1191 pub(crate) encode_count: IntCounter,
1192 pub(crate) encode_seconds: Counter,
1193 pub(crate) decode_count: IntCounter,
1194 pub(crate) decode_seconds: Counter,
1195}
1196
1197impl CodecMetrics {
1198 pub(crate) fn encode<R, F: FnOnce() -> R>(&self, f: F) -> R {
1199 let now = Instant::now();
1200 let r = f();
1201 self.encode_count.inc();
1202 self.encode_seconds.inc_by(now.elapsed().as_secs_f64());
1203 r
1204 }
1205
1206 pub(crate) fn decode<R, F: FnOnce() -> R>(&self, f: F) -> R {
1207 let now = Instant::now();
1208 let r = f();
1209 self.decode_count.inc();
1210 self.decode_seconds.inc_by(now.elapsed().as_secs_f64());
1211 r
1212 }
1213}
1214
1215#[derive(Debug)]
1216pub struct StateMetrics {
1217 pub(crate) apply_spine_fast_path: IntCounter,
1218 pub(crate) apply_spine_slow_path: IntCounter,
1219 pub(crate) apply_spine_slow_path_lenient: IntCounter,
1220 pub(crate) apply_spine_slow_path_lenient_adjustment: IntCounter,
1221 pub(crate) apply_spine_slow_path_with_reconstruction: IntCounter,
1222 pub(crate) apply_spine_flattened: IntCounter,
1223 pub(crate) update_state_noop_path: IntCounter,
1224 pub(crate) update_state_empty_path: IntCounter,
1225 pub(crate) update_state_fast_path: IntCounter,
1226 pub(crate) update_state_slow_path: IntCounter,
1227 pub(crate) rollup_at_seqno_migration: IntCounter,
1228 pub(crate) fetch_recent_live_diffs_fast_path: IntCounter,
1229 pub(crate) fetch_recent_live_diffs_slow_path: IntCounter,
1230 pub(crate) writer_added: IntCounter,
1231 pub(crate) writer_removed: IntCounter,
1232 pub(crate) force_apply_hostname: IntCounter,
1233 pub(crate) rollup_write_success: IntCounter,
1234 pub(crate) rollup_write_noop_latest: IntCounter,
1235 pub(crate) rollup_write_noop_truncated: IntCounter,
1236 pub(crate) hollow_run_missing_on_delete: IntCounter,
1237 pub(crate) finalized_rollup_assigned: IntCounter,
1238}
1239
1240impl StateMetrics {
1241 pub(crate) fn new(registry: &MetricsRegistry) -> Self {
1242 let rollup_write_noop: IntCounterVec = registry.register(metric!(
1243 name: "mz_persist_state_rollup_write_noop",
1244 help: "count of no-op rollup writes",
1245 var_labels: ["reason"],
1246 ));
1247
1248 StateMetrics {
1249 apply_spine_fast_path: registry.register(metric!(
1250 name: "mz_persist_state_apply_spine_fast_path",
1251 help: "count of spine diff applications that hit the fast path",
1252 )),
1253 apply_spine_slow_path: registry.register(metric!(
1254 name: "mz_persist_state_apply_spine_slow_path",
1255 help: "count of spine diff applications that hit the slow path",
1256 )),
1257 apply_spine_slow_path_lenient: registry.register(metric!(
1258 name: "mz_persist_state_apply_spine_slow_path_lenient",
1259 help: "count of spine diff applications that hit the lenient compaction apply path",
1260 )),
1261 apply_spine_slow_path_lenient_adjustment: registry.register(metric!(
1262 name: "mz_persist_state_apply_spine_slow_path_lenient_adjustment",
1263 help: "count of adjustments made by the lenient compaction apply path",
1264 )),
1265 apply_spine_slow_path_with_reconstruction: registry.register(metric!(
1266 name: "mz_persist_state_apply_spine_slow_path_with_reconstruction",
1267 help: "count of spine diff applications that hit the slow path with extra spine reconstruction step",
1268 )),
1269 apply_spine_flattened: registry.register(metric!(
1270 name: "mz_persist_state_apply_spine_flattened",
1271 help: "count of spine diff applications that flatten the trace",
1272 )),
1273 update_state_noop_path: registry.register(metric!(
1274 name: "mz_persist_state_update_state_noop_path",
1275 help: "count of state update applications that no-oped due to shared state",
1276 )),
1277 update_state_empty_path: registry.register(metric!(
1278 name: "mz_persist_state_update_state_empty_path",
1279 help: "count of state update applications that found no new updates",
1280 )),
1281 update_state_fast_path: registry.register(metric!(
1282 name: "mz_persist_state_update_state_fast_path",
1283 help: "count of state update applications that hit the fast path",
1284 )),
1285 update_state_slow_path: registry.register(metric!(
1286 name: "mz_persist_state_update_state_slow_path",
1287 help: "count of state update applications that hit the slow path",
1288 )),
1289 finalized_rollup_assigned: registry.register(metric!(
1290 name: "mz_persist_state_finalized_rollup_assigned",
1291 help: "count of rollups assigned on finalized shards, normally two or three per shard (steady growth means a rollup loop)",
1292 )),
1293 rollup_at_seqno_migration: registry.register(metric!(
1294 name: "mz_persist_state_rollup_at_seqno_migration",
1295 help: "count of fetch_rollup_at_seqno calls that only worked because of the migration",
1296 )),
1297 fetch_recent_live_diffs_fast_path: registry.register(metric!(
1298 name: "mz_persist_state_fetch_recent_live_diffs_fast_path",
1299 help: "count of fetch_recent_live_diffs that hit the fast path",
1300 )),
1301 fetch_recent_live_diffs_slow_path: registry.register(metric!(
1302 name: "mz_persist_state_fetch_recent_live_diffs_slow_path",
1303 help: "count of fetch_recent_live_diffs that hit the slow path",
1304 )),
1305 writer_added: registry.register(metric!(
1306 name: "mz_persist_state_writer_added",
1307 help: "count of writers added to the state",
1308 )),
1309 writer_removed: registry.register(metric!(
1310 name: "mz_persist_state_writer_removed",
1311 help: "count of writers removed from the state",
1312 )),
1313 force_apply_hostname: registry.register(metric!(
1314 name: "mz_persist_state_force_applied_hostname",
1315 help: "count of when hostname diffs needed to be force applied",
1316 )),
1317 rollup_write_success: registry.register(metric!(
1318 name: "mz_persist_state_rollup_write_success",
1319 help: "count of rollups written successful (may not be linked in to state)",
1320 )),
1321 rollup_write_noop_latest: rollup_write_noop.with_label_values(&["latest"]),
1322 rollup_write_noop_truncated: rollup_write_noop.with_label_values(&["truncated"]),
1323 hollow_run_missing_on_delete: registry.register(metric!(
1324 name: "mz_persist_state_hollow_run_missing_on_delete",
1325 help: "count of hollow run blobs found already missing while deleting the parts they reference",
1326 )),
1327 }
1328 }
1329}
1330
1331#[derive(Debug)]
1332pub struct ShardsMetrics {
1333 encoded_rollup_size: mz_ore::metrics::UIntGaugeVec,
1345 encoded_diff_size: mz_ore::metrics::IntCounterVec,
1346 hollow_batch_count: mz_ore::metrics::UIntGaugeVec,
1347 spine_batch_count: mz_ore::metrics::UIntGaugeVec,
1348 batch_part_count: mz_ore::metrics::UIntGaugeVec,
1349 batch_part_version_count: mz_ore::metrics::UIntGaugeVec,
1350 update_count: mz_ore::metrics::UIntGaugeVec,
1351 rollup_count: mz_ore::metrics::UIntGaugeVec,
1352 largest_batch_size: mz_ore::metrics::UIntGaugeVec,
1353 seqnos_held: mz_ore::metrics::UIntGaugeVec,
1354 seqnos_since_last_rollup: mz_ore::metrics::UIntGaugeVec,
1355 gc_seqno_held_parts: mz_ore::metrics::UIntGaugeVec,
1356 gc_live_diffs: mz_ore::metrics::UIntGaugeVec,
1357 gc_finished: mz_ore::metrics::IntCounterVec,
1358 compaction_applied: mz_ore::metrics::IntCounterVec,
1359 cmd_succeeded: mz_ore::metrics::IntCounterVec,
1360 usage_current_state_batches_bytes: mz_ore::metrics::UIntGaugeVec,
1361 usage_current_state_rollups_bytes: mz_ore::metrics::UIntGaugeVec,
1362 usage_referenced_not_current_state_bytes: mz_ore::metrics::UIntGaugeVec,
1363 usage_not_leaked_not_referenced_bytes: mz_ore::metrics::UIntGaugeVec,
1364 usage_leaked_bytes: mz_ore::metrics::UIntGaugeVec,
1365 blob_gets: mz_ore::metrics::IntCounterVec,
1366 blob_sets: mz_ore::metrics::IntCounterVec,
1367 unconsolidated_snapshot: mz_ore::metrics::IntCounterVec,
1368 inline_part_count: UIntGaugeVec,
1369 compact_batches: UIntGaugeVec,
1370 compacting_batches: UIntGaugeVec,
1371 noncompact_batches: UIntGaugeVec,
1372 process_blob_gets: IntCounter,
1373 process_blob_sets: IntCounter,
1374 process_encoded_diff_size: IntCounter,
1375 process_unconsolidated_snapshot: IntCounter,
1376 shards: Arc<Mutex<BTreeMap<ShardId, Weak<ShardMetrics>>>>,
1380}
1381
1382struct PerShardMetricsFilter {
1394 configs: Arc<ConfigSet>,
1395 mode: (String, ShardMetricsExport),
1397 invalid_mode: IntCounter,
1398 allow: (String, Option<Regex>),
1401 invalid_regex: IntCounter,
1402}
1403
1404impl PerShardMetricsFilter {
1405 fn filter(&mut self, families: &mut Vec<MetricFamily>) {
1406 if self.mode().per_shard() {
1407 return;
1408 }
1409 let allow = self.allow_regex();
1410 families.retain_mut(|f| {
1411 if !PER_SHARD_FAMILIES.iter().any(|p| p.name == f.name()) {
1412 return true;
1413 }
1414 let Some(allow) = allow else {
1415 return false;
1416 };
1417 f.mut_metric().retain(|m| {
1418 m.get_label()
1419 .iter()
1420 .any(|l| matches!(l.name(), "shard" | "name") && allow.is_match(l.value()))
1421 });
1422 !f.get_metric().is_empty()
1423 });
1424 }
1425
1426 fn allow_regex(&mut self) -> Option<&Regex> {
1433 let value = PER_SHARD_METRICS_ENABLE_REGEX.get(&self.configs);
1434 if value != self.allow.0 {
1435 let compiled = if value.is_empty() {
1436 None
1437 } else {
1438 Regex::new(&value)
1439 .inspect_err(|err| {
1440 warn!(
1441 "invalid {}, keeping no per-shard series: {err}",
1442 PER_SHARD_METRICS_ENABLE_REGEX.name()
1443 )
1444 })
1445 .ok()
1446 };
1447 self.allow = (value, compiled);
1448 }
1449 if !self.allow.0.is_empty() && self.allow.1.is_none() {
1450 self.invalid_regex.inc();
1451 }
1452 self.allow.1.as_ref()
1453 }
1454
1455 fn mode(&mut self) -> ShardMetricsExport {
1460 let value = SHARD_METRICS.get(&self.configs);
1461 if value != self.mode.0 {
1462 let parsed = ShardMetricsExport::parse(&value).unwrap_or_else(|| {
1463 let default = ShardMetricsExport::default();
1464 warn!(
1465 "unrecognized {}: '{value}', exporting '{}'",
1466 SHARD_METRICS.name(),
1467 default.as_str()
1468 );
1469 default
1470 });
1471 self.mode = (value, parsed);
1472 }
1473 if self.mode.1.as_str() != self.mode.0 {
1474 self.invalid_mode.inc();
1475 }
1476 self.mode.1
1477 }
1478}
1479
1480impl ShardsMetrics {
1481 fn new(registry: &MetricsRegistry, configs: Arc<ConfigSet>) -> Self {
1482 let shards = Arc::new(Mutex::new(BTreeMap::new()));
1483 registry.register_collector(ShardsAggregateMetrics::new(Arc::clone(&shards), configs));
1484 ShardsMetrics {
1485 encoded_rollup_size: registry.register(metric!(
1486 name: "mz_persist_shard_rollup_size_bytes",
1487 help: "total encoded rollup size by shard",
1488 var_labels: ["shard", "name"],
1489 )),
1490 encoded_diff_size: registry.register(metric!(
1491 name: "mz_persist_shard_diff_size_bytes",
1492 help: "total encoded diff size by shard",
1493 var_labels: ["shard", "name"],
1494 )),
1495 hollow_batch_count: registry.register(metric!(
1496 name: "mz_persist_shard_hollow_batch_count",
1497 help: "count of hollow batches by shard",
1498 var_labels: ["shard", "name"],
1499 )),
1500 spine_batch_count: registry.register(metric!(
1501 name: "mz_persist_shard_spine_batch_count",
1502 help: "count of spine batches by shard",
1503 var_labels: ["shard", "name"],
1504 )),
1505 batch_part_count: registry.register(metric!(
1506 name: "mz_persist_shard_batch_part_count",
1507 help: "count of batch parts by shard",
1508 var_labels: ["shard", "name"],
1509 )),
1510 batch_part_version_count: registry.register(metric!(
1511 name: "mz_persist_shard_batch_part_version_count",
1512 help: "count of batch parts by shard and version",
1513 var_labels: ["shard", "name", "version"],
1514 )),
1515 update_count: registry.register(metric!(
1516 name: "mz_persist_shard_update_count",
1517 help: "count of updates by shard",
1518 var_labels: ["shard", "name"],
1519 )),
1520 rollup_count: registry.register(metric!(
1521 name: "mz_persist_shard_rollup_count",
1522 help: "count of rollups by shard",
1523 var_labels: ["shard", "name"],
1524 )),
1525 largest_batch_size: registry.register(metric!(
1526 name: "mz_persist_shard_largest_batch_size",
1527 help: "largest encoded batch size by shard",
1528 var_labels: ["shard", "name"],
1529 )),
1530 seqnos_held: registry.register(metric!(
1531 name: "mz_persist_shard_seqnos_held",
1532 help: "maximum count of gc-ineligible states by shard",
1533 var_labels: ["shard", "name"],
1534 )),
1535 seqnos_since_last_rollup: registry.register(metric!(
1536 name: "mz_persist_shard_seqnos_since_last_rollup",
1537 help: "count of seqnos since last rollup",
1538 var_labels: ["shard", "name"],
1539 )),
1540 gc_seqno_held_parts: registry.register(metric!(
1541 name: "mz_persist_shard_gc_seqno_held_parts",
1542 help: "count of parts referenced by some live state but not the current state (ie. parts kept only to satisfy seqno holds) at GC time",
1543 var_labels: ["shard", "name"],
1544 )),
1545 gc_live_diffs: registry.register(metric!(
1546 name: "mz_persist_shard_gc_live_diffs",
1547 help: "the number of diffs (or, alternatively, the number of seqnos) present in consensus state at GC time",
1548 var_labels: ["shard", "name"],
1549 )),
1550 gc_finished: registry.register(metric!(
1551 name: "mz_persist_shard_gc_finished",
1552 help: "count of garbage collections finished by shard",
1553 var_labels: ["shard", "name"],
1554 )),
1555 compaction_applied: registry.register(metric!(
1556 name: "mz_persist_shard_compaction_applied",
1557 help: "count of compactions applied to state by shard",
1558 var_labels: ["shard", "name"],
1559 )),
1560 cmd_succeeded: registry.register(metric!(
1561 name: "mz_persist_shard_cmd_succeeded",
1562 help: "count of commands succeeded by shard",
1563 var_labels: ["shard", "name"],
1564 )),
1565 usage_current_state_batches_bytes: registry.register(metric!(
1566 name: "mz_persist_shard_usage_current_state_batches_bytes",
1567 help: "data in batches/parts referenced by current version of state",
1568 var_labels: ["shard", "name"],
1569 )),
1570 usage_current_state_rollups_bytes: registry.register(metric!(
1571 name: "mz_persist_shard_usage_current_state_rollups_bytes",
1572 help: "data in rollups referenced by current version of state",
1573 var_labels: ["shard", "name"],
1574 )),
1575 usage_referenced_not_current_state_bytes: registry.register(metric!(
1576 name: "mz_persist_shard_usage_referenced_not_current_state_bytes",
1577 help: "data referenced only by a previous version of state",
1578 var_labels: ["shard", "name"],
1579 )),
1580 usage_not_leaked_not_referenced_bytes: registry.register(metric!(
1581 name: "mz_persist_shard_usage_not_leaked_not_referenced_bytes",
1582 help: "data written by an active writer but not referenced by any version of state",
1583 var_labels: ["shard", "name"],
1584 )),
1585 usage_leaked_bytes: registry.register(metric!(
1586 name: "mz_persist_shard_usage_leaked_bytes",
1587 help: "data reclaimable by a leaked blob detector",
1588 var_labels: ["shard", "name"],
1589 )),
1590 blob_gets: registry.register(metric!(
1591 name: "mz_persist_shard_blob_gets",
1592 help: "number of Blob::get calls for this shard",
1593 var_labels: ["shard", "name"],
1594 )),
1595 blob_sets: registry.register(metric!(
1596 name: "mz_persist_shard_blob_sets",
1597 help: "number of Blob::set calls for this shard",
1598 var_labels: ["shard", "name"],
1599 )),
1600 unconsolidated_snapshot: registry.register(metric!(
1601 name: "mz_persist_shard_unconsolidated_snapshot",
1602 help: "in snapshot_and_read, the number of times consolidating the raw data wasn't enough to produce consolidated output",
1603 var_labels: ["shard", "name"],
1604 )),
1605 inline_part_count: registry.register(metric!(
1606 name: "mz_persist_shard_inline_part_count",
1607 help: "count of parts inline in shard metadata",
1608 var_labels: ["shard", "name"],
1609 )),
1610 compact_batches: registry.register(metric!(
1611 name: "mz_persist_shard_compact_batches",
1612 help: "number of fully compact batches in the shard",
1613 var_labels: ["shard", "name"],
1614 )),
1615 compacting_batches: registry.register(metric!(
1616 name: "mz_persist_shard_compacting_batches",
1617 help: "number of batches in the shard with compactions in progress",
1618 var_labels: ["shard", "name"],
1619 )),
1620 noncompact_batches: registry.register(metric!(
1621 name: "mz_persist_shard_noncompact_batches",
1622 help: "number of batches in the shard that aren't compact and have no ongoing compaction",
1623 var_labels: ["shard", "name"],
1624 )),
1625 process_blob_gets: registry.register(metric!(
1626 name: "mz_persist_blob_gets",
1627 help: "number of Blob::get calls for batch parts, over all shards",
1628 )),
1629 process_blob_sets: registry.register(metric!(
1630 name: "mz_persist_blob_sets",
1631 help: "number of Blob::set calls for batch parts, over all shards",
1632 )),
1633 process_encoded_diff_size: registry.register(metric!(
1634 name: "mz_persist_diff_size_bytes",
1635 help: "total encoded diff size, over all shards",
1636 )),
1637 process_unconsolidated_snapshot: registry.register(metric!(
1638 name: "mz_persist_unconsolidated_snapshot",
1639 help: "in snapshot_and_read, the number of times consolidating the raw data wasn't enough to produce consolidated output, over all shards",
1640 )),
1641 shards,
1642 }
1643 }
1644
1645 pub fn shard(&self, shard_id: &ShardId, name: &str) -> Arc<ShardMetrics> {
1646 let mut shards = self.shards.lock().expect("mutex poisoned");
1647 if let Some(shard) = shards.get(shard_id) {
1648 if let Some(shard) = shard.upgrade() {
1649 return Arc::clone(&shard);
1650 } else {
1651 assert!(shards.remove(shard_id).is_some());
1652 }
1653 }
1654 let shard = Arc::new(ShardMetrics::new(shard_id, name, self));
1655 assert!(
1656 shards
1657 .insert(shard_id.clone(), Arc::downgrade(&shard))
1658 .is_none()
1659 );
1660 shard
1661 }
1662
1663 fn live_shards(
1668 shards: &Arc<Mutex<BTreeMap<ShardId, Weak<ShardMetrics>>>>,
1669 ) -> Vec<Arc<ShardMetrics>> {
1670 let mut shards = shards.lock().expect("mutex poisoned");
1671 let mut live = Vec::with_capacity(shards.len());
1672 shards.retain(|_, metrics| match metrics.upgrade() {
1673 Some(metrics) => {
1674 live.push(metrics);
1675 true
1676 }
1677 None => false,
1678 });
1679 live
1680 }
1681}
1682
1683struct PerShardFamily {
1686 name: &'static str,
1687 aggregate: ShardAggregate,
1688}
1689
1690enum ShardAggregate {
1691 Gauge(ShardGauge),
1693 VersionSum,
1695 Counter {
1702 #[allow(dead_code)]
1705 total: &'static str,
1706 },
1707}
1708
1709struct ShardGauge {
1710 help: &'static str,
1713 top_k: usize,
1715 sum: bool,
1717 get: fn(&ShardMetrics) -> u64,
1718}
1719
1720const SHARD_TOP_K: usize = 10;
1722
1723const PER_SHARD_FAMILIES: &[PerShardFamily] = &[
1726 PerShardFamily {
1727 name: "mz_persist_shard_rollup_size_bytes",
1728 aggregate: ShardAggregate::Gauge(ShardGauge {
1729 help: "total encoded rollup size by shard",
1730 top_k: SHARD_TOP_K,
1731 sum: true,
1732 get: |m| m.latest_rollup_size.get(),
1733 }),
1734 },
1735 PerShardFamily {
1736 name: "mz_persist_shard_diff_size_bytes",
1737 aggregate: ShardAggregate::Counter {
1738 total: "mz_persist_diff_size_bytes",
1739 },
1740 },
1741 PerShardFamily {
1742 name: "mz_persist_shard_hollow_batch_count",
1743 aggregate: ShardAggregate::Gauge(ShardGauge {
1744 help: "count of hollow batches by shard",
1745 top_k: SHARD_TOP_K,
1746 sum: true,
1747 get: |m| m.hollow_batch_count.get(),
1748 }),
1749 },
1750 PerShardFamily {
1751 name: "mz_persist_shard_spine_batch_count",
1752 aggregate: ShardAggregate::Gauge(ShardGauge {
1753 help: "count of spine batches by shard",
1754 top_k: SHARD_TOP_K,
1755 sum: true,
1756 get: |m| m.spine_batch_count.get(),
1757 }),
1758 },
1759 PerShardFamily {
1760 name: "mz_persist_shard_batch_part_count",
1761 aggregate: ShardAggregate::Gauge(ShardGauge {
1762 help: "count of batch parts by shard",
1763 top_k: SHARD_TOP_K,
1764 sum: true,
1765 get: |m| m.batch_part_count.get(),
1766 }),
1767 },
1768 PerShardFamily {
1769 name: "mz_persist_shard_batch_part_version_count",
1770 aggregate: ShardAggregate::VersionSum,
1771 },
1772 PerShardFamily {
1773 name: "mz_persist_shard_update_count",
1774 aggregate: ShardAggregate::Gauge(ShardGauge {
1775 help: "count of updates by shard",
1776 top_k: SHARD_TOP_K,
1777 sum: true,
1778 get: |m| m.update_count.get(),
1779 }),
1780 },
1781 PerShardFamily {
1782 name: "mz_persist_shard_rollup_count",
1783 aggregate: ShardAggregate::Gauge(ShardGauge {
1784 help: "count of rollups by shard",
1785 top_k: SHARD_TOP_K,
1786 sum: true,
1787 get: |m| m.rollup_count.get(),
1788 }),
1789 },
1790 PerShardFamily {
1791 name: "mz_persist_shard_largest_batch_size",
1792 aggregate: ShardAggregate::Gauge(ShardGauge {
1793 help: "largest encoded batch size by shard",
1794 top_k: SHARD_TOP_K,
1795 sum: false,
1796 get: |m| m.largest_batch_size.get(),
1797 }),
1798 },
1799 PerShardFamily {
1800 name: "mz_persist_shard_seqnos_held",
1801 aggregate: ShardAggregate::Gauge(ShardGauge {
1802 help: "maximum count of gc-ineligible states by shard",
1803 top_k: SHARD_TOP_K,
1804 sum: true,
1805 get: |m| m.seqnos_held.get(),
1806 }),
1807 },
1808 PerShardFamily {
1809 name: "mz_persist_shard_seqnos_since_last_rollup",
1810 aggregate: ShardAggregate::Gauge(ShardGauge {
1811 help: "count of seqnos since last rollup",
1812 top_k: SHARD_TOP_K,
1813 sum: true,
1814 get: |m| m.seqnos_since_last_rollup.get(),
1815 }),
1816 },
1817 PerShardFamily {
1818 name: "mz_persist_shard_gc_seqno_held_parts",
1819 aggregate: ShardAggregate::Gauge(ShardGauge {
1820 help: "count of parts referenced by some live state but not the current state (ie. parts kept only to satisfy seqno holds) at GC time",
1821 top_k: SHARD_TOP_K,
1822 sum: true,
1823 get: |m| m.gc_seqno_held_parts.get(),
1824 }),
1825 },
1826 PerShardFamily {
1827 name: "mz_persist_shard_gc_live_diffs",
1828 aggregate: ShardAggregate::Gauge(ShardGauge {
1829 help: "the number of diffs (or, alternatively, the number of seqnos) present in consensus state at GC time",
1830 top_k: SHARD_TOP_K,
1831 sum: true,
1832 get: |m| m.gc_live_diffs.get(),
1833 }),
1834 },
1835 PerShardFamily {
1836 name: "mz_persist_shard_gc_finished",
1837 aggregate: ShardAggregate::Counter {
1838 total: "mz_persist_gc_finished",
1839 },
1840 },
1841 PerShardFamily {
1842 name: "mz_persist_shard_compaction_applied",
1843 aggregate: ShardAggregate::Counter {
1844 total: "mz_persist_compaction_applied",
1845 },
1846 },
1847 PerShardFamily {
1848 name: "mz_persist_shard_cmd_succeeded",
1849 aggregate: ShardAggregate::Counter {
1850 total: "mz_persist_cmd_succeeded_count",
1851 },
1852 },
1853 PerShardFamily {
1854 name: "mz_persist_shard_usage_current_state_batches_bytes",
1855 aggregate: ShardAggregate::Gauge(ShardGauge {
1856 help: "data in batches/parts referenced by current version of state",
1857 top_k: SHARD_TOP_K,
1858 sum: true,
1859 get: |m| m.usage_current_state_batches_bytes.get(),
1860 }),
1861 },
1862 PerShardFamily {
1863 name: "mz_persist_shard_usage_current_state_rollups_bytes",
1864 aggregate: ShardAggregate::Gauge(ShardGauge {
1865 help: "data in rollups referenced by current version of state",
1866 top_k: SHARD_TOP_K,
1867 sum: true,
1868 get: |m| m.usage_current_state_rollups_bytes.get(),
1869 }),
1870 },
1871 PerShardFamily {
1872 name: "mz_persist_shard_usage_referenced_not_current_state_bytes",
1873 aggregate: ShardAggregate::Gauge(ShardGauge {
1874 help: "data referenced only by a previous version of state",
1875 top_k: SHARD_TOP_K,
1876 sum: true,
1877 get: |m| m.usage_referenced_not_current_state_bytes.get(),
1878 }),
1879 },
1880 PerShardFamily {
1881 name: "mz_persist_shard_usage_not_leaked_not_referenced_bytes",
1882 aggregate: ShardAggregate::Gauge(ShardGauge {
1883 help: "data written by an active writer but not referenced by any version of state",
1884 top_k: SHARD_TOP_K,
1885 sum: true,
1886 get: |m| m.usage_not_leaked_not_referenced_bytes.get(),
1887 }),
1888 },
1889 PerShardFamily {
1890 name: "mz_persist_shard_usage_leaked_bytes",
1891 aggregate: ShardAggregate::Gauge(ShardGauge {
1892 help: "data reclaimable by a leaked blob detector",
1893 top_k: SHARD_TOP_K,
1894 sum: true,
1895 get: |m| m.usage_leaked_bytes.get(),
1896 }),
1897 },
1898 PerShardFamily {
1899 name: "mz_persist_shard_blob_gets",
1900 aggregate: ShardAggregate::Counter {
1901 total: "mz_persist_blob_gets",
1902 },
1903 },
1904 PerShardFamily {
1905 name: "mz_persist_shard_blob_sets",
1906 aggregate: ShardAggregate::Counter {
1907 total: "mz_persist_blob_sets",
1908 },
1909 },
1910 PerShardFamily {
1911 name: "mz_persist_shard_unconsolidated_snapshot",
1912 aggregate: ShardAggregate::Counter {
1913 total: "mz_persist_unconsolidated_snapshot",
1914 },
1915 },
1916 PerShardFamily {
1917 name: "mz_persist_shard_inline_part_count",
1918 aggregate: ShardAggregate::Gauge(ShardGauge {
1919 help: "count of parts inline in shard metadata",
1920 top_k: SHARD_TOP_K,
1921 sum: true,
1922 get: |m| m.inline_part_count.get(),
1923 }),
1924 },
1925 PerShardFamily {
1926 name: "mz_persist_shard_compact_batches",
1927 aggregate: ShardAggregate::Gauge(ShardGauge {
1928 help: "number of fully compact batches in the shard",
1929 top_k: SHARD_TOP_K,
1930 sum: true,
1931 get: |m| m.compact_batches.get(),
1932 }),
1933 },
1934 PerShardFamily {
1935 name: "mz_persist_shard_compacting_batches",
1936 aggregate: ShardAggregate::Gauge(ShardGauge {
1937 help: "number of batches in the shard with compactions in progress",
1938 top_k: SHARD_TOP_K,
1939 sum: true,
1940 get: |m| m.compacting_batches.get(),
1941 }),
1942 },
1943 PerShardFamily {
1944 name: "mz_persist_shard_noncompact_batches",
1945 aggregate: ShardAggregate::Gauge(ShardGauge {
1946 help: "number of batches in the shard that aren't compact and have no ongoing compaction",
1947 top_k: SHARD_TOP_K,
1948 sum: true,
1949 get: |m| m.noncompact_batches.get(),
1950 }),
1951 },
1952];
1953
1954fn shard_gauges() -> impl Iterator<Item = (&'static str, &'static ShardGauge)> {
1956 PER_SHARD_FAMILIES
1957 .iter()
1958 .filter_map(|f| match &f.aggregate {
1959 ShardAggregate::Gauge(g) => Some((f.name, g)),
1960 _ => None,
1961 })
1962}
1963
1964const SHARD_INFO_NAME: &str = "mz_persist_shard_info";
1965const BATCH_PART_VERSION_COUNT_NAME: &str = "mz_persist_batch_part_version_count";
1966const BATCH_PART_VERSION_COUNT_HELP: &str = "count of batch parts by version, over all shards";
1967
1968#[derive(Debug)]
1971struct ShardKey(Arc<ShardMetrics>);
1972
1973impl AggregationKey for ShardKey {
1974 const LABEL_NAMES: &'static [&'static str] = &["shard", "name"];
1975
1976 fn label_values(&self) -> Vec<String> {
1977 vec![self.0.shard_id.to_string(), self.0.name.clone()]
1978 }
1979}
1980
1981#[derive(Debug)]
1989struct ShardsAggregateMetrics {
1990 shards: Arc<Mutex<BTreeMap<ShardId, Weak<ShardMetrics>>>>,
1991 configs: Arc<ConfigSet>,
1992 count: GenericGauge<AtomicI64>,
1993 stale_count: GenericGauge<AtomicI64>,
1994 gauges: AggregatedFamilies<ShardKey>,
1995 gauge_gets: Vec<fn(&ShardMetrics) -> u64>,
1998 batch_part_version_count: raw::UIntGaugeVec,
2001 shard_info: raw::UIntGaugeVec,
2003}
2004
2005impl ShardsAggregateMetrics {
2006 fn new(
2007 shards: Arc<Mutex<BTreeMap<ShardId, Weak<ShardMetrics>>>>,
2008 configs: Arc<ConfigSet>,
2009 ) -> Self {
2010 let gauges = shard_gauges()
2011 .map(|(name, g)| AggregatedFamily {
2012 name: name.to_string(),
2013 help: g.help.to_string(),
2014 sum: g.sum,
2015 top_k: Some(g.top_k),
2016 })
2017 .collect();
2018 ShardsAggregateMetrics {
2019 shards,
2020 configs,
2021 count: MakeCollector::make_collector(metric!(
2022 name: "mz_persist_shard_count",
2023 help: "count of all active shards on this process",
2024 )),
2025 stale_count: MakeCollector::make_collector(metric!(
2026 name: "mz_persist_stale_shard_count",
2027 help: "count of shards on this process whose persisted state version \
2028 is behind this process's build version; per-process, so summing \
2029 across processes counts (shard, process) pairs, not distinct shards",
2030 )),
2031 gauges: AggregatedFamilies::new(gauges),
2032 gauge_gets: shard_gauges().map(|(_, g)| g.get).collect(),
2033 batch_part_version_count: new_batch_part_version_count(),
2034 shard_info: new_shard_info(),
2035 }
2036 }
2037
2038 fn summaries(&self, live: Vec<Arc<ShardMetrics>>) -> Vec<MetricFamily> {
2040 let mut versions = BTreeMap::<String, u64>::new();
2041 let mut values = Vec::new();
2042 let mut snapshot = self.gauges.snapshot();
2043 for m in live {
2044 values.clear();
2045 values.extend(self.gauge_gets.iter().map(|get| get(&m)));
2046 let version_map = m
2047 .batch_part_version_map
2048 .lock()
2049 .expect("mutex should not be poisoned");
2050 for (version, metrics) in version_map.iter() {
2051 let n = metrics.batch_part_version_count.get();
2052 if n == 0 {
2053 continue;
2054 }
2055 match versions.get_mut(version) {
2056 Some(total) => *total += n,
2057 None => {
2058 versions.insert(version.clone(), n);
2059 }
2060 }
2061 }
2062 drop(version_map);
2063 snapshot.push(ShardKey(m), &values);
2064 }
2065
2066 let mut families = snapshot.finish();
2067 let batch_part_version_count = new_batch_part_version_count();
2068 for (version, n) in versions {
2069 batch_part_version_count
2070 .with_label_values(&[version.as_str()])
2071 .set(n);
2072 }
2073 families.extend(batch_part_version_count.collect());
2074 families
2075 }
2076}
2077
2078fn new_shard_info() -> raw::UIntGaugeVec {
2081 raw::UIntGaugeVec::new(
2082 PrometheusOpts::new(SHARD_INFO_NAME, "1 for each active shard on this process"),
2083 ShardKey::LABEL_NAMES,
2084 )
2085 .expect("valid gauge vec")
2086}
2087
2088fn new_batch_part_version_count() -> raw::UIntGaugeVec {
2089 raw::UIntGaugeVec::new(
2090 PrometheusOpts::new(BATCH_PART_VERSION_COUNT_NAME, BATCH_PART_VERSION_COUNT_HELP),
2091 &["version"],
2092 )
2093 .expect("valid gauge vec")
2094}
2095
2096impl Collector for ShardsAggregateMetrics {
2097 fn desc(&self) -> Vec<&Desc> {
2098 let mut descs = self.count.desc();
2099 descs.extend(self.stale_count.desc());
2100 descs.extend(self.gauges.descs());
2101 descs.extend(self.batch_part_version_count.desc());
2102 descs.extend(self.shard_info.desc());
2103 descs
2104 }
2105
2106 fn collect(&self) -> Vec<MetricFamily> {
2107 let live = ShardsMetrics::live_shards(&self.shards);
2108 let mut count = 0;
2109 let mut stale_count = 0;
2110 for m in &live {
2111 count += 1;
2112 if m.stale.load(Ordering::Relaxed) {
2113 stale_count += 1;
2114 }
2115 }
2116 self.count.set(count);
2117 self.stale_count.set(stale_count);
2118
2119 let mut families = Vec::new();
2120 if SHARD_INFO_METRIC.get(&self.configs) {
2121 let shard_info = new_shard_info();
2122 for m in &live {
2123 shard_info
2124 .with_label_values(&[m.shard_id.to_string(), m.name.clone()])
2125 .set(1);
2126 }
2127 families.extend(shard_info.collect());
2128 }
2129 if ShardMetricsExport::get(&self.configs).summary() {
2130 families.extend(self.summaries(live));
2131 }
2132 families.extend(self.count.collect());
2133 families.extend(self.stale_count.collect());
2134 families
2135 }
2136}
2137
2138#[derive(Debug)]
2139pub struct ShardMetrics {
2140 pub shard_id: ShardId,
2141 pub name: String,
2142 pub largest_batch_size: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2143 pub latest_rollup_size: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2144 pub encoded_diff_size: ShardCounter,
2145 pub hollow_batch_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2146 pub spine_batch_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2147 pub batch_part_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2148 batch_part_version_count: mz_ore::metrics::UIntGaugeVec,
2149 batch_part_version_map: Mutex<BTreeMap<String, BatchPartVersionMetrics>>,
2150 pub update_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2151 pub rollup_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2152 pub seqnos_held: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2153 pub seqnos_since_last_rollup: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2154 pub gc_seqno_held_parts: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2155 pub gc_live_diffs: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2156 pub usage_current_state_batches_bytes: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2157 pub usage_current_state_rollups_bytes: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2158 pub usage_referenced_not_current_state_bytes: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2159 pub usage_not_leaked_not_referenced_bytes: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2160 pub usage_leaked_bytes: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2161 pub gc_finished: DeleteOnDropCounter<AtomicU64, Vec<String>>,
2162 pub compaction_applied: DeleteOnDropCounter<AtomicU64, Vec<String>>,
2163 pub cmd_succeeded: DeleteOnDropCounter<AtomicU64, Vec<String>>,
2164 pub blob_gets: ShardCounter,
2165 pub blob_sets: ShardCounter,
2166 pub unconsolidated_snapshot: ShardCounter,
2167 pub inline_part_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2168 pub compact_batches: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2169 pub compacting_batches: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2170 pub noncompact_batches: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2171 pub stale: AtomicBool,
2175}
2176
2177impl ShardMetrics {
2178 pub fn new(shard_id: &ShardId, name: &str, shards_metrics: &ShardsMetrics) -> Self {
2179 let shard = shard_id.to_string();
2180 ShardMetrics {
2181 shard_id: *shard_id,
2182 name: name.to_string(),
2183 latest_rollup_size: shards_metrics
2184 .encoded_rollup_size
2185 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2186 encoded_diff_size: ShardCounter {
2187 shard: shards_metrics
2188 .encoded_diff_size
2189 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2190 process: shards_metrics.process_encoded_diff_size.clone(),
2191 },
2192 hollow_batch_count: shards_metrics
2193 .hollow_batch_count
2194 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2195 spine_batch_count: shards_metrics
2196 .spine_batch_count
2197 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2198 batch_part_count: shards_metrics
2199 .batch_part_count
2200 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2201 batch_part_version_count: shards_metrics.batch_part_version_count.clone(),
2202 batch_part_version_map: Mutex::new(BTreeMap::new()),
2203 update_count: shards_metrics
2204 .update_count
2205 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2206 rollup_count: shards_metrics
2207 .rollup_count
2208 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2209 largest_batch_size: shards_metrics
2210 .largest_batch_size
2211 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2212 seqnos_held: shards_metrics
2213 .seqnos_held
2214 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2215 seqnos_since_last_rollup: shards_metrics
2216 .seqnos_since_last_rollup
2217 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2218 gc_seqno_held_parts: shards_metrics
2219 .gc_seqno_held_parts
2220 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2221 gc_live_diffs: shards_metrics
2222 .gc_live_diffs
2223 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2224 gc_finished: shards_metrics
2225 .gc_finished
2226 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2227 compaction_applied: shards_metrics
2228 .compaction_applied
2229 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2230 cmd_succeeded: shards_metrics
2231 .cmd_succeeded
2232 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2233 usage_current_state_batches_bytes: shards_metrics
2234 .usage_current_state_batches_bytes
2235 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2236 usage_current_state_rollups_bytes: shards_metrics
2237 .usage_current_state_rollups_bytes
2238 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2239 usage_referenced_not_current_state_bytes: shards_metrics
2240 .usage_referenced_not_current_state_bytes
2241 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2242 usage_not_leaked_not_referenced_bytes: shards_metrics
2243 .usage_not_leaked_not_referenced_bytes
2244 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2245 usage_leaked_bytes: shards_metrics
2246 .usage_leaked_bytes
2247 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2248 blob_gets: ShardCounter {
2249 shard: shards_metrics
2250 .blob_gets
2251 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2252 process: shards_metrics.process_blob_gets.clone(),
2253 },
2254 blob_sets: ShardCounter {
2255 shard: shards_metrics
2256 .blob_sets
2257 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2258 process: shards_metrics.process_blob_sets.clone(),
2259 },
2260 unconsolidated_snapshot: ShardCounter {
2261 shard: shards_metrics
2262 .unconsolidated_snapshot
2263 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2264 process: shards_metrics.process_unconsolidated_snapshot.clone(),
2265 },
2266 inline_part_count: shards_metrics
2267 .inline_part_count
2268 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2269 compact_batches: shards_metrics
2270 .compact_batches
2271 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2272 compacting_batches: shards_metrics
2273 .compacting_batches
2274 .get_delete_on_drop_metric(vec![shard.clone(), name.to_string()]),
2275 noncompact_batches: shards_metrics
2276 .noncompact_batches
2277 .get_delete_on_drop_metric(vec![shard, name.to_string()]),
2278 stale: AtomicBool::new(false),
2279 }
2280 }
2281
2282 pub(crate) fn set_batch_part_versions<'a>(
2283 &self,
2284 batch_parts_by_version: impl Iterator<Item = &'a str>,
2285 ) {
2286 let mut map = self
2287 .batch_part_version_map
2288 .lock()
2289 .expect("mutex should not be poisoned");
2290 for x in map.values() {
2297 x.batch_part_version_count.set(0);
2298 }
2299
2300 for key in batch_parts_by_version {
2303 if !map.contains_key(key) {
2304 map.insert(
2305 key.to_owned(),
2306 BatchPartVersionMetrics {
2307 batch_part_version_count: self
2308 .batch_part_version_count
2309 .get_delete_on_drop_metric(vec![
2310 self.shard_id.to_string(),
2311 self.name.clone(),
2312 key.to_owned(),
2313 ]),
2314 },
2315 );
2316 }
2317 let value = map.get(key).expect("inserted above");
2318 value.batch_part_version_count.inc();
2319 }
2320 }
2321}
2322
2323#[derive(Debug)]
2326pub struct ShardCounter {
2327 shard: DeleteOnDropCounter<AtomicU64, Vec<String>>,
2328 process: IntCounter,
2329}
2330
2331impl ShardCounter {
2332 pub fn inc(&self) {
2333 self.inc_by(1);
2334 }
2335
2336 pub fn inc_by(&self, v: u64) {
2337 self.shard.inc_by(v);
2338 self.process.inc_by(v);
2339 }
2340}
2341
2342#[derive(Debug)]
2343pub struct BatchPartVersionMetrics {
2344 pub batch_part_version_count: DeleteOnDropGauge<AtomicU64, Vec<String>>,
2345}
2346
2347#[derive(Debug)]
2349pub struct UsageAuditMetrics {
2350 pub blob_batch_part_bytes: UIntGauge,
2352 pub blob_batch_part_count: UIntGauge,
2354 pub blob_rollup_bytes: UIntGauge,
2356 pub blob_rollup_count: UIntGauge,
2358 pub blob_bytes: UIntGauge,
2360 pub blob_count: UIntGauge,
2362 pub step_blob_metadata: Counter,
2364 pub step_state: Counter,
2366 pub step_math: Counter,
2368}
2369
2370impl UsageAuditMetrics {
2371 fn new(registry: &MetricsRegistry) -> Self {
2372 let step_timings: CounterVec = registry.register(metric!(
2373 name: "mz_persist_audit_step_seconds",
2374 help: "time spent on individual steps of audit",
2375 var_labels: ["step"],
2376 ));
2377 UsageAuditMetrics {
2378 blob_batch_part_bytes: registry.register(metric!(
2379 name: "mz_persist_audit_blob_batch_part_bytes",
2380 help: "total size of batch parts in blob",
2381 )),
2382 blob_batch_part_count: registry.register(metric!(
2383 name: "mz_persist_audit_blob_batch_part_count",
2384 help: "count of batch parts in blob",
2385 )),
2386 blob_rollup_bytes: registry.register(metric!(
2387 name: "mz_persist_audit_blob_rollup_bytes",
2388 help: "total size of state rollups stored in blob",
2389 )),
2390 blob_rollup_count: registry.register(metric!(
2391 name: "mz_persist_audit_blob_rollup_count",
2392 help: "count of all state rollups in blob",
2393 )),
2394 blob_bytes: registry.register(metric!(
2395 name: "mz_persist_audit_blob_bytes",
2396 help: "total size of blob",
2397 )),
2398 blob_count: registry.register(metric!(
2399 name: "mz_persist_audit_blob_count",
2400 help: "count of all blobs",
2401 )),
2402 step_blob_metadata: step_timings.with_label_values(&["blob_metadata"]),
2403 step_state: step_timings.with_label_values(&["state"]),
2404 step_math: step_timings.with_label_values(&["math"]),
2405 }
2406 }
2407}
2408
2409#[derive(Debug)]
2412pub enum UpdateDelta {
2413 Negative(u64),
2415 NonNegative(u64),
2417}
2418
2419impl UpdateDelta {
2420 pub fn new(new: usize, old: usize) -> Self {
2423 if new < old {
2424 UpdateDelta::Negative(CastFrom::cast_from(old - new))
2425 } else {
2426 UpdateDelta::NonNegative(CastFrom::cast_from(new - old))
2427 }
2428 }
2429}
2430
2431#[derive(Debug, Clone)]
2434pub struct SinkMetrics {
2435 correction_insertions_total: IntCounter,
2437 correction_deletions_total: IntCounter,
2439 correction_capacity_increases_total: IntCounter,
2441 correction_capacity_decreases_total: IntCounter,
2443 correction_max_per_sink_worker_len_updates: raw::UIntGaugeVec,
2445 correction_max_per_sink_worker_capacity_updates: raw::UIntGaugeVec,
2447}
2448
2449impl SinkMetrics {
2450 fn new(registry: &MetricsRegistry) -> Self {
2451 SinkMetrics {
2452 correction_insertions_total: registry.register(metric!(
2453 name: "mz_persist_sink_correction_insertions_total",
2454 help: "The cumulative insertions observed on the correction buffer across workers and persist sinks.",
2455 )),
2456 correction_deletions_total: registry.register(metric!(
2457 name: "mz_persist_sink_correction_deletions_total",
2458 help: "The cumulative deletions observed on the correction buffer across workers and persist sinks.",
2459 )),
2460 correction_capacity_increases_total: registry.register(metric!(
2461 name: "mz_persist_sink_correction_capacity_increases_total",
2462 help: "The cumulative capacity increases observed on the correction buffer across workers and persist sinks.",
2463 )),
2464 correction_capacity_decreases_total: registry.register(metric!(
2465 name: "mz_persist_sink_correction_capacity_decreases_total",
2466 help: "The cumulative capacity decreases observed on the correction buffer across workers and persist sinks.",
2467 )),
2468 correction_max_per_sink_worker_len_updates: registry.register(metric!(
2469 name: "mz_persist_sink_correction_max_per_sink_worker_len_updates",
2470 help: "The maximum length observed for the correction buffer of any single persist sink per worker.",
2471 var_labels: ["worker_id"],
2472 )),
2473 correction_max_per_sink_worker_capacity_updates: registry.register(metric!(
2474 name: "mz_persist_sink_correction_max_per_sink_worker_capacity_updates",
2475 help: "The maximum capacity observed for the correction buffer of any single persist sink per worker.",
2476 var_labels: ["worker_id"],
2477 )),
2478 }
2479 }
2480
2481 pub fn for_worker(&self, worker_id: usize) -> SinkWorkerMetrics {
2486 let worker = worker_id.to_string();
2487 let correction_max_per_sink_worker_len_updates = self
2488 .correction_max_per_sink_worker_len_updates
2489 .with_label_values(&[&worker]);
2490 let correction_max_per_sink_worker_capacity_updates = self
2491 .correction_max_per_sink_worker_capacity_updates
2492 .with_label_values(&[&worker]);
2493 SinkWorkerMetrics {
2494 correction_max_per_sink_worker_len_updates,
2495 correction_max_per_sink_worker_capacity_updates,
2496 }
2497 }
2498
2499 pub fn report_correction_update_deltas(
2505 &self,
2506 correction_len_delta: UpdateDelta,
2507 correction_cap_delta: UpdateDelta,
2508 ) {
2509 match correction_len_delta {
2511 UpdateDelta::NonNegative(delta) => {
2512 if delta > 0 {
2513 self.correction_insertions_total.inc_by(delta)
2514 }
2515 }
2516 UpdateDelta::Negative(delta) => self.correction_deletions_total.inc_by(delta),
2517 }
2518 match correction_cap_delta {
2520 UpdateDelta::NonNegative(delta) => {
2521 if delta > 0 {
2522 self.correction_capacity_increases_total.inc_by(delta)
2523 }
2524 }
2525 UpdateDelta::Negative(delta) => self.correction_capacity_decreases_total.inc_by(delta),
2526 }
2527 }
2528}
2529
2530#[derive(Clone, Debug)]
2532pub struct SinkWorkerMetrics {
2533 correction_max_per_sink_worker_len_updates: UIntGauge,
2534 correction_max_per_sink_worker_capacity_updates: UIntGauge,
2535}
2536
2537impl SinkWorkerMetrics {
2538 pub fn report_correction_update_totals(&self, correction_len: usize, correction_cap: usize) {
2543 let correction_len = CastFrom::cast_from(correction_len);
2545 if correction_len > self.correction_max_per_sink_worker_len_updates.get() {
2546 self.correction_max_per_sink_worker_len_updates
2547 .set(correction_len);
2548 }
2549 let correction_cap = CastFrom::cast_from(correction_cap);
2550 if correction_cap > self.correction_max_per_sink_worker_capacity_updates.get() {
2551 self.correction_max_per_sink_worker_capacity_updates
2552 .set(correction_cap);
2553 }
2554 }
2555}
2556
2557#[derive(Debug)]
2562pub struct BackpressureMetrics {
2563 pub emitted_bytes: IntCounter,
2565 pub last_backpressured_bytes: UIntGauge,
2569 pub retired_bytes: IntCounter,
2571}
2572
2573impl BackpressureMetrics {
2574 fn new(registry: &MetricsRegistry) -> Self {
2575 BackpressureMetrics {
2576 emitted_bytes: registry.register(metric!(
2577 name: "mz_persist_backpressure_emitted_bytes",
2578 help: "bytes emitted by backpressure operators",
2579 )),
2580 last_backpressured_bytes: registry.register(metric!(
2581 name: "mz_persist_backpressure_last_backpressured_bytes",
2582 help: "sum over backpressure operators of the inflight bytes each last \
2583 stalled on; not comparable to retired bytes, but nonzero growth \
2584 indicates backpressure is happening",
2585 )),
2586 retired_bytes: registry.register(metric!(
2587 name: "mz_persist_backpressure_retired_bytes",
2588 help: "bytes retired by processing downstream of backpressure operators",
2589 )),
2590 }
2591 }
2592}
2593
2594#[derive(Debug)]
2596pub struct AlertsMetrics {
2597 pub(crate) blob_failures: IntCounter,
2598 pub(crate) consensus_failures: IntCounter,
2599}
2600
2601impl AlertsMetrics {
2602 fn new(registry: &MetricsRegistry) -> Self {
2603 AlertsMetrics {
2604 blob_failures: registry.register(metric!(
2605 name: "mz_persist_blob_failures",
2606 help: "count of all blob operation failures",
2607 const_labels: {"honeycomb" => "import"},
2608 )),
2609 consensus_failures: registry.register(metric!(
2610 name: "mz_persist_consensus_failures",
2611 help: "count of determinate consensus operation failures",
2612 const_labels: {"honeycomb" => "import"},
2613 )),
2614 }
2615 }
2616}
2617
2618#[derive(Debug)]
2620pub struct PubSubServerMetrics {
2621 pub(crate) active_connections: UIntGauge,
2622 pub(crate) broadcasted_diff_count: IntCounter,
2623 pub(crate) broadcasted_diff_bytes: IntCounter,
2624 pub(crate) broadcasted_diff_dropped_channel_full: IntCounter,
2625
2626 pub(crate) push_seconds: Counter,
2627 pub(crate) subscribe_seconds: Counter,
2628 pub(crate) unsubscribe_seconds: Counter,
2629 pub(crate) connection_cleanup_seconds: Counter,
2630
2631 pub(crate) push_call_count: IntCounter,
2632 pub(crate) subscribe_call_count: IntCounter,
2633 pub(crate) unsubscribe_call_count: IntCounter,
2634}
2635
2636impl PubSubServerMetrics {
2637 pub(crate) fn new(registry: &MetricsRegistry) -> Self {
2638 let op_timings: CounterVec = registry.register(metric!(
2639 name: "mz_persist_pubsub_server_operation_seconds",
2640 help: "time spent in pubsub server performing each operation",
2641 var_labels: ["op"],
2642 ));
2643 let call_count: IntCounterVec = registry.register(metric!(
2644 name: "mz_persist_pubsub_server_call_count",
2645 help: "count of each pubsub server message received",
2646 var_labels: ["call"],
2647 ));
2648
2649 Self {
2650 active_connections: registry.register(metric!(
2651 name: "mz_persist_pubsub_server_active_connections",
2652 help: "number of active connections to server",
2653 )),
2654 broadcasted_diff_count: registry.register(metric!(
2655 name: "mz_persist_pubsub_server_broadcasted_diff_count",
2656 help: "count of total broadcast diff messages sent",
2657 )),
2658 broadcasted_diff_bytes: registry.register(metric!(
2659 name: "mz_persist_pubsub_server_broadcasted_diff_bytes",
2660 help: "count of total broadcast diff bytes sent",
2661 )),
2662 broadcasted_diff_dropped_channel_full: registry.register(metric!(
2663 name: "mz_persist_pubsub_server_broadcasted_diff_dropped_channel_full",
2664 help: "count of diffs dropped due to full connection channel",
2665 )),
2666
2667 push_seconds: op_timings.with_label_values(&["push"]),
2668 subscribe_seconds: op_timings.with_label_values(&["subscribe"]),
2669 unsubscribe_seconds: op_timings.with_label_values(&["unsubscribe"]),
2670 connection_cleanup_seconds: op_timings.with_label_values(&["cleanup"]),
2671
2672 push_call_count: call_count.with_label_values(&["push"]),
2673 subscribe_call_count: call_count.with_label_values(&["subscribe"]),
2674 unsubscribe_call_count: call_count.with_label_values(&["unsubscribe"]),
2675 }
2676 }
2677}
2678
2679#[derive(Debug)]
2681pub struct PubSubClientMetrics {
2682 pub sender: PubSubClientSenderMetrics,
2683 pub receiver: PubSubClientReceiverMetrics,
2684 pub grpc_connection: PubSubGrpcClientConnectionMetrics,
2685}
2686
2687impl PubSubClientMetrics {
2688 fn new(registry: &MetricsRegistry) -> Self {
2689 PubSubClientMetrics {
2690 sender: PubSubClientSenderMetrics::new(registry),
2691 receiver: PubSubClientReceiverMetrics::new(registry),
2692 grpc_connection: PubSubGrpcClientConnectionMetrics::new(registry),
2693 }
2694 }
2695}
2696
2697#[derive(Debug)]
2698pub struct PubSubGrpcClientConnectionMetrics {
2699 pub(crate) connected: UIntGauge,
2700 pub(crate) connection_established_count: IntCounter,
2701 pub(crate) connect_call_attempt_count: IntCounter,
2702 pub(crate) broadcast_recv_lagged_count: IntCounter,
2703 pub(crate) grpc_error_count: IntCounter,
2704}
2705
2706impl PubSubGrpcClientConnectionMetrics {
2707 fn new(registry: &MetricsRegistry) -> Self {
2708 Self {
2709 connected: registry.register(metric!(
2710 name: "mz_persist_pubsub_client_grpc_connected",
2711 help: "whether the grpc client is currently connected",
2712 )),
2713 connection_established_count: registry.register(metric!(
2714 name: "mz_persist_pubsub_client_grpc_connection_established_count",
2715 help: "count of grpc connection establishments to pubsub server",
2716 )),
2717 connect_call_attempt_count: registry.register(metric!(
2718 name: "mz_persist_pubsub_client_grpc_connect_call_attempt_count",
2719 help: "count of connection call attempts (including retries) to pubsub server",
2720 )),
2721 broadcast_recv_lagged_count: registry.register(metric!(
2722 name: "mz_persist_pubsub_client_grpc_broadcast_recv_lagged_count",
2723 help: "times a message was missed by broadcast receiver due to lag",
2724 )),
2725 grpc_error_count: registry.register(metric!(
2726 name: "mz_persist_pubsub_client_grpc_error_count",
2727 help: "count of grpc errors received",
2728 )),
2729 }
2730 }
2731}
2732
2733#[derive(Clone, Debug)]
2734pub struct PubSubClientReceiverMetrics {
2735 pub(crate) push_received: IntCounter,
2736 pub(crate) unknown_message_received: IntCounter,
2737 pub(crate) approx_diff_latency_seconds: Histogram,
2738
2739 pub(crate) state_pushed_diff_fast_path: IntCounter,
2740 pub(crate) state_pushed_diff_slow_path_succeeded: IntCounter,
2741 pub(crate) state_pushed_diff_slow_path_failed: IntCounter,
2742
2743 pub(crate) diff_applied: IntCounter,
2744 pub(crate) diff_not_applied_stale: IntCounter,
2745 pub(crate) diff_not_applied_out_of_order: IntCounter,
2746}
2747
2748impl PubSubClientReceiverMetrics {
2749 fn new(registry: &MetricsRegistry) -> Self {
2750 let call_received: IntCounterVec = registry.register(metric!(
2751 name: "mz_persist_pubsub_client_call_received",
2752 help: "times a pubsub client call was received",
2753 var_labels: ["call"],
2754 ));
2755
2756 Self {
2757 push_received: call_received.with_label_values(&["push"]),
2758 unknown_message_received: call_received.with_label_values(&["unknown"]),
2759 approx_diff_latency_seconds: registry.register(metric!(
2760 name: "mz_persist_pubsub_client_approx_diff_apply_latency_seconds",
2761 help: "histogram of (approximate) latency between sending a diff and applying it",
2762 buckets: prometheus::exponential_buckets(0.001, 2.0, 13).expect("buckets"),
2763 )),
2764
2765 state_pushed_diff_fast_path: registry.register(metric!(
2766 name: "mz_persist_pubsub_client_receiver_state_push_diff_fast_path",
2767 help: "count fast-path state push_diff calls",
2768 )),
2769 state_pushed_diff_slow_path_succeeded: registry.register(metric!(
2770 name: "mz_persist_pubsub_client_receiver_state_push_diff_slow_path_succeeded",
2771 help: "count of successful slow-path state push_diff calls",
2772 )),
2773 state_pushed_diff_slow_path_failed: registry.register(metric!(
2774 name: "mz_persist_pubsub_client_receiver_state_push_diff_slow_path_failed",
2775 help: "count of unsuccessful slow-path state push_diff calls",
2776 )),
2777 diff_applied: registry.register(metric!(
2778 name: "mz_persist_pubsub_client_receiver_diff_applied",
2779 help: "number of diffs received via pubsub that applied",
2780 )),
2781 diff_not_applied_stale: registry.register(metric!(
2782 name: "mz_persist_pubsub_client_receiver_diff_not_applied_stale",
2783 help: "number of diffs received via pubsub that did not apply due to staleness",
2784 )),
2785 diff_not_applied_out_of_order: registry.register(metric!(
2786 name: "mz_persist_pubsub_client_receiver_diff_not_applied_out_of_order",
2787 help: "number of diffs received via pubsub that did not apply due to out-of-order delivery",
2788 )),
2789 }
2790 }
2791}
2792
2793#[derive(Debug)]
2794pub struct PubSubClientSenderMetrics {
2795 pub push: PubSubClientCallMetrics,
2796 pub subscribe: PubSubClientCallMetrics,
2797 pub unsubscribe: PubSubClientCallMetrics,
2798}
2799
2800#[derive(Debug)]
2801pub struct PubSubClientCallMetrics {
2802 pub(crate) succeeded: IntCounter,
2803 pub(crate) bytes_sent: IntCounter,
2804 pub(crate) failed: IntCounter,
2805}
2806
2807impl PubSubClientSenderMetrics {
2808 fn new(registry: &MetricsRegistry) -> Self {
2809 let call_bytes_sent: IntCounterVec = registry.register(metric!(
2810 name: "mz_persist_pubsub_client_call_bytes_sent",
2811 help: "number of bytes sent for a given pubsub client call",
2812 var_labels: ["call"],
2813 ));
2814 let call_succeeded: IntCounterVec = registry.register(metric!(
2815 name: "mz_persist_pubsub_client_call_succeeded",
2816 help: "times a pubsub client call succeeded",
2817 var_labels: ["call"],
2818 ));
2819 let call_failed: IntCounterVec = registry.register(metric!(
2820 name: "mz_persist_pubsub_client_call_failed",
2821 help: "times a pubsub client call failed",
2822 var_labels: ["call"],
2823 ));
2824
2825 Self {
2826 push: PubSubClientCallMetrics {
2827 succeeded: call_succeeded.with_label_values(&["push"]),
2828 failed: call_failed.with_label_values(&["push"]),
2829 bytes_sent: call_bytes_sent.with_label_values(&["push"]),
2830 },
2831 subscribe: PubSubClientCallMetrics {
2832 succeeded: call_succeeded.with_label_values(&["subscribe"]),
2833 failed: call_failed.with_label_values(&["subscribe"]),
2834 bytes_sent: call_bytes_sent.with_label_values(&["subscribe"]),
2835 },
2836 unsubscribe: PubSubClientCallMetrics {
2837 succeeded: call_succeeded.with_label_values(&["unsubscribe"]),
2838 failed: call_failed.with_label_values(&["unsubscribe"]),
2839 bytes_sent: call_bytes_sent.with_label_values(&["unsubscribe"]),
2840 },
2841 }
2842 }
2843}
2844
2845#[derive(Debug)]
2846pub struct LocksMetrics {
2847 pub(crate) applier_read_cacheable: LockMetrics,
2848 pub(crate) applier_read_noncacheable: LockMetrics,
2849 pub(crate) applier_write: LockMetrics,
2850 pub(crate) watch: LockMetrics,
2851}
2852
2853#[derive(Debug, Clone)]
2854pub struct LockMetrics {
2855 pub(crate) acquire_count: IntCounter,
2856 pub(crate) blocking_acquire_count: IntCounter,
2857 pub(crate) blocking_seconds: Counter,
2858}
2859
2860#[derive(Debug)]
2861pub struct WatchMetrics {
2862 pub(crate) wait_woken_via_watch: IntCounter,
2863 pub(crate) wait_woken_via_sleep: IntCounter,
2864 pub(crate) wait_resolved_via_watch: IntCounter,
2865 pub(crate) wait_resolved_via_sleep: IntCounter,
2866 pub(crate) notify_sent: IntCounter,
2867 pub(crate) notify_upper_sent: IntCounter,
2868 pub(crate) notify_noop: IntCounter,
2869 pub(crate) notify_recv: IntCounter,
2870 pub(crate) notify_lagged: IntCounter,
2871 pub(crate) notify_wait_started: IntCounter,
2872 pub(crate) notify_wait_finished: IntCounter,
2873}
2874
2875impl WatchMetrics {
2876 fn new(registry: &MetricsRegistry) -> Self {
2877 WatchMetrics {
2878 wait_woken_via_watch: registry.register(metric!(
2879 name: "mz_persist_wait_woken_via_watch",
2880 help: "count of wait-for-uppers wakes via watch notify",
2881 )),
2882 wait_woken_via_sleep: registry.register(metric!(
2883 name: "mz_persist_wait_woken_via_sleep",
2884 help: "count of wait-for-uppers wakes via sleep",
2885 )),
2886 wait_resolved_via_watch: registry.register(metric!(
2887 name: "mz_persist_wait_resolved_via_watch",
2888 help: "count of wait-for-uppers resolved via watch notify",
2889 )),
2890 wait_resolved_via_sleep: registry.register(metric!(
2891 name: "mz_persist_wait_resolved_via_sleep",
2892 help: "count of wait-for-uppers resolved via sleep",
2893 )),
2894 notify_sent: registry.register(metric!(
2895 name: "mz_persist_watch_notify_sent",
2896 help: "count of watch notifications sent to a non-empty broadcast channel",
2897 )),
2898 notify_upper_sent: registry.register(metric!(
2899 name: "mz_persist_watch_notify_upper_sent",
2900 help: "count of strict shard upper advances signaled to upper waiters",
2901 )),
2902 notify_noop: registry.register(metric!(
2903 name: "mz_persist_watch_notify_noop",
2904 help: "count of watch notifications sent to an broadcast channel",
2905 )),
2906 notify_recv: registry.register(metric!(
2907 name: "mz_persist_watch_notify_recv",
2908 help: "count of watch notifications received from the broadcast channel",
2909 )),
2910 notify_lagged: registry.register(metric!(
2911 name: "mz_persist_watch_notify_lagged",
2912 help: "count of lagged events in the watch notification broadcast channel",
2913 )),
2914 notify_wait_started: registry.register(metric!(
2915 name: "mz_persist_watch_notify_wait_started",
2916 help: "count of watch wait calls started",
2917 )),
2918 notify_wait_finished: registry.register(metric!(
2919 name: "mz_persist_watch_notify_wait_finished",
2920 help: "count of watch wait calls resolved",
2921 )),
2922 }
2923 }
2924}
2925
2926#[derive(Debug)]
2927pub struct PushdownMetrics {
2928 pub(crate) parts_filtered_count: IntCounter,
2929 pub(crate) parts_filtered_bytes: IntCounter,
2930 pub(crate) parts_fetched_count: IntCounter,
2931 pub(crate) parts_fetched_bytes: IntCounter,
2932 pub(crate) parts_audited_count: IntCounter,
2933 pub(crate) parts_audited_bytes: IntCounter,
2934 pub(crate) parts_inline_count: IntCounter,
2935 pub(crate) parts_inline_bytes: IntCounter,
2936 pub(crate) parts_faked_count: IntCounter,
2937 pub(crate) parts_faked_bytes: IntCounter,
2938 pub(crate) parts_stats_trimmed_count: IntCounter,
2939 pub(crate) parts_stats_trimmed_bytes: IntCounter,
2940 pub(crate) parts_projection_trimmed_bytes: IntCounter,
2941 pub part_stats: PartStatsMetrics,
2942}
2943
2944impl PushdownMetrics {
2945 fn new(registry: &MetricsRegistry) -> Self {
2946 PushdownMetrics {
2947 parts_filtered_count: registry.register(metric!(
2948 name: "mz_persist_pushdown_parts_filtered_count",
2949 help: "count of parts filtered by pushdown",
2950 )),
2951 parts_filtered_bytes: registry.register(metric!(
2952 name: "mz_persist_pushdown_parts_filtered_bytes",
2953 help: "total size of parts filtered by pushdown in bytes",
2954 )),
2955 parts_fetched_count: registry.register(metric!(
2956 name: "mz_persist_pushdown_parts_fetched_count",
2957 help: "count of parts not filtered by pushdown",
2958 )),
2959 parts_fetched_bytes: registry.register(metric!(
2960 name: "mz_persist_pushdown_parts_fetched_bytes",
2961 help: "total size of parts not filtered by pushdown in bytes",
2962 )),
2963 parts_audited_count: registry.register(metric!(
2964 name: "mz_persist_pushdown_parts_audited_count",
2965 help: "count of parts fetched only for pushdown audit",
2966 )),
2967 parts_audited_bytes: registry.register(metric!(
2968 name: "mz_persist_pushdown_parts_audited_bytes",
2969 help: "total size of parts fetched only for pushdown audit",
2970 )),
2971 parts_inline_count: registry.register(metric!(
2972 name: "mz_persist_pushdown_parts_inline_count",
2973 help: "count of parts not fetched because they were inline",
2974 )),
2975 parts_inline_bytes: registry.register(metric!(
2976 name: "mz_persist_pushdown_parts_inline_bytes",
2977 help: "total size of parts not fetched because they were inline",
2978 )),
2979 parts_faked_count: registry.register(metric!(
2980 name: "mz_persist_pushdown_parts_faked_count",
2981 help: "count of parts faked because of aggressive projection pushdown",
2982 )),
2983 parts_faked_bytes: registry.register(metric!(
2984 name: "mz_persist_pushdown_parts_faked_bytes",
2985 help: "total size of parts replaced with fakes by aggressive projection pushdown",
2986 )),
2987 parts_stats_trimmed_count: registry.register(metric!(
2988 name: "mz_persist_pushdown_parts_stats_trimmed_count",
2989 help: "count of trimmed part stats",
2990 )),
2991 parts_stats_trimmed_bytes: registry.register(metric!(
2992 name: "mz_persist_pushdown_parts_stats_trimmed_bytes",
2993 help: "total bytes trimmed from part stats",
2994 )),
2995 parts_projection_trimmed_bytes: registry.register(metric!(
2996 name: "mz_persist_pushdown_parts_projection_trimmed_bytes",
2997 help: "total bytes trimmed from columnar data because of projection pushdown",
2998 )),
2999 part_stats: PartStatsMetrics::new(registry),
3000 }
3001 }
3002}
3003
3004#[derive(Debug)]
3005pub struct ConsolidationMetrics {
3006 pub(crate) parts_fetched: IntCounter,
3007 pub(crate) parts_skipped: IntCounter,
3008 pub(crate) parts_wasted: IntCounter,
3009 pub(crate) wrong_sort: IntCounter,
3010}
3011
3012impl ConsolidationMetrics {
3013 fn new(registry: &MetricsRegistry) -> Self {
3014 ConsolidationMetrics {
3015 parts_fetched: registry.register(metric!(
3016 name: "mz_persist_consolidation_parts_fetched_count",
3017 help: "count of parts that were fetched and used during consolidation",
3018 )),
3019 parts_skipped: registry.register(metric!(
3020 name: "mz_persist_consolidation_parts_skipped_count",
3021 help: "count of parts that were never needed during consolidation",
3022 )),
3023 parts_wasted: registry.register(metric!(
3024 name: "mz_persist_consolidation_parts_wasted_count",
3025 help: "count of parts that were fetched but not needed during consolidation",
3026 )),
3027 wrong_sort: registry.register(metric!(
3028 name: "mz_persist_consolidation_wrong_sort_count",
3029 help: "count of runs that were sorted using the wrong ordering for the current consolidation",
3030 )),
3031 }
3032 }
3033}
3034
3035#[derive(Debug)]
3036pub struct BlobMemCache {
3037 pub(crate) size_blobs: UIntGauge,
3038 pub(crate) size_bytes: UIntGauge,
3039 pub(crate) hits_blobs: IntCounter,
3040 pub(crate) hits_bytes: IntCounter,
3041 pub(crate) evictions: IntCounter,
3042}
3043
3044impl BlobMemCache {
3045 fn new(registry: &MetricsRegistry) -> Self {
3046 BlobMemCache {
3047 size_blobs: registry.register(metric!(
3048 name: "mz_persist_blob_cache_size_blobs",
3049 help: "count of blobs in the cache",
3050 const_labels: {"cache" => "mem"},
3051 )),
3052 size_bytes: registry.register(metric!(
3053 name: "mz_persist_blob_cache_size_bytes",
3054 help: "total size of blobs in the cache",
3055 const_labels: {"cache" => "mem"},
3056 )),
3057 hits_blobs: registry.register(metric!(
3058 name: "mz_persist_blob_cache_hits_blobs",
3059 help: "count of blobs served via cache instead of s3",
3060 const_labels: {"cache" => "mem"},
3061 )),
3062 hits_bytes: registry.register(metric!(
3063 name: "mz_persist_blob_cache_hits_bytes",
3064 help: "total size of blobs served via cache instead of s3",
3065 const_labels: {"cache" => "mem"},
3066 )),
3067 evictions: registry.register(metric!(
3068 name: "mz_persist_blob_cache_evictions",
3069 help: "count of capacity-based cache evictions",
3070 const_labels: {"cache" => "mem"},
3071 )),
3072 }
3073 }
3074}
3075
3076#[derive(Debug)]
3077pub struct SemaphoreMetrics {
3078 cfg: PersistConfig,
3079 registry: MetricsRegistry,
3080 fetch: OnceCell<MetricsSemaphore>,
3081}
3082
3083impl SemaphoreMetrics {
3084 fn new(cfg: PersistConfig, registry: MetricsRegistry) -> Self {
3085 SemaphoreMetrics {
3086 cfg,
3087 registry,
3088 fetch: OnceCell::new(),
3089 }
3090 }
3091
3092 async fn fetch(&self) -> &MetricsSemaphore {
3096 if let Some(x) = self.fetch.get() {
3097 return x;
3099 }
3100 let cfg = self.cfg.clone();
3101 let registry = self.registry.clone();
3102 let init = async move {
3103 let total_permits = match cfg.announce_memory_limit {
3104 Some(mem) if cfg.is_cc_active => {
3107 info!("fetch semaphore awaiting first dyncfg values");
3110 let () = cfg.configs_synced_once().await;
3111 let total_permits = usize::cast_lossy(
3112 f64::cast_lossy(mem) * FETCH_SEMAPHORE_PERMIT_ADJUSTMENT.get(&cfg),
3113 );
3114 info!("fetch_semaphore got first dyncfg values");
3115 total_permits
3116 }
3117 Some(_) | None => Semaphore::MAX_PERMITS,
3118 };
3119 MetricsSemaphore::new(®istry, "fetch", total_permits)
3120 };
3121 self.fetch.get_or_init(|| init).await
3122 }
3123
3124 pub(crate) async fn acquire_fetch_permits(&self, encoded_size_bytes: usize) -> MetricsPermits {
3125 let requested_permits = f64::cast_lossy(encoded_size_bytes);
3128 let requested_permits = requested_permits * FETCH_SEMAPHORE_COST_ADJUSTMENT.get(&self.cfg);
3129 let requested_permits = usize::cast_lossy(requested_permits);
3130 self.fetch().await.acquire_permits(requested_permits).await
3131 }
3132}
3133
3134#[derive(Debug)]
3135pub struct MetricsSemaphore {
3136 name: &'static str,
3137 semaphore: Arc<Semaphore>,
3138 total_permits: usize,
3139 acquire_count: IntCounter,
3140 blocking_count: IntCounter,
3141 blocking_seconds: Counter,
3142 acquired_permits: IntCounter,
3143 released_permits: IntCounter,
3144 _available_permits: ComputedUIntGauge,
3145}
3146
3147impl MetricsSemaphore {
3148 pub fn new(registry: &MetricsRegistry, name: &'static str, total_permits: usize) -> Self {
3149 let total_permits = std::cmp::min(total_permits, Semaphore::MAX_PERMITS);
3150 let semaphore = Arc::new(Semaphore::new(total_permits));
3153 MetricsSemaphore {
3154 name,
3155 total_permits,
3156 acquire_count: registry.register(metric!(
3157 name: "mz_persist_semaphore_acquire_count",
3158 help: "count of acquire calls (not acquired permits count)",
3159 const_labels: {"name" => name},
3160 )),
3161 blocking_count: registry.register(metric!(
3162 name: "mz_persist_semaphore_blocking_count",
3163 help: "count of acquire calls that had to block",
3164 const_labels: {"name" => name},
3165 )),
3166 blocking_seconds: registry.register(metric!(
3167 name: "mz_persist_semaphore_blocking_seconds",
3168 help: "total time spent blocking on permit acquisition",
3169 const_labels: {"name" => name},
3170 )),
3171 acquired_permits: registry.register(metric!(
3172 name: "mz_persist_semaphore_acquired_permits",
3173 help: "total sum of acquired permits",
3174 const_labels: {"name" => name},
3175 )),
3176 released_permits: registry.register(metric!(
3177 name: "mz_persist_semaphore_released_permits",
3178 help: "total sum of released permits",
3179 const_labels: {"name" => name},
3180 )),
3181 _available_permits: registry.register_computed_gauge(
3182 metric!(
3183 name: "mz_persist_semaphore_available_permits",
3184 help: "currently available permits according to the semaphore",
3185 ),
3186 {
3187 let semaphore = Arc::clone(&semaphore);
3188 move || u64::cast_from(semaphore.available_permits())
3189 },
3190 ),
3191 semaphore,
3192 }
3193 }
3194
3195 pub async fn acquire_permits(&self, requested_permits: usize) -> MetricsPermits {
3196 let total_permits = u32::try_from(self.total_permits).unwrap_or(u32::MAX);
3199 let requested_permits = u32::try_from(requested_permits).unwrap_or(u32::MAX);
3200 let requested_permits = std::cmp::min(requested_permits, total_permits);
3201 let wrap = |_permit| {
3202 self.acquired_permits.inc_by(u64::from(requested_permits));
3203 MetricsPermits {
3204 _permit,
3205 released_metric: self.released_permits.clone(),
3206 count: requested_permits,
3207 }
3208 };
3209
3210 self.acquire_count.inc();
3212 match Arc::clone(&self.semaphore).try_acquire_many_owned(requested_permits) {
3213 Ok(x) => return wrap(x),
3214 Err(_) => {}
3215 };
3216
3217 self.blocking_count.inc();
3219 let start = Instant::now();
3220 let ret = Arc::clone(&self.semaphore)
3221 .acquire_many_owned(requested_permits)
3222 .instrument(info_span!("acquire_permits"))
3223 .await;
3224 let elapsed = start.elapsed();
3225 self.blocking_seconds.inc_by(elapsed.as_secs_f64());
3226 debug!(
3227 "acquisition of {} {} permits blocked for {:?}",
3228 self.name, requested_permits, elapsed
3229 );
3230 wrap(ret.expect("semaphore is never closed"))
3231 }
3232}
3233
3234#[derive(Debug)]
3235pub struct MetricsPermits {
3236 _permit: OwnedSemaphorePermit,
3237 released_metric: IntCounter,
3238 count: u32,
3239}
3240
3241impl Drop for MetricsPermits {
3242 fn drop(&mut self) {
3243 self.released_metric.inc_by(u64::from(self.count))
3244 }
3245}
3246
3247#[derive(Debug)]
3248pub struct ExternalOpMetrics {
3249 started: IntCounter,
3250 succeeded: IntCounter,
3251 failed: IntCounter,
3252 bytes: IntCounter,
3253 seconds: Counter,
3254 seconds_histogram: Option<Histogram>,
3255 alerts_metrics: Arc<AlertsMetrics>,
3256}
3257
3258impl ExternalOpMetrics {
3259 async fn run_op<R, F, OpFn, ErrFn>(
3260 &self,
3261 op_fn: OpFn,
3262 on_err_fn: ErrFn,
3263 ) -> Result<R, ExternalError>
3264 where
3265 F: std::future::Future<Output = Result<R, ExternalError>>,
3266 OpFn: FnOnce() -> F,
3267 ErrFn: FnOnce(&AlertsMetrics, &ExternalError),
3268 {
3269 self.started.inc();
3270 let start = Instant::now();
3271 let res = op_fn().await;
3272 let elapsed_seconds = start.elapsed().as_secs_f64();
3273 self.seconds.inc_by(elapsed_seconds);
3274 if let Some(h) = &self.seconds_histogram {
3275 h.observe(elapsed_seconds);
3276 }
3277 match res.as_ref() {
3278 Ok(_) => self.succeeded.inc(),
3279 Err(err) => {
3280 self.failed.inc();
3281 on_err_fn(&self.alerts_metrics, err);
3282 }
3283 };
3284 res
3285 }
3286
3287 fn run_stream<'a, R: 'a, S, OpFn, ErrFn>(
3288 &'a self,
3289 op_fn: OpFn,
3290 mut on_err_fn: ErrFn,
3291 ) -> impl futures::Stream<Item = Result<R, ExternalError>> + 'a
3292 where
3293 S: futures::Stream<Item = Result<R, ExternalError>> + Unpin + 'a,
3294 OpFn: FnOnce() -> S,
3295 ErrFn: FnMut(&AlertsMetrics, &ExternalError) + 'a,
3296 {
3297 self.started.inc();
3298 let start = Instant::now();
3299 let mut stream = op_fn();
3300 stream! {
3301 let mut succeeded = true;
3302 while let Some(res) = stream.next().await {
3303 if let Err(err) = res.as_ref() {
3304 on_err_fn(&self.alerts_metrics, err);
3305 succeeded = false;
3306 }
3307 yield res;
3308 }
3309 if succeeded {
3310 self.succeeded.inc()
3311 } else {
3312 self.failed.inc()
3313 }
3314 let elapsed_seconds = start.elapsed().as_secs_f64();
3315 self.seconds.inc_by(elapsed_seconds);
3316 if let Some(h) = &self.seconds_histogram {
3317 h.observe(elapsed_seconds);
3318 }
3319 }
3320 }
3321}
3322
3323#[derive(Debug)]
3324pub struct BlobMetrics {
3325 set: ExternalOpMetrics,
3326 get: ExternalOpMetrics,
3327 list_keys: ExternalOpMetrics,
3328 delete: ExternalOpMetrics,
3329 restore: ExternalOpMetrics,
3330 delete_noop: IntCounter,
3331 blob_sizes: Histogram,
3332 pub rtt_latency: Gauge,
3333}
3334
3335#[derive(Debug)]
3336pub struct MetricsBlob {
3337 blob: Arc<dyn Blob>,
3338 metrics: Arc<Metrics>,
3339}
3340
3341impl MetricsBlob {
3342 pub fn new(blob: Arc<dyn Blob>, metrics: Arc<Metrics>) -> Self {
3343 MetricsBlob { blob, metrics }
3344 }
3345
3346 fn on_err(alerts_metrics: &AlertsMetrics, _err: &ExternalError) {
3347 alerts_metrics.blob_failures.inc()
3348 }
3349}
3350
3351#[async_trait]
3352impl Blob for MetricsBlob {
3353 #[instrument(name = "blob::get", fields(shard=blob_key_shard_id(key)))]
3354 async fn get(&self, key: &str) -> Result<Option<SegmentedBytes>, ExternalError> {
3355 let res = self
3356 .metrics
3357 .blob
3358 .get
3359 .run_op(|| self.blob.get(key), Self::on_err)
3360 .await;
3361 if let Ok(Some(value)) = res.as_ref() {
3362 self.metrics
3363 .blob
3364 .get
3365 .bytes
3366 .inc_by(u64::cast_from(value.len()));
3367 }
3368 res
3369 }
3370
3371 #[instrument(name = "blob::list_keys_and_metadata", fields(shard=blob_key_shard_id(key_prefix)))]
3372 async fn list_keys_and_metadata(
3373 &self,
3374 key_prefix: &str,
3375 f: &mut (dyn FnMut(BlobMetadata) + Send + Sync),
3376 ) -> Result<(), ExternalError> {
3377 let mut byte_total = 0;
3378 let mut instrumented = |blob_metadata: BlobMetadata| {
3379 byte_total += blob_metadata.key.len();
3382 f(blob_metadata)
3383 };
3384
3385 let res = self
3386 .metrics
3387 .blob
3388 .list_keys
3389 .run_op(
3390 || {
3391 self.blob
3392 .list_keys_and_metadata(key_prefix, &mut instrumented)
3393 },
3394 Self::on_err,
3395 )
3396 .await;
3397
3398 self.metrics
3399 .blob
3400 .list_keys
3401 .bytes
3402 .inc_by(u64::cast_from(byte_total));
3403
3404 res
3405 }
3406
3407 #[instrument(name = "blob::set", fields(shard=blob_key_shard_id(key),size_bytes=value.len()))]
3408 async fn set(&self, key: &str, value: Bytes) -> Result<(), ExternalError> {
3409 let bytes = value.len();
3410 let res = self
3411 .metrics
3412 .blob
3413 .set
3414 .run_op(|| self.blob.set(key, value), Self::on_err)
3415 .await;
3416 if res.is_ok() {
3417 self.metrics.blob.set.bytes.inc_by(u64::cast_from(bytes));
3418 self.metrics.blob.blob_sizes.observe(f64::cast_lossy(bytes));
3419 }
3420 res
3421 }
3422
3423 #[instrument(name = "blob::delete", fields(shard=blob_key_shard_id(key)))]
3424 async fn delete(&self, key: &str) -> Result<Option<usize>, ExternalError> {
3425 let bytes = self
3426 .metrics
3427 .blob
3428 .delete
3429 .run_op(|| self.blob.delete(key), Self::on_err)
3430 .await?;
3431 if let Some(bytes) = bytes {
3432 self.metrics.blob.delete.bytes.inc_by(u64::cast_from(bytes));
3433 } else {
3434 self.metrics.blob.delete_noop.inc();
3435 }
3436 Ok(bytes)
3437 }
3438
3439 async fn restore(&self, key: &str) -> Result<(), ExternalError> {
3440 self.metrics
3441 .blob
3442 .restore
3443 .run_op(|| self.blob.restore(key), Self::on_err)
3444 .await
3445 }
3446}
3447
3448#[derive(Debug)]
3449pub struct ConsensusMetrics {
3450 list_keys: ExternalOpMetrics,
3451 head: ExternalOpMetrics,
3452 compare_and_set: ExternalOpMetrics,
3453 scan: ExternalOpMetrics,
3454 truncate: ExternalOpMetrics,
3455 truncated_count: IntCounter,
3456 pub rtt_latency: Gauge,
3457}
3458
3459#[derive(Debug)]
3460pub struct MetricsConsensus {
3461 consensus: Arc<dyn Consensus>,
3462 metrics: Arc<Metrics>,
3463}
3464
3465impl MetricsConsensus {
3466 pub fn new(consensus: Arc<dyn Consensus>, metrics: Arc<Metrics>) -> Self {
3467 MetricsConsensus { consensus, metrics }
3468 }
3469
3470 fn on_err(alerts_metrics: &AlertsMetrics, err: &ExternalError) {
3471 if let ExternalError::Indeterminate(_) = err {
3475 alerts_metrics.consensus_failures.inc()
3476 }
3477 }
3478}
3479
3480#[async_trait]
3481impl Consensus for MetricsConsensus {
3482 fn list_keys(&self) -> ResultStream<'_, String> {
3483 Box::pin(
3484 self.metrics
3485 .consensus
3486 .list_keys
3487 .run_stream(|| self.consensus.list_keys(), Self::on_err),
3488 )
3489 }
3490
3491 #[instrument(name = "consensus::head", fields(shard=key))]
3492 async fn head(&self, key: &str) -> Result<Option<VersionedData>, ExternalError> {
3493 let res = self
3494 .metrics
3495 .consensus
3496 .head
3497 .run_op(|| self.consensus.head(key), Self::on_err)
3498 .await;
3499 if let Ok(Some(data)) = res.as_ref() {
3500 self.metrics
3501 .consensus
3502 .head
3503 .bytes
3504 .inc_by(u64::cast_from(data.data.len()));
3505 }
3506 res
3507 }
3508
3509 #[instrument(name = "consensus::compare_and_set", fields(shard=key,size_bytes=new.data.len()))]
3510 async fn compare_and_set(
3511 &self,
3512 key: &str,
3513 new: VersionedData,
3514 ) -> Result<CaSResult, ExternalError> {
3515 let bytes = new.data.len();
3516 let res = self
3517 .metrics
3518 .consensus
3519 .compare_and_set
3520 .run_op(|| self.consensus.compare_and_set(key, new), Self::on_err)
3521 .await;
3522 match res.as_ref() {
3523 Ok(CaSResult::Committed) => self
3524 .metrics
3525 .consensus
3526 .compare_and_set
3527 .bytes
3528 .inc_by(u64::cast_from(bytes)),
3529 Ok(CaSResult::ExpectationMismatch) | Err(_) => {}
3530 }
3531 res
3532 }
3533
3534 #[instrument(name = "consensus::scan", fields(shard=key))]
3535 async fn scan(
3536 &self,
3537 key: &str,
3538 from: SeqNo,
3539 limit: usize,
3540 ) -> Result<Vec<VersionedData>, ExternalError> {
3541 let res = self
3542 .metrics
3543 .consensus
3544 .scan
3545 .run_op(|| self.consensus.scan(key, from, limit), Self::on_err)
3546 .await;
3547 if let Ok(dataz) = res.as_ref() {
3548 let bytes: usize = dataz.iter().map(|x| x.data.len()).sum();
3549 self.metrics
3550 .consensus
3551 .scan
3552 .bytes
3553 .inc_by(u64::cast_from(bytes));
3554 }
3555 res
3556 }
3557
3558 #[instrument(name = "consensus::truncate", fields(shard=key))]
3559 async fn truncate(&self, key: &str, seqno: SeqNo) -> Result<Option<usize>, ExternalError> {
3560 let metrics = &self.metrics.consensus;
3561 let deleted = metrics
3562 .truncate
3563 .run_op(|| self.consensus.truncate(key, seqno), Self::on_err)
3564 .await?;
3565 if let Some(deleted) = deleted {
3566 metrics.truncated_count.inc_by(u64::cast_from(deleted));
3567 }
3568 Ok(deleted)
3569 }
3570}
3571
3572#[derive(Debug, Clone)]
3575pub struct TaskMetrics {
3576 f64_gauges: Vec<(Gauge, fn(&tokio_metrics::TaskMetrics) -> f64)>,
3577 u64_gauges: Vec<(
3578 GenericGauge<AtomicU64>,
3579 fn(&tokio_metrics::TaskMetrics) -> u64,
3580 )>,
3581 monitor: TaskMonitor,
3582}
3583
3584impl TaskMetrics {
3585 pub fn new(name: &str) -> Self {
3586 let monitor = TaskMonitor::new();
3587 Self {
3588 f64_gauges: vec![
3589 (
3590 Gauge::make_collector(metric!(
3591 name: "mz_persist_task_total_idle_duration",
3592 help: "Seconds of time spent idling, ie. waiting for a task to be woken up.",
3593 const_labels: {"name" => name}
3594 )),
3595 |m| m.total_idle_duration.as_secs_f64(),
3596 ),
3597 (
3598 Gauge::make_collector(metric!(
3599 name: "mz_persist_task_total_scheduled_duration",
3600 help: "Seconds of time spent scheduled, ie. ready to poll but not yet polled.",
3601 const_labels: {"name" => name}
3602 )),
3603 |m| m.total_scheduled_duration.as_secs_f64(),
3604 ),
3605 ],
3606 u64_gauges: vec![
3607 (
3608 MakeCollector::make_collector(metric!(
3609 name: "mz_persist_task_total_scheduled_count",
3610 help: "The total number of task schedules. Useful for computing the average scheduled time.",
3611 const_labels: {"name" => name}
3612 )),
3613 |m| m.total_scheduled_count,
3614 ),
3615 (
3616 MakeCollector::make_collector(metric!(
3617 name: "mz_persist_task_total_idled_count",
3618 help: "The total number of task idles. Useful for computing the average idle time.",
3619 const_labels: {"name" => name}
3620 ,
3621 )),
3622 |m| m.total_idled_count,
3623 ),
3624 ],
3625 monitor,
3626 }
3627 }
3628
3629 pub fn instrument_task<F>(&self, task: F) -> tokio_metrics::Instrumented<F> {
3632 TaskMonitor::instrument(&self.monitor, task)
3633 }
3634}
3635
3636impl Collector for TaskMetrics {
3637 fn desc(&self) -> Vec<&Desc> {
3638 let mut descs = Vec::with_capacity(self.f64_gauges.len() + self.u64_gauges.len());
3639 for (g, _) in &self.f64_gauges {
3640 descs.extend(g.desc());
3641 }
3642 for (g, _) in &self.u64_gauges {
3643 descs.extend(g.desc());
3644 }
3645 descs
3646 }
3647
3648 fn collect(&self) -> Vec<MetricFamily> {
3649 let mut families = Vec::with_capacity(self.f64_gauges.len() + self.u64_gauges.len());
3650 let metrics = self.monitor.cumulative();
3651 for (g, metrics_fn) in &self.f64_gauges {
3652 g.set(metrics_fn(&metrics));
3653 families.extend(g.collect());
3654 }
3655 for (g, metrics_fn) in &self.u64_gauges {
3656 g.set(metrics_fn(&metrics));
3657 families.extend(g.collect());
3658 }
3659 families
3660 }
3661}
3662
3663#[derive(Debug)]
3664pub struct TasksMetrics {
3665 pub heartbeat_read: TaskMetrics,
3666}
3667
3668impl TasksMetrics {
3669 fn new(registry: &MetricsRegistry) -> Self {
3670 let heartbeat_read = TaskMetrics::new("heartbeat_read");
3671 registry.register_collector(heartbeat_read.clone());
3672 TasksMetrics { heartbeat_read }
3673 }
3674}
3675
3676#[derive(Debug)]
3677pub struct SchemaMetrics {
3678 pub(crate) cache_fetch_state_count: IntCounter,
3679 pub(crate) cache_schema: SchemaCacheMetrics,
3680 pub(crate) cache_migration: SchemaCacheMetrics,
3681 pub(crate) migration_count_same: IntCounter,
3682 pub(crate) migration_count_codec: IntCounter,
3683 pub(crate) migration_count_either: IntCounter,
3684 pub(crate) migration_len_legacy_codec: IntCounter,
3685 pub(crate) migration_len_either_codec: IntCounter,
3686 pub(crate) migration_len_either_arrow: IntCounter,
3687 pub(crate) migration_new_count: IntCounter,
3688 pub(crate) migration_new_seconds: Counter,
3689 pub(crate) migration_migrate_seconds: Counter,
3690}
3691
3692impl SchemaMetrics {
3693 fn new(registry: &MetricsRegistry) -> Self {
3694 let cached: IntCounterVec = registry.register(metric!(
3695 name: "mz_persist_schema_cache_cached_count",
3696 help: "count of schema cache entries served from cache",
3697 var_labels: ["op"],
3698 ));
3699 let computed: IntCounterVec = registry.register(metric!(
3700 name: "mz_persist_schema_cache_computed_count",
3701 help: "count of schema cache entries computed",
3702 var_labels: ["op"],
3703 ));
3704 let unavailable: IntCounterVec = registry.register(metric!(
3705 name: "mz_persist_schema_cache_unavailable_count",
3706 help: "count of schema cache entries unavailable at current state",
3707 var_labels: ["op"],
3708 ));
3709 let added: IntCounterVec = registry.register(metric!(
3710 name: "mz_persist_schema_cache_added_count",
3711 help: "count of schema cache entries added",
3712 var_labels: ["op"],
3713 ));
3714 let dropped: IntCounterVec = registry.register(metric!(
3715 name: "mz_persist_schema_cache_dropped_count",
3716 help: "count of schema cache entries dropped",
3717 var_labels: ["op"],
3718 ));
3719 let cache = |name| SchemaCacheMetrics {
3720 cached_count: cached.with_label_values(&[name]),
3721 computed_count: computed.with_label_values(&[name]),
3722 unavailable_count: unavailable.with_label_values(&[name]),
3723 added_count: added.with_label_values(&[name]),
3724 dropped_count: dropped.with_label_values(&[name]),
3725 };
3726 let migration_count: IntCounterVec = registry.register(metric!(
3727 name: "mz_persist_schema_migration_count",
3728 help: "count of fetch part migrations",
3729 var_labels: ["op"],
3730 ));
3731 let migration_len: IntCounterVec = registry.register(metric!(
3732 name: "mz_persist_schema_migration_len",
3733 help: "count of migrated update records",
3734 var_labels: ["op"],
3735 ));
3736 SchemaMetrics {
3737 cache_fetch_state_count: registry.register(metric!(
3738 name: "mz_persist_schema_cache_fetch_state_count",
3739 help: "count of state fetches by the schema cache",
3740 )),
3741 cache_schema: cache("schema"),
3742 cache_migration: cache("migration"),
3743 migration_count_same: migration_count.with_label_values(&["same"]),
3744 migration_count_codec: migration_count.with_label_values(&["codec"]),
3745 migration_count_either: migration_count.with_label_values(&["either"]),
3746 migration_len_legacy_codec: migration_len.with_label_values(&["legacy_codec"]),
3747 migration_len_either_codec: migration_len.with_label_values(&["either_codec"]),
3748 migration_len_either_arrow: migration_len.with_label_values(&["either_arrow"]),
3749 migration_new_count: registry.register(metric!(
3750 name: "mz_persist_schema_migration_new_count",
3751 help: "count of migrations constructed",
3752 )),
3753 migration_new_seconds: registry.register(metric!(
3754 name: "mz_persist_schema_migration_new_seconds",
3755 help: "seconds spent constructing migration logic",
3756 )),
3757 migration_migrate_seconds: registry.register(metric!(
3758 name: "mz_persist_schema_migration_migrate_seconds",
3759 help: "seconds spent applying migration logic",
3760 )),
3761 }
3762 }
3763}
3764
3765#[derive(Debug, Clone)]
3766pub struct SchemaCacheMetrics {
3767 pub(crate) cached_count: IntCounter,
3768 pub(crate) computed_count: IntCounter,
3769 pub(crate) unavailable_count: IntCounter,
3770 pub(crate) added_count: IntCounter,
3771 pub(crate) dropped_count: IntCounter,
3772}
3773
3774#[derive(Debug)]
3775pub struct InlineMetrics {
3776 pub(crate) part_commit_count: IntCounter,
3777 pub(crate) part_commit_bytes: IntCounter,
3778 pub(crate) backpressure: BatchWriteMetrics,
3779}
3780
3781impl InlineMetrics {
3782 fn new(registry: &MetricsRegistry) -> Self {
3783 InlineMetrics {
3784 part_commit_count: registry.register(metric!(
3785 name: "mz_persist_inline_part_commit_count",
3786 help: "count of inline parts committed to state",
3787 )),
3788 part_commit_bytes: registry.register(metric!(
3789 name: "mz_persist_inline_part_commit_bytes",
3790 help: "total size of of inline parts committed to state",
3791 )),
3792 backpressure: BatchWriteMetrics::new(registry, "inline_backpressure"),
3793 }
3794 }
3795}
3796
3797fn blob_key_shard_id(key: &str) -> Option<String> {
3798 let (shard_id, _) = BlobKey::parse_ids(key).ok()?;
3799 Some(shard_id.to_string())
3800}
3801
3802pub fn encode_ts_metric<T: Codec64>(ts: &Antichain<T>) -> i64 {
3804 match ts.elements().first() {
3814 Some(ts) => i64::from_le_bytes(Codec64::encode(ts)),
3815 None => i64::MAX,
3816 }
3817}
3818
3819#[cfg(test)]
3820mod tests {
3821 use std::collections::BTreeSet;
3822
3823 use mz_dyncfg::ConfigUpdates;
3824 use mz_ore::metrics::aggregation::PERCENTILES;
3825
3826 use crate::cfg::SHARD_METRICS;
3827
3828 use super::*;
3829
3830 #[mz_ore::test]
3831 fn shards_aggregate_metrics_one_pass() {
3832 let registry = MetricsRegistry::new();
3833 let configs = Arc::clone(&PersistConfig::new_for_tests().configs);
3834 let shards = ShardsMetrics::new(®istry, Arc::clone(&configs));
3835 let agg = ShardsAggregateMetrics::new(Arc::clone(&shards.shards), configs);
3836 let a = shards.shard(&ShardId::new(), "a");
3837 let b = shards.shard(&ShardId::new(), "b");
3838
3839 agg.collect();
3841 assert_eq!(agg.count.get(), 2);
3842 assert_eq!(agg.stale_count.get(), 0);
3843
3844 a.stale.store(true, Ordering::Relaxed);
3845 agg.collect();
3846 assert_eq!(agg.count.get(), 2);
3847 assert_eq!(agg.stale_count.get(), 1);
3848
3849 b.stale.store(true, Ordering::Relaxed);
3850 agg.collect();
3851 assert_eq!(agg.stale_count.get(), 2);
3852
3853 a.stale.store(false, Ordering::Relaxed);
3856 drop(b);
3857 agg.collect();
3858 assert_eq!(agg.count.get(), 1);
3859 assert_eq!(agg.stale_count.get(), 0);
3860 }
3861
3862 #[mz_ore::test]
3863 fn per_shard_families_match_registrations() {
3864 let cfg = PersistConfig::new_for_tests();
3865 set_shard_metrics(&cfg, ShardMetricsExport::Both);
3866 let registry = MetricsRegistry::new();
3867 let metrics = Metrics::new(&cfg, ®istry);
3868 let shard = metrics.shards.shard(&ShardId::new(), "s");
3869 shard.set_batch_part_versions(["v1"].into_iter());
3870 let gathered = registry.gather();
3871
3872 let registered: BTreeSet<_> = gathered
3873 .iter()
3874 .filter(|f| !f.name().ends_with("_topk"))
3875 .filter(|f| {
3876 f.get_metric()
3877 .iter()
3878 .any(|m| m.get_label().iter().any(|l| l.name() == "shard"))
3879 })
3880 .map(|f| f.name())
3881 .collect();
3882 let listed: BTreeSet<_> = PER_SHARD_FAMILIES.iter().map(|f| f.name).collect();
3883 assert_eq!(registered, listed);
3884
3885 for (name, gauge) in shard_gauges() {
3888 let registered = find(&gathered, name)
3889 .unwrap_or_else(|| panic!("{name} not gathered"))
3890 .help();
3891 assert_eq!(gauge.help, registered, "{name}");
3892 }
3893
3894 let gathered: BTreeSet<_> = gathered.iter().map(|f| f.name()).collect();
3895 for family in PER_SHARD_FAMILIES {
3896 if let ShardAggregate::Counter { total } = family.aggregate {
3897 assert!(gathered.contains(total), "{total} not gathered");
3898 }
3899 }
3900 }
3901
3902 #[mz_ore::test]
3903 fn every_shard_gauge_has_its_aggregates() {
3904 let registry = MetricsRegistry::new();
3905 let configs = Arc::clone(&PersistConfig::new_for_tests().configs);
3906 let shards = ShardsMetrics::new(®istry, Arc::clone(&configs));
3907 let agg = ShardsAggregateMetrics::new(Arc::clone(&shards.shards), configs);
3908 let declared: BTreeSet<_> = agg.desc().iter().map(|d| d.fq_name.clone()).collect();
3909 for (gauge, g) in shard_gauges() {
3910 for suffix in ["_percentile", "_topk"] {
3911 let name = format!("{gauge}{suffix}");
3912 assert!(declared.contains(&name), "{name} not declared");
3913 }
3914 let sum = format!("{gauge}_sum");
3915 assert_eq!(declared.contains(&sum), g.sum, "{sum}");
3916 }
3917 }
3918
3919 fn find<'a>(families: &'a [MetricFamily], name: &str) -> Option<&'a MetricFamily> {
3920 families.iter().find(|f| f.name() == name)
3921 }
3922
3923 fn label<'a>(m: &'a prometheus::proto::Metric, name: &str) -> &'a str {
3924 m.get_label()
3925 .iter()
3926 .find(|l| l.name() == name)
3927 .map(|l| l.value())
3928 .unwrap_or_else(|| panic!("no label {name}"))
3929 }
3930
3931 fn gauge_set(
3934 families: &[MetricFamily],
3935 name: &str,
3936 label_name: &str,
3937 ) -> BTreeSet<(String, u64)> {
3938 find(families, name).map_or_else(BTreeSet::new, |f| {
3939 f.get_metric()
3940 .iter()
3941 .map(|m| {
3942 (
3943 label(m, label_name).to_string(),
3944 u64::cast_lossy(m.get_gauge().value()),
3945 )
3946 })
3947 .collect()
3948 })
3949 }
3950
3951 fn scalar(families: &[MetricFamily], name: &str) -> f64 {
3952 let f = find(families, name).unwrap_or_else(|| panic!("{name} not gathered"));
3953 let m = &f.get_metric()[0];
3954 if f.get_field_type() == prometheus::proto::MetricType::COUNTER {
3955 m.get_counter().value()
3956 } else {
3957 m.get_gauge().value()
3958 }
3959 }
3960
3961 fn metrics_with_shards(n: u64) -> (PersistConfig, MetricsRegistry, Vec<Arc<ShardMetrics>>) {
3964 let cfg = PersistConfig::new_for_tests();
3965 let registry = MetricsRegistry::new();
3966 let metrics = Metrics::new(&cfg, ®istry);
3967 let shards = (1..=n)
3968 .map(|i| {
3969 let shard = metrics.shards.shard(&ShardId::new(), &format!("s{i}"));
3970 shard.usage_current_state_batches_bytes.set(i);
3971 shard.set_batch_part_versions(["v1"].into_iter());
3972 shard
3973 })
3974 .collect();
3975 (cfg, registry, shards)
3976 }
3977
3978 fn set_shard_metrics(cfg: &PersistConfig, mode: ShardMetricsExport) {
3979 let mut updates = ConfigUpdates::default();
3980 updates.add(&SHARD_METRICS, mode.as_str());
3981 cfg.apply_from(&updates);
3982 }
3983
3984 fn family_names(families: &[MetricFamily]) -> BTreeSet<String> {
3985 families.iter().map(|f| f.name().to_string()).collect()
3986 }
3987
3988 fn always_exported() -> BTreeSet<String> {
3991 let mut names: BTreeSet<_> = ["mz_persist_shard_count", "mz_persist_stale_shard_count"]
3992 .into_iter()
3993 .map(String::from)
3994 .collect();
3995 names.extend(PER_SHARD_FAMILIES.iter().filter_map(|f| match f.aggregate {
3996 ShardAggregate::Counter { total } => Some(total.to_string()),
3997 _ => None,
3998 }));
3999 names
4000 }
4001
4002 #[mz_ore::test]
4003 fn shard_metrics_modes_round_trip() {
4004 for mode in ShardMetricsExport::ALL {
4005 assert_eq!(ShardMetricsExport::parse(mode.as_str()), Some(mode));
4006 }
4007 assert_eq!(
4008 ShardMetricsExport::parse(SHARD_METRICS.default()),
4009 Some(ShardMetricsExport::default())
4010 );
4011 assert_eq!(ShardMetricsExport::parse("not_a_mode"), None);
4012 }
4013
4014 #[mz_ore::test]
4015 fn unknown_shard_metrics_mode_exports_the_default() {
4016 let (cfg, registry, _shards) = metrics_with_shards(3);
4017 let summary = family_names(®istry.gather());
4018 let invalid =
4019 |families: &[MetricFamily]| scalar(families, "mz_persist_shard_metrics_mode_invalid");
4020
4021 let mut updates = ConfigUpdates::default();
4022 updates.add(&SHARD_METRICS, "summry");
4023 cfg.apply_from(&updates);
4024
4025 let gathered = registry.gather();
4026 assert_eq!(family_names(&gathered), summary);
4027 assert_eq!(invalid(&gathered), 0.0);
4029 assert_eq!(invalid(®istry.gather()), 1.0);
4030
4031 set_shard_metrics(&cfg, ShardMetricsExport::Both);
4032 let gathered = registry.gather();
4033 assert!(summary.is_subset(&family_names(&gathered)));
4034 assert_eq!(invalid(&gathered), 2.0);
4035 assert_eq!(invalid(®istry.gather()), 2.0);
4036 }
4037
4038 #[mz_ore::test]
4039 fn counter_totals_are_unchanged_by_the_mode() {
4040 let (cfg, registry, shards) = metrics_with_shards(3);
4041 for (i, shard) in shards.iter().enumerate() {
4042 shard.blob_gets.inc_by(u64::cast_from(i) + 1);
4043 shard.blob_sets.inc();
4044 }
4045 let totals = |families: &[MetricFamily]| -> BTreeMap<&'static str, f64> {
4046 PER_SHARD_FAMILIES
4047 .iter()
4048 .filter_map(|f| match f.aggregate {
4049 ShardAggregate::Counter { total } => Some((total, scalar(families, total))),
4050 _ => None,
4051 })
4052 .collect()
4053 };
4054 let both = registry.gather();
4055 assert_eq!(totals(&both)["mz_persist_blob_gets"], 6.0);
4056
4057 for mode in ShardMetricsExport::ALL {
4060 set_shard_metrics(&cfg, mode);
4061 assert_eq!(totals(®istry.gather()), totals(&both), "{mode:?}");
4062 }
4063 }
4064
4065 #[mz_ore::test]
4066 fn each_shard_metrics_mode_exports_its_families() {
4067 let (cfg, registry, _shards) = metrics_with_shards(3);
4068 set_shard_metrics(&cfg, ShardMetricsExport::Both);
4069 let both = family_names(®istry.gather());
4070 let per_shard: BTreeSet<_> = PER_SHARD_FAMILIES
4071 .iter()
4072 .map(|f| f.name.to_string())
4073 .collect();
4074 let summary: BTreeSet<_> = both
4075 .iter()
4076 .filter(|n| {
4077 n.ends_with("_percentile")
4078 || n.ends_with("_sum")
4079 || n.ends_with("_topk")
4080 || *n == "mz_persist_batch_part_version_count"
4081 })
4082 .cloned()
4083 .collect();
4084 let always = always_exported();
4085 assert!(both.is_superset(&per_shard));
4086 assert!(both.is_superset(&always));
4087 assert!(!summary.is_empty());
4088 assert!(always.is_disjoint(&per_shard) && always.is_disjoint(&summary));
4089
4090 for mode in ShardMetricsExport::ALL {
4093 set_shard_metrics(&cfg, mode);
4094 let mut expected = both.clone();
4095 if !mode.per_shard() {
4096 expected.retain(|n| !per_shard.contains(n));
4097 }
4098 if !mode.summary() {
4099 expected.retain(|n| !summary.contains(n));
4100 }
4101 assert!(expected.is_superset(&always), "{mode:?}");
4102 assert_eq!(family_names(®istry.gather()), expected, "{mode:?}");
4103 }
4104 }
4105
4106 #[mz_ore::test]
4107 #[cfg_attr(miri, ignore)] fn summary_scrape_is_flat_in_shard_count() {
4109 let scrape = |n: u64, mode: ShardMetricsExport| {
4110 let (cfg, registry, _shards) = metrics_with_shards(n);
4111 set_shard_metrics(&cfg, mode);
4112 let families = registry.gather();
4113 let series: usize = families.iter().map(|f| f.get_metric().len()).sum();
4114 let body = prometheus::TextEncoder::new()
4115 .encode_to_string(&families)
4116 .expect("encodable");
4117 (series, body.len())
4118 };
4119 let (few_series, few_bytes) = scrape(10, ShardMetricsExport::Summary);
4120 let (many_series, many_bytes) = scrape(10_000, ShardMetricsExport::Summary);
4121 let (both_series, both_bytes) = scrape(10_000, ShardMetricsExport::Both);
4122 assert_eq!(few_series, many_series);
4123 assert!(
4124 both_series >= many_series + PER_SHARD_FAMILIES.len() * 10_000,
4125 "{both_series} vs {many_series}"
4126 );
4127 assert!(many_bytes < few_bytes + 4096, "{many_bytes} vs {few_bytes}");
4129 assert!(
4130 both_bytes > 100 * many_bytes,
4131 "{both_bytes} vs {many_bytes}"
4132 );
4133 }
4134
4135 #[mz_ore::test]
4136 fn shard_info_lists_live_shards_when_enabled() {
4137 let (cfg, registry, mut shards) = metrics_with_shards(3);
4138 let info =
4139 |registry: &MetricsRegistry| gauge_set(®istry.gather(), SHARD_INFO_NAME, "name");
4140 let mut updates = ConfigUpdates::default();
4141 updates.add(&SHARD_INFO_METRIC, true);
4142 cfg.apply_from(&updates);
4143 for mode in ShardMetricsExport::ALL {
4145 set_shard_metrics(&cfg, mode);
4146 let expected = ["s1", "s2", "s3"].map(|n| (n.to_string(), 1)).into();
4147 assert_eq!(info(®istry), expected, "{mode:?}");
4148 }
4149
4150 shards.pop();
4151 assert_eq!(info(®istry).len(), 2);
4152 }
4153
4154 fn set_enable_regex(cfg: &PersistConfig, regex: &str) {
4155 let mut updates = ConfigUpdates::default();
4156 updates.add(&PER_SHARD_METRICS_ENABLE_REGEX, regex);
4157 cfg.apply_from(&updates);
4158 }
4159
4160 fn per_shard_series(
4162 families: &[MetricFamily],
4163 ) -> BTreeMap<(String, Vec<(String, String)>), prometheus::proto::Metric> {
4164 families
4165 .iter()
4166 .filter(|f| PER_SHARD_FAMILIES.iter().any(|p| p.name == f.name()))
4167 .flat_map(|f| {
4168 f.get_metric().iter().map(|m| {
4169 let labels = m
4170 .get_label()
4171 .iter()
4172 .map(|l| (l.name().to_string(), l.value().to_string()))
4173 .collect();
4174 ((f.name().to_string(), labels), m.clone())
4175 })
4176 })
4177 .collect()
4178 }
4179
4180 fn exported_shard_names(families: &[MetricFamily]) -> BTreeSet<String> {
4182 per_shard_series(families)
4183 .into_keys()
4184 .map(|(_, labels)| {
4185 labels
4186 .into_iter()
4187 .find(|(k, _)| k == "name")
4188 .expect("per-shard series have a name label")
4189 .1
4190 })
4191 .collect()
4192 }
4193
4194 #[mz_ore::test]
4195 fn enable_regex_keeps_matching_shards_unchanged() {
4196 let (cfg, registry, shards) = metrics_with_shards(5);
4197 set_shard_metrics(&cfg, ShardMetricsExport::Both);
4198 let both = registry.gather();
4199 set_shard_metrics(&cfg, ShardMetricsExport::Summary);
4200 let summary = registry.gather();
4201 assert!(exported_shard_names(&summary).is_empty());
4202
4203 let shard_id = shards[2].shard_id.to_string();
4206 set_enable_regex(&cfg, &shard_id);
4207 let enabled = registry.gather();
4208 let expected: BTreeMap<_, _> = per_shard_series(&both)
4209 .into_iter()
4210 .filter(|((_, labels), _)| labels.contains(&("shard".into(), shard_id.clone())))
4211 .collect();
4212 assert_eq!(expected.len(), PER_SHARD_FAMILIES.len());
4213 assert_eq!(per_shard_series(&enabled), expected);
4214 assert_eq!(family_names(&enabled), {
4215 let mut names = family_names(&summary);
4216 names.extend(PER_SHARD_FAMILIES.iter().map(|f| f.name.to_string()));
4217 names
4218 });
4219
4220 set_enable_regex(&cfg, "^s2$");
4222 assert_eq!(
4223 exported_shard_names(®istry.gather()),
4224 BTreeSet::from(["s2".to_string()])
4225 );
4226 set_enable_regex(&cfg, "^s(1|4)$");
4227 assert_eq!(
4228 exported_shard_names(®istry.gather()),
4229 BTreeSet::from(["s1".to_string(), "s4".to_string()])
4230 );
4231
4232 set_enable_regex(&cfg, "");
4234 assert_eq!(family_names(®istry.gather()), family_names(&summary));
4235
4236 set_enable_regex(&cfg, "^s2$");
4238 set_shard_metrics(&cfg, ShardMetricsExport::None);
4239 let gathered = registry.gather();
4240 assert_eq!(
4241 exported_shard_names(&gathered),
4242 BTreeSet::from(["s2".to_string()])
4243 );
4244 assert!(gathered.iter().all(|f| !f.name().ends_with("_percentile")));
4245 set_shard_metrics(&cfg, ShardMetricsExport::Both);
4246 assert_eq!(exported_shard_names(®istry.gather()).len(), 5);
4247 }
4248
4249 #[mz_ore::test]
4250 fn unanchored_enable_regex_over_matches() {
4251 let cfg = PersistConfig::new_for_tests();
4252 let registry = MetricsRegistry::new();
4253 let metrics = Metrics::new(&cfg, ®istry);
4254 let shard = |name: &str| metrics.shards.shard(&ShardId::new(), name);
4255 let _named: Vec<_> = (1..=10).map(|i| shard(&format!("src{i}"))).collect();
4258 set_shard_metrics(&cfg, ShardMetricsExport::Summary);
4259
4260 set_enable_regex(&cfg, "src1");
4263 assert_eq!(
4264 exported_shard_names(®istry.gather()),
4265 BTreeSet::from(["src1".to_string(), "src10".to_string()])
4266 );
4267
4268 let target = shard("by-id");
4273 let fragment = target.shard_id.to_string()[3..9].to_string();
4274 let decoy = shard(&format!("t-{fragment}-t"));
4275 assert!(!decoy.shard_id.to_string().contains(&fragment));
4276 set_enable_regex(&cfg, &fragment);
4277 let kept = exported_shard_names(®istry.gather());
4278 assert!(kept.contains(&target.name), "{kept:?}");
4279 assert!(kept.contains(&decoy.name), "{kept:?}");
4280 }
4281
4282 #[mz_ore::test]
4283 fn invalid_enable_regex_fails_closed() {
4284 let (cfg, registry, _shards) = metrics_with_shards(3);
4285 set_shard_metrics(&cfg, ShardMetricsExport::Summary);
4286 let summary = family_names(®istry.gather());
4287 let invalid = |families: &[MetricFamily]| {
4288 scalar(families, "mz_persist_per_shard_metrics_regex_invalid")
4289 };
4290
4291 set_enable_regex(&cfg, "(");
4292 let gathered = registry.gather();
4293 assert_eq!(family_names(&gathered), summary);
4294 assert_eq!(invalid(&gathered), 0.0);
4296 assert_eq!(invalid(®istry.gather()), 1.0);
4297
4298 set_enable_regex(&cfg, "^s1$");
4299 let gathered = registry.gather();
4300 assert_eq!(
4301 exported_shard_names(&gathered),
4302 BTreeSet::from(["s1".to_string()])
4303 );
4304 assert_eq!(invalid(&gathered), 2.0);
4305 assert_eq!(invalid(®istry.gather()), 2.0);
4306 }
4307
4308 fn gauge_count(families: &[MetricFamily], name: &str) -> usize {
4309 find(families, name).map_or(0, |f| f.get_metric().len())
4310 }
4311
4312 fn percentile(families: &[MetricFamily], name: &str, percentile: &str) -> u64 {
4314 gauge_set(families, name, "percentile")
4315 .into_iter()
4316 .find_map(|(p, v)| (p == percentile).then_some(v))
4317 .unwrap_or_else(|| panic!("no {percentile} in {name}"))
4318 }
4319
4320 #[mz_ore::test]
4321 fn shard_aggregates_fold_live_shards() {
4322 let registry = MetricsRegistry::new();
4323 let metrics = Metrics::new(&PersistConfig::new_for_tests(), ®istry);
4324 let mut shards: Vec<_> = (1..=12u64)
4325 .map(|i| {
4326 let shard = metrics.shards.shard(&ShardId::new(), &format!("s{i}"));
4327 shard.usage_current_state_batches_bytes.set(i * 100);
4328 shard
4329 })
4330 .collect();
4331 shards[0].set_batch_part_versions(["v1", "v1", "v2"].into_iter());
4332 shards[1].set_batch_part_versions(["v1"].into_iter());
4333
4334 let gathered = registry.gather();
4335 assert_eq!(scalar(&gathered, "mz_persist_shard_count"), 12.0);
4336 let percentile_families = gathered
4337 .iter()
4338 .filter(|f| {
4339 f.name().starts_with("mz_persist_shard_") && f.name().ends_with("_percentile")
4340 })
4341 .count();
4342 assert_eq!(percentile_families, shard_gauges().count());
4343 for (gauge, _) in shard_gauges() {
4344 let name = format!("{gauge}_percentile");
4345 assert_eq!(gauge_count(&gathered, &name), PERCENTILES.len(), "{name}");
4346 }
4347 let percentiles = "mz_persist_shard_usage_current_state_batches_bytes_percentile";
4348 assert_eq!(percentile(&gathered, percentiles, "min"), 100);
4349 assert_eq!(percentile(&gathered, percentiles, "p50"), 600);
4350 assert_eq!(percentile(&gathered, percentiles, "max"), 1200);
4351 let top_k = "mz_persist_shard_usage_current_state_batches_bytes_topk";
4352 let expected: BTreeSet<_> = shards[2..]
4353 .iter()
4354 .map(|s| {
4355 (
4356 s.shard_id.to_string(),
4357 s.usage_current_state_batches_bytes.get(),
4358 )
4359 })
4360 .collect();
4361 assert_eq!(gauge_set(&gathered, top_k, "shard"), expected);
4362 assert_eq!(
4363 gauge_set(&gathered, "mz_persist_batch_part_version_count", "version"),
4364 BTreeSet::from([("v1".to_string(), 3), ("v2".to_string(), 1)])
4365 );
4366
4367 let largest = shards.pop().expect("non-empty");
4370 let largest_id = largest.shard_id.to_string();
4371 drop(largest);
4372 shards[0].set_batch_part_versions(["v1"].into_iter());
4373 let gathered = registry.gather();
4374 assert_eq!(scalar(&gathered, "mz_persist_shard_count"), 11.0);
4375 assert_eq!(percentile(&gathered, percentiles, "max"), 1100);
4376 let top_k_shards = gauge_set(&gathered, top_k, "shard");
4377 assert_eq!(top_k_shards.len(), SHARD_TOP_K);
4378 assert!(top_k_shards.iter().all(|(shard, _)| *shard != largest_id));
4379 assert_eq!(
4380 gauge_set(&gathered, "mz_persist_batch_part_version_count", "version"),
4381 BTreeSet::from([("v1".to_string(), 2)])
4382 );
4383 }
4384
4385 #[mz_ore::test]
4386 fn process_counters_survive_shard_drop() {
4387 let cfg = PersistConfig::new_for_tests();
4388 set_shard_metrics(&cfg, ShardMetricsExport::Both);
4389 let registry = MetricsRegistry::new();
4390 let metrics = Metrics::new(&cfg, ®istry);
4391 let a = metrics.shards.shard(&ShardId::new(), "a");
4392 let b = metrics.shards.shard(&ShardId::new(), "b");
4393 a.blob_gets.inc_by(5);
4394 b.blob_gets.inc();
4395 a.encoded_diff_size.inc_by(100);
4396
4397 let gathered = registry.gather();
4398 assert_eq!(scalar(&gathered, "mz_persist_blob_gets"), 6.0);
4399 assert_eq!(gauge_count(&gathered, "mz_persist_shard_blob_gets"), 2);
4400
4401 drop(a);
4402 let gathered = registry.gather();
4403 assert_eq!(scalar(&gathered, "mz_persist_blob_gets"), 6.0);
4404 assert_eq!(scalar(&gathered, "mz_persist_diff_size_bytes"), 100.0);
4405 assert_eq!(gauge_count(&gathered, "mz_persist_shard_blob_gets"), 1);
4406 }
4407}