commonware-runtime 2026.5.0

Execute asynchronous tasks with a configurable scheduler.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! Utility functions for metrics

pub mod histogram;
mod registration;
pub mod status;
pub(crate) mod task;

/// Prefix for runtime metrics.
pub(crate) const METRICS_PREFIX: &str = "runtime";

pub use commonware_runtime_macros::{EncodeLabelSet, EncodeLabelValue, EncodeStruct};
pub use prometheus_client::{
    collector, encoding,
    encoding::{
        CounterValueEncoder, DescriptorEncoder, EncodeCounterValue, EncodeExemplarTime,
        EncodeExemplarValue, EncodeGaugeValue, EncodeLabel, EncodeLabelKey,
        EncodeLabelSet as EncodeLabelSetTrait, EncodeLabelValue as EncodeLabelValueTrait,
        EncodeMetric, ExemplarValueEncoder, GaugeValueEncoder, LabelEncoder, LabelKeyEncoder,
        LabelSetEncoder, LabelValueEncoder, MetricEncoder, NoLabelSet,
    },
    metrics::{MetricType, TypedMetric},
    registry,
    registry::Metric,
};

/// Underlying Prometheus metric types. Used when constructing a metric
/// to pass to [`crate::Metrics::register`].
pub mod raw {
    pub use prometheus_client::metrics::{
        counter::Counter,
        family::{self, Family},
        gauge::Gauge,
        histogram::Histogram,
    };
}

use commonware_utils::sync::Mutex;
use prometheus_client::encoding::{
    text::{encode, encode_eof},
    MetricEncoder as PromMetricEncoder,
};
pub use registration::Registration;
use std::{
    any::Any,
    borrow::Cow,
    collections::{BTreeMap, HashMap},
    ops::Deref,
    sync::{atomic::Ordering, Arc, Weak},
};

/// Native integer width used by [`raw::Gauge`] on this target.
///
/// `i64` on platforms with 64-bit atomics, `i32` otherwise. Matches
/// `prometheus_client::metrics::gauge::Gauge`'s backing type.
#[cfg(target_has_atomic = "64")]
pub type GaugeValue = i64;
#[cfg(not(target_has_atomic = "64"))]
pub type GaugeValue = i32;

/// A registered counter metric.
pub type Counter = Registered<raw::Counter>;
/// A registered gauge metric.
pub type Gauge = Registered<raw::Gauge>;
/// A registered histogram metric.
pub type Histogram = Registered<raw::Histogram>;
/// A registered family of counters keyed by `L`.
pub type CounterFamily<L> = Registered<raw::Family<L, raw::Counter>>;
/// A registered family of gauges keyed by `L`.
pub type GaugeFamily<L> = Registered<raw::Family<L, raw::Gauge>>;

/// Convenience methods for Prometheus gauges.
pub trait GaugeExt {
    /// Set a gauge from a lossless integer conversion.
    fn try_set<T: TryInto<GaugeValue>>(&self, value: T) -> Result<GaugeValue, T::Error>;

    /// Atomically raise a gauge to at least the provided value.
    fn try_set_max<T: TryInto<GaugeValue> + Copy>(&self, value: T) -> Result<GaugeValue, T::Error>;
}

impl GaugeExt for raw::Gauge {
    fn try_set<T: TryInto<GaugeValue>>(&self, value: T) -> Result<GaugeValue, T::Error> {
        let value = value.try_into()?;
        Ok(self.set(value))
    }

    fn try_set_max<T: TryInto<GaugeValue> + Copy>(&self, value: T) -> Result<GaugeValue, T::Error> {
        let value = value.try_into()?;
        Ok(self.inner().fetch_max(value, Ordering::Relaxed))
    }
}

pub use histogram::HistogramExt;

/// One-line constructors for the common metric types.
pub trait MetricsExt: crate::Metrics {
    /// Register a counter with the runtime.
    fn counter<N: Into<String>, H: Into<String>>(&self, name: N, help: H) -> Counter {
        self.register(name, help, raw::Counter::default())
    }

    /// Register a gauge with the runtime.
    fn gauge<N: Into<String>, H: Into<String>>(&self, name: N, help: H) -> Gauge {
        self.register(name, help, raw::Gauge::default())
    }

    /// Register a histogram with the runtime.
    fn histogram<N: Into<String>, H: Into<String>, I>(
        &self,
        name: N,
        help: H,
        buckets: I,
    ) -> Histogram
    where
        I: IntoIterator<Item = f64>,
    {
        self.register(name, help, raw::Histogram::new(buckets))
    }

    /// Register a metric family with the runtime.
    fn family<N, H, S, M>(&self, name: N, help: H) -> Registered<raw::Family<S, M>>
    where
        N: Into<String>,
        H: Into<String>,
        S: Clone + std::hash::Hash + Eq,
        M: Default,
        raw::Family<S, M>: Metric,
    {
        self.register(name, help, raw::Family::<S, M>::default())
    }
}

impl<T: crate::Metrics> MetricsExt for T {}

/// Validates that a label matches Prometheus metric name format: `[a-zA-Z][a-zA-Z0-9_]*`.
///
/// # Panics
///
/// Panics if the label is empty, starts with a non-alphabetic character,
/// or contains characters other than `[a-zA-Z0-9_]`.
pub fn validate_label(label: &str) {
    let mut chars = label.chars();
    assert!(
        chars.next().is_some_and(|c| c.is_ascii_alphabetic()),
        "label must start with [a-zA-Z]: {label}"
    );
    assert!(
        chars.all(|c| c.is_ascii_alphanumeric() || c == '_'),
        "label must only contain [a-zA-Z0-9_]: {label}"
    );
}

/// Add an attribute to a sorted attribute list, maintaining sorted order via binary search.
///
/// Returns `true` if the key was new, `false` if it was a duplicate (value overwritten).
pub fn add_attribute(
    attributes: &mut Vec<(String, String)>,
    key: &str,
    value: impl std::fmt::Display,
) -> bool {
    let key_string = key.to_string();
    let value_string = value.to_string();

    match attributes.binary_search_by(|(k, _)| k.cmp(&key_string)) {
        Ok(pos) => {
            attributes[pos].1 = value_string;
            false
        }
        Err(pos) => {
            attributes.insert(pos, (key_string, value_string));
            true
        }
    }
}

#[cfg(any(test, feature = "test-utils"))]
fn matches_metric_name(full: &str, name: &str) -> bool {
    full == name
        || full
            .strip_suffix(name)
            .is_some_and(|prefix| prefix.ends_with('_'))
}

/// Return `true` if encoded Prometheus metrics contain a sample with `name` and `value`.
///
/// `name` may be either the full encoded metric name or its unprefixed suffix.
/// Labels attached to the sample are ignored.
#[cfg(any(test, feature = "test-utils"))]
#[must_use]
pub fn has_metric_value(metrics: &str, name: &str, value: impl std::fmt::Display) -> bool {
    let value = value.to_string();
    metrics.lines().any(|line| {
        let line = line.trim();
        if line.starts_with('#') {
            return false;
        }

        let Some(sample_end) = line.find(|c: char| c == '{' || c.is_whitespace()) else {
            return false;
        };
        let sample_name = &line[..sample_end];
        if !matches_metric_name(sample_name, name) {
            return false;
        }

        let mut rest = &line[sample_end..];
        if let Some(labeled) = rest.strip_prefix('{') {
            let Some(labels_end) = labeled.find('}') else {
                return false;
            };
            rest = &labeled[labels_end + 1..];
        }
        if !rest.chars().next().is_some_and(char::is_whitespace) {
            return false;
        }

        rest.split_whitespace().next() == Some(value.as_str())
    })
}

/// Count the number of running tasks whose name starts with the given prefix.
///
/// This function encodes metrics and counts tasks that are currently running
/// (have a value of 1) and whose name starts with the specified prefix.
///
/// This is useful for verifying that all child tasks under a given label hierarchy
/// have been properly shut down.
///
/// # Example
///
/// ```rust
/// use commonware_runtime::{
///     deterministic, telemetry::metrics::count_running_tasks, Clock, Metrics, Runner, Spawner,
///     Supervisor,
/// };
/// use std::time::Duration;
///
/// let executor = deterministic::Runner::default();
/// executor.start(|context| async move {
///     // Spawn a task under a labeled context
///     let handle = context.child("worker").spawn(|ctx| async move {
///         ctx.sleep(Duration::from_secs(100)).await;
///     });
///
///     // Allow the task to start
///     context.sleep(Duration::from_millis(10)).await;
///
///     // Count running tasks with "worker" prefix
///     let count = count_running_tasks(&context, "worker");
///     assert!(count > 0, "worker task should be running");
///
///     // Abort the task
///     handle.abort();
///     let _ = handle.await;
///     context.sleep(Duration::from_millis(10)).await;
///
///     // Verify task is stopped
///     let count = count_running_tasks(&context, "worker");
///     assert_eq!(count, 0, "worker task should be stopped");
/// });
/// ```
#[cfg(any(test, feature = "test-utils"))]
pub fn count_running_tasks(metrics: &impl crate::Metrics, prefix: &str) -> usize {
    let encoded = metrics.encode();
    encoded
        .lines()
        .filter_map(|line| {
            if !line.starts_with("runtime_tasks_running{") || !line.contains("kind=\"Task\"") {
                return None;
            }
            let name = line.split("name=\"").nth(1)?.split('"').next()?;
            if !name.starts_with(prefix) {
                return None;
            }
            line.trim_end().rsplit(' ').next()?.parse::<usize>().ok()
        })
        .sum()
}

// Adaptation of client_rust's internal descriptor encoder.
//
// Source:
// https://github.com/prometheus/client_rust/blob/4a6d40a55443d5b18f5be311d246c03e56f417d6/src/encoding/text.rs#L218-L275
fn encode_descriptor<W>(
    writer: &mut W,
    name: &str,
    help: &str,
    metric_type: MetricType,
) -> Result<(), std::fmt::Error>
where
    W: std::fmt::Write,
{
    writer.write_str("# HELP ")?;
    writer.write_str(name)?;
    writer.write_str(" ")?;
    writer.write_str(help)?;
    writer.write_str("\n# TYPE ")?;
    writer.write_str(name)?;
    writer.write_str(" ")?;
    writer.write_str(metric_type.as_str())?;
    writer.write_str("\n")?;
    Ok(())
}

/// Join a metric or label prefix with a child name using Prometheus' `_` separator.
pub(crate) fn prefixed_name(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_string()
    } else {
        format!("{prefix}_{name}")
    }
}

/// Build a child context label by appending `label` to `prefix`, asserting that
/// `label` is valid and does not shadow the reserved runtime metric prefix.
pub(crate) fn child_label(prefix: &str, label: &str) -> String {
    validate_label(label);
    let name = prefixed_name(prefix, label);
    assert!(
        !name.starts_with(METRICS_PREFIX),
        "using runtime label is not allowed"
    );
    name
}

struct RegistryGuard {
    id: usize,
    registry: Weak<Mutex<RegistryInner>>,
}

impl Drop for RegistryGuard {
    fn drop(&mut self) {
        let Some(registry) = self.registry.upgrade() else {
            return;
        };
        registry.lock().release_registration(self.id);
    }
}

/// A metric handle whose lifetime controls registry exposure and attached cleanup.
#[must_use = "registered metrics are removed when the returned handle is dropped"]
pub struct Registered<M> {
    metric: Arc<M>,
    registration: Registration,
}

impl<M> Clone for Registered<M> {
    fn clone(&self) -> Self {
        Self {
            metric: self.metric.clone(),
            registration: self.registration.clone(),
        }
    }
}

impl<M> Registered<M> {
    /// Create a metric handle with an explicit lifecycle registration.
    ///
    /// The provided [`Registration`] controls what happens when the last clone
    /// of this handle is dropped. Use [`Registration::from`] with `()` for a
    /// raw handle that is not exposed by a runtime registry.
    pub fn with_registration(metric: M, registration: Registration) -> Self {
        Self {
            metric: Arc::new(metric),
            registration,
        }
    }

    pub fn metric(&self) -> &M {
        self.metric.as_ref()
    }
}

impl<S, M, C> Registered<raw::Family<S, M, C>>
where
    S: Clone + std::hash::Hash + Eq,
    C: raw::family::MetricConstructor<M>,
{
    pub fn get_by<Q>(&self, label_set: &Q) -> Option<impl Deref<Target = M> + '_>
    where
        for<'a> S: From<&'a Q>,
    {
        let label_set = S::from(label_set);
        self.get(&label_set)
    }

    pub fn get_or_create_by<Q>(&self, label_set: &Q) -> impl Deref<Target = M> + '_
    where
        for<'a> S: From<&'a Q>,
    {
        let label_set = S::from(label_set);
        self.get_or_create(&label_set)
    }

    pub fn remove_by<Q>(&self, label_set: &Q) -> bool
    where
        for<'a> S: From<&'a Q>,
    {
        let label_set = S::from(label_set);
        self.remove(&label_set)
    }
}

impl<M> Deref for Registered<M> {
    type Target = M;

    fn deref(&self) -> &Self::Target {
        self.metric()
    }
}

impl<M: std::fmt::Debug> std::fmt::Debug for Registered<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Registered")
            .field("metric", self.metric())
            .finish_non_exhaustive()
    }
}

type MetricAttributes = Vec<(Cow<'static, str>, Cow<'static, str>)>;
type MetricKey = (String, MetricAttributes);
type SampleEncoder = dyn Fn(&mut String) -> Result<(), std::fmt::Error> + Send + Sync;

struct PendingMetricEntry {
    family_name: String,
    attributes: MetricAttributes,
    encode_samples: Box<SampleEncoder>,
    metric_any: Arc<dyn Any + Send + Sync>,
}

pub(crate) struct SharedMetric<M>(pub(crate) Arc<M>);

impl<M: std::fmt::Debug> std::fmt::Debug for SharedMetric<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<M: EncodeMetric> EncodeMetric for SharedMetric<M> {
    fn encode(&self, encoder: PromMetricEncoder<'_>) -> Result<(), std::fmt::Error> {
        self.0.encode(encoder)
    }

    fn metric_type(&self) -> MetricType {
        self.0.metric_type()
    }
}

fn create_sample_encoder<M>(
    name: String,
    labels: MetricAttributes,
    metric: Arc<M>,
) -> Box<SampleEncoder>
where
    M: Metric,
{
    // TODO (#3659): Avoid allocating an upstream registry per metric once
    // `prometheus-client` exposes a public sample-only `MetricEncoder` path
    // for encoding one metric with const labels.
    let mut registry = registry::Registry::with_labels(labels.into_iter());
    registry.register(name, "", SharedMetric(metric));

    Box::new(move |samples| {
        let mut encoded = String::new();
        encode(&mut encoded, &registry).expect("encoding temporary metric registry failed");
        for line in encoded.lines() {
            if line.starts_with('#') {
                continue;
            }
            samples.push_str(line);
            samples.push('\n');
        }
        Ok(())
    })
}

fn owned_attributes(attributes: Vec<(String, String)>) -> MetricAttributes {
    attributes
        .into_iter()
        .map(|(k, v)| (Cow::Owned(k), Cow::Owned(v)))
        .collect()
}

// Match upstream prometheus-client's `Descriptor::new` normalization.
//
// Source:
// https://github.com/prometheus/client_rust/blob/4a6d40a55443d5b18f5be311d246c03e56f417d6/src/registry.rs#L340-L348
fn normalize_help(help: String) -> String {
    help + "."
}

struct MetricEntry {
    family_name: String,
    attributes: MetricAttributes,
    encode_samples: Box<SampleEncoder>,
    metric_any: Arc<dyn Any + Send + Sync>,
    claims: usize,
    family_index: usize,
}

#[derive(Debug)]
struct MetricFamily {
    help: String,
    metric_type: MetricType,
    descriptor: String,
    metric_ids: Vec<usize>,
}

/// Manages metrics with explicit lifetimes.
#[derive(Clone)]
pub struct Registry {
    inner: Arc<Mutex<RegistryInner>>,
}

struct RegistryInner {
    /// Dense metric storage indexed by stable metric id.
    metrics: Vec<Option<MetricEntry>>,
    /// Metric ids that can be reused after a metric is fully unregistered.
    free_metric_ids: Vec<usize>,
    /// Metric families keyed by family name, kept sorted for deterministic encoding.
    families: BTreeMap<String, MetricFamily>,
    /// Exact metric keys for duplicate registration detection.
    keys: HashMap<MetricKey, usize>,
    /// Monotonic id source used when there is no reusable metric slot.
    next_metric_id: usize,
}

impl Default for Registry {
    fn default() -> Self {
        Self::new()
    }
}

impl Registry {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(RegistryInner::new())),
        }
    }

    pub(crate) fn register<M>(
        &self,
        name: String,
        help: String,
        attributes: Vec<(String, String)>,
        metric: Arc<M>,
    ) -> Registered<M>
    where
        M: Metric,
    {
        let mut inner = self.inner.lock();
        inner.register(Arc::downgrade(&self.inner), name, help, attributes, metric)
    }

    pub fn encode(&self) -> String {
        self.inner.lock().encode()
    }
}

impl RegistryInner {
    fn new() -> Self {
        Self {
            metrics: Vec::new(),
            free_metric_ids: Vec::new(),
            families: BTreeMap::new(),
            keys: HashMap::new(),
            next_metric_id: 0,
        }
    }

    fn register<M>(
        &mut self,
        registry: Weak<Mutex<Self>>,
        name: String,
        help: String,
        attributes: Vec<(String, String)>,
        metric: Arc<M>,
    ) -> Registered<M>
    where
        M: Metric,
    {
        let attributes = owned_attributes(attributes);
        let help = normalize_help(help);
        let metric_type = metric.metric_type();
        let encode_samples =
            create_sample_encoder(name.clone(), attributes.clone(), metric.clone());
        let key = (name.clone(), attributes.clone());
        if let Some(existing_id) = self.keys.get(&key).copied() {
            let entry = self.metric_ref(existing_id);
            if let Some(family) = self.families.get(&name) {
                assert_eq!(
                    family.help, help,
                    "metric family `{}` registered with inconsistent help text",
                    name
                );
            }
            let existing_metric = Arc::clone(&entry.metric_any)
                .downcast::<M>()
                .unwrap_or_else(|_| {
                    panic!(
                        "duplicate metric `{}` with attributes {:?} registered with different type",
                        key.0, key.1
                    )
                });
            self.claim_registration(existing_id);
            return Registered {
                metric: existing_metric,
                registration: Registration::from(RegistryGuard {
                    id: existing_id,
                    registry,
                }),
            };
        }
        self.assert_family_matches(&name, &help, metric_type);

        let id = self.allocate_metric_id();
        let registration = Registration::from(RegistryGuard { id, registry });
        let metric_any: Arc<dyn Any + Send + Sync> = metric.clone();
        self.insert_metric_entry(
            id,
            help,
            metric_type,
            PendingMetricEntry {
                family_name: name,
                attributes,
                encode_samples,
                metric_any,
            },
        );
        Registered {
            metric,
            registration,
        }
    }

    fn metric_slot_mut(&mut self, id: usize) -> &mut Option<MetricEntry> {
        if id == self.metrics.len() {
            self.metrics.push(None);
        }
        &mut self.metrics[id]
    }

    fn metric_ref(&self, id: usize) -> &MetricEntry {
        self.metrics
            .get(id)
            .and_then(Option::as_ref)
            .expect("metric id missing from registry")
    }

    fn metric_mut(&mut self, id: usize) -> &mut MetricEntry {
        self.metrics
            .get_mut(id)
            .and_then(Option::as_mut)
            .expect("metric id missing from registry")
    }

    fn allocate_metric_id(&mut self) -> usize {
        if let Some(id) = self.free_metric_ids.pop() {
            return id;
        }
        let id = self.next_metric_id;
        self.next_metric_id = self
            .next_metric_id
            .checked_add(1)
            .expect("metric id overflow");
        id
    }

    fn assert_family_matches(&self, name: &str, help: &str, metric_type: MetricType) {
        if let Some(family) = self.families.get(name) {
            assert_eq!(
                family.help, help,
                "metric family `{}` registered with inconsistent help text",
                name
            );
            assert_eq!(
                family.metric_type.as_str(),
                metric_type.as_str(),
                "metric family `{}` registered with inconsistent metric type",
                name
            );
        }
    }

    fn insert_metric_entry(
        &mut self,
        id: usize,
        help: String,
        metric_type: MetricType,
        entry: PendingMetricEntry,
    ) {
        let PendingMetricEntry {
            family_name,
            attributes,
            encode_samples,
            metric_any,
        } = entry;
        self.keys
            .insert((family_name.clone(), attributes.clone()), id);
        let family = match self.families.entry(family_name.clone()) {
            std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
            std::collections::btree_map::Entry::Vacant(entry) => {
                let mut descriptor = String::new();
                encode_descriptor(&mut descriptor, &family_name, &help, metric_type)
                    .expect("encoding cached descriptor failed");
                entry.insert(MetricFamily {
                    help,
                    metric_type,
                    descriptor,
                    metric_ids: Vec::new(),
                })
            }
        };
        let family_index = family.metric_ids.len();
        family.metric_ids.push(id);
        self.metric_slot_mut(id).replace(MetricEntry {
            family_name,
            attributes,
            encode_samples,
            metric_any,
            claims: 1,
            family_index,
        });
    }

    fn claim_registration(&mut self, id: usize) {
        let entry = self.metric_mut(id);
        entry.claims = entry
            .claims
            .checked_add(1)
            .expect("registration claims overflow");
    }

    fn release_registration(&mut self, id: usize) {
        let entry = self.metric_mut(id);
        entry.claims = entry
            .claims
            .checked_sub(1)
            .expect("registration claim count underflow");
        if entry.claims > 0 {
            return;
        }
        self.drop_metric_entry(id);
    }

    fn drop_metric_entry(&mut self, id: usize) {
        let metric = self
            .metrics
            .get_mut(id)
            .and_then(Option::take)
            .expect("metric id missing from registry");
        let MetricEntry {
            family_name,
            attributes,
            family_index,
            ..
        } = metric;
        let key = (family_name, attributes);
        if self.keys.get(&key).copied() == Some(id) {
            self.keys.remove(&key);
        }
        let (family_name, _) = key;
        let (swapped_metric_id, remove_family) = {
            let family = self
                .families
                .get_mut(&family_name)
                .expect("family missing during unregister");
            let removed = family.metric_ids.swap_remove(family_index);
            assert_eq!(removed, id, "family index mismatch during unregister");
            let swapped = family.metric_ids.get(family_index).copied();
            (swapped, family.metric_ids.is_empty())
        };
        if let Some(swapped_metric_id) = swapped_metric_id {
            self.metric_mut(swapped_metric_id).family_index = family_index;
        }
        if remove_family {
            self.families.remove(&family_name);
        }
        self.free_metric_ids.push(id);
    }

    pub fn encode(&self) -> String {
        let mut output = String::new();
        let mut samples = String::new();
        for family in self.families.values() {
            samples.clear();
            for metric_id in &family.metric_ids {
                let metric = self.metric_ref(*metric_id);
                (metric.encode_samples)(&mut samples).expect("encoding live metric samples failed");
            }
            // Suppress the HELP/TYPE descriptor when the family produced no
            // samples (e.g. a `Family<S, M>` with no child entries). Matches
            // upstream prometheus-client's empty-metric filtering.
            if samples.is_empty() {
                continue;
            }
            output.push_str(&family.descriptor);
            output.push_str(&samples);
        }

        encode_eof(&mut output).expect("encoding EOF failed");
        output
    }
}

pub(crate) struct Scope {
    registry: Registry,
    prefix: String,
}

pub(crate) trait Register {
    /// Register a metric under this scope's prefix.
    fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M>;

    /// Create a child scope by appending `prefix` to the current prefix.
    fn sub_registry(&mut self, prefix: &str) -> Scope;
}

impl Register for Registry {
    fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M> {
        validate_label(name);
        Self::register(
            self,
            name.to_string(),
            help.to_string(),
            Vec::new(),
            Arc::new(metric),
        )
    }

    fn sub_registry(&mut self, prefix: &str) -> Scope {
        validate_label(prefix);
        Scope {
            registry: self.clone(),
            prefix: prefix.to_string(),
        }
    }
}

impl Register for Scope {
    fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M> {
        validate_label(name);
        let name = prefixed_name(&self.prefix, name);
        let help = help.to_string();
        let metric = Arc::new(metric);
        Registry::register(&self.registry, name, help, Vec::new(), metric)
    }

    fn sub_registry(&mut self, prefix: &str) -> Scope {
        validate_label(prefix);
        Self {
            registry: self.registry.clone(),
            prefix: prefixed_name(&self.prefix, prefix),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{deterministic, Metrics as _, Runner, Spawner, Supervisor as _};
    use commonware_macros::test_traced;
    use futures::future;
    use std::sync::mpsc::{self, TryRecvError};

    #[test]
    fn test_has_metric_value_unlabeled() {
        let metrics = "# HELP storage_items_tracked items\nstorage_items_tracked 2\n";
        assert!(has_metric_value(metrics, "items_tracked", 2));
        assert!(has_metric_value(metrics, "storage_items_tracked", 2));
        assert!(!has_metric_value(metrics, "items_tracked_extra", 2));
        assert!(!has_metric_value(metrics, "items_tracked", 3));
    }

    #[test]
    fn test_has_metric_value_labeled() {
        let metrics = r#"storage_init_items_tracked{index="2"} 2"#;
        assert!(has_metric_value(metrics, "items_tracked", 2));
        assert!(has_metric_value(metrics, "storage_init_items_tracked", 2));
    }

    #[test_traced]
    fn test_count_running_tasks() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Initially no tasks with "worker" prefix
            assert_eq!(
                count_running_tasks(&context, "worker"),
                0,
                "no worker tasks initially"
            );

            // Spawn a task under a labeled context that stays running
            let handle1 = context.child("worker").spawn(|_| async move {
                future::pending::<()>().await;
            });

            // Count running tasks with "worker" prefix
            let count = count_running_tasks(&context, "worker");
            assert_eq!(count, 1, "worker task should be running");

            // Non-matching prefix should return 0
            assert_eq!(
                count_running_tasks(&context, "other"),
                0,
                "no tasks with 'other' prefix"
            );

            // Spawn a nested task (worker_child)
            let handle2 = context
                .child("worker")
                .child("child")
                .spawn(|_| async move {
                    future::pending::<()>().await;
                });

            // Count should include both parent and nested tasks
            let count = count_running_tasks(&context, "worker");
            assert_eq!(count, 2, "both worker and worker_child should be counted");

            // Abort parent task
            handle1.abort();
            let _ = handle1.await;

            // Only nested task remains
            let count = count_running_tasks(&context, "worker");
            assert_eq!(count, 1, "only worker_child should remain");

            // Abort nested task
            handle2.abort();
            let _ = handle2.await;

            // All tasks stopped
            assert_eq!(
                count_running_tasks(&context, "worker"),
                0,
                "all worker tasks should be stopped"
            );
        });
    }

    #[test_traced]
    fn test_no_duplicate_metrics() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Register metrics under different labels (no duplicates)
            let c1 = raw::Counter::<u64>::default();
            let _metric_a = context.child("a").register("test", "help", c1);
            let c2 = raw::Counter::<u64>::default();
            let _metric_b = context.child("b").register("test", "help", c2);
        });
        // Test passes if runtime doesn't panic on shutdown
    }

    #[test_traced]
    fn test_duplicate_metrics_reuse_existing_handle() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let c1 = raw::Counter::<u64>::default();
            let metric_a = context.child("a").register("test", "help", c1);
            let c2 = raw::Counter::<u64>::default();
            let metric_b = context.child("a").register("test", "help", c2);

            assert!(std::ptr::eq(metric_a.metric(), metric_b.metric()));

            metric_a.inc();
            metric_b.inc_by(2);
            let encoded = context.encode();
            assert!(encoded.contains("a_test_total 3"));
        });
    }

    #[test]
    fn test_claims_track_register_calls_not_handle_clones() {
        let registry = Registry::new();
        let key: MetricKey = ("votes".to_string(), Vec::new());

        let first = registry.register(
            key.0.clone(),
            "vote count".to_string(),
            Vec::new(),
            Arc::new(raw::Counter::<u64>::default()),
        );
        let first_clone = first.clone();
        let id = {
            let registry = registry.inner.lock();
            let id = *registry.keys.get(&key).expect("metric key missing");
            assert_eq!(registry.metric_ref(id).claims, 1);
            id
        };

        let second = registry.register(
            key.0,
            "vote count".to_string(),
            Vec::new(),
            Arc::new(raw::Counter::<u64>::default()),
        );
        let second_clone = second.clone();
        {
            let registry = registry.inner.lock();
            assert_eq!(registry.metric_ref(id).claims, 2);
        }

        drop(first);
        drop(second);
        {
            let registry = registry.inner.lock();
            assert_eq!(registry.metric_ref(id).claims, 2);
        }

        drop(second_clone);
        {
            let registry = registry.inner.lock();
            assert_eq!(registry.metric_ref(id).claims, 1);
        }

        drop(first_clone);
        let registry = registry.inner.lock();
        assert!(
            registry.keys.is_empty(),
            "keys left behind: {:?}",
            registry.keys
        );
        assert!(
            registry.families.is_empty(),
            "families left behind: {:?}",
            registry.families
        );
    }

    #[test]
    #[should_panic(expected = "registered with different type")]
    fn test_duplicate_metrics_different_type_panics() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let counter = raw::Counter::<u64>::default();
            let _metric_a = context.child("a").register("test", "help", counter);
            let gauge = raw::Gauge::<i64>::default();
            let _metric_b = context.child("a").register("test", "help", gauge);
        });
    }

    #[test]
    fn test_duplicate_register_acquires_during_last_drop_window() {
        let registry = Registry::new();
        let key: MetricKey = ("votes".to_string(), Vec::new());

        let original = registry.register(
            key.0.clone(),
            "vote count".to_string(),
            Vec::new(),
            Arc::new(raw::Counter::<u64>::default()),
        );
        let original_metric = Arc::clone(&original.metric);
        let _original = std::mem::ManuallyDrop::new(original);
        let original_id = {
            let registry = registry.inner.lock();
            *registry.keys.get(&key).expect("metric key missing")
        };
        // Simulate the final drop after it has decided to clean up but before
        // it obtains the registry lock. The dropped claim is still counted in
        // this window.
        let duplicate = registry.register(
            key.0,
            "vote count".to_string(),
            Vec::new(),
            Arc::new(raw::Counter::<u64>::default()),
        );
        assert!(Arc::ptr_eq(&original_metric, &duplicate.metric));

        registry.inner.lock().release_registration(original_id);

        duplicate.inc_by(7);
        let encoded = registry.encode();
        assert!(
            encoded.contains("votes_total 7"),
            "last drop removed duplicate registration: {encoded}"
        );

        drop(duplicate);
        let registry = registry.inner.lock();
        assert!(
            registry.keys.is_empty(),
            "keys left behind: {:?}",
            registry.keys
        );
        assert!(
            registry.families.is_empty(),
            "families left behind: {:?}",
            registry.families
        );
    }

    #[test]
    fn test_registered_with_registration_notifies_on_last_drop() {
        struct NotifyOnDrop(mpsc::Sender<&'static str>);

        impl Drop for NotifyOnDrop {
            fn drop(&mut self) {
                let _ = self.0.send("dropped");
            }
        }

        let (tx, rx) = mpsc::channel();
        let registered = Registered::with_registration(
            raw::Counter::<u64>::default(),
            Registration::from(NotifyOnDrop(tx)),
        );
        let clone = registered.clone();

        drop(registered);
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));

        drop(clone);
        assert_eq!(rx.recv().unwrap(), "dropped");
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
    }

    fn register_counter(registry: &Registry, name: &str, help: &str, value: u64) -> Counter {
        let counter = raw::Counter::<u64>::default();
        counter.inc_by(value);
        registry.register(
            name.to_string(),
            help.to_string(),
            Vec::new(),
            Arc::new(counter),
        )
    }

    #[test]
    fn test_encode_is_deterministic() {
        let registry = Registry::default();
        let _beta = register_counter(&registry, "beta", "beta counter", 2);
        let _alpha = register_counter(&registry, "alpha", "alpha counter", 1);
        let first = registry.encode();
        let second = registry.encode();
        assert_eq!(first, second);
        let alpha = first
            .find("# TYPE alpha")
            .expect("alpha family header present");
        let beta = first
            .find("# TYPE beta")
            .expect("beta family header present");
        assert!(alpha < beta, "families emitted in sorted order: {first}");
    }

    #[test]
    fn test_encode_emits_single_eof() {
        let registry = Registry::default();
        let _a = register_counter(&registry, "a", "help", 1);
        let _b = register_counter(&registry, "b", "help", 2);
        let encoded = registry.encode();
        assert_eq!(encoded.matches("# EOF").count(), 1);
        assert!(
            encoded.ends_with("# EOF\n"),
            "must terminate with EOF: {encoded}"
        );
    }

    #[test]
    fn test_encode_type_aware_suffixes() {
        let registry = Registry::default();
        let _requests = register_counter(&registry, "requests", "request count", 3);
        let histogram = raw::Histogram::new([0.1, 1.0, 10.0]);
        histogram.observe(0.5);
        let _histogram = registry.register(
            "latency".to_string(),
            "latency seconds".to_string(),
            Vec::new(),
            Arc::new(histogram),
        );
        let encoded = registry.encode();
        assert!(
            encoded.contains("requests_total 3"),
            "counter _total suffix: {encoded}"
        );
        assert!(
            encoded.contains("latency_bucket"),
            "histogram _bucket suffix: {encoded}"
        );
        assert!(
            encoded.contains("latency_sum"),
            "histogram _sum suffix: {encoded}"
        );
        assert!(
            encoded.contains("latency_count"),
            "histogram _count suffix: {encoded}"
        );
    }

    #[test]
    fn test_encode_shares_family_header_across_attributes() {
        let registry = Registry::default();
        let c1 = raw::Counter::<u64>::default();
        c1.inc();
        let _c1 = registry.register(
            "votes".to_string(),
            "vote count".to_string(),
            vec![("epoch".to_string(), "1".to_string())],
            Arc::new(c1),
        );
        let c2 = raw::Counter::<u64>::default();
        c2.inc_by(2);
        let _c2 = registry.register(
            "votes".to_string(),
            "vote count".to_string(),
            vec![("epoch".to_string(), "2".to_string())],
            Arc::new(c2),
        );
        let encoded = registry.encode();
        assert_eq!(
            encoded.matches("# HELP votes").count(),
            1,
            "single HELP: {encoded}"
        );
        assert_eq!(
            encoded.matches("# TYPE votes").count(),
            1,
            "single TYPE: {encoded}"
        );
        assert!(encoded.contains("votes_total{epoch=\"1\"} 1"));
        assert!(encoded.contains("votes_total{epoch=\"2\"} 2"));
    }

    #[test]
    fn test_encode_registers_without_prefix() {
        let registry = Registry::default();
        let _registered = register_counter(&registry, "votes", "vote count", 1);
        let encoded = registry.encode();
        assert!(
            encoded.contains("votes_total 1"),
            "no prefix applied: {encoded}"
        );
        assert!(
            encoded.starts_with("# HELP votes"),
            "family header at start: {encoded}"
        );
    }

    #[test]
    fn test_encode_suppresses_empty_family() {
        // A Family registered with no child entries should not emit its HELP/TYPE
        // descriptor on scrape. This matches upstream prometheus-client's
        // `encode_omit_empty` behavior.
        let registry = Registry::default();
        let empty_family = raw::Family::<Vec<(String, String)>, raw::Counter>::default();
        let _empty_family = registry.register(
            "votes".to_string(),
            "vote count".to_string(),
            Vec::new(),
            Arc::new(empty_family),
        );
        let _ticks = register_counter(&registry, "ticks", "tick count", 1);
        let encoded = registry.encode();
        assert!(!encoded.contains("votes"), "empty family leaked: {encoded}");
        assert!(
            encoded.contains("ticks_total 1"),
            "populated metric missing: {encoded}"
        );
        assert_eq!(encoded.matches("# EOF").count(), 1);
    }

    #[test]
    fn test_encode_matches_upstream_registry() {
        // Byte-for-byte parity between our `Registry::encode` and upstream
        // prometheus-client's `registry::Registry::encode` on an equivalent
        // metric set. Covers HELP normalization (trailing `.`), TYPE lines,
        // counter `_total` suffix, histogram `_bucket`/`_sum`/`_count`, and
        // the single final `# EOF`. Our registry emits families in sorted
        // order (see `test_encode_is_deterministic`); upstream preserves
        // registration order. Register here in sorted order so the parity
        // assertion only flags real format divergences.
        let counter = raw::Counter::<u64>::default();
        counter.inc_by(7);
        let gauge = raw::Gauge::<i64>::default();
        gauge.set(-3);
        let histogram = raw::Histogram::new([0.1, 1.0]);
        histogram.observe(0.5);

        let ours = Registry::default();
        let _latency = ours.register(
            "latency".to_string(),
            "request latency seconds".to_string(),
            Vec::new(),
            Arc::new(histogram.clone()),
        );
        let _level = ours.register(
            "level".to_string(),
            "current level".to_string(),
            Vec::new(),
            Arc::new(gauge.clone()),
        );
        let _votes = ours.register(
            "votes".to_string(),
            "number of votes".to_string(),
            Vec::new(),
            Arc::new(counter.clone()),
        );
        let ours_encoded = ours.encode();

        let mut theirs = registry::Registry::default();
        theirs.register("latency", "request latency seconds", histogram);
        theirs.register("level", "current level", gauge);
        theirs.register("votes", "number of votes", counter);
        let mut theirs_encoded = String::new();
        encode(&mut theirs_encoded, &theirs).expect("upstream encode failed");

        assert_eq!(
            ours_encoded, theirs_encoded,
            "output diverged from upstream prometheus-client registry"
        );
    }

    #[test]
    fn test_shuffled_duplicate_drops_do_not_leave_registry_entries() {
        let registry = Registry::new();
        let mut handles = Vec::new();

        for _ in 0..8 {
            handles.push(registry.register(
                "votes".to_string(),
                "vote count".to_string(),
                Vec::new(),
                Arc::new(raw::Counter::<u64>::default()),
            ));
        }

        for index in [3, 0, 6, 1] {
            let _ = handles.swap_remove(index);
            handles.push(registry.register(
                "votes".to_string(),
                "vote count".to_string(),
                Vec::new(),
                Arc::new(raw::Counter::<u64>::default()),
            ));
        }

        drop(handles);
        let registry = registry.inner.lock();
        assert!(
            registry.keys.is_empty(),
            "keys left behind: {:?}",
            registry.keys
        );
        assert!(
            registry.families.is_empty(),
            "families left behind: {:?}",
            registry.families
        );
    }
}