CodeSampleX

샘플

github.com/prometheus/client_model v0.2.0

검증된 샘플 — golang github.com/prometheus/client_model v0.2.0. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: dto.Histogram and dto.Bucket getter…

sha256:0b492566541b5cf2f4c54d7319f2c29fe40422acd2d4d1a96a62145440e24f27

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go linux 24 · ubuntu · glibc 2.39 x64 go go go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

케이스

HOW
목표
verify pkg:golang/github.com/prometheus/client_model@v0.2.0
패키지
환경
go
생성일
2026-08-28T00:23:29Z

컨트랙트

  1. dto.Histogram and dto.Bucket getter methods return zero or nil for nil and empty instances.
  2. dto.Histogram initializes and accesses sample count, sample sum, and cumulative bucket distributions.
  3. dto.Histogram embeds within dto.Metric with labels and timestamp.
  4. dto.Histogram.Reset clears sample count, sample sum, and bucket collections back to zero values.
  5. dto.Histogram serializes and deserializes losslessly across protobuf wire format.

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • histogram.go
  • spec.json
  • test/contract_test.go

소스 아티팩트 내려받기 (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 pkg:golang/github.com/prometheus/client_model@v0.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_model@v0.2.0

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:60877eb8b78431c832bc8e8e99be47832addcb7971483ab102381212a7fa8b03","contract":["dto.Histogram and dto.Bucket getter methods return zero or nil for nil and empty instances.","dto.Histogram initializes and accesses sample count, sample sum, and cumulative bucket distributions.","dto.Histogram embeds within dto.Metric with labels and timestamp.","dto.Histogram.Reset clears sample count, sample sum, and bucket collections back to zero values.","dto.Histogram serializes and deserializes losslessly across protobuf wire format."],"goal":"verify pkg:golang/github.com/prometheus/client_model@v0.2.0","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_model@v0.2.0"],"schemaVersion":1},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","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.2.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_model@v0.2.0","verifierAdapter":"golang@1"}
go.mod
module example.com/histogram

go 1.22

require (
	github.com/golang/protobuf v1.5.0
	github.com/prometheus/client_model v0.2.0
)

require google.golang.org/protobuf v1.26.0-rc.1 // indirect
go.sum
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
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.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
github.com/prometheus/client_model v0.2.0/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.26.0-rc.1 h1:7QnIQpGRHE5RnLKnESfDoxm2dTapTZua5a0kS0A+VXQ=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
histogram.go
package histogram

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

// BucketConfig holds cumulative count and upper bound configuration for a bucket.
type BucketConfig struct {
	CumulativeCount uint64
	UpperBound      float64
}

// CreateHistogram creates a dto.Histogram with the specified sample count, sample sum, and buckets.
func CreateHistogram(sampleCount uint64, sampleSum float64, buckets []BucketConfig) *dto.Histogram {
	bucketList := make([]*dto.Bucket, 0, len(buckets))
	for _, b := range buckets {
		bucketList = append(bucketList, &dto.Bucket{
			CumulativeCount: proto.Uint64(b.CumulativeCount),
			UpperBound:      proto.Float64(b.UpperBound),
		})
	}
	return &dto.Histogram{
		SampleCount: proto.Uint64(sampleCount),
		SampleSum:   proto.Float64(sampleSum),
		Bucket:      bucketList,
	}
}

// CreateHistogramMetric creates a dto.Metric wrapping a Histogram with labels and optional timestamp.
func CreateHistogramMetric(labels map[string]string, h *dto.Histogram, timestampMs int64) *dto.Metric {
	var labelPairs []*dto.LabelPair
	for k, v := range labels {
		labelPairs = append(labelPairs, &dto.LabelPair{
			Name:  proto.String(k),
			Value: proto.String(v),
		})
	}
	m := &dto.Metric{
		Label:     labelPairs,
		Histogram: h,
	}
	if timestampMs > 0 {
		m.TimestampMs = proto.Int64(timestampMs)
	}
	return m
}

// RoundTripHistogram marshals and unmarshals a Histogram using protobuf.
func RoundTripHistogram(h *dto.Histogram) (*dto.Histogram, error) {
	data, err := proto.Marshal(h)
	if err != nil {
		return nil, err
	}
	out := &dto.Histogram{}
	if err := proto.Unmarshal(data, out); err != nil {
		return nil, err
	}
	return out, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/prometheus/client_model@v0.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_model@v0.2.0"
  ]
}
test/contract_test.go
package test

import (
	"math"
	"testing"

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

	"example.com/histogram"
)

func TestHistogramNilAndDefaults(t *testing.T) {
	var nilH *dto.Histogram
	if got := nilH.GetSampleCount(); got != 0 {
		t.Errorf("nilH.GetSampleCount() = %d, want 0", got)
	}
	if got := nilH.GetSampleSum(); got != 0 {
		t.Errorf("nilH.GetSampleSum() = %f, want 0", got)
	}
	if got := nilH.GetBucket(); got != nil {
		t.Errorf("nilH.GetBucket() = %v, want nil", got)
	}

	var nilB *dto.Bucket
	if got := nilB.GetCumulativeCount(); got != 0 {
		t.Errorf("nilB.GetCumulativeCount() = %d, want 0", got)
	}
	if got := nilB.GetUpperBound(); got != 0 {
		t.Errorf("nilB.GetUpperBound() = %f, want 0", got)
	}

	emptyH := &dto.Histogram{}
	if got := emptyH.GetSampleCount(); got != 0 {
		t.Errorf("emptyH.GetSampleCount() = %d, want 0", got)
	}
	if got := emptyH.GetSampleSum(); got != 0 {
		t.Errorf("emptyH.GetSampleSum() = %f, want 0", got)
	}
	if got := emptyH.GetBucket(); got != nil {
		t.Errorf("emptyH.GetBucket() = %v, want nil", got)
	}
}

func TestCreateHistogramAndGetters(t *testing.T) {
	buckets := []histogram.BucketConfig{
		{CumulativeCount: 10, UpperBound: 0.1},
		{CumulativeCount: 25, UpperBound: 0.5},
		{CumulativeCount: 30, UpperBound: 1.0},
		{CumulativeCount: 30, UpperBound: math.Inf(1)},
	}
	sampleCount := uint64(30)
	sampleSum := 12.345

	h := histogram.CreateHistogram(sampleCount, sampleSum, buckets)
	if got := h.GetSampleCount(); got != sampleCount {
		t.Errorf("h.GetSampleCount() = %d, want %d", got, sampleCount)
	}
	if got := h.GetSampleSum(); got != sampleSum {
		t.Errorf("h.GetSampleSum() = %f, want %f", got, sampleSum)
	}
	bList := h.GetBucket()
	if len(bList) != len(buckets) {
		t.Fatalf("len(h.GetBucket()) = %d, want %d", len(bList), len(buckets))
	}
	for i, want := range buckets {
		if got := bList[i].GetCumulativeCount(); got != want.CumulativeCount {
			t.Errorf("bucket[%d].GetCumulativeCount() = %d, want %d", i, got, want.CumulativeCount)
		}
		if got := bList[i].GetUpperBound(); got != want.UpperBound {
			t.Errorf("bucket[%d].GetUpperBound() = %f, want %f", i, got, want.UpperBound)
		}
	}
}

func TestHistogramMetricEmbedding(t *testing.T) {
	buckets := []histogram.BucketConfig{
		{CumulativeCount: 5, UpperBound: 100.0},
		{CumulativeCount: 10, UpperBound: 500.0},
	}
	h := histogram.CreateHistogram(10, 2500.0, buckets)
	labels := map[string]string{"le": "100", "path": "/api/v1"}
	ts := int64(1700000000000)

	metric := histogram.CreateHistogramMetric(labels, h, ts)
	if metric.GetHistogram() == nil {
		t.Fatal("metric.GetHistogram() returned nil")
	}
	if metric.GetHistogram().GetSampleCount() != 10 {
		t.Errorf("sample count = %d, want 10", metric.GetHistogram().GetSampleCount())
	}
	if metric.GetTimestampMs() != ts {
		t.Errorf("timestamp = %d, want %d", metric.GetTimestampMs(), ts)
	}
}

func TestHistogramReset(t *testing.T) {
	h := &dto.Histogram{
		SampleCount: proto.Uint64(100),
		SampleSum:   proto.Float64(500.5),
		Bucket: []*dto.Bucket{
			{
				CumulativeCount: proto.Uint64(100),
				UpperBound:      proto.Float64(1.0),
			},
		},
	}

	h.Reset()

	if got := h.GetSampleCount(); got != 0 {
		t.Errorf("after Reset(), h.GetSampleCount() = %d, want 0", got)
	}
	if got := h.GetSampleSum(); got != 0 {
		t.Errorf("after Reset(), h.GetSampleSum() = %f, want 0", got)
	}
	if got := h.GetBucket(); got != nil {
		t.Errorf("after Reset(), h.GetBucket() = %v, want nil", got)
	}
}

func TestHistogramProtobufRoundTrip(t *testing.T) {
	buckets := []histogram.BucketConfig{
		{CumulativeCount: 3, UpperBound: 0.05},
		{CumulativeCount: 8, UpperBound: 0.25},
		{CumulativeCount: 15, UpperBound: 1.0},
	}
	original := histogram.CreateHistogram(15, 7.89, buckets)

	deserialized, err := histogram.RoundTripHistogram(original)
	if err != nil {
		t.Fatalf("RoundTripHistogram failed: %v", err)
	}
	if deserialized.GetSampleCount() != original.GetSampleCount() {
		t.Errorf("deserialized SampleCount = %d, want %d", deserialized.GetSampleCount(), original.GetSampleCount())
	}
	if deserialized.GetSampleSum() != original.GetSampleSum() {
		t.Errorf("deserialized SampleSum = %f, want %f", deserialized.GetSampleSum(), original.GetSampleSum())
	}
	if len(deserialized.GetBucket()) != len(original.GetBucket()) {
		t.Fatalf("deserialized Bucket length = %d, want %d", len(deserialized.GetBucket()), len(original.GetBucket()))
	}
	for i := range original.GetBucket() {
		if deserialized.GetBucket()[i].GetCumulativeCount() != original.GetBucket()[i].GetCumulativeCount() {
			t.Errorf("bucket[%d] count mismatch", i)
		}
		if deserialized.GetBucket()[i].GetUpperBound() != original.GetBucket()[i].GetUpperBound() {
			t.Errorf("bucket[%d] upper bound mismatch", i)
		}
	}
}

오리진 시더

익명