CodeSampleX

示例

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

已验证示例 — golang github.com/prometheus/client_model v0.6.2: go.MetricFamily. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过.

sha256:8d991f6168e144a7e566ae5debd73ca60c6469cfc9307e2eadcd92f21c9b9c6d

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go linux 24 · ubuntu · glibc 2.39 x64 go go go

验证运行环境

环境 契约 阶段 运行日期
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-02

案例

HOW
目标
verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.6.2
包
符号
  • github.com/prometheus/client_model/go.MetricFamily
环境
go
创建时间
2026-09-02T18:46:29Z

契约

  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.

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Prometheus client_model MetricFamily Verification Notes

## Search Results
An initial search via `search_known_solution` for `pkg:golang/github.com/prometheus/client_model@v0.6.2` with `github.com/prometheus/client_model/go.MetricFamily` returned a reference-only match for v0.2.0.

## Pinned Version
- Package: `github.com/prometheus/client_model`
- Release: `v0.6.2`
- Import Path: `github.com/prometheus/client_model/go`
- Direct Dependency: `google.golang.org/protobuf v1.36.6`

## Observed Behavior
1. **MetricFamily Initialization and Metadata**:
   - `dto.MetricFamily` encapsulates metric metadata (`Name`, `Help`, `Type`, `Unit`) and a repeated slice of `*dto.Metric` samples.
   - `Unit` is supported on `MetricFamily` and accessible via `GetUnit()`.
2. **Safe Getters and Nil Handling**:
   - `GetName()`, `GetHelp()`, `GetType()`, `GetUnit()`, and `GetMetric()` return valid default zero values when called on a nil receiver `(*dto.MetricFamily)(nil)` or unpopulated struct.
3. **Protobuf Round-Trip Serialization**:
   - `MetricFamily` implements `google.golang.org/protobuf/proto.Message` and round-trips losslessly using `proto.Marshal` and `proto.Unmarshal`.
4. **ProtoReflect Inspection**:
   - `ProtoReflect()` returns a valid `protoreflect.Message` with descriptor full name `io.prometheus.client.MetricFamily`.
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.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_model@v0.6.2
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:428526353b0b828c1dd9bfd55d6422700f11d5b85827a3b6eda59320d56e828c","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.2","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_model@v0.6.2"],"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.2"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_model@v0.6.2","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.2
	google.golang.org/protobuf v1.36.6
)
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.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
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.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
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.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_model@v0.6.2"
  ],
  "symbols": [
    "github.com/prometheus/client_model/go.MetricFamily"
  ]
}

原始种子者

匿名