Skip to main content

mito2/
metrics.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub(crate) mod file_metadata;
16pub(crate) mod manifest_size;
17
18use std::time::{Duration, Instant};
19
20use lazy_static::lazy_static;
21use prometheus::*;
22use puffin::puffin_manager::stager::StagerNotifier;
23
24/// Stage label.
25pub const STAGE_LABEL: &str = "stage";
26/// Type label.
27pub const TYPE_LABEL: &str = "type";
28const CACHE_EVICTION_CAUSE: &str = "cause";
29/// Reason to flush.
30pub const FLUSH_REASON: &str = "reason";
31/// File type label.
32pub const FILE_TYPE_LABEL: &str = "file_type";
33/// Region worker id label.
34pub const WORKER_LABEL: &str = "worker";
35/// Partition label.
36pub const PARTITION_LABEL: &str = "partition";
37/// Staging dir type label.
38pub const STAGING_TYPE: &str = "index_staging";
39/// Recycle bin type label.
40pub const RECYCLE_TYPE: &str = "recycle_bin";
41
42/// Discard reason when an operation cannot admit extension index work.
43pub(crate) const INDEX_DISCARD_ADMISSION_REJECTED: &str = "admission_rejected";
44/// Discard reason when a creator exceeds its retained-memory allowance.
45pub(crate) const INDEX_DISCARD_MEMORY_BUDGET_EXCEEDED: &str = "memory_budget_exceeded";
46
47// Write metrics.
48lazy_static! {
49    /// Global write buffer size in bytes.
50    pub static ref WRITE_BUFFER_BYTES: IntGauge =
51        register_int_gauge!("greptime_mito_write_buffer_bytes", "mito write buffer bytes").unwrap();
52    /// Global memtable dictionary size in bytes.
53    pub static ref MEMTABLE_DICT_BYTES: IntGauge =
54        register_int_gauge!("greptime_mito_memtable_dict_bytes", "mito memtable dictionary size in bytes").unwrap();
55    /// Gauge for open regions in each worker.
56    pub static ref REGION_COUNT: IntGaugeVec =
57        register_int_gauge_vec!(
58            "greptime_mito_region_count",
59            "mito region count in each worker",
60            &[WORKER_LABEL],
61        ).unwrap();
62    /// Elapsed time to handle requests.
63    pub static ref HANDLE_REQUEST_ELAPSED: HistogramVec = register_histogram_vec!(
64            "greptime_mito_handle_request_elapsed",
65            "mito handle request elapsed",
66            &[TYPE_LABEL],
67            // 0.01 ~ 10000
68            exponential_buckets(0.01, 10.0, 7).unwrap(),
69        )
70        .unwrap();
71
72    /// Close-time WAL releases that the log store failed to admit.
73    pub static ref WAL_RELEASE_ADMISSION_FAILURE_TOTAL: IntCounter = register_int_counter!(
74        "greptime_mito_wal_release_admission_failure_total",
75        "Close-time WAL release admission failures"
76    ).unwrap();
77
78    // ------ Flush related metrics
79    /// Counter of scheduled flush requests.
80    /// Note that the flush scheduler may merge some flush requests.
81    pub static ref FLUSH_REQUESTS_TOTAL: IntCounterVec = register_int_counter_vec!(
82            "greptime_mito_flush_requests_total",
83            "mito flush requests total",
84            &[FLUSH_REASON]
85        )
86        .unwrap();
87    /// Counter of scheduled failed flush jobs.
88    pub static ref FLUSH_FAILURE_TOTAL: IntCounter =
89        register_int_counter!("greptime_mito_flush_failure_total", "mito flush failure total").unwrap();
90    /// Elapsed time of a flush job.
91    pub static ref FLUSH_ELAPSED: HistogramVec = register_histogram_vec!(
92            "greptime_mito_flush_elapsed",
93            "mito flush elapsed",
94            &[TYPE_LABEL],
95            // 1 ~ 625
96            exponential_buckets(1.0, 5.0, 6).unwrap(),
97        )
98        .unwrap();
99    /// Histogram of flushed bytes.
100    pub static ref FLUSH_BYTES_TOTAL: IntCounter =
101        register_int_counter!("greptime_mito_flush_bytes_total", "mito flush bytes total").unwrap();
102    /// Gauge for inflight flush tasks.
103    pub static ref INFLIGHT_FLUSH_COUNT: IntGauge =
104        register_int_gauge!(
105            "greptime_mito_inflight_flush_count",
106            "inflight flush count",
107        ).unwrap();
108    // ------ End of flush related metrics
109
110
111    // ------ Write related metrics
112    //
113    /// Counter of rejected write requests.
114    pub static ref WRITE_REJECT_TOTAL: IntCounter =
115        register_int_counter!("greptime_mito_write_reject_total", "mito write reject total").unwrap();
116    /// Elapsed time of each write stage.
117    pub static ref WRITE_STAGE_ELAPSED: HistogramVec = register_histogram_vec!(
118            "greptime_mito_write_stage_elapsed",
119            "mito write stage elapsed",
120            &[STAGE_LABEL],
121            // 0.01 ~ 1000
122            exponential_buckets(0.01, 10.0, 6).unwrap(),
123        )
124        .unwrap();
125    /// Counter of rows to write.
126    pub static ref WRITE_ROWS_TOTAL: IntCounterVec = register_int_counter_vec!(
127        "greptime_mito_write_rows_total",
128        "mito write rows total",
129        &[TYPE_LABEL]
130    )
131    .unwrap();
132}
133
134// Compaction metrics.
135lazy_static! {
136    /// Timer of different stages in compaction.
137    /// - pick
138    /// - merge (in parallel)
139    ///   - iter_source
140    ///   - write_batch
141    ///   - update_index
142    ///   - upload_parquet
143    ///   - upload puffin
144    /// - write_manifest
145    pub static ref COMPACTION_STAGE_ELAPSED: HistogramVec = register_histogram_vec!(
146        "greptime_mito_compaction_stage_elapsed",
147        "mito compaction stage elapsed",
148        &[STAGE_LABEL],
149        // 1 ~ 100000
150        exponential_buckets(1.0, 10.0, 6).unwrap(),
151    )
152    .unwrap();
153    /// TWCS candidate planning wall time, including blocking-pool waits and
154    /// empty/error attempts. `mode` is fair or stateless, never a region ID.
155    pub static ref TWCS_PICK_ELAPSED: HistogramVec = register_histogram_vec!(
156        "greptime_mito_twcs_pick_elapsed_seconds",
157        "twcs candidate planning wall time including blocking-pool waits",
158        &["mode"],
159        // 100us ~ 105s, so sub-second planning regressions are visible too.
160        exponential_buckets(0.0001, 4.0, 11).unwrap(),
161    ).unwrap();
162    /// Windows whose candidate discovery actually started, including windows
163    /// with no eligible candidates; excludes windows skipped by early exit.
164    pub static ref TWCS_SCANNED_WINDOWS: IntCounterVec = register_int_counter_vec!(
165        "greptime_mito_twcs_scanned_windows_total",
166        "twcs windows evaluated during candidate discovery",
167        &["mode"],
168    ).unwrap();
169    /// Automatic seeds attempted within the output budget, including seeds
170    /// absorbed by or rejected with a LastNonNull closure. Excludes work left
171    /// behind by the budget; counts attempts, not admission or completion.
172    /// Promoted means the seed reached the waiting threshold at selection time.
173    pub static ref TWCS_SELECTED_CANDIDATES: IntCounterVec = register_int_counter_vec!(
174        "greptime_mito_twcs_selected_candidates_total",
175        "automatic twcs seeds selected by class and normal or promoted priority",
176        &["class", "priority"],
177    ).unwrap();
178    /// Elapsed time of each successfully published compaction unit, labeled by `type`.
179    /// - local: one dependency unit, from task start through worker apply acknowledgement
180    /// - remote: one remote job, from request start through publication
181    pub static ref COMPACTION_ELAPSED_TOTAL: HistogramVec =
182        register_histogram_vec!(
183        "greptime_mito_compaction_total_elapsed",
184        "mito compaction elapsed per published unit",
185        &[TYPE_LABEL],
186        // 1 ~ 100000
187        exponential_buckets(1.0, 10.0, 6).unwrap(),
188    ).unwrap();
189    /// Counter of all requested compaction task.
190    pub static ref COMPACTION_REQUEST_COUNT: IntCounter =
191        register_int_counter!("greptime_mito_compaction_requests_total", "mito compaction requests total").unwrap();
192    /// Counter of failed compaction task.
193    pub static ref COMPACTION_FAILURE_COUNT: IntCounter =
194        register_int_counter!("greptime_mito_compaction_failure_total", "mito compaction failure total").unwrap();
195
196    /// Prepared compaction units waiting for global admission.
197    pub static ref COMPACTION_READY_UNITS: IntGauge = register_int_gauge!(
198        "greptime_mito_compaction_ready_units", "prepared units waiting for global admission"
199    ).unwrap();
200    /// Includes authorized work not yet polled, through task exit and lease release.
201    pub static ref COMPACTION_ADMITTED_UNITS: IntGauge = register_int_gauge!(
202        "greptime_mito_compaction_admitted_units", "compaction units holding global execution capacity"
203    ).unwrap();
204    pub static ref COMPACTION_ADMISSION_WAIT: Histogram = register_histogram!(
205        "greptime_mito_compaction_admission_wait_seconds", "time prepared units wait for admission",
206        exponential_buckets(0.001, 4.0, 10).unwrap()
207    ).unwrap();
208    /// Gauge for inflight compaction tasks: local units and remote jobs.
209    pub static ref INFLIGHT_COMPACTION_COUNT: IntGauge =
210        register_int_gauge!(
211            "greptime_mito_inflight_compaction_count",
212            "inflight compaction count",
213        ).unwrap();
214
215    /// Bytes reserved by compaction memory manager.
216    pub static ref COMPACTION_MEMORY_IN_USE: IntGauge =
217        register_int_gauge!(
218            "greptime_mito_compaction_memory_in_use_bytes",
219            "bytes currently reserved for compaction tasks",
220        )
221        .unwrap();
222    /// Configured compaction memory limit.
223    pub static ref COMPACTION_MEMORY_LIMIT: IntGauge =
224        register_int_gauge!(
225            "greptime_mito_compaction_memory_limit_bytes",
226            "maximum bytes allowed for compaction tasks",
227        )
228        .unwrap();
229    /// Wait time to obtain compaction memory.
230    pub static ref COMPACTION_MEMORY_WAIT: Histogram = register_histogram!(
231        "greptime_mito_compaction_memory_wait_seconds",
232        "time waiting for compaction memory",
233        // 0.01s ~ ~10s
234        exponential_buckets(0.01, 2.0, 10).unwrap(),
235    ).unwrap();
236    /// Counter of rejected compaction memory allocations.
237    pub static ref COMPACTION_MEMORY_REJECTED: IntCounterVec =
238        register_int_counter_vec!(
239            "greptime_mito_compaction_memory_rejected_total",
240            "number of compaction tasks rejected due to memory limit",
241            &[TYPE_LABEL]
242        ).unwrap();
243}
244
245// Query metrics.
246lazy_static! {
247    /// Timer of different stages in query.
248    pub static ref READ_STAGE_ELAPSED: HistogramVec = register_histogram_vec!(
249        "greptime_mito_read_stage_elapsed",
250        "mito read stage elapsed",
251        &[STAGE_LABEL],
252        // 0.01 ~ 10000
253        exponential_buckets(0.01, 10.0, 7).unwrap(),
254    )
255    .unwrap();
256    pub static ref READ_STAGE_FETCH_PAGES: Histogram = READ_STAGE_ELAPSED.with_label_values(&["fetch_pages"]);
257    /// Aggregated columnar reader work, published once per stream.
258    pub static ref COLUMNAR_READ_COUNT: IntCounterVec = register_int_counter_vec!(
259        "greptime_mito_columnar_read_count", "Columnar read operations by kind", &[TYPE_LABEL]
260    ).unwrap();
261    /// Payload bytes requested and fetched, excluding metadata.
262    pub static ref COLUMNAR_READ_BYTES: IntCounterVec = register_int_counter_vec!(
263        "greptime_mito_columnar_read_bytes", "Columnar payload bytes by kind", &[TYPE_LABEL]
264    ).unwrap();
265    /// Number of in-progress scan per partition.
266    pub static ref IN_PROGRESS_SCAN: IntGaugeVec = register_int_gauge_vec!(
267        "greptime_mito_in_progress_scan",
268        "mito in progress scan per partition",
269        &[TYPE_LABEL, PARTITION_LABEL]
270    )
271    .unwrap();
272    /// Counter of rows read from different source.
273    pub static ref READ_ROWS_TOTAL: IntCounterVec =
274        register_int_counter_vec!("greptime_mito_read_rows_total", "mito read rows total", &[TYPE_LABEL]).unwrap();
275    /// Counter of filtered rows during merge.
276    pub static ref MERGE_FILTER_ROWS_TOTAL: IntCounterVec =
277        register_int_counter_vec!("greptime_mito_merge_filter_rows_total", "mito merge filter rows total", &[TYPE_LABEL]).unwrap();
278    /// Counter of row groups read.
279    pub static ref READ_ROW_GROUPS_TOTAL: IntCounterVec =
280        register_int_counter_vec!("greptime_mito_read_row_groups_total", "mito read row groups total", &[TYPE_LABEL]).unwrap();
281    /// Counter of filtered rows by precise filter.
282    pub static ref PRECISE_FILTER_ROWS_TOTAL: IntCounterVec =
283        register_int_counter_vec!("greptime_mito_precise_filter_rows_total", "mito precise filter rows total", &[TYPE_LABEL]).unwrap();
284    pub static ref READ_ROWS_IN_ROW_GROUP_TOTAL: IntCounterVec =
285        register_int_counter_vec!("greptime_mito_read_rows_in_row_group_total", "mito read rows in row group total", &[TYPE_LABEL]).unwrap();
286    /// Histogram for the number of SSTs to scan per query.
287    pub static ref READ_SST_COUNT: Histogram = register_histogram!(
288        "greptime_mito_read_sst_count",
289        "Number of SSTs to scan in a scan task",
290        vec![1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 256.0, 1024.0],
291    ).unwrap();
292    /// Planned maximum concurrent sources per query scan limit evaluation or compaction reader.
293    /// Includes memtables counted by the file limit, rejected scans, and memory-budgeted scans.
294    pub static ref SCAN_MAX_CONCURRENT_FILES: HistogramVec = register_histogram_vec!(
295        "greptime_mito_scan_max_concurrent_files",
296        "Estimated maximum concurrent files (including memtable sources) per query scan limit evaluation or compaction reader",
297        &[TYPE_LABEL],
298        vec![0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 384.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0],
299    ).unwrap();
300    /// Histogram for the number of rows returned per query.
301    pub static ref READ_ROWS_RETURN: Histogram = register_histogram!(
302        "greptime_mito_read_rows_return",
303        "Number of rows returned in a scan task",
304        exponential_buckets(100.0, 10.0, 8).unwrap(),
305    ).unwrap();
306    /// Histogram for the number of batches returned per query.
307    pub static ref READ_BATCHES_RETURN: Histogram = register_histogram!(
308        "greptime_mito_read_batches_return",
309        "Number of rows returned in a scan task",
310        exponential_buckets(100.0, 10.0, 7).unwrap(),
311    ).unwrap();
312    /// Gauge for scan memory usage in bytes.
313    pub static ref SCAN_MEMORY_USAGE_BYTES: IntGauge = register_int_gauge!(
314        "greptime_mito_scan_memory_usage_bytes",
315        "current scan memory usage in bytes"
316    ).unwrap();
317    /// Counter of scan allocation attempts that could not acquire memory immediately.
318    pub static ref SCAN_MEMORY_EXHAUSTED_TOTAL: IntCounter = register_int_counter!(
319        "greptime_mito_scan_memory_exhausted_total",
320        "total number of times scan memory was unavailable for immediate acquisition"
321    ).unwrap();
322    /// Counter of scan requests that ultimately failed due to memory pressure.
323    pub static ref SCAN_REQUESTS_REJECTED_TOTAL: IntCounter = register_int_counter!(
324        "greptime_mito_scan_requests_rejected_total",
325        "total number of scan requests that ultimately failed due to memory limit"
326    ).unwrap();
327    /// Gauge for active file range builders in the pruner.
328    pub static ref PRUNER_ACTIVE_BUILDERS: IntGauge = register_int_gauge!(
329        "greptime_mito_pruner_active_builders",
330        "number of active file range builders in the pruner"
331    ).unwrap();
332}
333
334pub(crate) fn cache_loading_metrics(
335    cache_type: &'static str,
336) -> std::sync::Arc<common_cache::metrics::CacheMetrics> {
337    use common_cache::metrics::{CacheMetrics, OperationMetrics};
338
339    let operation = |stage| OperationMetrics {
340        started: CACHE_NATIVE_LOAD_EVENTS.with_label_values(&[cache_type, stage, "started"]),
341        succeeded: CACHE_NATIVE_LOAD_EVENTS.with_label_values(&[cache_type, stage, "success"]),
342        failed: CACHE_NATIVE_LOAD_EVENTS.with_label_values(&[cache_type, stage, "error"]),
343        cancelled: CACHE_NATIVE_LOAD_EVENTS.with_label_values(&[cache_type, stage, "cancelled"]),
344        active: CACHE_NATIVE_LOAD_ACTIVE.with_label_values(&[cache_type, stage]),
345        elapsed: CACHE_NATIVE_LOAD_ELAPSED.with_label_values(&[cache_type, stage]),
346    };
347    std::sync::Arc::new(CacheMetrics {
348        requests: operation("request"),
349        loads: operation("loader"),
350    })
351}
352
353// Cache metrics.
354lazy_static! {
355    pub static ref RANGE_CACHE_STAGING_BYTES: IntGauge = register_int_gauge!(
356        "greptime_mito_range_cache_staging_bytes",
357        "Referenced batch bytes retained by active shared range buffers, including unread streaming batches"
358    )
359    .unwrap();
360    pub static ref RANGE_CACHE_STREAMING_BYTES: IntGauge = register_int_gauge!(
361        "greptime_mito_range_cache_streaming_bytes",
362        "Referenced bytes retained for active readers after full-result cache admission stops"
363    ).unwrap();
364}
365
366lazy_static! {
367    /// Native cache request and actual loader lifecycle; request is not a waiter count.
368    pub static ref CACHE_NATIVE_LOAD_EVENTS: IntCounterVec = register_int_counter_vec!(
369        "greptime_mito_cache_native_load_events_total",
370        "Native cache request and executed loader outcomes; requests include hits and shared loads",
371        &[TYPE_LABEL, STAGE_LABEL, "event"]
372    ).unwrap();
373    pub static ref CACHE_NATIVE_LOAD_ACTIVE: IntGaugeVec = register_int_gauge_vec!(
374        "greptime_mito_cache_native_load_active",
375        "Active native cache requests or executed loaders, not waiting requests",
376        &[TYPE_LABEL, STAGE_LABEL]
377    ).unwrap();
378    pub static ref CACHE_NATIVE_LOAD_ELAPSED: HistogramVec = register_histogram_vec!(
379        "greptime_mito_cache_native_load_seconds",
380        "Native cache request or executed loader wall time including suspension and cancellation, not CPU time",
381        &[TYPE_LABEL, STAGE_LABEL], exponential_buckets(0.0001, 10.0, 6).unwrap()
382    ).unwrap();
383
384    /// Cache hit counter.
385    pub static ref CACHE_HIT: IntCounterVec = register_int_counter_vec!(
386        "greptime_mito_cache_hit",
387        "mito cache hit",
388        &[TYPE_LABEL]
389    )
390    .unwrap();
391    /// Cache miss counter.
392    pub static ref CACHE_MISS: IntCounterVec = register_int_counter_vec!(
393        "greptime_mito_cache_miss",
394        "mito cache miss",
395        &[TYPE_LABEL]
396    )
397    .unwrap();
398    /// Cache size in bytes.
399    pub static ref CACHE_BYTES: common_cache::metrics::CacheSizeMetrics = {
400        let metrics = common_cache::metrics::CacheSizeMetrics::new(
401            prometheus::Opts::new("greptime_mito_cache_bytes", "mito cache bytes; backend cache weights are approximate"),
402            &[TYPE_LABEL],
403        ).unwrap();
404        prometheus::register(Box::new(metrics.clone())).unwrap();
405        metrics
406    };
407    /// Download bytes counter in the write cache.
408    pub static ref WRITE_CACHE_DOWNLOAD_BYTES_TOTAL: IntCounter = register_int_counter!(
409        "mito_write_cache_download_bytes_total",
410        "mito write cache download bytes total",
411    ).unwrap();
412    /// Timer of the downloading task in the write cache.
413    pub static ref WRITE_CACHE_DOWNLOAD_ELAPSED: HistogramVec = register_histogram_vec!(
414        "mito_write_cache_download_elapsed",
415        "mito write cache download elapsed",
416        &[TYPE_LABEL],
417        // 0.1 ~ 10000
418        exponential_buckets(0.1, 10.0, 6).unwrap(),
419    ).unwrap();
420    /// Number of inflight download tasks.
421    pub static ref WRITE_CACHE_INFLIGHT_DOWNLOAD: IntGauge = register_int_gauge!(
422        "mito_write_cache_inflight_download_count",
423        "mito write cache inflight download tasks",
424    ).unwrap();
425    /// Upload bytes counter.
426    pub static ref UPLOAD_BYTES_TOTAL: IntCounter = register_int_counter!(
427        "mito_upload_bytes_total",
428        "mito upload bytes total",
429    )
430    .unwrap();
431    /// Bounded event labels distinguish lookup misses from actual shared loads.
432    pub static ref RANGE_CACHE_WORKER_EVENTS: IntCounterVec = register_int_counter_vec!(
433        "greptime_mito_range_cache_worker_events_total",
434        "Range cache load coordination and SST retirement events",
435        &["event"]
436    )
437    .unwrap();
438
439    /// Cache eviction counter, labeled with cache type and eviction reason.
440    pub static ref CACHE_EVICTION: IntCounterVec = register_int_counter_vec!(
441        "greptime_mito_cache_eviction",
442        "mito cache eviction",
443        &[TYPE_LABEL, CACHE_EVICTION_CAUSE]
444    ).unwrap();
445}
446
447// Index metrics.
448lazy_static! {
449    /// Stale index publications rejected.
450    pub static ref INDEX_PUBLICATION_STALE_TOTAL: IntCounterVec =
451        register_int_counter_vec!(
452            "greptime_mito_index_publication_stale_total",
453            "stale index publications rejected",
454            &[STAGE_LABEL],
455        ).unwrap();
456    /// Number of failures while cleaning local state for stale index artifacts.
457    pub static ref INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL: IntCounter =
458        register_int_counter!(
459            "greptime_mito_index_artifact_cleanup_failure_total",
460            "failures while cleaning local state for stale index artifacts",
461        ).unwrap();
462    /// Timer of index application.
463    pub static ref INDEX_APPLY_ELAPSED: HistogramVec = register_histogram_vec!(
464        "greptime_index_apply_elapsed",
465        "index apply elapsed",
466        &[TYPE_LABEL],
467        // 0.01 ~ 1000
468        exponential_buckets(0.01, 10.0, 6).unwrap(),
469    )
470    .unwrap();
471    /// Gauge of index apply memory usage.
472    pub static ref INDEX_APPLY_MEMORY_USAGE: IntGauge = register_int_gauge!(
473        "greptime_index_apply_memory_usage",
474        "index apply memory usage",
475    )
476    .unwrap();
477    /// Timer of index creation.
478    pub static ref INDEX_CREATE_ELAPSED: HistogramVec = register_histogram_vec!(
479        "greptime_index_create_elapsed",
480        "index create elapsed",
481        &[STAGE_LABEL, TYPE_LABEL],
482        // 0.1 ~ 10000
483        exponential_buckets(0.1, 10.0, 6).unwrap(),
484    )
485    .unwrap();
486    /// Counter of rows indexed.
487    pub static ref INDEX_CREATE_ROWS_TOTAL: IntCounterVec = register_int_counter_vec!(
488        "greptime_index_create_rows_total",
489        "index create rows total",
490        &[TYPE_LABEL],
491    )
492    .unwrap();
493    /// Counter of created index bytes.
494    pub static ref INDEX_CREATE_BYTES_TOTAL: IntCounterVec = register_int_counter_vec!(
495        "greptime_index_create_bytes_total",
496        "index create bytes total",
497        &[TYPE_LABEL],
498    )
499    .unwrap();
500    /// Optional index kinds discarded by a resource policy, not a build error.
501    pub static ref INDEX_CREATE_DISCARDED_TOTAL: IntCounterVec = register_int_counter_vec!(
502        "greptime_index_create_discarded_total",
503        "index kinds omitted or discarded by resource policy",
504        &[TYPE_LABEL, "reason"],
505    ).unwrap();
506    /// Gauge of index create memory usage. The `extension` type aggregates retained
507    /// memory across optional creators, not individual algorithms: one creator may
508    /// share state across several algorithms.
509    pub static ref INDEX_CREATE_MEMORY_USAGE: IntGaugeVec = register_int_gauge_vec!(
510        "greptime_index_create_memory_usage",
511        "index create memory usage",
512        &[TYPE_LABEL],
513    ).unwrap();
514    /// Counter of r/w bytes on index related IO operations.
515    pub static ref INDEX_IO_BYTES_TOTAL: IntCounterVec = register_int_counter_vec!(
516        "greptime_index_io_bytes_total",
517        "index io bytes total",
518        &[TYPE_LABEL, FILE_TYPE_LABEL]
519    )
520    .unwrap();
521    /// Counter of read bytes on puffin files.
522    pub static ref INDEX_PUFFIN_READ_BYTES_TOTAL: IntCounter = INDEX_IO_BYTES_TOTAL
523        .with_label_values(&["read", "puffin"]);
524    /// Counter of write bytes on puffin files.
525    pub static ref INDEX_PUFFIN_WRITE_BYTES_TOTAL: IntCounter = INDEX_IO_BYTES_TOTAL
526        .with_label_values(&["write", "puffin"]);
527    /// Counter of read bytes on intermediate files.
528    pub static ref INDEX_INTERMEDIATE_READ_BYTES_TOTAL: IntCounter = INDEX_IO_BYTES_TOTAL
529        .with_label_values(&["read", "intermediate"]);
530    /// Counter of write bytes on intermediate files.
531    pub static ref INDEX_INTERMEDIATE_WRITE_BYTES_TOTAL: IntCounter = INDEX_IO_BYTES_TOTAL
532        .with_label_values(&["write", "intermediate"]);
533
534    /// Counter of r/w operations on index related IO operations, e.g. read, write, seek and flush.
535    pub static ref INDEX_IO_OP_TOTAL: IntCounterVec = register_int_counter_vec!(
536        "greptime_index_io_op_total",
537        "index io op total",
538        &[TYPE_LABEL, FILE_TYPE_LABEL]
539    )
540    .unwrap();
541    /// Counter of read operations on puffin files.
542    pub static ref INDEX_PUFFIN_READ_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
543        .with_label_values(&["read", "puffin"]);
544    /// Counter of seek operations on puffin files.
545    pub static ref INDEX_PUFFIN_SEEK_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
546        .with_label_values(&["seek", "puffin"]);
547    /// Counter of write operations on puffin files.
548    pub static ref INDEX_PUFFIN_WRITE_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
549        .with_label_values(&["write", "puffin"]);
550    /// Counter of flush operations on puffin files.
551    pub static ref INDEX_PUFFIN_FLUSH_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
552        .with_label_values(&["flush", "puffin"]);
553    /// Counter of read operations on intermediate files.
554    pub static ref INDEX_INTERMEDIATE_READ_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
555        .with_label_values(&["read", "intermediate"]);
556    /// Counter of seek operations on intermediate files.
557    pub static ref INDEX_INTERMEDIATE_SEEK_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
558        .with_label_values(&["seek", "intermediate"]);
559    /// Counter of write operations on intermediate files.
560    pub static ref INDEX_INTERMEDIATE_WRITE_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
561        .with_label_values(&["write", "intermediate"]);
562    /// Counter of flush operations on intermediate files.
563    pub static ref INDEX_INTERMEDIATE_FLUSH_OP_TOTAL: IntCounter = INDEX_IO_OP_TOTAL
564        .with_label_values(&["flush", "intermediate"]);
565}
566
567lazy_static! {
568    // Manifest related metrics:
569
570    /// Elapsed time of manifest operation. Labeled with "op".
571    pub static ref MANIFEST_OP_ELAPSED: HistogramVec = register_histogram_vec!(
572        "greptime_manifest_op_elapsed",
573        "mito manifest operation elapsed",
574        &["op"],
575        // 0.01 ~ 1000
576        exponential_buckets(0.01, 10.0, 6).unwrap(),
577    ).unwrap();
578
579
580    pub static ref REGION_WORKER_HANDLE_WRITE_ELAPSED: HistogramVec = register_histogram_vec!(
581        "greptime_region_worker_handle_write",
582        "elapsed time for handling writes in region worker loop",
583        &["stage"],
584        exponential_buckets(0.001, 10.0, 5).unwrap()
585    ).unwrap();
586
587}
588
589lazy_static! {
590    /// Counter for compaction input file size.
591    pub static ref COMPACTION_INPUT_BYTES: Counter = register_counter!(
592        "greptime_mito_compaction_input_bytes",
593        "mito compaction input file size",
594        ).unwrap();
595
596    /// Counter for compaction output file size.
597    pub static ref COMPACTION_OUTPUT_BYTES: Counter = register_counter!(
598        "greptime_mito_compaction_output_bytes",
599        "mito compaction output file size",
600        ).unwrap();
601
602    /// Active series count in TimeSeriesMemtable
603    pub static ref MEMTABLE_ACTIVE_SERIES_COUNT: IntGauge = register_int_gauge!(
604        "greptime_mito_memtable_active_series_count",
605        "active time series count in TimeSeriesMemtable",
606        ).unwrap();
607
608    /// Active field builder count in TimeSeriesMemtable
609    pub static ref MEMTABLE_ACTIVE_FIELD_BUILDER_COUNT: IntGauge = register_int_gauge!(
610        "greptime_mito_memtable_field_builder_count",
611        "active field builder count in TimeSeriesMemtable",
612        ).unwrap();
613
614    /// Number of stalling write requests in each worker.
615    pub static ref WRITE_STALLING: IntGaugeVec = register_int_gauge_vec!(
616            "greptime_mito_write_stalling_count",
617            "mito stalled write request in each worker",
618            &[WORKER_LABEL]
619        ).unwrap();
620    /// Number of ref files
621    pub static ref GC_REF_FILE_CNT: IntGauge = register_int_gauge!(
622            "greptime_gc_ref_file_count",
623            "gc ref file count",
624        ).unwrap();
625    /// Total number of stalled write requests.
626    pub static ref WRITE_STALL_TOTAL: IntCounter = register_int_counter!(
627        "greptime_mito_write_stall_total",
628        "Total number of stalled write requests"
629    ).unwrap();
630    /// Time waiting for requests to be handled by the region worker.
631    pub static ref REQUEST_WAIT_TIME: HistogramVec = register_histogram_vec!(
632            "greptime_mito_request_wait_time",
633            "mito request wait time before being handled by region worker",
634            &[WORKER_LABEL],
635            // 0.001 ~ 10000
636            exponential_buckets(0.001, 10.0, 8).unwrap(),
637        )
638        .unwrap();
639
640    /// Counter for the number of files deleted by the GC worker.
641    pub static ref GC_DELETE_FILE_CNT: IntCounter =
642        register_int_counter!(
643            "greptime_mito_gc_delete_file_count",
644            "mito gc deleted file count",
645        ).unwrap();
646
647    /// Counter for the number of unparsable files skipped by GC.
648    pub static ref GC_SKIPPED_UNPARSABLE_FILES: IntCounter =
649        register_int_counter!(
650            "greptime_mito_gc_skipped_unparsable_files",
651            "mito gc skipped unparsable files count",
652        ).unwrap();
653
654    /// Counter for the number of orphaned index files found by GC.
655    pub static ref GC_ORPHANED_INDEX_FILES: IntCounter =
656        register_int_counter!(
657            "greptime_mito_gc_orphaned_index_files",
658            "mito gc orphaned index files count",
659        ).unwrap();
660
661    /// Histogram for GC operation duration by stage.
662    pub static ref GC_DURATION_SECONDS: HistogramVec = register_histogram_vec!(
663        "greptime_mito_gc_duration_seconds",
664        "GC operation duration by stage",
665        &[STAGE_LABEL],
666        exponential_buckets(0.01, 10.0, 6).unwrap(),
667    ).unwrap();
668
669    /// Counter for GC runs by mode.
670    pub static ref GC_RUNS_TOTAL: IntCounterVec = register_int_counter_vec!(
671        "greptime_mito_gc_runs_total",
672        "Total GC runs by mode",
673        &["mode"],
674    ).unwrap();
675
676    /// Counter for GC errors by type.
677    pub static ref GC_ERRORS_TOTAL: IntCounterVec = register_int_counter_vec!(
678        "greptime_mito_gc_errors_total",
679        "Total GC errors by type",
680        &["error_type"],
681    ).unwrap();
682
683    /// Counter for total files deleted by GC, labeled by file type.
684    pub static ref GC_FILES_DELETED_TOTAL: IntCounterVec = register_int_counter_vec!(
685        "greptime_mito_gc_files_deleted_total",
686        "Total files deleted by GC",
687        &[FILE_TYPE_LABEL],
688    ).unwrap();
689
690    /// Total number of files downloaded during cache fill on region open.
691    pub static ref CACHE_FILL_DOWNLOADED_FILES: IntCounter = register_int_counter!(
692        "mito_cache_fill_downloaded_files",
693        "mito cache fill downloaded files count",
694    ).unwrap();
695
696    /// Number of files pending download during cache fill on region open.
697    pub static ref CACHE_FILL_PENDING_FILES: IntGauge = register_int_gauge!(
698        "mito_cache_fill_pending_files",
699        "mito cache fill pending files count",
700    ).unwrap();
701
702    /// Counter of flush files.
703    pub static ref FLUSH_FILE_TOTAL: IntCounter =
704        register_int_counter!("greptime_mito_flush_file_total", "mito flushed file count").unwrap();
705
706    /// Elapsed time of the SST writes of tail replays, by stage.
707    pub static ref TAIL_REPLAY_ELAPSED: HistogramVec = register_histogram_vec!(
708        "greptime_mito_tail_replay_elapsed",
709        "mito tail replay elapsed",
710        &[TYPE_LABEL],
711        // 1 ~ 3125
712        exponential_buckets(1.0, 5.0, 6).unwrap(),
713    )
714    .unwrap();
715    /// Bytes of SSTs from completed chunk writes of tail replays, including chunks of rounds
716    /// that fail later.
717    pub static ref TAIL_REPLAY_BYTES_TOTAL: IntCounter = register_int_counter!(
718        "greptime_mito_tail_replay_bytes_total",
719        "mito tail replay bytes total"
720    )
721    .unwrap();
722    /// Count of SSTs written by tail replays, including SSTs of failed rounds that were deleted.
723    pub static ref TAIL_REPLAY_FILE_TOTAL: IntCounter = register_int_counter!(
724        "greptime_mito_tail_replay_file_total",
725        "mito tail replay file count"
726    )
727    .unwrap();
728    /// Count of failed tail replay rounds.
729    pub static ref TAIL_REPLAY_FAILURE_TOTAL: IntCounter = register_int_counter!(
730        "greptime_mito_tail_replay_failure_total",
731        "mito tail replay failure total"
732    )
733    .unwrap();
734}
735
736#[cfg(feature = "hdfs-object-store")]
737lazy_static! {
738    /// Counter for the number of temporary files deleted by the sweeper.
739    pub static ref SWEEP_FILES_DELETED_TOTAL: IntCounter = register_int_counter!(
740        "greptime_mito_sweep_files_deleted_total",
741        "Total temporary files deleted by the sweeper",
742    ).unwrap();
743
744    /// Counter for the number of failures while sweeping temporary files.
745    pub static ref SWEEP_ERRORS_TOTAL: IntCounter = register_int_counter!(
746        "greptime_mito_sweep_errors_total",
747        "Total failures while sweeping temporary files",
748    ).unwrap();
749
750    /// Counter for the number of temporary file sweeps run.
751    pub static ref SWEEP_RUNS_TOTAL: IntCounter = register_int_counter!(
752        "greptime_mito_sweep_runs_total",
753        "Total temporary file sweeps run",
754    ).unwrap();
755}
756
757/// Stager notifier to collect metrics.
758pub struct StagerMetrics {
759    cache_hit: IntCounter,
760    cache_miss: IntCounter,
761    staging_cache_bytes: IntGauge,
762    recycle_cache_bytes: IntGauge,
763    cache_eviction: IntCounter,
764    staging_miss_read: Histogram,
765}
766
767impl StagerMetrics {
768    /// Creates a new stager notifier.
769    pub fn new() -> Self {
770        Self {
771            cache_hit: CACHE_HIT.with_label_values(&[STAGING_TYPE]),
772            cache_miss: CACHE_MISS.with_label_values(&[STAGING_TYPE]),
773            staging_cache_bytes: CACHE_BYTES.with_label_values(&[STAGING_TYPE]),
774            recycle_cache_bytes: CACHE_BYTES.with_label_values(&[RECYCLE_TYPE]),
775            cache_eviction: CACHE_EVICTION.with_label_values(&[STAGING_TYPE, "size"]),
776            staging_miss_read: READ_STAGE_ELAPSED.with_label_values(&["staging_miss_read"]),
777        }
778    }
779}
780
781impl Default for StagerMetrics {
782    fn default() -> Self {
783        Self::new()
784    }
785}
786
787impl StagerNotifier for StagerMetrics {
788    fn on_cache_hit(&self, _size: u64) {
789        self.cache_hit.inc();
790    }
791
792    fn on_cache_miss(&self, _size: u64) {
793        self.cache_miss.inc();
794    }
795
796    fn on_cache_insert(&self, size: u64) {
797        self.staging_cache_bytes.add(size as i64);
798    }
799
800    fn on_load_dir(&self, duration: Duration) {
801        self.staging_miss_read.observe(duration.as_secs_f64());
802    }
803
804    fn on_load_blob(&self, duration: Duration) {
805        self.staging_miss_read.observe(duration.as_secs_f64());
806    }
807
808    fn on_cache_evict(&self, size: u64) {
809        self.cache_eviction.inc();
810        self.staging_cache_bytes.sub(size as i64);
811    }
812
813    fn on_recycle_insert(&self, size: u64) {
814        self.recycle_cache_bytes.add(size as i64);
815    }
816
817    fn on_recycle_clear(&self, size: u64) {
818        self.recycle_cache_bytes.sub(size as i64);
819    }
820}
821
822/// Stream-local counters avoid contended metric updates for every tiny sample block.
823/// Stage durations sum elapsed work within a stream, not CPU time or query wall latency.
824/// Stages ending in `_wall` include awaits; concurrent streams can overlap.
825/// Preparation components partition the work inside `columnar_prepare_wall`; reader
826/// stages (`columnar_series_*`) are nested within preparation's discovery stage.
827/// `columnar_prepare_acquire_wall` is per caller and includes waiting for shared
828/// preparation, so overlapping caller times must not be summed as execution time.
829/// Series decode includes decompression and integrity validation; materialization
830/// includes dictionary expansion into projected Arrow arrays. Counters are aggregated
831/// per stream/preparation, never labeled by query, file, column name, or series ID.
832#[derive(Default)]
833pub(crate) struct ColumnarReadMetrics {
834    pub(crate) counts: std::collections::BTreeMap<&'static str, u64>,
835    pub(crate) bytes: std::collections::BTreeMap<&'static str, u64>,
836    elapsed: std::collections::BTreeMap<&'static str, Duration>,
837}
838
839/// Records a stage's elapsed time even when an awaited operation fails or is cancelled.
840/// The borrowed accumulator outlives this guard and flushes once with its owner.
841pub(crate) struct ColumnarStageTimer<'a> {
842    elapsed: &'a mut Duration,
843    started: Instant,
844}
845
846impl Drop for ColumnarStageTimer<'_> {
847    fn drop(&mut self) {
848        *self.elapsed += self.started.elapsed();
849    }
850}
851
852impl ColumnarReadMetrics {
853    pub(crate) fn timer(&mut self, stage: &'static str) -> ColumnarStageTimer<'_> {
854        ColumnarStageTimer {
855            elapsed: self.elapsed.entry(stage).or_default(),
856            started: Instant::now(),
857        }
858    }
859
860    pub(crate) fn add_elapsed(&mut self, stage: &'static str, elapsed: Duration) {
861        *self.elapsed.entry(stage).or_default() += elapsed;
862    }
863}
864
865impl Drop for ColumnarReadMetrics {
866    fn drop(&mut self) {
867        for (stage, elapsed) in &self.elapsed {
868            READ_STAGE_ELAPSED
869                .with_label_values(&[stage])
870                .observe(elapsed.as_secs_f64());
871        }
872        for (kind, count) in &self.counts {
873            COLUMNAR_READ_COUNT
874                .with_label_values(&[kind])
875                .inc_by(*count);
876        }
877        for (kind, bytes) in &self.bytes {
878            COLUMNAR_READ_BYTES
879                .with_label_values(&[kind])
880                .inc_by(*bytes);
881        }
882    }
883}
884
885lazy_static! {
886    pub static ref CACHE_PAGE_LOADED_BYTES: IntCounterVec = register_int_counter_vec!(
887        "greptime_mito_cache_page_loaded_bytes_total",
888        "Bytes produced by successful page loaders, excluding waiters",
889        &[TYPE_LABEL]
890    )
891    .unwrap();
892    /// Configured capacity summed across live page caches in each category.
893    pub static ref CACHE_CAPACITY_BYTES: common_cache::metrics::CacheSizeMetrics = {
894        let metrics = common_cache::metrics::CacheSizeMetrics::new(
895            prometheus::Opts::new("greptime_mito_cache_capacity_bytes", "Configured capacity of live page caches in bytes"),
896            &[TYPE_LABEL],
897        ).unwrap();
898        prometheus::register(Box::new(metrics.clone())).unwrap();
899        metrics
900    };
901}
902
903/// Binds shared page/cache I/O metrics while retaining the business hit/miss labels.
904pub(crate) fn cache_page_observer(
905    cache_name_label: &'static str,
906    cache_category_label: &'static str,
907    lookup_counts: fn(usize, usize) -> (usize, usize),
908) -> common_cache::paged::PageCacheObserver {
909    use common_cache::paged::PageEvent;
910    let hits = CACHE_HIT.with_label_values(&[cache_category_label]);
911    let misses = CACHE_MISS.with_label_values(&[cache_category_label]);
912    let loaded = CACHE_PAGE_LOADED_BYTES.with_label_values(&[cache_name_label]);
913    common_cache::paged::PageCacheObserver {
914        bytes: CACHE_BYTES.bind(&[cache_category_label]),
915        capacity: CACHE_CAPACITY_BYTES.bind(&[cache_category_label]),
916        loads: Some(cache_loading_metrics(cache_name_label)),
917        events: std::sync::Arc::new(move |event| match event {
918            PageEvent::Lookup {
919                hits: count,
920                misses: missing,
921            } => {
922                let (count, missing) = lookup_counts(count, missing);
923                hits.inc_by(count as u64);
924                misses.inc_by(missing as u64);
925            }
926            PageEvent::Loaded { bytes } => loaded.inc_by(bytes),
927            PageEvent::Evicted { cause } => CACHE_EVICTION
928                .with_label_values(&[cache_category_label, cause.as_str()])
929                .inc(),
930        }),
931    }
932}
933
934lazy_static! {
935    pub static ref CACHE_PAGE_BYTES: IntCounterVec = register_int_counter_vec!(
936        "greptime_mito_cache_page_bytes_total",
937        "Logical page fetch bytes by kind; not physical backend bytes",
938        &[TYPE_LABEL, "kind"]
939    )
940    .unwrap();
941}
942
943/// Records logical byte amplification independently of physical batch reads.
944pub(crate) fn cache_page_fetch_metrics(
945    cache_type: &'static str,
946    stats: &common_cache::paged::PageFetchStats,
947) {
948    for (kind, value) in [
949        ("requested", stats.requested_bytes),
950        ("aligned", stats.aligned_bytes),
951        ("unique_requested", stats.unique_requested_bytes),
952        ("cached", stats.cached_bytes),
953    ] {
954        CACHE_PAGE_BYTES
955            .with_label_values(&[cache_type, kind])
956            .inc_by(value);
957    }
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963    use common_cache::paged::{PageEvent, PageFetchStats};
964
965    #[tokio::test]
966    async fn stage_timer_retains_failed_and_cancelled_waits() {
967        let mut metrics = ColumnarReadMetrics::default();
968        let result = async {
969            let mut timer = metrics.timer("columnar_series_fetch_wall");
970            // Backdate the clock to keep the lifetime test deterministic without sleeping.
971            timer.started -= Duration::from_secs(1);
972            std::future::ready(Err::<(), ()>(())).await?;
973            Ok::<(), ()>(())
974        }
975        .await;
976        assert!(result.is_err());
977        let failed = metrics.elapsed["columnar_series_fetch_wall"];
978        assert!(failed >= Duration::from_secs(1));
979
980        let mut wait = Box::pin(async {
981            let mut timer = metrics.timer("columnar_series_fetch_wall");
982            timer.started -= Duration::from_secs(1);
983            std::future::pending::<()>().await;
984        });
985        assert!(futures::poll!(&mut wait).is_pending());
986        drop(wait);
987        // Dropping the suspended future must add to, rather than replace, earlier work.
988        assert!(metrics.elapsed["columnar_series_fetch_wall"] >= failed + Duration::from_secs(1));
989    }
990
991    #[test]
992    fn page_cache_capacity_sums_live_instances_by_category() {
993        use bytes::Bytes;
994        use common_cache::paged::PagedCache;
995        use prometheus::core::Collector;
996
997        let category = "test_shared_page_category";
998        let sample = || {
999            CACHE_CAPACITY_BYTES
1000                .collect()
1001                .into_iter()
1002                .flat_map(|family| family.get_metric().to_vec())
1003                .find(|metric| {
1004                    metric
1005                        .get_label()
1006                        .iter()
1007                        .any(|label| label.value() == category)
1008                })
1009                .unwrap()
1010                .get_gauge()
1011                .as_ref()
1012                .unwrap()
1013                .value()
1014        };
1015        let make_cache = |name, capacity| {
1016            PagedCache::<u64>::new(
1017                name,
1018                capacity,
1019                64,
1020                |_, bytes: &Bytes| bytes.len() as u32,
1021                cache_page_observer(name, category, |hits, misses| (hits, misses)),
1022            )
1023        };
1024        let first = make_cache("test_first_pages", 128);
1025        let second = make_cache("test_second_pages", 256);
1026        assert_eq!(sample(), 384.0);
1027        drop(first);
1028        assert_eq!(sample(), 256.0);
1029        drop(second);
1030        assert_eq!(sample(), 0.0);
1031    }
1032
1033    #[test]
1034    fn test_page_observer_retains_business_lookup_units() {
1035        let page = cache_page_observer("test_page_unit", "test_page_unit", |hits, misses| {
1036            (hits, misses)
1037        });
1038        let request =
1039            cache_page_observer("test_request_unit", "test_request_unit", |hits, misses| {
1040                (usize::from(hits > 0), usize::from(misses > 0))
1041            });
1042        for observer in [&page, &request] {
1043            (observer.events)(PageEvent::Lookup { hits: 3, misses: 2 });
1044            (observer.events)(PageEvent::Loaded { bytes: 4096 });
1045        }
1046        assert_eq!(CACHE_HIT.with_label_values(&["test_page_unit"]).get(), 3);
1047        assert_eq!(CACHE_MISS.with_label_values(&["test_page_unit"]).get(), 2);
1048        assert_eq!(CACHE_HIT.with_label_values(&["test_request_unit"]).get(), 1);
1049        assert_eq!(
1050            CACHE_MISS.with_label_values(&["test_request_unit"]).get(),
1051            1
1052        );
1053        cache_page_fetch_metrics(
1054            "test_page_unit",
1055            &PageFetchStats {
1056                requested_bytes: 7,
1057                aligned_bytes: 12,
1058                unique_requested_bytes: 6,
1059                cached_bytes: 3,
1060                ..Default::default()
1061            },
1062        );
1063        for (kind, expected) in [
1064            ("requested", 7),
1065            ("aligned", 12),
1066            ("unique_requested", 6),
1067            ("cached", 3),
1068        ] {
1069            assert_eq!(
1070                CACHE_PAGE_BYTES
1071                    .with_label_values(&["test_page_unit", kind])
1072                    .get(),
1073                expected
1074            );
1075        }
1076    }
1077}