ktstr/stats/
metric_id.rs

1//! Typed metric identifiers — a discoverable, typo-proof handle for the built-in
2//! metric registry ([`super::METRICS`]), plus a first-class string escape for
3//! scheduler-runtime / payload-supplied keys.
4//!
5//! [`BuiltinMetric`] is one variant per [`super::METRICS`] entry: the entire
6//! built-in metric vocabulary in one readable, completable enum. A misspelled
7//! built-in metric is a COMPILE error, not a silent runtime `None` — closing the
8//! silent-wrong-answer class where a typo'd metric name yields `None` and a test
9//! vacuously passes having asserted nothing.
10//!
11//! [`MetricId`] unifies the typed built-in path with the open scheduler-runtime
12//! string path behind one `impl Into<MetricId>` accessor argument:
13//! `phase_metric(BuiltinMetric::TaobenchTotalOpsPerCpuSec)` and
14//! `phase_metric("scx_custom_runtime_key")` both compile through the same
15//! signature — the known one typed and discoverable, the dynamic one a first-class
16//! string escape (existing `&str` call sites keep compiling, canonicalized to the
17//! `Builtin` variant when the string names a registered metric).
18//!
19//! GUARDRAIL: a `MetricId::Dynamic` whose string is NOT a registered name has no
20//! declared [`super::MetricKind`] ([`MetricId::def`] returns `None`); callers must
21//! never aggregate such a metric as a guessed kind (the math-protocol silent-lie
22//! class). Resolve-by-name or fold conservatively — never assume `Counter`.
23//!
24//! The 1:1 correspondence with [`super::METRICS`] is pinned by
25//! `tests::builtin_metric_is_one_to_one_with_registry` (both directions), so a
26//! registry entry without an enum variant — or an enum variant without a registry
27//! entry — fails the build.
28
29use std::borrow::Cow;
30
31use super::{MetricDef, metric_def};
32
33/// Define [`BuiltinMetric`] from the single `(variant => wire_name)` source of
34/// truth, generating the enum, `wire_name()`, `from_wire_name()`, and `ALL` so the
35/// three can never drift from each other (the registry-vs-enum drift is caught
36/// separately by the pin-test).
37macro_rules! builtin_metrics {
38    ($($variant:ident => $wire:literal),* $(,)?) => {
39        /// One variant per `super::METRICS` entry — the discoverable built-in
40        /// metric vocabulary. [`Self::wire_name`] is the stable registry / sidecar
41        /// / CI string; [`Self::def`] resolves the full `MetricDef`. Pinned 1:1
42        /// to `METRICS`.
43        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
44        pub enum BuiltinMetric { $($variant),* }
45
46        impl BuiltinMetric {
47            /// The stable registry / sidecar / CI wire name — the `&str` key into
48            /// `super::METRICS` and the ext-metrics maps.
49            pub const fn wire_name(self) -> &'static str {
50                match self { $(Self::$variant => $wire,)* }
51            }
52
53            /// Classify a wire name back to its variant, or `None` for a
54            /// non-built-in (scheduler-runtime / payload) key.
55            pub fn from_wire_name(name: &str) -> Option<Self> {
56                match name { $($wire => Some(Self::$variant),)* _ => None }
57            }
58
59            /// Every built-in metric (registry-order-independent). Drives typed
60            /// all-metrics sweeps and the 1:1 pin-test.
61            pub const ALL: &'static [BuiltinMetric] = &[$(Self::$variant),*];
62        }
63    };
64}
65
66builtin_metrics! {
67    // Run-level typed / derived metrics (Gauge / Peak / Counter / Rate /
68    // Distribution / WorstLowest / WakeLatencyTailRatio / WorstCrossNodeRatio).
69    WorstSpread => "worst_spread",
70    WorstGapMs => "worst_gap_ms",
71    TotalMigrations => "total_migrations",
72    WorstMigrationRatio => "worst_migration_ratio",
73    MaxImbalanceRatio => "max_imbalance_ratio",
74    AvgImbalanceRatio => "avg_imbalance_ratio",
75    MaxDsqDepth => "max_dsq_depth",
76    AvgDsqDepth => "avg_dsq_depth",
77    StuckCount => "stuck_count",
78    TotalFallback => "total_fallback",
79    TotalKeepLast => "total_keep_last",
80    TotalFallbackPooled => "total_fallback_pooled",
81    TotalKeepLastPooled => "total_keep_last_pooled",
82    TotalEventVcpuSec => "total_event_vcpu_sec",
83    FallbackPerVcpuSec => "fallback_per_vcpu_sec",
84    KeepLastPerVcpuSec => "keep_last_per_vcpu_sec",
85    TotalRunDelay => "total_run_delay",
86    TotalPcount => "total_pcount",
87    TotalSchedCount => "total_sched_count",
88    TotalYldCount => "total_yld_count",
89    TotalSchedGoidle => "total_sched_goidle",
90    TotalTtwuCount => "total_ttwu_count",
91    TotalTtwuLocal => "total_ttwu_local",
92    TotalRunDelayNsPerSched => "total_run_delay_ns_per_sched",
93    TtwuLocalFraction => "ttwu_local_fraction",
94    SchedGoidleFraction => "sched_goidle_fraction",
95    // Dilation-safe schedstat activity densities (total_X divided by mean vCPU
96    // CPU seconds over the same window) + their shared CPU-time denominator.
97    TotalSchedstatVcpuSec => "total_schedstat_vcpu_sec",
98    RunDelayPerVcpuSec => "run_delay_per_vcpu_sec",
99    PcountPerVcpuSec => "pcount_per_vcpu_sec",
100    SchedCountPerVcpuSec => "sched_count_per_vcpu_sec",
101    YldCountPerVcpuSec => "yld_count_per_vcpu_sec",
102    TtwuCountPerVcpuSec => "ttwu_count_per_vcpu_sec",
103    SchedGoidlePerVcpuSec => "sched_goidle_per_vcpu_sec",
104    AvgNrRunning => "avg_nr_running",
105    WorstP99WakeLatencyUs => "worst_p99_wake_latency_us",
106    WorstMedianWakeLatencyUs => "worst_median_wake_latency_us",
107    WorstWakeLatencyCv => "worst_wake_latency_cv",
108    WorstP99TimerLatencyUs => "worst_p99_timer_latency_us",
109    WorstMedianTimerLatencyUs => "worst_median_timer_latency_us",
110    WorstP999TimerLatencyUs => "worst_p999_timer_latency_us",
111    WorstTimerLatencyUs => "worst_timer_latency_us",
112    IterationRate => "iteration_rate",
113    TotalIterations => "total_iterations",
114    TotalCpuTimeSec => "total_cpu_time_sec",
115    TotalIterationsPooled => "total_iterations_pooled",
116    // Whole-run taobench CPU-throughput + hit (run-level pool of the WorkType::Taobench
117    // engine, derived by populate_run_pooled_taobench). 4 Counter components
118    // (RENDER_SUPPRESSED_COMPONENTS) + 4 derived Rates. Distinct from the
119    // per-phase taobench_*_ops_per_cpu_sec below (MetricKind::PerPhase).
120    TotalTaobenchOps => "total_taobench_ops",
121    TotalTaobenchFastOps => "total_taobench_fast_ops",
122    TotalTaobenchSlowOps => "total_taobench_slow_ops",
123    TotalTaobenchWallSec => "total_taobench_wall_sec",
124    TotalTaobenchCpuSec => "total_taobench_cpu_sec",
125    TaobenchTotalOpsPerCpuSecWhole => "taobench_total_ops_per_cpu_sec_whole",
126    TaobenchFastOpsPerCpuSecWhole => "taobench_fast_ops_per_cpu_sec_whole",
127    TaobenchSlowOpsPerCpuSecWhole => "taobench_slow_ops_per_cpu_sec_whole",
128    TaobenchHitFraction => "taobench_hit_fraction",
129    // taobench whole-run open-loop serve-latency percentiles (PerRunDistribution).
130    TaobenchServeP50UsWhole => "taobench_serve_p50_us_whole",
131    TaobenchServeP90UsWhole => "taobench_serve_p90_us_whole",
132    TaobenchServeP99UsWhole => "taobench_serve_p99_us_whole",
133    TaobenchServeP999UsWhole => "taobench_serve_p999_us_whole",
134    TaobenchServeMinUsWhole => "taobench_serve_min_us_whole",
135    TaobenchServeMaxUsWhole => "taobench_serve_max_us_whole",
136    // taobench whole-run command-time hit: get_cmds + get_hits Counter components
137    // → taobench_command_hit_rate (Σhits/Σcmds) Rate.
138    TotalTaobenchGetCmds => "total_taobench_get_cmds",
139    TotalTaobenchGetHits => "total_taobench_get_hits",
140    TaobenchCommandHitRate => "taobench_command_hit_rate",
141    // schbench whole-run Class-3 (loop Counter + role-separate run-delay gate
142    // Rates + their Counter components), re-pooled by populate_run_pooled_schbench.
143    TotalSchbenchMsgRunDelayNs => "total_schbench_msg_run_delay_ns",
144    TotalSchbenchMsgPcount => "total_schbench_msg_pcount",
145    TotalSchbenchWorkerRunDelayNs => "total_schbench_worker_run_delay_ns",
146    TotalSchbenchWorkerPcount => "total_schbench_worker_pcount",
147    TotalSchbenchLoops => "total_schbench_loops",
148    TotalSchbenchWorkerCpuSec => "total_schbench_worker_cpu_sec",
149    SchbenchTotalLoopsPerCpuSec => "schbench_total_loops_per_cpu_sec",
150    SchbenchLoopsPerCpuSec => "schbench_loops_per_cpu_sec",
151    SchbenchMsgRunDelayNsPerSched => "schbench_msg_run_delay_ns_per_sched",
152    SchbenchWorkerRunDelayNsPerSched => "schbench_worker_run_delay_ns_per_sched",
153    // schbench whole-run distributional metrics (MetricKind::PerRunDistribution),
154    // union-recomputed by populate_run_pooled_schbench_distribution; *_whole names
155    // distinct from the per-phase percentile keys.
156    WakeupP50LatencyUsWhole => "wakeup_p50_latency_us_whole",
157    WakeupP90LatencyUsWhole => "wakeup_p90_latency_us_whole",
158    WakeupP99LatencyUsWhole => "wakeup_p99_latency_us_whole",
159    WakeupP999LatencyUsWhole => "wakeup_p999_latency_us_whole",
160    WakeupMinLatencyUsWhole => "wakeup_min_latency_us_whole",
161    WakeupMaxLatencyUsWhole => "wakeup_max_latency_us_whole",
162    RequestP50LatencyUsWhole => "request_p50_latency_us_whole",
163    RequestP90LatencyUsWhole => "request_p90_latency_us_whole",
164    RequestP99LatencyUsWhole => "request_p99_latency_us_whole",
165    RequestP999LatencyUsWhole => "request_p999_latency_us_whole",
166    RequestMinLatencyUsWhole => "request_min_latency_us_whole",
167    RequestMaxLatencyUsWhole => "request_max_latency_us_whole",
168    RpsP20Whole => "rps_p20_whole",
169    RpsP50Whole => "rps_p50_whole",
170    RpsP90Whole => "rps_p90_whole",
171    RpsMinWhole => "rps_min_whole",
172    RpsMaxWhole => "rps_max_whole",
173    SystemTimeNs => "system_time_ns",
174    UserTimeNs => "user_time_ns",
175    ObservedTaskCpuTimeNs => "observed_task_cpu_time_ns",
176    SystemCpuFraction => "system_cpu_fraction",
177    WorstMeanRunDelayUs => "worst_mean_run_delay_us",
178    WorstRunDelayUs => "worst_run_delay_us",
179    WorstWakeLatencyTailRatio => "worst_wake_latency_tail_ratio",
180    WorstIterationsPerWorker => "worst_iterations_per_worker",
181    WorstIterationsPerCpuSec => "worst_iterations_per_cpu_sec",
182    WorstPageLocality => "worst_page_locality",
183    WorstCrossNodeMigrationRatio => "worst_cross_node_migration_ratio",
184    TotalCpuTimeNs => "total_cpu_time_ns",
185
186    // IRQ observability — host-side observer-free signals, run-level
187    // ext-only (accessor |_| None; populated via the read_sample fold like
188    // system_time_ns). Counters / Gauge(Avg) / Peak + 3 derived rates + 2
189    // hidden capture-window duration components. Require num_snapshots >= 2
190    // (per_cpu_time freeze capture) + CONFIG_IRQ_TIME_ACCOUNTING for the
191    // time signals; loud-absent (None), never false-zero, when off. System-wide
192    // PSI-irq (psi_irq_full_avg10 / total_irq_pressure_us) is host-walked from
193    // the global psi_system per monitor sample and folded run-level, NOT a guest
194    // /proc read; see its own block below.
195    TotalHardirqs => "total_hardirqs",
196    TotalSoftirqNetRx => "total_softirq_net_rx",
197    TotalSoftirqNetTx => "total_softirq_net_tx",
198    TotalSoftirqTimer => "total_softirq_timer",
199    TotalSoftirqSched => "total_softirq_sched",
200    TotalIrqTimeNs => "total_irq_time_ns",
201    TotalSoftirqTimeNs => "total_softirq_time_ns",
202    TotalStealTimeNs => "total_steal_time_ns",
203    AvgIrqUtil => "avg_irq_util",
204    MaxAvgIrqUtil => "max_avg_irq_util",
205    HardirqsPerCpuSec => "hardirqs_per_cpu_sec",
206    NetRxSoftirqsPerCpuSec => "net_rx_softirqs_per_cpu_sec",
207    IrqTimeFraction => "irq_time_fraction",
208    // Hidden rate-denominator components (accessor |_| None, bucket-derived):
209    // the capture-WINDOW duration (first→last freeze span), NOT the full
210    // delivered guest CPU time. _sec backs count-rates; _ns the fraction.
211    TotalPhaseGuestCpuSec => "total_phase_guest_cpu_sec",
212    TotalPhaseGuestCpuNs => "total_phase_guest_cpu_ns",
213
214    // Per-CPU IRQ spatial axis (the busiest-CPU dimension; the IRQ counters
215    // above are the cross-CPU SUM). Custom per-CPU-delta bucket-fold, NOT a
216    // read_sample arm (read_sample yields one f64 per freeze, no per-CPU
217    // vector). max_cpu_hardirqs = max over CPUs of each CPU's hardirq delta;
218    // _concentration = max / mean over the reporting CPUs. Both Peak.
219    MaxCpuHardirqs => "max_cpu_hardirqs",
220    MaxCpuHardirqConcentration => "max_cpu_hardirq_concentration",
221    // Per-CPU NET_RX softirq spatial axis (the softirq sibling of the hardirq
222    // axis above): max_cpu_softirq_net_rx = busiest CPU's NET_RX softirq-run
223    // delta; _concentration = max / mean over reporting CPUs. Both Peak.
224    MaxCpuSoftirqNetRx => "max_cpu_softirq_net_rx",
225    MaxCpuSoftirqNetRxConcentration => "max_cpu_softirq_net_rx_concentration",
226    // scx_layered util-compensation scale: per-CPU first→last cpustat-delta
227    // clamped scale, then mean across CPUs. Gauge(Avg)/LowerBetter; same
228    // per-CPU-delta bucket-fold family as the per-CPU IRQ axis above
229    // (assert::phase_build::fold_util_comp_scale), NOT a read_sample arm.
230    AvgCpuUtilCompScale => "avg_cpu_util_comp_scale",
231
232    // scx_lavd per-task latency-criticality (normalized_lat_cri, [0,1024])
233    // host-read from the sdt_alloc arena each freeze, folded over (freeze, task):
234    // mean -> avg_task_lat_cri (Gauge(Avg)), max -> max_task_lat_cri (Peak). Both
235    // Informational; computed in assert::phase_build::fold_lat_cri, NOT a
236    // read_sample arm. lavd-only (loud-absent for schedulers whose arena payload
237    // has no normalized_lat_cri member).
238    AvgTaskLatCri => "avg_task_lat_cri",
239    MaxTaskLatCri => "max_task_lat_cri",
240
241    // Per-cgroup PSI-irq spatial axis (host cgroup-walk capture → per-phase fold):
242    // the busiest workload-leaf cgroup dimension. max_cgroup_irq_pressure = the busiest leaf's
243    // IRQ-full stall delta (µs); _concentration = max / mean over the reporting
244    // leaves (the cgroup-isolation signal); max_cgroup_psi_irq_avg10 = the worst
245    // leaf's avg10 gauge (%). All Peak; folded per-phase in assert::phase_build
246    // (fold_per_cgroup_psi) from the freeze cgroup_psi capture.
247    MaxCgroupIrqPressure => "max_cgroup_irq_pressure",
248    MaxCgroupIrqPressureConcentration => "max_cgroup_irq_pressure_concentration",
249    MaxCgroupPsiIrqAvg10 => "max_cgroup_psi_irq_avg10",
250
251    // System-wide PSI-irq pressure (host-walked from the global psi_system per
252    // monitor sample, folded run-level in MonitorSummary). avg10 = mean
253    // 10s-EWMA full-pressure percent (Gauge); total = cumulative full-stall µs
254    // over the window (Counter). Gated on CONFIG_PSI + CONFIG_IRQ_TIME_ACCOUNTING
255    // (PSI_IRQ_FULL in BTF); loud-absent (None) when off.
256    PsiIrqFullAvg10 => "psi_irq_full_avg10",
257    TotalIrqPressureUs => "total_irq_pressure_us",
258
259    // Per-phase scalars (MetricKind::PerPhase) — schbench / taobench engine
260    // metrics, surfaced via the per-phase PhaseBucket path (const-named).
261    WakeupP50LatencyUs => "wakeup_p50_latency_us",
262    WakeupP90LatencyUs => "wakeup_p90_latency_us",
263    WakeupP99LatencyUs => "wakeup_p99_latency_us",
264    WakeupP999LatencyUs => "wakeup_p999_latency_us",
265    RequestP50LatencyUs => "request_p50_latency_us",
266    RequestP90LatencyUs => "request_p90_latency_us",
267    RequestP99LatencyUs => "request_p99_latency_us",
268    RequestP999LatencyUs => "request_p999_latency_us",
269    SchedDelayMsgUs => "sched_delay_msg_us",
270    SchedDelayWorkerUs => "sched_delay_worker_us",
271    SchbenchLoopCount => "schbench_loop_count",
272    TaobenchTotalOpsPerCpuSec => "taobench_total_ops_per_cpu_sec",
273    TaobenchFastOpsPerCpuSec => "taobench_fast_ops_per_cpu_sec",
274    TaobenchSlowOpsPerCpuSec => "taobench_slow_ops_per_cpu_sec",
275    TaobenchHitRatio => "taobench_hit_ratio",
276    TaobenchHitRate => "taobench_hit_rate",
277    // taobench per-phase open-loop serve-latency percentiles (PerPhase, µs).
278    TaobenchServeP50Us => "taobench_serve_p50_us",
279    TaobenchServeP90Us => "taobench_serve_p90_us",
280    TaobenchServeP99Us => "taobench_serve_p99_us",
281    TaobenchServeP999Us => "taobench_serve_p999_us",
282    TaobenchServeMinUs => "taobench_serve_min_us",
283    TaobenchServeMaxUs => "taobench_serve_max_us",
284    WakeupMinLatencyUs => "wakeup_min_latency_us",
285    WakeupMaxLatencyUs => "wakeup_max_latency_us",
286    RequestMinLatencyUs => "request_min_latency_us",
287    RequestMaxLatencyUs => "request_max_latency_us",
288    RpsP20 => "rps_p20",
289    RpsP50 => "rps_p50",
290    RpsP90 => "rps_p90",
291    RpsMin => "rps_min",
292    RpsMax => "rps_max",
293
294    // Per-phase scalars inserted as bare literals by the non-schbench carrier
295    // derivation (run_metrics.rs write_carrier_scalars) — the per-cgroup
296    // wake/run-delay/off-cpu/migration/locality family.
297    P99WakeLatencyUs => "p99_wake_latency_us",
298    MedianWakeLatencyUs => "median_wake_latency_us",
299    WakeLatencyCv => "wake_latency_cv",
300    P99TimerLatencyUs => "p99_timer_latency_us",
301    MedianTimerLatencyUs => "median_timer_latency_us",
302    P999TimerLatencyUs => "p999_timer_latency_us",
303    MeanRunDelayUs => "mean_run_delay_us",
304    MaxRunDelayUs => "max_run_delay_us",
305    AvgOffCpuPct => "avg_off_cpu_pct",
306    MinOffCpuPct => "min_off_cpu_pct",
307    MaxOffCpuPct => "max_off_cpu_pct",
308    OffCpuSpreadPct => "off_cpu_spread_pct",
309    MigrationRatio => "migration_ratio",
310    IterationsPerWorker => "iterations_per_worker",
311    PageLocality => "page_locality",
312    CrossNodeMigrationRatio => "cross_node_migration_ratio",
313}
314
315impl BuiltinMetric {
316    /// The full registry definition (polarity / kind / unit / tolerances /
317    /// accessor). Total — the pin-test guarantees every variant resolves in
318    /// `super::METRICS`.
319    pub fn def(self) -> &'static MetricDef {
320        metric_def(self.wire_name())
321            .expect("BuiltinMetric variant must resolve in METRICS (pinned by test)")
322    }
323}
324
325/// A metric identifier accepted by every metric accessor via `impl Into<MetricId>`:
326/// a typed [`BuiltinMetric`] (the common, discoverable, typo-proof case) or a
327/// dynamic scheduler-runtime / payload string (the open keyspace). One call shape
328/// for both — `phase_metric(BuiltinMetric::X)` and `phase_metric("runtime_key")`.
329#[derive(Debug, Clone, PartialEq, Eq, Hash)]
330pub enum MetricId {
331    /// A compile-time-known built-in metric (carries its registry kind via
332    /// [`BuiltinMetric::def`]).
333    Builtin(BuiltinMetric),
334    /// A scheduler-runtime / payload-supplied key not in the built-in registry.
335    Dynamic(Cow<'static, str>),
336}
337
338impl MetricId {
339    /// The wire-name key — into `super::METRICS` and the ext-metrics maps. For
340    /// a `Builtin` this is the inner [`BuiltinMetric::wire_name`]; for a `Dynamic`
341    /// it is the raw key string.
342    pub fn as_str(&self) -> &str {
343        match self {
344            MetricId::Builtin(b) => b.wire_name(),
345            MetricId::Dynamic(s) => s.as_ref(),
346        }
347    }
348
349    /// The registry definition if this id names a REGISTERED metric — `Some` for
350    /// every `Builtin`; `None` for a genuine scheduler-runtime key. Via the `From`
351    /// impls a registered name canonicalizes to `Builtin`, so a `Dynamic` reached
352    /// through the public `impl Into<MetricId>` path never holds a registered name
353    /// and resolves to `None` here; the `Dynamic` registry lookup is a defensive
354    /// fallback for a directly-constructed `MetricId::Dynamic`. The GUARDRAIL: a
355    /// `None` here means no declared kind, so the caller must not aggregate the
356    /// value as a guessed kind (resolve-by-name or fold conservatively).
357    pub fn def(&self) -> Option<&'static MetricDef> {
358        match self {
359            MetricId::Builtin(b) => Some(b.def()),
360            MetricId::Dynamic(s) => metric_def(s.as_ref()),
361        }
362    }
363}
364
365impl From<BuiltinMetric> for MetricId {
366    fn from(b: BuiltinMetric) -> Self {
367        MetricId::Builtin(b)
368    }
369}
370
371impl From<&BuiltinMetric> for MetricId {
372    /// Borrowed-`BuiltinMetric` convenience — sweeping [`BuiltinMetric::ALL`]
373    /// yields `&BuiltinMetric`; it is `Copy`, so this is a trivial copy-then-wrap.
374    fn from(b: &BuiltinMetric) -> Self {
375        MetricId::Builtin(*b)
376    }
377}
378
379impl From<&str> for MetricId {
380    /// Canonicalize a string: if it names a built-in, yield the typed `Builtin`
381    /// (so a known reached by string still carries the typed identity + kind);
382    /// otherwise `Dynamic`. A non-built-in `&str` is owned (the dynamic path is
383    /// not hot; correctness over the micro-alloc).
384    fn from(s: &str) -> Self {
385        match BuiltinMetric::from_wire_name(s) {
386            Some(b) => MetricId::Builtin(b),
387            None => MetricId::Dynamic(Cow::Owned(s.to_owned())),
388        }
389    }
390}
391
392impl From<String> for MetricId {
393    fn from(s: String) -> Self {
394        match BuiltinMetric::from_wire_name(&s) {
395            Some(b) => MetricId::Builtin(b),
396            None => MetricId::Dynamic(Cow::Owned(s)),
397        }
398    }
399}
400
401impl From<&String> for MetricId {
402    /// Borrowed-`String` convenience — iterating owned metric names (a
403    /// `HashMap<String, _>`'s keys, a `Vec<String>`) yields `&String`;
404    /// delegates to the `&str` canonicalization.
405    fn from(s: &String) -> Self {
406        Self::from(s.as_str())
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use crate::stats::METRICS;
414
415    /// The enum is pinned 1:1 to the registry, both directions, so adding a
416    /// METRICS entry without a BuiltinMetric variant (or vice versa) fails here.
417    #[test]
418    fn builtin_metric_is_one_to_one_with_registry() {
419        // (1) every variant resolves to a registry entry.
420        for b in BuiltinMetric::ALL {
421            assert!(
422                metric_def(b.wire_name()).is_some(),
423                "BuiltinMetric::{b:?} (wire {:?}) is not in METRICS",
424                b.wire_name()
425            );
426        }
427        // (2) every registry entry has a variant (no entry without a typed id).
428        for m in METRICS {
429            assert!(
430                BuiltinMetric::from_wire_name(m.name).is_some(),
431                "METRICS entry {:?} has no BuiltinMetric variant",
432                m.name
433            );
434        }
435        // (3) cardinality: catches a duplicate variant or a duplicate registry
436        // name that (1)+(2) would individually miss.
437        assert_eq!(
438            BuiltinMetric::ALL.len(),
439            METRICS.len(),
440            "BuiltinMetric::ALL ({}) != METRICS ({})",
441            BuiltinMetric::ALL.len(),
442            METRICS.len()
443        );
444    }
445
446    /// wire_name <-> from_wire_name roundtrips for every variant.
447    #[test]
448    fn wire_name_roundtrips() {
449        for b in BuiltinMetric::ALL {
450            assert_eq!(BuiltinMetric::from_wire_name(b.wire_name()), Some(*b));
451        }
452    }
453
454    /// The MetricId hybrid: a built-in string canonicalizes to Builtin (typed +
455    /// def() resolves); a non-built-in string stays Dynamic with def() == None
456    /// (the no-guessed-kind guardrail).
457    #[test]
458    fn metric_id_canonicalizes_builtin_and_quarantines_dynamic() {
459        let typed: MetricId = BuiltinMetric::TaobenchTotalOpsPerCpuSec.into();
460        let from_str: MetricId = "taobench_total_ops_per_cpu_sec".into();
461        assert_eq!(
462            typed, from_str,
463            "a built-in string canonicalizes to Builtin"
464        );
465        assert_eq!(typed.as_str(), "taobench_total_ops_per_cpu_sec");
466        assert!(typed.def().is_some(), "a built-in carries its registry def");
467
468        let dynamic: MetricId = "scx_layered_layer0_depth".into();
469        assert!(
470            matches!(dynamic, MetricId::Dynamic(_)),
471            "a non-registered key stays Dynamic"
472        );
473        assert!(
474            dynamic.def().is_none(),
475            "a Dynamic key has no def() -> caller must not guess its kind"
476        );
477    }
478}