CodeSampleX

Ejemplo

github.com/prometheus/client_golang v1.19.1: prometheus.NewHistogram

Muestra verificada para golang github.com/prometheus/client_golang v1.19.1: prometheus.NewHistogram. El contrato se ejecutó en go 1.26 · linux alpine/x64 …

sha256:cdb9d104b685ac149837d413a71180a522d470b595b34b44df896393478dc8fa

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-26
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-07

Caso

HOW
Objetivo
verify github.com/prometheus/client_golang/prometheus.NewHistogram in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Paquetes
Símbolos
  • github.com/prometheus/client_golang/prometheus.NewHistogram
Entorno
go
Creado
2026-08-26T13:34:37Z

Contrato

  1. prometheus.NewHistogram creates a Histogram metric initialized with zero sample count and zero sample sum, using DefBuckets if no custom buckets are specified.
  2. Histogram.Observe records sample values, accumulating the total sample count, sample sum, and cumulative counts across configured bucket upper bounds.
  3. Histogram.Write serializes the histogram state into a Prometheus dto.Metric protobuf message including sample count, sample sum, and bucket cumulative counts.
  4. Histogram.Describe provides the metric descriptor including configured namespace, subsystem, name, and help string.

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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_golang/prometheus.NewHistogram in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/client_golang@v1.19.1
Demonstrate these symbols/APIs:
  - github.com/prometheus/client_golang/prometheus.NewHistogram
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:eb425ad813dc379d2a6c1c1365b56f557b5137ba522cb9f68701fa591531bf3f","constraints":{"executionContext":"go"},"contract":["prometheus.NewHistogram creates a Histogram metric initialized with zero sample count and zero sample sum, using DefBuckets if no custom buckets are specified.","Histogram.Observe records sample values, accumulating the total sample count, sample sum, and cumulative counts across configured bucket upper bounds.","Histogram.Write serializes the histogram state into a Prometheus dto.Metric protobuf message including sample count, sample sum, and bucket cumulative counts.","Histogram.Describe provides the metric descriptor including configured namespace, subsystem, name, and help string."],"goal":"verify github.com/prometheus/client_golang/prometheus.NewHistogram in pkg:golang/github.com/prometheus/client_golang@v1.19.1","kind":"HOW","packages":["pkg:golang/github.com/prometheus/client_golang@v1.19.1"],"schemaVersion":1,"symbols":["github.com/prometheus/client_golang/prometheus.NewHistogram"]},"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_golang@v1.19.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_golang@v1.19.1","symbols":["github.com/prometheus/client_golang/prometheus.NewHistogram"],"verifierAdapter":"golang@1"}
go.mod
module example.com/histogram

go 1.22

require (
	github.com/prometheus/client_golang v1.19.1
	github.com/prometheus/client_model v0.5.0
)

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.2.0 // indirect
	github.com/prometheus/common v0.48.0 // indirect
	github.com/prometheus/procfs v0.12.0 // indirect
	golang.org/x/sys v0.17.0 // indirect
	google.golang.org/protobuf v1.33.0 // indirect
)
go.sum
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=
github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE=
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc=
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
main.go
package main

import (
	"fmt"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
)

func main() {
	opts := prometheus.HistogramOpts{
		Namespace: "myapp",
		Subsystem: "http",
		Name:      "request_duration_seconds",
		Help:      "HTTP request duration distribution in seconds.",
		Buckets:   []float64{0.1, 0.5, 1.0, 2.5, 5.0},
	}

	hist := prometheus.NewHistogram(opts)

	hist.Observe(0.05)
	hist.Observe(0.4)
	hist.Observe(1.2)
	hist.Observe(3.0)

	var metric dto.Metric
	if err := hist.Write(&metric); err != nil {
		panic(err)
	}

	h := metric.GetHistogram()
	fmt.Printf("Sample Count: %d\n", h.GetSampleCount())
	fmt.Printf("Sample Sum: %f\n", h.GetSampleSum())
	for _, b := range h.GetBucket() {
		fmt.Printf("Bucket <= %f: %d\n", b.GetUpperBound(), b.GetCumulativeCount())
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_golang/prometheus.NewHistogram in pkg:golang/github.com/prometheus/client_golang@v1.19.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/client_golang@v1.19.1"
  ],
  "symbols": [
    "github.com/prometheus/client_golang/prometheus.NewHistogram"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract_test.go
package test

import (
	"math"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
)

func TestNewHistogramDefaultBuckets(t *testing.T) {
	opts := prometheus.HistogramOpts{
		Name: "test_default_buckets",
		Help: "Histogram with default buckets",
	}
	hist := prometheus.NewHistogram(opts)
	if hist == nil {
		t.Fatal("prometheus.NewHistogram returned nil")
	}

	// Verify initial state
	var metric dto.Metric
	if err := hist.Write(&metric); err != nil {
		t.Fatalf("hist.Write failed: %v", err)
	}

	h := metric.GetHistogram()
	if h == nil {
		t.Fatal("metric.GetHistogram() returned nil")
	}
	if h.GetSampleCount() != 0 {
		t.Errorf("initial sample count = %d, want 0", h.GetSampleCount())
	}
	if h.GetSampleSum() != 0.0 {
		t.Errorf("initial sample sum = %f, want 0.0", h.GetSampleSum())
	}

	// Default buckets count should match prometheus.DefBuckets count
	buckets := h.GetBucket()
	if len(buckets) != len(prometheus.DefBuckets) {
		t.Errorf("got %d buckets, want %d (DefBuckets)", len(buckets), len(prometheus.DefBuckets))
	}
}

func TestNewHistogramObserveAndBuckets(t *testing.T) {
	customBuckets := []float64{0.1, 0.5, 1.0, 5.0}
	opts := prometheus.HistogramOpts{
		Namespace: "testing",
		Subsystem: "requests",
		Name:      "duration_seconds",
		Help:      "Test request duration",
		Buckets:   customBuckets,
		ConstLabels: prometheus.Labels{
			"env": "unit-test",
		},
	}

	hist := prometheus.NewHistogram(opts)

	// Observe values across different buckets
	hist.Observe(0.05) // <= 0.1, <= 0.5, <= 1.0, <= 5.0
	hist.Observe(0.25) // <= 0.5, <= 1.0, <= 5.0
	hist.Observe(0.50) // <= 0.5, <= 1.0, <= 5.0
	hist.Observe(2.00) // <= 5.0
	hist.Observe(10.0) // > 5.0 (only in +Inf)

	var metric dto.Metric
	if err := hist.Write(&metric); err != nil {
		t.Fatalf("hist.Write failed: %v", err)
	}

	// Check const label
	labels := metric.GetLabel()
	foundLabel := false
	for _, l := range labels {
		if l.GetName() == "env" && l.GetValue() == "unit-test" {
			foundLabel = true
			break
		}
	}
	if !foundLabel {
		t.Errorf("const label 'env=unit-test' not found in metric labels: %v", labels)
	}

	h := metric.GetHistogram()
	if h.GetSampleCount() != 5 {
		t.Errorf("sample count = %d, want 5", h.GetSampleCount())
	}

	expectedSum := 0.05 + 0.25 + 0.50 + 2.00 + 10.0
	if math.Abs(h.GetSampleSum()-expectedSum) > 1e-9 {
		t.Errorf("sample sum = %f, want %f", h.GetSampleSum(), expectedSum)
	}

	// Buckets:
	// <= 0.1: 1 (0.05)
	// <= 0.5: 3 (0.05, 0.25, 0.50)
	// <= 1.0: 3 (0.05, 0.25, 0.50)
	// <= 5.0: 4 (0.05, 0.25, 0.50, 2.00)
	expectedCumulative := []uint64{1, 3, 3, 4}
	buckets := h.GetBucket()
	if len(buckets) != len(customBuckets) {
		t.Fatalf("got %d buckets, want %d", len(buckets), len(customBuckets))
	}

	for i, b := range buckets {
		if b.GetUpperBound() != customBuckets[i] {
			t.Errorf("bucket %d upper bound = %f, want %f", i, b.GetUpperBound(), customBuckets[i])
		}
		if b.GetCumulativeCount() != expectedCumulative[i] {
			t.Errorf("bucket %d (%f) cumulative count = %d, want %d", i, b.GetUpperBound(), b.GetCumulativeCount(), expectedCumulative[i])
		}
	}
}

func TestNewHistogramMetricDescription(t *testing.T) {
	opts := prometheus.HistogramOpts{
		Namespace: "service",
		Name:      "latency_seconds",
		Help:      "Service latency in seconds",
	}
	hist := prometheus.NewHistogram(opts)

	descChan := make(chan *prometheus.Desc, 1)
	hist.Describe(descChan)
	desc := <-descChan

	if desc == nil {
		t.Fatal("hist.Describe returned nil Desc")
	}
	if desc.String() == "" {
		t.Error("hist.Describe returned empty string representation")
	}
}

Seeder de origen

anónimo