CodeSampleX

Exemplo

github.com/prometheus/client_model v0.6.1: go.MetricFamily

Amostra verificada para golang github.com/prometheus/client_model v0.6.1: go.MetricFamily. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:ac95654d512dcd30962ad5d584f972be9d5ae9e2f9f15e8558c3a50982548136

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-05

Caso

HOW
Objetivo
verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.6.1
Pacotes
Símbolos
  • github.com/prometheus/client_model/go.MetricFamily
Ambiente
go
Criado
2026-09-05T11:57:12Z

Contrato

  1. MetricFamily initializes and organizes Prometheus metric data including Name, Help, Unit, MetricType, and Metric collections.
  2. MetricFamily getter methods GetName, GetHelp, GetType, GetUnit, and GetMetric safely access protobuf fields with default zero-value fallbacks when receiver or fields are nil.
  3. MetricFamily structures containing Counter, Gauge, and Histogram metrics with LabelPairs round-trip losslessly through google.golang.org/protobuf serialization and deserialization.
  4. MetricFamily implements google.golang.org/protobuf protoreflect.Message interface with io.prometheus.client.MetricFamily descriptor full name.

Arquivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • metric_family.go
  • metric_family_test.go
  • spec.json

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Prometheus client_model MetricFamily Verification Notes

## Target
- Package: `pkg:golang/github.com/prometheus/client_model@v0.6.1`
- Release: `v0.6.1`
- Import Path: `github.com/prometheus/client_model/go`
- Symbol: `github.com/prometheus/client_model/go.MetricFamily`
- Dependency: `google.golang.org/protobuf v1.33.0`

## Proved Behavior
1. MetricFamily initializes and organizes Prometheus metric data including Name, Help, Unit, MetricType, and Metric collections.
2. MetricFamily getter methods GetName, GetHelp, GetType, GetUnit, and GetMetric safely access protobuf fields with default zero-value fallbacks when receiver or fields are nil.
3. MetricFamily structures containing Counter, Gauge, and Histogram metrics with LabelPairs round-trip losslessly through google.golang.org/protobuf serialization and deserialization.
4. MetricFamily implements google.golang.org/protobuf protoreflect.Message interface with io.prometheus.client.MetricFamily descriptor full name.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_model@v0.6.1
Demonstrate these symbols/APIs:
  - github.com/prometheus/client_model/go.MetricFamily

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:b4cb3e1cfe4ef155aacf80927b336d758b9c801e90e69a6c22165761802cf3e8","contract":["MetricFamily initializes and organizes Prometheus metric data including Name, Help, Unit, MetricType, and Metric collections.","MetricFamily getter methods GetName, GetHelp, GetType, GetUnit, and GetMetric safely access protobuf fields with default zero-value fallbacks when receiver or fields are nil.","MetricFamily structures containing Counter, Gauge, and Histogram metrics with LabelPairs round-trip losslessly through google.golang.org/protobuf serialization and deserialization.","MetricFamily implements google.golang.org/protobuf protoreflect.Message interface with io.prometheus.client.MetricFamily descriptor full name."],"goal":"verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.6.1","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_model@v0.6.1"],"schemaVersion":1,"symbols":["github.com/prometheus/client_model/go.MetricFamily"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/prometheus/client_model@v0.6.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_model@v0.6.1","symbols":["github.com/prometheus/client_model/go.MetricFamily"],"verifierAdapter":"golang@1"}
go.mod
module example.com/metricfamilysample

go 1.22.0

require (
	github.com/prometheus/client_model v0.6.1
	google.golang.org/protobuf v1.33.0
)
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
metric_family.go
package metricfamilysample

import (
	"sort"

	dto "github.com/prometheus/client_model/go"
	"google.golang.org/protobuf/proto"
)

// BuildCounterMetricFamily constructs a MetricFamily with COUNTER type, documentation, unit, and a Metric sample.
func BuildCounterMetricFamily(name, help, unit string, labels map[string]string, value float64) *dto.MetricFamily {
	labelPairs := buildSortedLabelPairs(labels)

	metric := &dto.Metric{
		Label: labelPairs,
		Counter: &dto.Counter{
			Value: proto.Float64(value),
		},
	}

	mf := &dto.MetricFamily{
		Name:   proto.String(name),
		Help:   proto.String(help),
		Type:   dto.MetricType_COUNTER.Enum(),
		Metric: []*dto.Metric{metric},
	}
	if unit != "" {
		mf.Unit = proto.String(unit)
	}

	return mf
}

// BuildGaugeMetricFamily constructs a MetricFamily with GAUGE type, documentation, unit, and a Metric sample.
func BuildGaugeMetricFamily(name, help, unit string, labels map[string]string, value float64) *dto.MetricFamily {
	labelPairs := buildSortedLabelPairs(labels)

	metric := &dto.Metric{
		Label: labelPairs,
		Gauge: &dto.Gauge{
			Value: proto.Float64(value),
		},
	}

	mf := &dto.MetricFamily{
		Name:   proto.String(name),
		Help:   proto.String(help),
		Type:   dto.MetricType_GAUGE.Enum(),
		Metric: []*dto.Metric{metric},
	}
	if unit != "" {
		mf.Unit = proto.String(unit)
	}

	return mf
}

// BuildHistogramMetricFamily constructs a MetricFamily with HISTOGRAM type, documentation, unit, and bucket samples.
func BuildHistogramMetricFamily(name, help, unit string, labels map[string]string, count uint64, sum float64, buckets map[float64]uint64) *dto.MetricFamily {
	labelPairs := buildSortedLabelPairs(labels)

	upperBounds := make([]float64, 0, len(buckets))
	for bound := range buckets {
		upperBounds = append(upperBounds, bound)
	}
	sort.Float64s(upperBounds)

	pbBuckets := make([]*dto.Bucket, 0, len(upperBounds))
	for _, ub := range upperBounds {
		pbBuckets = append(pbBuckets, &dto.Bucket{
			UpperBound:      proto.Float64(ub),
			CumulativeCount: proto.Uint64(buckets[ub]),
		})
	}

	metric := &dto.Metric{
		Label: labelPairs,
		Histogram: &dto.Histogram{
			SampleCount: proto.Uint64(count),
			SampleSum:   proto.Float64(sum),
			Bucket:      pbBuckets,
		},
	}

	mf := &dto.MetricFamily{
		Name:   proto.String(name),
		Help:   proto.String(help),
		Type:   dto.MetricType_HISTOGRAM.Enum(),
		Metric: []*dto.Metric{metric},
	}
	if unit != "" {
		mf.Unit = proto.String(unit)
	}

	return mf
}

// RoundTripMetricFamily serializes and deserializes a MetricFamily using google.golang.org/protobuf/proto.
func RoundTripMetricFamily(mf *dto.MetricFamily) (*dto.MetricFamily, error) {
	data, err := proto.Marshal(mf)
	if err != nil {
		return nil, err
	}
	out := &dto.MetricFamily{}
	if err := proto.Unmarshal(data, out); err != nil {
		return nil, err
	}
	return out, nil
}

func buildSortedLabelPairs(labels map[string]string) []*dto.LabelPair {
	if len(labels) == 0 {
		return nil
	}
	keys := make([]string, 0, len(labels))
	for k := range labels {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	pairs := make([]*dto.LabelPair, 0, len(keys))
	for _, k := range keys {
		pairs = append(pairs, &dto.LabelPair{
			Name:  proto.String(k),
			Value: proto.String(labels[k]),
		})
	}
	return pairs
}
metric_family_test.go
package metricfamilysample_test

import (
	"testing"

	dto "github.com/prometheus/client_model/go"
	"google.golang.org/protobuf/proto"

	"example.com/metricfamilysample"
)

func TestMetricFamilyGettersAndNilSafety(t *testing.T) {
	var nilMF *dto.MetricFamily

	// Assert safe nil receiver access returns zero values
	if nilMF.GetName() != "" {
		t.Errorf("expected empty string for nil GetName, got %q", nilMF.GetName())
	}
	if nilMF.GetHelp() != "" {
		t.Errorf("expected empty string for nil GetHelp, got %q", nilMF.GetHelp())
	}
	if nilMF.GetType() != dto.MetricType_COUNTER {
		t.Errorf("expected default MetricType_COUNTER for nil GetType, got %v", nilMF.GetType())
	}
	if nilMF.GetUnit() != "" {
		t.Errorf("expected empty string for nil GetUnit, got %q", nilMF.GetUnit())
	}
	if nilMF.GetMetric() != nil {
		t.Errorf("expected nil slice for nil GetMetric, got %v", nilMF.GetMetric())
	}

	// Assert unpopulated struct returns zero values
	emptyMF := &dto.MetricFamily{}
	if emptyMF.GetName() != "" {
		t.Errorf("expected empty string for empty GetName, got %q", emptyMF.GetName())
	}
	if emptyMF.GetHelp() != "" {
		t.Errorf("expected empty string for empty GetHelp, got %q", emptyMF.GetHelp())
	}
	if emptyMF.GetType() != dto.MetricType_COUNTER {
		t.Errorf("expected default MetricType_COUNTER for empty GetType, got %v", emptyMF.GetType())
	}
	if emptyMF.GetUnit() != "" {
		t.Errorf("expected empty string for empty GetUnit, got %q", emptyMF.GetUnit())
	}
	if emptyMF.GetMetric() != nil {
		t.Errorf("expected nil slice for empty GetMetric, got %v", emptyMF.GetMetric())
	}

	// Assert populated struct getters return assigned values
	name := "http_requests_total"
	help := "Total number of HTTP requests processed"
	unit := "requests"
	mf := &dto.MetricFamily{
		Name: proto.String(name),
		Help: proto.String(help),
		Type: dto.MetricType_COUNTER.Enum(),
		Unit: proto.String(unit),
	}

	if mf.GetName() != name {
		t.Errorf("expected GetName() = %q, got %q", name, mf.GetName())
	}
	if mf.GetHelp() != help {
		t.Errorf("expected GetHelp() = %q, got %q", help, mf.GetHelp())
	}
	if mf.GetType() != dto.MetricType_COUNTER {
		t.Errorf("expected GetType() = %v, got %v", dto.MetricType_COUNTER, mf.GetType())
	}
	if mf.GetUnit() != unit {
		t.Errorf("expected GetUnit() = %q, got %q", unit, mf.GetUnit())
	}
}

func TestBuildCounterMetricFamily(t *testing.T) {
	labels := map[string]string{
		"method": "GET",
		"status": "200",
	}
	mf := metricfamilysample.BuildCounterMetricFamily(
		"http_requests_total",
		"Total number of HTTP requests processed",
		"requests",
		labels,
		1024.0,
	)

	if mf.GetName() != "http_requests_total" {
		t.Fatalf("expected name http_requests_total, got %s", mf.GetName())
	}
	if mf.GetHelp() != "Total number of HTTP requests processed" {
		t.Fatalf("expected help match, got %s", mf.GetHelp())
	}
	if mf.GetUnit() != "requests" {
		t.Fatalf("expected unit requests, got %s", mf.GetUnit())
	}
	if mf.GetType() != dto.MetricType_COUNTER {
		t.Fatalf("expected type COUNTER, got %v", mf.GetType())
	}
	if len(mf.GetMetric()) != 1 {
		t.Fatalf("expected 1 metric, got %d", len(mf.GetMetric()))
	}

	m := mf.GetMetric()[0]
	if m.GetCounter() == nil {
		t.Fatalf("expected counter to be present")
	}
	if m.GetCounter().GetValue() != 1024.0 {
		t.Fatalf("expected counter value 1024.0, got %f", m.GetCounter().GetValue())
	}
	if len(m.GetLabel()) != 2 {
		t.Fatalf("expected 2 labels, got %d", len(m.GetLabel()))
	}
	if m.GetLabel()[0].GetName() != "method" || m.GetLabel()[0].GetValue() != "GET" {
		t.Errorf("unexpected first label: %v", m.GetLabel()[0])
	}
	if m.GetLabel()[1].GetName() != "status" || m.GetLabel()[1].GetValue() != "200" {
		t.Errorf("unexpected second label: %v", m.GetLabel()[1])
	}
}

func TestBuildGaugeMetricFamily(t *testing.T) {
	labels := map[string]string{
		"instance": "localhost:9090",
	}
	mf := metricfamilysample.BuildGaugeMetricFamily(
		"memory_usage_bytes",
		"Current memory usage in bytes",
		"bytes",
		labels,
		67108864.0,
	)

	if mf.GetName() != "memory_usage_bytes" {
		t.Fatalf("expected name memory_usage_bytes, got %s", mf.GetName())
	}
	if mf.GetUnit() != "bytes" {
		t.Fatalf("expected unit bytes, got %s", mf.GetUnit())
	}
	if mf.GetType() != dto.MetricType_GAUGE {
		t.Fatalf("expected type GAUGE, got %v", mf.GetType())
	}
	if len(mf.GetMetric()) != 1 {
		t.Fatalf("expected 1 metric, got %d", len(mf.GetMetric()))
	}

	m := mf.GetMetric()[0]
	if m.GetGauge() == nil {
		t.Fatalf("expected gauge to be present")
	}
	if m.GetGauge().GetValue() != 67108864.0 {
		t.Fatalf("expected gauge value 67108864.0, got %f", m.GetGauge().GetValue())
	}
}

func TestBuildHistogramMetricFamily(t *testing.T) {
	labels := map[string]string{
		"handler": "api_v1",
	}
	buckets := map[float64]uint64{
		0.05: 10,
		0.1:  25,
		0.5:  50,
		1.0:  60,
	}

	mf := metricfamilysample.BuildHistogramMetricFamily(
		"http_request_duration_seconds",
		"HTTP request duration in seconds",
		"seconds",
		labels,
		60,
		12.5,
		buckets,
	)

	if mf.GetName() != "http_request_duration_seconds" {
		t.Fatalf("expected name http_request_duration_seconds, got %s", mf.GetName())
	}
	if mf.GetUnit() != "seconds" {
		t.Fatalf("expected unit seconds, got %s", mf.GetUnit())
	}
	if mf.GetType() != dto.MetricType_HISTOGRAM {
		t.Fatalf("expected type HISTOGRAM, got %v", mf.GetType())
	}
	if len(mf.GetMetric()) != 1 {
		t.Fatalf("expected 1 metric, got %d", len(mf.GetMetric()))
	}

	h := mf.GetMetric()[0].GetHistogram()
	if h == nil {
		t.Fatalf("expected histogram to be present")
	}
	if h.GetSampleCount() != 60 {
		t.Fatalf("expected sample count 60, got %d", h.GetSampleCount())
	}
	if h.GetSampleSum() != 12.5 {
		t.Fatalf("expected sample sum 12.5, got %f", h.GetSampleSum())
	}
	if len(h.GetBucket()) != 4 {
		t.Fatalf("expected 4 buckets, got %d", len(h.GetBucket()))
	}
	if h.GetBucket()[0].GetUpperBound() != 0.05 || h.GetBucket()[0].GetCumulativeCount() != 10 {
		t.Errorf("unexpected bucket 0: %v", h.GetBucket()[0])
	}
}

func TestMetricFamilyProtobufRoundTripAndEqual(t *testing.T) {
	original := metricfamilysample.BuildHistogramMetricFamily(
		"rpc_latency_seconds",
		"RPC call latency",
		"seconds",
		map[string]string{"service": "catalog"},
		100,
		35.2,
		map[float64]uint64{0.1: 50, 0.5: 90, 1.0: 100},
	)

	deserialized, err := metricfamilysample.RoundTripMetricFamily(original)
	if err != nil {
		t.Fatalf("RoundTripMetricFamily failed: %v", err)
	}

	if !proto.Equal(original, deserialized) {
		t.Fatalf("deserialized MetricFamily is not proto.Equal to original")
	}

	if deserialized.GetName() != original.GetName() {
		t.Errorf("name mismatch: %q != %q", deserialized.GetName(), original.GetName())
	}
	if deserialized.GetUnit() != original.GetUnit() {
		t.Errorf("unit mismatch: %q != %q", deserialized.GetUnit(), original.GetUnit())
	}
	if deserialized.GetHelp() != original.GetHelp() {
		t.Errorf("help mismatch: %q != %q", deserialized.GetHelp(), original.GetHelp())
	}
	if deserialized.GetType() != original.GetType() {
		t.Errorf("type mismatch: %v != %v", deserialized.GetType(), original.GetType())
	}
}

func TestMetricFamilyProtoReflectDescriptor(t *testing.T) {
	mf := &dto.MetricFamily{}
	msg := mf.ProtoReflect()
	if msg == nil {
		t.Fatalf("expected non-nil protoreflect.Message")
	}

	desc := msg.Descriptor()
	if string(desc.FullName()) != "io.prometheus.client.MetricFamily" {
		t.Fatalf("expected descriptor full name io.prometheus.client.MetricFamily, got %s", desc.FullName())
	}

	fields := desc.Fields()
	if fields.ByName("name") == nil {
		t.Errorf("expected 'name' field in descriptor")
	}
	if fields.ByName("unit") == nil {
		t.Errorf("expected 'unit' field in descriptor")
	}
	if fields.ByName("help") == nil {
		t.Errorf("expected 'help' field in descriptor")
	}
	if fields.ByName("type") == nil {
		t.Errorf("expected 'type' field in descriptor")
	}
	if fields.ByName("metric") == nil {
		t.Errorf("expected 'metric' field in descriptor")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_model@v0.6.1"
  ],
  "symbols": [
    "github.com/prometheus/client_model/go.MetricFamily"
  ]
}

Seeder de origem

anônimo