CodeSampleX

Exemple

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

Échantillon vérifié pour golang github.com/prometheus/client_golang v1.19.1: prometheus.HistogramOpts. Le contrat s'est exécuté sur go 1.26 · linux…

sha256:b6a11528f4ddd8b9ad4cd61d2aa77d9874c09f513390903942190365f4ac572b

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07

Cas

HOW
Objectif
verify github.com/prometheus/client_golang/prometheus.HistogramOpts in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Paquets
Symboles
  • github.com/prometheus/client_golang/prometheus.HistogramOpts
Créé
2026-08-26T13:23:08Z

Contrat

  1. prometheus.HistogramOpts configures histogram metrics with custom Namespace, Subsystem, Name, Help, ConstLabels, and custom Buckets thresholds for tracking observations.
  2. prometheus.HistogramOpts defaults to prometheus.DefBuckets when Buckets slice is omitted or nil.
  3. prometheus.LinearBuckets generates linear bucket thresholds compatible with prometheus.HistogramOpts.Buckets.

Fichiers

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • histogram_test.go
  • spec.json

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# Prometheus HistogramOpts Verification Notes

## Search Results
An initial search via `search_known_solution` for `pkg:golang/github.com/prometheus/client_golang@v1.19.1` with `github.com/prometheus/client_golang/prometheus.HistogramOpts` yielded `NO_SAFE_MATCH`.

## Pinned Version
- Package: `github.com/prometheus/client_golang`
- Release: `v1.19.1` (in `go.mod` / `go.sum`)

## Observed Behavior
1. **HistogramOpts Configuration & Custom Buckets**:
   - `prometheus.HistogramOpts` configures histogram metric descriptors including `Namespace`, `Subsystem`, `Name`, `Help`, `ConstLabels`, and `Buckets`.
   - Passing custom bucket slices (e.g., `[]float64{0.1, 0.5, 1.0, 2.5, 5.0}`) to `prometheus.NewHistogram` configures explicit cumulative bucket boundaries.
   - Calling `.Observe(val)` properly increments cumulative bucket counts for all upper bounds `>= val`, and updates total sample count and sample sum.
2. **Default Buckets Fallback**:
   - When `Buckets` is nil or omitted in `HistogramOpts`, `prometheus.NewHistogram` falls back to `prometheus.DefBuckets` (`[]float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}`).
3. **Linear Buckets Generator**:
   - Helper functions like `prometheus.LinearBuckets(start, width, count)` generate equally spaced bucket slices that can be assigned directly to `HistogramOpts.Buckets`.
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.HistogramOpts 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.HistogramOpts

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:9ef4292ef556d8239c05521bab241c4a0cd4c99bb9cc6450341916f50d2237c2","contract":["prometheus.HistogramOpts configures histogram metrics with custom Namespace, Subsystem, Name, Help, ConstLabels, and custom Buckets thresholds for tracking observations.","prometheus.HistogramOpts defaults to prometheus.DefBuckets when Buckets slice is omitted or nil.","prometheus.LinearBuckets generates linear bucket thresholds compatible with prometheus.HistogramOpts.Buckets."],"goal":"verify github.com/prometheus/client_golang/prometheus.HistogramOpts 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.HistogramOpts"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"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.HistogramOpts"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

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=
histogram_test.go
package sample_test

import (
	"testing"

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

func TestHistogramOptsCustomBucketsAndObserve(t *testing.T) {
	opts := prometheus.HistogramOpts{
		Namespace: "myapp",
		Subsystem: "http",
		Name:      "request_duration_seconds",
		Help:      "Duration of HTTP requests in seconds.",
		ConstLabels: prometheus.Labels{
			"env": "production",
		},
		Buckets: []float64{0.1, 0.5, 1.0, 2.5, 5.0},
	}

	hist := prometheus.NewHistogram(opts)

	// Observe values
	hist.Observe(0.05) // <= 0.1, <= 0.5, <= 1.0, <= 2.5, <= 5.0
	hist.Observe(0.3)  // <= 0.5, <= 1.0, <= 2.5, <= 5.0
	hist.Observe(1.5)  // <= 2.5, <= 5.0
	hist.Observe(6.0)  // > 5.0 (only contributes to +Inf)

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

	h := metric.GetHistogram()
	if h == nil {
		t.Fatal("expected histogram metric data, got nil")
	}

	if gotCount := h.GetSampleCount(); gotCount != 4 {
		t.Errorf("expected sample count 4, got %d", gotCount)
	}

	expectedSum := 0.05 + 0.3 + 1.5 + 6.0
	if gotSum := h.GetSampleSum(); gotSum != expectedSum {
		t.Errorf("expected sample sum %f, got %f", expectedSum, gotSum)
	}

	buckets := h.GetBucket()
	if len(buckets) != len(opts.Buckets) {
		t.Fatalf("expected %d buckets, got %d", len(opts.Buckets), len(buckets))
	}

	expectedCounts := []uint64{1, 2, 2, 3, 3}
	for i, b := range buckets {
		if b.GetUpperBound() != opts.Buckets[i] {
			t.Errorf("bucket %d upper bound: expected %f, got %f", i, opts.Buckets[i], b.GetUpperBound())
		}
		if b.GetCumulativeCount() != expectedCounts[i] {
			t.Errorf("bucket %d cumulative count: expected %d, got %d", i, expectedCounts[i], b.GetCumulativeCount())
		}
	}

	// Verify const labels
	labels := metric.GetLabel()
	foundEnv := false
	for _, l := range labels {
		if l.GetName() == "env" && l.GetValue() == "production" {
			foundEnv = true
		}
	}
	if !foundEnv {
		t.Errorf("expected const label env=production, got %v", labels)
	}
}

func TestHistogramOptsDefaultBuckets(t *testing.T) {
	opts := prometheus.HistogramOpts{
		Name: "simple_latency_seconds",
		Help: "Simple latency histogram using default buckets.",
	}

	hist := prometheus.NewHistogram(opts)
	hist.Observe(0.01)

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

	h := metric.GetHistogram()
	if h == nil {
		t.Fatal("expected histogram metric data, got nil")
	}

	buckets := h.GetBucket()
	if len(buckets) != len(prometheus.DefBuckets) {
		t.Fatalf("expected default bucket count %d, got %d", len(prometheus.DefBuckets), len(buckets))
	}

	for i, b := range buckets {
		if b.GetUpperBound() != prometheus.DefBuckets[i] {
			t.Errorf("default bucket %d upper bound: expected %f, got %f", i, prometheus.DefBuckets[i], b.GetUpperBound())
		}
	}
}

func TestHistogramOptsLinearBuckets(t *testing.T) {
	linearBuckets := prometheus.LinearBuckets(10, 10, 5) // 10, 20, 30, 40, 50
	opts := prometheus.HistogramOpts{
		Namespace: "service",
		Subsystem: "queue",
		Name:      "job_processing_milliseconds",
		Help:      "Job processing time in milliseconds.",
		Buckets:   linearBuckets,
	}

	hist := prometheus.NewHistogram(opts)
	hist.Observe(25.0)

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

	h := metric.GetHistogram()
	if h == nil {
		t.Fatal("expected histogram metric data, got nil")
	}

	buckets := h.GetBucket()
	if len(buckets) != 5 {
		t.Fatalf("expected 5 buckets, got %d", len(buckets))
	}

	// 25.0 is <= 30, <= 40, <= 50
	expectedCumulative := []uint64{0, 0, 1, 1, 1}
	for i, b := range buckets {
		if b.GetCumulativeCount() != expectedCumulative[i] {
			t.Errorf("bucket %d cumulative count: expected %d, got %d", i, expectedCumulative[i], b.GetCumulativeCount())
		}
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_golang/prometheus.HistogramOpts 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.HistogramOpts"
  ]
}

Seeder d'origine

anonyme