Skip to main content

mz_adapter/
metrics.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::borrow::Cow;
11
12use mz_controller_types::ClusterId;
13use mz_ore::metric;
14use mz_ore::metrics::{
15    MakeCollector, MakeCollectorOpts, MetricTag, MetricVisibility, MetricsRegistry, UIntGauge,
16    remove_children_with_label,
17};
18use mz_ore::stats::{histogram_milliseconds_buckets, histogram_seconds_buckets};
19use mz_sql::ast::{
20    AsOf, AstInfo, CopyRelation, CopyStatement, SelectStatement, Statement, StatementKind,
21    SubscribeOutput, SubscribeStatement,
22};
23use mz_sql::session::hint::ApplicationNameHint;
24use mz_sql::session::user::User;
25use mz_sql::session::vars::IsolationLevel;
26use mz_sql_parser::ast::statement_kind_label_value;
27use prometheus::core::{AtomicU64, GenericCounter};
28use prometheus::{Histogram, HistogramVec, IntCounter, IntCounterVec, IntGaugeVec};
29
30use crate::statement_logging::StatementExecutionStrategy;
31
32pub(crate) const OCC_CALLER_SESSION: &str = "session";
33pub(crate) const OCC_CALLER_BACKGROUND: &str = "background";
34
35#[derive(Debug, Clone)]
36pub struct Metrics {
37    pub query_total: IntCounterVec,
38    pub query_policy_queries: IntCounterVec,
39    pub active_sessions: IntGaugeVec,
40    pub active_subscribes: IntGaugeVec,
41    pub active_internal_subscribes: IntGaugeVec,
42    pub active_copy_tos: IntGaugeVec,
43    pub queue_busy_seconds: Histogram,
44    pub commands: IntCounterVec,
45    pub storage_usage_collection_time_seconds: Histogram,
46    pub arrangement_sizes_collection_time_seconds: Histogram,
47    pub arrangement_sizes_rows_written: IntCounter,
48    pub hydration_history_mutations: IntCounterVec,
49    pub hydration_history_retention_batch_full: IntCounter,
50    pub hydration_history_rows_affected: IntCounterVec,
51    pub hydration_history_sweep_duration_seconds: Histogram,
52    pub subscribe_outputs: IntCounterVec,
53    pub as_of_queries: IntCounterVec,
54    pub canceled_peeks: IntCounter,
55    pub linearize_message_seconds: HistogramVec,
56    pub linearize_read_immediate_seconds: Histogram,
57    pub linearize_read_delayed_seconds: Histogram,
58    pub linearize_read_fast_path: IntCounter,
59    pub frontend_transaction_completions: IntCounter,
60    pub frontend_transaction_waits: IntCounter,
61    pub statement_logging_records: IntCounterVec,
62    pub statement_logging_unsampled_bytes: IntCounter,
63    pub statement_logging_actual_bytes: IntCounter,
64    pub message_batch: Histogram,
65    pub message_handling: HistogramVec,
66    pub optimization_notices: IntCounterVec,
67    pub append_table_duration_seconds: Histogram,
68    pub webhook_validation_reduce_failures: IntCounterVec,
69    pub webhook_get_appender: IntCounter,
70    pub row_set_finishing_seconds: Histogram,
71    pub session_startup_table_writes_seconds: Histogram,
72    pub parse_seconds: Histogram,
73    pub pgwire_message_processing_seconds: HistogramVec,
74    pub result_rows_first_to_last_byte_seconds: HistogramVec,
75    pub pgwire_ensure_transaction_seconds: HistogramVec,
76    pub catalog_snapshot_seconds: HistogramVec,
77    pub catalog_snapshot_cache: IntCounterVec,
78    pub catalog_arc_strong_count: UIntGauge,
79    pub catalog_arc_weak_count: UIntGauge,
80    pub pgwire_recv_scheduling_delay_ms: HistogramVec,
81    pub catalog_transact_seconds: HistogramVec,
82    pub catalog_transact_phase_seconds: HistogramVec,
83    pub apply_catalog_implications_seconds: Histogram,
84    pub group_commit_catalog_upper_seconds: Histogram,
85    pub occ_retry_count: HistogramVec,
86    pub by_cluster: ClusterLabeledMetrics,
87}
88
89impl Metrics {
90    pub(crate) fn register_into(registry: &MetricsRegistry) -> Self {
91        let linearize_message_seconds: HistogramVec = registry.register(metric!(
92            name: "mz_linearize_message_seconds",
93            help: "The number of seconds it takes to linearize strict serializable messages",
94            var_labels: ["type", "immediately_handled"],
95            buckets: histogram_seconds_buckets(0.000_128, 8.0),
96        ));
97        Self {
98            query_total: registry.register(metric!(
99                name: "mz_query_total",
100                help: "The total number of queries issued of the given type since process start.",
101                var_labels: ["session_type", "statement_type"],
102                visibility: MetricVisibility::Public,
103                tags: [MetricTag::Environment],
104            )),
105            query_policy_queries: registry.register(metric!(
106                name: "mz_query_policy_queries_total",
107                help: "Queries rejected by an enforced query policy or only warned by observe-only policies. Each query is counted once.",
108                var_labels: ["outcome"],
109            )),
110            active_sessions: registry.register(metric!(
111                name: "mz_active_sessions",
112                help: "The number of active coordinator sessions.",
113                var_labels: ["session_type"],
114                visibility: MetricVisibility::Public,
115                tags: [MetricTag::Environment],
116            )),
117            active_subscribes: registry.register(metric!(
118                name: "mz_active_subscribes",
119                help: "The number of active SUBSCRIBE queries.",
120                var_labels: ["session_type"],
121                visibility: MetricVisibility::Public,
122                tags: [MetricTag::Environment],
123            )),
124            active_internal_subscribes: registry.register(metric!(
125                name: "mz_active_internal_subscribes",
126                help: "The number of active internal subscribes used by read-then-write operations and background maintenance.",
127                var_labels: ["session_type"],
128            )),
129            active_copy_tos: registry.register(metric!(
130                name: "mz_active_copy_tos",
131                help: "The number of active COPY TO queries.",
132                var_labels: ["session_type"],
133            )),
134            queue_busy_seconds: registry.register(metric!(
135                name: "mz_coord_queue_busy_seconds",
136                help: "The number of seconds the coord queue was processing before it was empty. This is a sampled metric and does not measure the full coord queue wait/idle times.",
137                buckets: histogram_seconds_buckets(0.000_128, 32.0)
138            )),
139            commands: registry.register(metric!(
140                name: "mz_adapter_commands",
141                help: "The total number of adapter commands issued of the given type since process start.",
142                var_labels: ["command_type", "status", "application_name"],
143                visibility: MetricVisibility::Public,
144                tags: [MetricTag::Environment],
145            )),
146            storage_usage_collection_time_seconds: registry.register(metric!(
147                name: "mz_storage_usage_collection_time_seconds",
148                help: "The number of seconds the coord spends collecting usage metrics from storage.",
149                buckets: histogram_seconds_buckets(0.000_128, 8.0)
150            )),
151            arrangement_sizes_collection_time_seconds: registry.register(metric!(
152                name: "mz_arrangement_sizes_collection_time_seconds",
153                help: "Seconds to read mz_object_arrangement_sizes and prepare history records for one snapshot.",
154                buckets: histogram_seconds_buckets(0.000_128, 8.0)
155            )),
156            arrangement_sizes_rows_written: registry.register(metric!(
157                name: "mz_arrangement_sizes_rows_written_total",
158                help: "Total rows appended to mz_object_arrangement_size_history since process start.",
159            )),
160            hydration_history_mutations: registry.register(metric!(
161                name: "mz_hydration_history_mutations_total",
162                help: "Total hydration-history collection and retention mutations since process start.",
163                var_labels: ["operation", "outcome"],
164            )),
165            hydration_history_retention_batch_full: registry.register(metric!(
166                name: "mz_hydration_history_retention_batch_full_total",
167                help: "Total hydration-history retention batches that were full. Repeated increments mean retention may not be keeping up with its schedule.",
168            )),
169            hydration_history_rows_affected: registry.register(metric!(
170                name: "mz_hydration_history_rows_affected_total",
171                help: "Total rows changed by hydration-history maintenance since process start.",
172                var_labels: ["action"],
173            )),
174            hydration_history_sweep_duration_seconds: registry.register(metric!(
175                name: "mz_hydration_history_sweep_duration_seconds",
176                help: "Wall time of a complete hydration-history collection and retention sweep.",
177                buckets: histogram_seconds_buckets(0.128, 1024.0),
178            )),
179            subscribe_outputs: registry.register(metric!(
180                name: "mz_subscribe_outputs",
181                help: "The total number of different subscribe outputs used",
182                var_labels: ["session_type", "subscribe_output"],
183            )),
184            as_of_queries: registry.register(metric!(
185                name: "mz_as_of_queries_total",
186                help: "The total number of SELECT and SUBSCRIBE executions with an AS OF clause.",
187                var_labels: ["session_type", "kind", "statement", "application_name"],
188            )),
189            canceled_peeks: registry.register(metric!(
190                name: "mz_canceled_peeks_total",
191                help: "The total number of canceled peeks since process start.",
192            )),
193            linearize_read_immediate_seconds: linearize_message_seconds.with_label_values(&["read", "true"]),
194            linearize_read_delayed_seconds: linearize_message_seconds.with_label_values(&["read", "false"]),
195            linearize_message_seconds,
196            linearize_read_fast_path: registry.register(metric!(
197                name: "mz_linearize_read_fast_path_total",
198                help: "The number of ordinary strict serializable reads already linearized at transaction end",
199            )),
200            frontend_transaction_completions: registry.register(metric!(
201                name: "mz_frontend_transaction_completions_total",
202                help: "Read-only transaction completion attempts owned by the session.",
203            )),
204            frontend_transaction_waits: registry.register(metric!(
205                name: "mz_frontend_transaction_waits_total",
206                help: "Session-owned transaction completions that need a fresh oracle check.",
207            )),
208            statement_logging_records: registry.register(metric! {
209                name: "mz_statement_logging_record_count",
210                help: "The total number of SQL statements tagged with whether or not they were recorded.",
211                var_labels: ["sample"],
212            }),
213            statement_logging_unsampled_bytes: registry.register(metric!(
214                name: "mz_statement_logging_unsampled_bytes",
215                help: "The total amount of SQL text that would have been logged if statement logging were unsampled.",
216            )),
217            statement_logging_actual_bytes: registry.register(metric!(
218                name: "mz_statement_logging_actual_bytes",
219                help: "The total amount of SQL text that was logged by statement logging.",
220            )),
221            message_batch: registry.register(metric!(
222                name: "mz_coordinator_message_batch_size",
223                help: "Message batch size handled by the coordinator.",
224                buckets: vec![0., 1., 2., 3., 4., 6., 8., 12., 16., 24., 32., 48., 64.],
225            )),
226            message_handling: registry.register(metric!(
227                name: "mz_slow_message_handling",
228                help: "Latency for ALL coordinator messages. 'slow' is in the name for legacy reasons, but is not accurate.",
229                var_labels: ["message_kind"],
230                buckets: histogram_seconds_buckets(0.000_128, 512.0),
231            )),
232            optimization_notices: registry.register(metric!(
233                name: "mz_optimization_notices",
234                help: "Number of optimization notices per notice type.",
235                var_labels: ["notice_type"],
236            )),
237            append_table_duration_seconds: registry.register(metric!(
238                name: "mz_append_table_duration_seconds",
239                help: "Latency for appending to any (user or system) table.",
240                buckets: histogram_seconds_buckets(0.128, 32.0),
241            )),
242            webhook_validation_reduce_failures: registry.register(metric!(
243                name: "mz_webhook_validation_reduce_failures",
244                help: "Count of how many times we've failed to reduce a webhook source's CHECK statement.",
245                var_labels: ["reason"],
246            )),
247            webhook_get_appender: registry.register(metric!(
248                name: "mz_webhook_get_appender_count",
249                help: "Count of getting a webhook appender from the Coordinator.",
250            )),
251            row_set_finishing_seconds: registry.register(metric!(
252                name: "mz_row_set_finishing_seconds",
253                help: "The time it takes to run RowSetFinishing::finish.",
254                buckets: histogram_seconds_buckets(0.000_128, 16.0),
255            )),
256            session_startup_table_writes_seconds: registry.register(metric!(
257                name: "mz_session_startup_table_writes_seconds",
258                help: "If we had to wait for builtin table writes before processing a query, how long did we wait for.",
259                buckets: histogram_seconds_buckets(0.000_008, 4.0),
260            )),
261            parse_seconds: registry.register(metric!(
262                name: "mz_parse_seconds",
263                help: "The time it takes to parse a SQL statement. (Works for both Simple Queries and the Extended Query protocol.)",
264                buckets: histogram_seconds_buckets(0.001, 8.0),
265            )),
266            pgwire_message_processing_seconds: registry.register(metric!(
267                name: "mz_pgwire_message_processing_seconds",
268                help: "The time it takes to process each of the pgwire message types, measured in the Adapter frontend",
269                var_labels: ["message_type"],
270                buckets: histogram_seconds_buckets(0.001, 512.0),
271            )),
272            result_rows_first_to_last_byte_seconds: registry.register(metric!(
273                name: "mz_result_rows_first_to_last_byte_seconds",
274                help: "The time from just before sending the first result row to sending a final response message after having successfully flushed the last result row to the connection. (This can span multiple FETCH statements.) (This is never observed for unbounded SUBSCRIBEs, i.e., which have no last result row.)",
275                var_labels: ["statement_type"],
276                buckets: histogram_seconds_buckets(0.001, 8192.0),
277            )),
278            pgwire_ensure_transaction_seconds: registry.register(metric!(
279                name: "mz_pgwire_ensure_transaction_seconds",
280                help: "The time it takes to run `ensure_transactions` when processing pgwire messages.",
281                var_labels: ["message_type"],
282                buckets: histogram_seconds_buckets(0.001, 512.0),
283            )),
284            catalog_snapshot_seconds: registry.register(metric!(
285                name: "mz_catalog_snapshot_seconds",
286                help: "The time it takes to fetch a catalog snapshot from the Coordinator. \
287                       Only observed on session snapshot cache misses.",
288                var_labels: ["context"],
289                buckets: histogram_seconds_buckets(0.001, 512.0),
290            )),
291            catalog_snapshot_cache: registry.register(metric!(
292                name: "mz_catalog_snapshot_cache",
293                help: "Hits and misses of the session-side catalog snapshot cache. A miss \
294                       costs a Coordinator round-trip.",
295                var_labels: ["context", "result"],
296            )),
297            catalog_arc_strong_count: registry.register(metric!(
298                name: "mz_catalog_arc_strong_count",
299                help: "The number of strong references to the current catalog snapshot: roughly, \
300                       in-flight users plus a small constant baseline.",
301            )),
302            catalog_arc_weak_count: registry.register(metric!(
303                name: "mz_catalog_arc_weak_count",
304                help: "The number of weak references to the current catalog snapshot: sessions \
305                       whose snapshot cache points at the current catalog version (older \
306                       versions are not counted). Drops on catalog changes and recovers as \
307                       session caches repopulate.",
308            )),
309            pgwire_recv_scheduling_delay_ms: registry.register(metric!(
310                name: "mz_pgwire_recv_scheduling_delay_ms",
311                help: "The time between a pgwire connection's receiver task being woken up by incoming data and getting polled.",
312                var_labels: ["message_type"],
313                buckets: histogram_milliseconds_buckets(0.128, 512000.),
314            )),
315            catalog_transact_seconds: registry.register(metric!(
316                name: "mz_catalog_transact_seconds",
317                help: "The time it takes to run various catalog transact methods.",
318                var_labels: ["method"],
319                buckets: histogram_seconds_buckets(0.001, 32.0),
320            )),
321            catalog_transact_phase_seconds: registry.register(metric!(
322                name: "mz_catalog_transact_phase_seconds",
323                help: "Wall time of the individual phases of a coordinator catalog transaction, to attribute where transact time is spent. Phases overlap and do not sum to mz_catalog_transact_seconds. The transact phase includes the durable catalog sync and commit.",
324                var_labels: ["phase"],
325                buckets: histogram_seconds_buckets(0.000_128, 32.0),
326            )),
327            apply_catalog_implications_seconds: registry.register(metric!(
328                name: "mz_apply_catalog_implications_seconds",
329                help: "The time it takes to apply catalog implications.",
330                buckets: histogram_seconds_buckets(0.001, 32.0),
331            )),
332            group_commit_catalog_upper_seconds: registry.register(metric!(
333                name: "mz_group_commit_catalog_upper_seconds",
334                help: "The time it takes to advance the catalog shard upper for a txns-shard write (group commits and table register/forget).",
335                buckets: histogram_seconds_buckets(0.001, 32.0),
336            )),
337            occ_retry_count: registry.register(metric!(
338                name: "mz_occ_read_then_write_retry_count",
339                help: "Number of OCC retries per read-then-write operation.",
340                var_labels: ["caller"],
341                buckets: vec![
342                    0., 1., 2., 3., 5., 10., 25., 50., 100., 200., 300., 500., 750., 1000.,
343                ],
344            )),
345            by_cluster: ClusterLabeledMetrics::register_into(registry),
346        }
347    }
348
349    pub(crate) fn row_set_finishing_seconds(&self) -> Histogram {
350        self.row_set_finishing_seconds.clone()
351    }
352
353    pub(crate) fn session_metrics(&self) -> SessionMetrics {
354        SessionMetrics {
355            row_set_finishing_seconds: self.row_set_finishing_seconds(),
356            session_startup_table_writes_seconds: self.session_startup_table_writes_seconds.clone(),
357            query_total: self.query_total.clone(),
358            subscribe_outputs: self.subscribe_outputs.clone(),
359            as_of_queries: self.as_of_queries.clone(),
360            by_cluster: self.by_cluster.clone(),
361            query_policy_queries: self.query_policy_queries.clone(),
362            optimization_notices: self.optimization_notices.clone(),
363            statement_logging_records: self.statement_logging_records.clone(),
364            statement_logging_unsampled_bytes: self.statement_logging_unsampled_bytes.clone(),
365            statement_logging_actual_bytes: self.statement_logging_actual_bytes.clone(),
366        }
367    }
368}
369
370/// Metrics to be accessed from a [`crate::session::Session`].
371#[derive(Debug, Clone)]
372pub struct SessionMetrics {
373    row_set_finishing_seconds: Histogram,
374    session_startup_table_writes_seconds: Histogram,
375    query_total: IntCounterVec,
376    subscribe_outputs: IntCounterVec,
377    as_of_queries: IntCounterVec,
378    by_cluster: ClusterLabeledMetrics,
379    query_policy_queries: IntCounterVec,
380    optimization_notices: IntCounterVec,
381    statement_logging_records: IntCounterVec,
382    statement_logging_unsampled_bytes: IntCounter,
383    statement_logging_actual_bytes: IntCounter,
384}
385
386impl SessionMetrics {
387    pub(crate) fn row_set_finishing_seconds(&self) -> &Histogram {
388        &self.row_set_finishing_seconds
389    }
390
391    pub(crate) fn session_startup_table_writes_seconds(&self) -> &Histogram {
392        &self.session_startup_table_writes_seconds
393    }
394
395    pub(crate) fn query_total(&self, label_values: &[&str]) -> GenericCounter<AtomicU64> {
396        self.query_total.with_label_values(label_values)
397    }
398
399    pub(crate) fn subscribe_outputs(&self, label_values: &[&str]) -> GenericCounter<AtomicU64> {
400        self.subscribe_outputs.with_label_values(label_values)
401    }
402
403    pub(crate) fn as_of_queries(&self, label_values: &[&str]) -> GenericCounter<AtomicU64> {
404        self.as_of_queries.with_label_values(label_values)
405    }
406
407    pub(crate) fn query_policy_queries(&self, outcome: &str) -> GenericCounter<AtomicU64> {
408        self.query_policy_queries.with_label_values(&[outcome])
409    }
410
411    pub(crate) fn by_cluster(&self) -> &ClusterLabeledMetrics {
412        &self.by_cluster
413    }
414
415    pub(crate) fn optimization_notices(&self, label_values: &[&str]) -> GenericCounter<AtomicU64> {
416        self.optimization_notices.with_label_values(label_values)
417    }
418
419    pub(crate) fn statement_logging_records(
420        &self,
421        label_values: &[&str],
422    ) -> GenericCounter<AtomicU64> {
423        self.statement_logging_records
424            .with_label_values(label_values)
425    }
426
427    pub(crate) fn statement_logging_unsampled_bytes(&self) -> &IntCounter {
428        &self.statement_logging_unsampled_bytes
429    }
430
431    pub(crate) fn statement_logging_actual_bytes(&self) -> &IntCounter {
432        &self.statement_logging_actual_bytes
433    }
434}
435
436pub(crate) fn session_type_label_value(user: &User) -> &'static str {
437    match user.is_internal() {
438        true => "system",
439        false => "user",
440    }
441}
442
443pub fn statement_type_label_value<T>(stmt: &Statement<T>) -> &'static str
444where
445    T: AstInfo,
446{
447    statement_kind_label_value(StatementKind::from(stmt))
448}
449
450pub(crate) fn subscribe_output_label_value<T>(output: &SubscribeOutput<T>) -> &'static str
451where
452    T: AstInfo,
453{
454    match output {
455        SubscribeOutput::Diffs => "diffs",
456        SubscribeOutput::WithinTimestampOrderBy { .. } => "within_timestamp_order_by",
457        SubscribeOutput::EnvelopeUpsert { .. } => "envelope_upsert",
458        SubscribeOutput::EnvelopeDebezium { .. } => "envelope_debezium",
459    }
460}
461
462/// Returns the `mz_as_of_queries_total` label values for an execution of `stmt`, or `None` if
463/// `stmt` is not a `SELECT` or `SUBSCRIBE` with an `AS OF` clause. A `COPY` counts as the
464/// statement it copies.
465pub(crate) fn as_of_query_label_values<T>(
466    session_type: &'static str,
467    application_name: ApplicationNameHint,
468    stmt: &Statement<T>,
469) -> Option<[&'static str; 4]>
470where
471    T: AstInfo,
472{
473    let (as_of, statement) = match stmt {
474        Statement::Select(SelectStatement {
475            as_of: Some(as_of), ..
476        })
477        | Statement::Copy(CopyStatement {
478            relation:
479                CopyRelation::Select(SelectStatement {
480                    as_of: Some(as_of), ..
481                }),
482            ..
483        }) => (as_of, "select"),
484        Statement::Subscribe(SubscribeStatement {
485            as_of: Some(as_of), ..
486        })
487        | Statement::Copy(CopyStatement {
488            relation:
489                CopyRelation::Subscribe(SubscribeStatement {
490                    as_of: Some(as_of), ..
491                }),
492            ..
493        }) => (as_of, "subscribe"),
494        _ => return None,
495    };
496    let kind = match as_of {
497        AsOf::At(_) => "at",
498        AsOf::AtLeast(_) => "at_least",
499    };
500    Some([session_type, kind, statement, application_name.as_str()])
501}
502
503/// Adapter metrics whose series carry a cluster id label.
504///
505/// Series are created on first observation, as for any labeled metric, and
506/// `remove_cluster` deletes a dropped cluster's series from every vec that
507/// `register` put here.
508#[derive(Debug, Clone)]
509pub struct ClusterLabeledMetrics {
510    time_to_first_row_seconds: HistogramVec,
511    determine_timestamp: IntCounterVec,
512    timestamp_difference_for_bounded_staleness_ms: HistogramVec,
513    /// Every vec above with the label that carries its cluster id. `register`
514    /// is the only way in, so a vec registered any other way is not swept.
515    delete_on_cluster_drop: Vec<ClusterLabeledVec>,
516}
517
518/// A metric vec with the name of the label that carries the cluster id.
519#[derive(Debug, Clone)]
520enum ClusterLabeledVec {
521    Histogram(HistogramVec, &'static str),
522    Counter(IntCounterVec, &'static str),
523}
524
525impl ClusterLabeledVec {
526    fn delete_cluster(&self, cluster: &str) {
527        match self {
528            Self::Histogram(vec, label) => remove_children_with_label(vec, label, cluster),
529            Self::Counter(vec, label) => remove_children_with_label(vec, label, cluster),
530        }
531    }
532}
533
534impl ClusterLabeledMetrics {
535    fn register_into(registry: &MetricsRegistry) -> Self {
536        let mut vecs = Vec::new();
537        Self {
538            time_to_first_row_seconds: Self::register(
539                registry,
540                &mut vecs,
541                ClusterLabeledVec::Histogram,
542                "instance_id",
543                metric! {
544                    name: "mz_time_to_first_row_seconds",
545                    help: "Latency of an execute for a successful query from pgwire's perspective",
546                    var_labels: ["instance_id", "isolation_level", "strategy", "application_name"],
547                    // NOTE: Measurements below 512 microseconds are negligible, so omit those buckets.
548                    buckets: histogram_seconds_buckets(0.000_512, 32.0)
549                },
550            ),
551            determine_timestamp: Self::register(
552                registry,
553                &mut vecs,
554                ClusterLabeledVec::Counter,
555                "compute_instance",
556                metric!(
557                    name: "mz_determine_timestamp",
558                    help: "The total number of calls to determine_timestamp.",
559                    var_labels: ["respond_immediately", "isolation_level", "compute_instance"],
560                ),
561            ),
562            timestamp_difference_for_bounded_staleness_ms: Self::register(
563                registry,
564                &mut vecs,
565                ClusterLabeledVec::Histogram,
566                "compute_instance",
567                metric!(
568                    name: "mz_timestamp_difference_for_bounded_staleness_ms",
569                    help: "How much older bounded-staleness timestamps are compared to serializable, in milliseconds. Measures the actual staleness incurred.",
570                    var_labels: ["compute_instance"],
571                    buckets: histogram_milliseconds_buckets(1., 8000.),
572                ),
573            ),
574            delete_on_cluster_drop: vecs,
575        }
576    }
577
578    /// Registers `opts` and records it, wrapped by `wrap`, with `cluster_label`
579    /// as the label carrying its cluster id, so `remove_cluster` covers it.
580    ///
581    /// Panics if `cluster_label` is not a variable label of `opts`.
582    fn register<M: MakeCollector>(
583        registry: &MetricsRegistry,
584        vecs: &mut Vec<ClusterLabeledVec>,
585        wrap: fn(M, &'static str) -> ClusterLabeledVec,
586        cluster_label: &'static str,
587        opts: MakeCollectorOpts,
588    ) -> M {
589        assert!(
590            opts.opts
591                .variable_labels
592                .iter()
593                .any(|label| label == cluster_label),
594            "{cluster_label} is not a label of {}",
595            opts.opts.name
596        );
597        let vec: M = registry.register(opts);
598        // A metric vec is a handle onto shared state, so the clone sees the
599        // same children as the field.
600        vecs.push(wrap(vec.clone(), cluster_label));
601        vec
602    }
603
604    /// Deletes the series of `cluster_id`.
605    pub(crate) fn remove_cluster(&self, cluster_id: ClusterId) {
606        let cluster = cluster_id.to_string();
607        for vec in &self.delete_on_cluster_drop {
608            vec.delete_cluster(&cluster);
609        }
610    }
611
612    /// Statements without a cluster or strategy record under the "none" label value.
613    pub(crate) fn time_to_first_row_seconds(
614        &self,
615        cluster_id: Option<ClusterId>,
616        isolation_level: IsolationLevel,
617        strategy: Option<StatementExecutionStrategy>,
618        application_name: ApplicationNameHint,
619    ) -> Histogram {
620        let instance = match cluster_id {
621            Some(id) => Cow::Owned(id.to_string()),
622            None => Cow::Borrowed("none"),
623        };
624        self.time_to_first_row_seconds.with_label_values(&[
625            instance.as_ref(),
626            isolation_level.as_variant_str(),
627            strategy.map_or("none", |strategy| strategy.name()),
628            application_name.as_str(),
629        ])
630    }
631
632    pub(crate) fn determine_timestamp(
633        &self,
634        cluster_id: ClusterId,
635        respond_immediately: bool,
636        isolation_level: IsolationLevel,
637    ) -> GenericCounter<AtomicU64> {
638        self.determine_timestamp.with_label_values(&[
639            if respond_immediately { "true" } else { "false" },
640            isolation_level.as_variant_str(),
641            &cluster_id.to_string(),
642        ])
643    }
644
645    pub(crate) fn timestamp_difference_for_bounded_staleness_ms(
646        &self,
647        cluster_id: ClusterId,
648    ) -> Histogram {
649        self.timestamp_difference_for_bounded_staleness_ms
650            .with_label_values(&[&cluster_id.to_string()])
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use std::collections::BTreeSet;
657
658    use super::*;
659
660    const U1: ClusterId = ClusterId::User(1);
661    const U2: ClusterId = ClusterId::User(2);
662
663    fn families(registry: &MetricsRegistry) -> BTreeSet<String> {
664        registry
665            .gather()
666            .into_iter()
667            .map(|family| family.name().to_string())
668            .collect()
669    }
670
671    /// Names of the families with a series carrying `value` under any label.
672    fn families_with_label_value(registry: &MetricsRegistry, value: &str) -> BTreeSet<String> {
673        registry
674            .gather()
675            .into_iter()
676            .filter(|family| {
677                family
678                    .get_metric()
679                    .iter()
680                    .flat_map(|metric| metric.get_label())
681                    .any(|label| label.value() == value)
682            })
683            .map(|family| family.name().to_string())
684            .collect()
685    }
686
687    fn observe_first_row(
688        metrics: &ClusterLabeledMetrics,
689        cluster_id: Option<ClusterId>,
690        strategy: Option<StatementExecutionStrategy>,
691    ) {
692        metrics
693            .time_to_first_row_seconds(
694                cluster_id,
695                IsolationLevel::StrictSerializable,
696                strategy,
697                ApplicationNameHint::from_str("psql"),
698            )
699            .observe(0.1);
700    }
701
702    #[mz_ore::test]
703    fn dropping_a_cluster_removes_its_series() {
704        let registry = MetricsRegistry::new();
705        let metrics = ClusterLabeledMetrics::register_into(&registry);
706
707        observe_first_row(&metrics, Some(U1), None);
708        observe_first_row(
709            &metrics,
710            Some(U1),
711            Some(StatementExecutionStrategy::FastPath),
712        );
713        observe_first_row(&metrics, Some(U2), None);
714        metrics
715            .determine_timestamp(U1, true, IsolationLevel::Serializable)
716            .inc();
717        metrics
718            .timestamp_difference_for_bounded_staleness_ms(U1)
719            .observe(5.0);
720        assert_eq!(
721            families_with_label_value(&registry, "u1"),
722            families(&registry),
723            "every registered family needs a u1 series for the drop to be exercised"
724        );
725
726        metrics.remove_cluster(U1);
727
728        assert_eq!(
729            families_with_label_value(&registry, "u1"),
730            BTreeSet::new(),
731            "u1 series survived the drop"
732        );
733        assert_eq!(
734            families_with_label_value(&registry, "u2"),
735            BTreeSet::from(["mz_time_to_first_row_seconds".to_string()]),
736            "the other cluster's series must be untouched"
737        );
738    }
739
740    #[mz_ore::test]
741    fn statements_without_a_cluster_are_unaffected_by_drops() {
742        let registry = MetricsRegistry::new();
743        let metrics = ClusterLabeledMetrics::register_into(&registry);
744        observe_first_row(&metrics, None, Some(StatementExecutionStrategy::Constant));
745        observe_first_row(&metrics, Some(U1), None);
746        metrics.remove_cluster(U1);
747        assert_eq!(families_with_label_value(&registry, "u1"), BTreeSet::new());
748        assert_eq!(
749            families_with_label_value(&registry, "none"),
750            BTreeSet::from(["mz_time_to_first_row_seconds".to_string()])
751        );
752    }
753
754    #[mz_ore::test]
755    #[should_panic(expected = "is not a label of mz_test")]
756    fn registering_under_a_label_the_metric_lacks_panics() {
757        let registry = MetricsRegistry::new();
758        let _: IntCounterVec = ClusterLabeledMetrics::register(
759            &registry,
760            &mut Vec::new(),
761            ClusterLabeledVec::Counter,
762            "cluster_id",
763            metric!(
764                name: "mz_test",
765                help: "test",
766                var_labels: ["compute_instance"],
767            ),
768        );
769    }
770}