client_rust icon indicating copy to clipboard operation
client_rust copied to clipboard

Counter and Family encode empty LabelSet differently

Open howardjohn opened this issue 3 months ago • 2 comments

If you create a Family, the empty label set will encode like metric{} 2. If you use a raw Counter, it will encode like counter 2.

This seems like an unintended difference

use std::fmt::Error;
use prometheus_client::encoding::EncodeLabelSet;
use prometheus_client::encoding::text::encode;
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;

#[test]
fn test_counter_vs_family() {
    let mut registry = Registry::default();
    let family: Family::<EmptyLabels, Counter> = Family::default();
    let ctr: Counter = Counter::default();
    registry.register("family", "", family.clone());
    registry.register("counter", "", ctr.clone());

    #[derive(Eq, PartialEq, Hash, Debug, Clone)]
    struct EmptyLabels {}

    impl EncodeLabelSet for EmptyLabels {
        fn encode(&self, _encoder: &mut prometheus_client::encoding::LabelSetEncoder) -> Result<(), Error> {
            Ok(())
        }
    }

    family.get_or_create(&EmptyLabels {}).inc();
    ctr.inc();

    let mut encoded = String::new();

    encode(&mut encoded, &registry).unwrap();
    println!("{}", encoded);
}

# HELP family .
# TYPE family counter
family_total{} 1
# HELP counter .
# TYPE counter counter
counter_total 1
# EOF

howardjohn avatar Sep 22 '25 18:09 howardjohn

The difference is the family_labels is Some(EmptyLabels) here for Family (https://github.com/prometheus/client_rust/blob/ad05f0ff2ea6b2802a306dc9686389f29eb3b25a/src/encoding/text.rs#L497) and None for Counter

howardjohn avatar Sep 22 '25 18:09 howardjohn

Note (AFAIK) both are valid outputs. It just seems odd they are inconsistent. The reason I am looking into this is allegedly DataDog parses these differently, but I think if it it does that is a DD bug

howardjohn avatar Sep 22 '25 18:09 howardjohn