CodeSampleX

Ejemplo

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

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

sha256:7b97409a4200a3b4485edba72093209428a96c579e487bf5c17b78e6b29c75f5

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.NewCounterVec in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Paquetes
Símbolos
  • github.com/prometheus/client_golang/prometheus.NewCounterVec
Entorno
go
Creado
2026-08-26T13:26:40Z

Contrato

  1. prometheus.NewCounterVec creates a non-nil CounterVec metric collector configured with CounterOpts and label names.
  2. CounterVec.WithLabelValues and CounterVec.With return Counter metrics partitioned by label values.
  3. CounterVec.GetMetricWithLabelValues validates label value counts against variable label names.
  4. CounterVec.CurryWith binds a subset of labels returning a curried CounterVec referencing the same underlying metrics.
  5. CounterVec.DeleteLabelValues and CounterVec.Delete remove metrics from the vector.
  6. CounterVec.Reset deletes all metrics from the vector.

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

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:e40e3feaacdc7982af60c942755cfba267de714b02913a95e8c1b35481272391","contract":["prometheus.NewCounterVec creates a non-nil CounterVec metric collector configured with CounterOpts and label names.","CounterVec.WithLabelValues and CounterVec.With return Counter metrics partitioned by label values.","CounterVec.GetMetricWithLabelValues validates label value counts against variable label names.","CounterVec.CurryWith binds a subset of labels returning a curried CounterVec referencing the same underlying metrics.","CounterVec.DeleteLabelValues and CounterVec.Delete remove metrics from the vector.","CounterVec.Reset deletes all metrics from the vector."],"goal":"verify github.com/prometheus/client_golang/prometheus.NewCounterVec 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.NewCounterVec"]},"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.NewCounterVec"],"verifierAdapter":"golang@1"}
go.mod
module example.com/countervec

go 1.26.6

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() {
	httpRequestsTotal := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "http",
			Subsystem: "server",
			Name:      "requests_total",
			Help:      "Total number of HTTP requests processed, partitioned by method and status code.",
		},
		[]string{"method", "code"},
	)

	// Increment counter with label values
	httpRequestsTotal.WithLabelValues("POST", "200").Inc()
	httpRequestsTotal.WithLabelValues("POST", "200").Add(2)
	httpRequestsTotal.With(prometheus.Labels{"method": "GET", "code": "404"}).Inc()

	// Read metric value
	var metric dto.Metric
	if counter, err := httpRequestsTotal.GetMetricWithLabelValues("POST", "200"); err == nil {
		_ = counter.Write(&metric)
		fmt.Printf("POST 200 count: %f\n", metric.GetCounter().GetValue())
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_golang/prometheus.NewCounterVec 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.NewCounterVec"
  ]
}
test/contract_test.go
package test

import (
	"testing"

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

func getCounterValue(t *testing.T, counter prometheus.Counter) float64 {
	t.Helper()
	var m dto.Metric
	if err := counter.Write(&m); err != nil {
		t.Fatalf("failed to write metric: %v", err)
	}
	if m.GetCounter() == nil {
		t.Fatal("expected counter metric, got nil")
	}
	return m.GetCounter().GetValue()
}

func TestNewCounterVecCreation(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "http",
			Subsystem: "server",
			Name:      "requests_total",
			Help:      "Total number of HTTP requests.",
		},
		[]string{"method", "code"},
	)
	if vec == nil {
		t.Fatal("expected non-nil CounterVec")
	}

	// Verify Describe emits a descriptor
	ch := make(chan *prometheus.Desc, 1)
	vec.Describe(ch)
	close(ch)

	desc := <-ch
	if desc == nil {
		t.Fatal("expected non-nil Desc from Describe")
	}
}

func TestCounterVecWithLabelValuesAndWith(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "test_counter",
			Help: "Test counter vector",
		},
		[]string{"service", "status"},
	)

	// 1. WithLabelValues
	c1 := vec.WithLabelValues("auth", "200")
	if c1 == nil {
		t.Fatal("expected non-nil Counter from WithLabelValues")
	}
	c1.Inc()
	c1.Add(4.5)

	if got := getCounterValue(t, c1); got != 5.5 {
		t.Errorf("expected counter value 5.5, got %v", got)
	}

	// 2. With
	c2 := vec.With(prometheus.Labels{"service": "api", "status": "500"})
	if c2 == nil {
		t.Fatal("expected non-nil Counter from With")
	}
	c2.Add(2.0)

	if got := getCounterValue(t, c2); got != 2.0 {
		t.Errorf("expected counter value 2.0, got %v", got)
	}

	// Ensure c1 and c2 are separate metrics
	if got := getCounterValue(t, c1); got != 5.5 {
		t.Errorf("expected c1 to remain 5.5, got %v", got)
	}
}

func TestCounterVecGetMetricValidation(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "validation_counter",
			Help: "Counter for validation tests",
		},
		[]string{"zone", "tier"},
	)

	// Wrong number of label values
	if _, err := vec.GetMetricWithLabelValues("us-east"); err == nil {
		t.Error("expected error when label values length is less than label names")
	}
	if _, err := vec.GetMetricWithLabelValues("us-east", "web", "extra"); err == nil {
		t.Error("expected error when label values length exceeds label names")
	}

	// Wrong label names in map
	if _, err := vec.GetMetricWith(prometheus.Labels{"invalid": "val", "tier": "web"}); err == nil {
		t.Error("expected error when invalid label names are provided")
	}

	// Correct label values
	c, err := vec.GetMetricWithLabelValues("us-east", "web")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	c.Inc()
	if got := getCounterValue(t, c); got != 1.0 {
		t.Errorf("expected counter value 1.0, got %v", got)
	}
}

func TestCounterVecCurryWith(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "curried_counter",
			Help: "Counter for currying tests",
		},
		[]string{"region", "cluster", "endpoint"},
	)

	// Curry with subset of labels
	curriedVec, err := vec.CurryWith(prometheus.Labels{"region": "us-west", "cluster": "alpha"})
	if err != nil {
		t.Fatalf("CurryWith failed: %v", err)
	}

	// Use remaining variable label
	c := curriedVec.WithLabelValues("/health")
	c.Add(3.0)

	// Fetch from original vec to ensure shared underlying metric
	origCounter, err := vec.GetMetricWithLabelValues("us-west", "alpha", "/health")
	if err != nil {
		t.Fatalf("GetMetricWithLabelValues on original vec failed: %v", err)
	}
	if got := getCounterValue(t, origCounter); got != 3.0 {
		t.Errorf("expected value 3.0 in original metric, got %v", got)
	}

	// Currying with non-existent label returns error
	if _, err := vec.CurryWith(prometheus.Labels{"nonexistent": "value"}); err == nil {
		t.Error("expected error when currying with unknown label name")
	}
}

func TestCounterVecDeleteAndReset(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "lifecycle_counter",
			Help: "Counter for delete and reset tests",
		},
		[]string{"tenant"},
	)

	vec.WithLabelValues("tenant-a").Inc()
	vec.WithLabelValues("tenant-b").Inc()

	// Delete existing
	deleted := vec.DeleteLabelValues("tenant-a")
	if !deleted {
		t.Error("expected DeleteLabelValues to return true for existing label")
	}

	// Delete non-existing
	deletedAgain := vec.DeleteLabelValues("tenant-a")
	if deletedAgain {
		t.Error("expected DeleteLabelValues to return false for already deleted label")
	}

	// Reset clears everything
	vec.Reset()
	deletedAfterReset := vec.DeleteLabelValues("tenant-b")
	if deletedAfterReset {
		t.Error("expected DeleteLabelValues to return false after Reset")
	}
}

Seeder de origen

anónimo