CodeSampleX

Пример

github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4: go.MetricFamily

Проверенный пример — golang github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4: go.MetricFamily. Контракт выполнен на go 1.26 · linux…

sha256:10642a056437381a0441d54c3959245848a5758e35201b37ac79922fe7dd682e

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-10-13

Кейс

HOW
Цель
verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4
Пакеты
Символы
  • github.com/prometheus/client_model/go.MetricFamily
Окружение
go
Создан
2026-10-13T16:41:01Z

Контракт

  1. MetricFamily initializes and organizes Prometheus metric data including Name, Help, MetricType, and Metric collections.
  2. MetricFamily getter methods GetName, GetHelp, GetType, and GetMetric safely access protobuf fields with default zero-value fallbacks when receiver or fields are nil.
  3. MetricFamily structures containing Counter and Gauge metrics with LabelPairs round-trip losslessly through protobuf serialization and deserialization.

Файлы

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • metric_family.go
  • spec.json

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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.0.0-20190812154241-14fe0d1b01d4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4
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.
contract_test.go
package sample

import (
	"testing"

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

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

	// Assert safe nil receiver access returns default 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.GetMetric() != nil {
		t.Errorf("expected nil slice for nil GetMetric, got %v", nilMF.GetMetric())
	}

	// Assert unpopulated struct returns default 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.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"
	mf := &dto.MetricFamily{
		Name: proto.String(name),
		Help: proto.String(help),
		Type: dto.MetricType_COUNTER.Enum(),
	}

	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())
	}
}

func TestBuildCounterMetricFamily(t *testing.T) {
	labels := map[string]string{
		"method": "GET",
		"status": "200",
	}
	mf := BuildCounterMetricFamily(
		"http_requests_total",
		"Total number of HTTP requests processed",
		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.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 := BuildGaugeMetricFamily(
		"memory_usage_bytes",
		"Current memory usage in bytes",
		labels,
		67108864.0,
	)

	if mf.GetName() != "memory_usage_bytes" {
		t.Fatalf("expected name memory_usage_bytes, got %s", mf.GetName())
	}
	if mf.GetHelp() != "Current memory usage in bytes" {
		t.Fatalf("expected help match, got %s", mf.GetHelp())
	}
	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 TestMetricFamilyProtobufRoundTrip(t *testing.T) {
	originalCounter := BuildCounterMetricFamily(
		"rpc_requests_total",
		"Total RPC requests",
		map[string]string{"service": "auth"},
		42.0,
	)

	deserCounter, err := RoundTripMetricFamily(originalCounter)
	if err != nil {
		t.Fatalf("RoundTripMetricFamily counter failed: %v", err)
	}
	if !proto.Equal(originalCounter, deserCounter) {
		t.Fatalf("deserialized counter MetricFamily is not proto.Equal to original")
	}

	originalGauge := BuildGaugeMetricFamily(
		"active_connections",
		"Active network connections",
		map[string]string{"proto": "tcp"},
		128.0,
	)

	deserGauge, err := RoundTripMetricFamily(originalGauge)
	if err != nil {
		t.Fatalf("RoundTripMetricFamily gauge failed: %v", err)
	}
	if !proto.Equal(originalGauge, deserGauge) {
		t.Fatalf("deserialized gauge MetricFamily is not proto.Equal to original")
	}
}
csx.json
{"case":{"caseId":"case:sha256:822bc1ac50ab7de389377165dad3878a91ceb0dcf1c11a1f525d251511241e59","contract":["MetricFamily initializes and organizes Prometheus metric data including Name, Help, MetricType, and Metric collections.","MetricFamily getter methods GetName, GetHelp, GetType, and GetMetric safely access protobuf fields with default zero-value fallbacks when receiver or fields are nil.","MetricFamily structures containing Counter and Gauge metrics with LabelPairs round-trip losslessly through protobuf serialization and deserialization."],"goal":"verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4"],"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.0.0-20190812154241-14fe0d1b01d4"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4","symbols":["github.com/prometheus/client_model/go.MetricFamily"],"verifierAdapter":"golang@1"}
go.mod
module example.com/metricfamilysample

go 1.22.0

require (
	github.com/golang/protobuf v1.5.4
	github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4
)

require google.golang.org/protobuf v1.33.0 // indirect
go.sum
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
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.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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 sample

import (
	"sort"

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

// BuildCounterMetricFamily constructs a MetricFamily for counter metrics.
func BuildCounterMetricFamily(name, help string, labels map[string]string, value float64) *dto.MetricFamily {
	labelPairs := buildSortedLabelPairs(labels)

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

	return &dto.MetricFamily{
		Name:   proto.String(name),
		Help:   proto.String(help),
		Type:   dto.MetricType_COUNTER.Enum(),
		Metric: []*dto.Metric{metric},
	}
}

// BuildGaugeMetricFamily constructs a MetricFamily for gauge metrics.
func BuildGaugeMetricFamily(name, help string, labels map[string]string, value float64) *dto.MetricFamily {
	labelPairs := buildSortedLabelPairs(labels)

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

	return &dto.MetricFamily{
		Name:   proto.String(name),
		Help:   proto.String(help),
		Type:   dto.MetricType_GAUGE.Enum(),
		Metric: []*dto.Metric{metric},
	}
}

// RoundTripMetricFamily marshals and unmarshals a MetricFamily using protobuf.
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
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_model/go.MetricFamily in pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_model@v0.0.0-20190812154241-14fe0d1b01d4"
  ],
  "symbols": [
    "github.com/prometheus/client_model/go.MetricFamily"
  ]
}

Исходный сидер

аноним