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 debian/x64 · docker에서 contract를 실행해…

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"
  ]
}

오리진 시더

익명