CodeSampleX

Sample

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

Verified sample for golang github.com/prometheus/client_model v0.6.2: go.Summary. The contract ran on go 1.26 · linux debian/x64 · docker and passed.

sha256:254e531890656c1f23b012cd6a2c763eba48a4b7ffc3f56a7c102d080237ac2e

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment go 1.26 linux 24 · ubuntu · glibc 2.39 amd64 go 1.26 go 1.26 go 1

Verification-run environments

Environment Contract Stages Run
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-01

Case

HOW
Goal
verify github.com/prometheus/client_model/go.Summary in pkg:golang/github.com/prometheus/client_model@v0.6.2
Packages
Symbols
  • github.com/prometheus/client_model/go.Summary
Environment
go 1.26.6
Created
2026-09-01T22:32:48Z

Contract

  1. dto.Summary initializes with SampleCount, SampleSum, and Quantile list
  2. dto.Summary getters GetSampleCount, GetSampleSum, and GetQuantile return expected values
  3. dto.Summary supports CreatedTimestamp with timestamppb
  4. dto.Summary embeds into Metric and MetricFamily with MetricType_SUMMARY
  5. dto.Summary marshals and unmarshals round-trip via protobuf wire format

Files

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

Download the source artifact (tar.gz)

Source

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.Summary 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.Summary

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:6dcc5a9751e3068a58ce2d5152f8f1421d24a1ba30b6610b041c6c406081204a","contract":["dto.Summary initializes with SampleCount, SampleSum, and Quantile list","dto.Summary getters GetSampleCount, GetSampleSum, and GetQuantile return expected values","dto.Summary supports CreatedTimestamp with timestamppb","dto.Summary embeds into Metric and MetricFamily with MetricType_SUMMARY","dto.Summary marshals and unmarshals round-trip via protobuf wire format"],"goal":"verify github.com/prometheus/client_model/go.Summary 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.Summary"]},"contractCommand":["go","test","./..."],"environment":{"arch":"amd64","distro":"ubuntu","ecosystem":"golang","language":"go","languageVersion":"1.26.6","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","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.Summary"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_model/go.Summary 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.Summary"
  ]
}
summary.go
package sample

import (
	"fmt"
	"sort"
	"time"

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

// NewSummary creates a populated Prometheus Summary metric with count, sum, and quantile observations.
func NewSummary(sampleCount uint64, sampleSum float64, quantiles map[float64]float64) *dto.Summary {
	var qList []*dto.Quantile
	if len(quantiles) > 0 {
		// Sort quantile keys for deterministic order
		keys := make([]float64, 0, len(quantiles))
		for k := range quantiles {
			keys = append(keys, k)
		}
		sort.Float64s(keys)

		for _, k := range keys {
			q := k
			v := quantiles[k]
			qList = append(qList, &dto.Quantile{
				Quantile: &q,
				Value:    &v,
			})
		}
	}

	return &dto.Summary{
		SampleCount: &sampleCount,
		SampleSum:   &sampleSum,
		Quantile:    qList,
	}
}

// NewSummaryWithTimestamp creates a Summary metric with an explicit creation timestamp.
func NewSummaryWithTimestamp(sampleCount uint64, sampleSum float64, quantiles map[float64]float64, createdAt time.Time) *dto.Summary {
	summary := NewSummary(sampleCount, sampleSum, quantiles)
	summary.CreatedTimestamp = timestamppb.New(createdAt)
	return summary
}

// WrapInMetricFamily wraps a Summary metric in a Prometheus Metric and MetricFamily.
func WrapInMetricFamily(name, help string, labels map[string]string, summary *dto.Summary) *dto.MetricFamily {
	metricType := dto.MetricType_SUMMARY

	var labelPairs []*dto.LabelPair
	if len(labels) > 0 {
		keys := make([]string, 0, len(labels))
		for k := range labels {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			nameCopy := k
			valCopy := labels[k]
			labelPairs = append(labelPairs, &dto.LabelPair{
				Name:  &nameCopy,
				Value: &valCopy,
			})
		}
	}

	metric := &dto.Metric{
		Label:   labelPairs,
		Summary: summary,
	}

	return &dto.MetricFamily{
		Name:   &name,
		Help:   &help,
		Type:   &metricType,
		Metric: []*dto.Metric{metric},
	}
}

// CalculateAverage returns the arithmetic mean of observed samples (SampleSum / SampleCount).
func CalculateAverage(summary *dto.Summary) (float64, error) {
	if summary == nil {
		return 0, fmt.Errorf("summary is nil")
	}
	count := summary.GetSampleCount()
	if count == 0 {
		return 0, fmt.Errorf("sample count is zero")
	}
	return summary.GetSampleSum() / float64(count), nil
}

// GetQuantileValue retrieves the value for a target quantile from the summary, if present.
func GetQuantileValue(summary *dto.Summary, targetQuantile float64) (float64, bool) {
	if summary == nil {
		return 0, false
	}
	for _, q := range summary.GetQuantile() {
		if q.GetQuantile() == targetQuantile {
			return q.GetValue(), true
		}
	}
	return 0, false
}

// MarshalSummary serializes a Summary protobuf message to binary wire format.
func MarshalSummary(summary *dto.Summary) ([]byte, error) {
	if summary == nil {
		return nil, fmt.Errorf("summary is nil")
	}
	return proto.Marshal(summary)
}

// UnmarshalSummary parses binary wire format data into a Summary protobuf message.
func UnmarshalSummary(data []byte) (*dto.Summary, error) {
	var summary dto.Summary
	if err := proto.Unmarshal(data, &summary); err != nil {
		return nil, fmt.Errorf("failed to unmarshal summary: %w", err)
	}
	return &summary, nil
}
test/contract_test.go
package contract_test

import (
	"math"
	"testing"
	"time"

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

	"sample"
)

func TestContract_Summary_BasicFields(t *testing.T) {
	count := uint64(100)
	sum := 2540.5
	quantiles := map[float64]float64{
		0.5:  20.1,
		0.9:  35.4,
		0.99: 50.8,
	}

	summary := sample.NewSummary(count, sum, quantiles)
	if summary == nil {
		t.Fatal("expected summary to be non-nil")
	}

	if summary.GetSampleCount() != count {
		t.Fatalf("expected sample count %d, got %d", count, summary.GetSampleCount())
	}

	if math.Abs(summary.GetSampleSum()-sum) > 1e-9 {
		t.Fatalf("expected sample sum %f, got %f", sum, summary.GetSampleSum())
	}

	qList := summary.GetQuantile()
	if len(qList) != 3 {
		t.Fatalf("expected 3 quantiles, got %d", len(qList))
	}

	// Verify quantile getters
	v50, ok := sample.GetQuantileValue(summary, 0.5)
	if !ok || math.Abs(v50-20.1) > 1e-9 {
		t.Fatalf("expected quantile 0.5 value 20.1, got %f (found: %v)", v50, ok)
	}

	v90, ok := sample.GetQuantileValue(summary, 0.9)
	if !ok || math.Abs(v90-35.4) > 1e-9 {
		t.Fatalf("expected quantile 0.9 value 35.4, got %f (found: %v)", v90, ok)
	}

	v99, ok := sample.GetQuantileValue(summary, 0.99)
	if !ok || math.Abs(v99-50.8) > 1e-9 {
		t.Fatalf("expected quantile 0.99 value 50.8, got %f (found: %v)", v99, ok)
	}

	// Missing quantile
	_, ok = sample.GetQuantileValue(summary, 0.75)
	if ok {
		t.Fatal("expected quantile 0.75 to not be found")
	}

	// Calculate average
	avg, err := sample.CalculateAverage(summary)
	if err != nil {
		t.Fatalf("unexpected error calculating average: %v", err)
	}
	expectedAvg := 2540.5 / 100.0
	if math.Abs(avg-expectedAvg) > 1e-9 {
		t.Fatalf("expected average %f, got %f", expectedAvg, avg)
	}
}

func TestContract_Summary_CreatedTimestamp(t *testing.T) {
	now := time.Unix(1725200000, 0).UTC()
	summary := sample.NewSummaryWithTimestamp(10, 50.0, nil, now)

	ts := summary.GetCreatedTimestamp()
	if ts == nil {
		t.Fatal("expected created timestamp to be non-nil")
	}

	if ts.AsTime() != now {
		t.Fatalf("expected timestamp %v, got %v", now, ts.AsTime())
	}
}

func TestContract_Summary_MetricFamilyWrapping(t *testing.T) {
	summary := sample.NewSummary(42, 105.0, map[float64]float64{0.5: 2.5})
	mf := sample.WrapInMetricFamily(
		"http_request_duration_seconds",
		"HTTP request duration summary",
		map[string]string{"handler": "test_handler", "method": "GET"},
		summary,
	)

	if mf.GetName() != "http_request_duration_seconds" {
		t.Fatalf("expected name http_request_duration_seconds, got %s", mf.GetName())
	}
	if mf.GetHelp() != "HTTP request duration summary" {
		t.Fatalf("expected help match, got %s", mf.GetHelp())
	}
	if mf.GetType() != dto.MetricType_SUMMARY {
		t.Fatalf("expected MetricType_SUMMARY, 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.GetSummary() == nil {
		t.Fatal("expected summary inside metric to be non-nil")
	}
	if m.GetSummary().GetSampleCount() != 42 {
		t.Fatalf("expected sample count 42, got %d", m.GetSummary().GetSampleCount())
	}
	if len(m.GetLabel()) != 2 {
		t.Fatalf("expected 2 labels, got %d", len(m.GetLabel()))
	}
}

func TestContract_Summary_ProtobufSerialization(t *testing.T) {
	summary := sample.NewSummary(500, 12500.0, map[float64]float64{
		0.5:  22.0,
		0.95: 48.5,
	})

	data, err := sample.MarshalSummary(summary)
	if err != nil {
		t.Fatalf("failed to marshal summary: %v", err)
	}
	if len(data) == 0 {
		t.Fatal("expected marshaled bytes to be non-empty")
	}

	restored, err := sample.UnmarshalSummary(data)
	if err != nil {
		t.Fatalf("failed to unmarshal summary: %v", err)
	}

	if !proto.Equal(summary, restored) {
		t.Fatalf("expected unmarshaled summary to equal original summary")
	}
	if restored.GetSampleCount() != 500 {
		t.Fatalf("expected sample count 500, got %d", restored.GetSampleCount())
	}
	if math.Abs(restored.GetSampleSum()-12500.0) > 1e-9 {
		t.Fatalf("expected sample sum 12500.0, got %f", restored.GetSampleSum())
	}
}

Origin Seeder

anonymous