CodeSampleX

Пример

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

Проверенный пример — golang github.com/prometheus/client_golang v1.19.1: prometheus.CounterVec. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и…

sha256:d2b86e62ecb59afbfd4ffe86f56fef98baac5ae83ba206620beaa54d9f1053af

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 amd64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
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

Кейс

HOW
Цель
verify github.com/prometheus/client_golang/prometheus.CounterVec in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Пакеты
Символы
  • github.com/prometheus/client_golang/prometheus.CounterVec
Окружение
go 1.26.6
Создан
2026-08-26T13:08:38Z

Контракт

  1. prometheus.NewCounterVec initializes a CounterVec partitioned by specified label dimensions.
  2. prometheus.CounterVec.WithLabelValues and With return independent Counter metrics that increment and add correctly.
  3. prometheus.CounterVec.GetMetricWith retrieves the Counter metric for matching label maps, returning an error on invalid or missing labels.
  4. prometheus.CounterVec.DeleteLabelValues and Delete remove specific partitioned metrics and return true if found.
  5. prometheus.CounterVec.CurryWith pre-binds label values to return a curried CounterVec with reduced label dimensions.
  6. prometheus.CounterVec.Reset deletes all metrics from the CounterVec.

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.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 github.com/prometheus/client_golang/prometheus.CounterVec 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.CounterVec
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:8020ba40f410392f73e7ca412a31ef4a16bb8f0d36bdc64b00cdc80dbe8d36cc","contract":["prometheus.NewCounterVec initializes a CounterVec partitioned by specified label dimensions.","prometheus.CounterVec.WithLabelValues and With return independent Counter metrics that increment and add correctly.","prometheus.CounterVec.GetMetricWith retrieves the Counter metric for matching label maps, returning an error on invalid or missing labels.","prometheus.CounterVec.DeleteLabelValues and Delete remove specific partitioned metrics and return true if found.","prometheus.CounterVec.CurryWith pre-binds label values to return a curried CounterVec with reduced label dimensions.","prometheus.CounterVec.Reset deletes all metrics from the CounterVec."],"goal":"verify github.com/prometheus/client_golang/prometheus.CounterVec 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.CounterVec"]},"contractCommand":["go","test","./..."],"environment":{"arch":"amd64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go","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_golang@v1.19.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/client_golang@v1.19.1","symbols":["github.com/prometheus/client_golang/prometheus.CounterVec"],"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.6.2
)

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/prometheus/common v0.55.0 // indirect
	github.com/prometheus/procfs v0.21.1 // indirect
	golang.org/x/sys v0.47.0 // indirect
	google.golang.org/protobuf v1.36.11 // 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.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
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.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=
github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"

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

func main() {
	counterVec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "Total number of HTTP requests processed, partitioned by method and status code.",
		},
		[]string{"method", "code"},
	)

	// Increment and add to counter metrics with label values
	counterVec.WithLabelValues("GET", "200").Inc()
	counterVec.WithLabelValues("POST", "200").Add(10.0)

	// Access metric using Labels map
	if metric, err := counterVec.GetMetricWith(prometheus.Labels{"method": "GET", "code": "200"}); err == nil {
		var pb dto.Metric
		if err := metric.Write(&pb); err == nil {
			fmt.Printf("GET 200 count: %f\n", pb.GetCounter().GetValue())
		}
	}

	// Curry the CounterVec with a fixed method label
	if curried, err := counterVec.CurryWith(prometheus.Labels{"method": "POST"}); err == nil {
		curried.WithLabelValues("500").Inc()
	}

	// Delete a specific label combination
	deleted := counterVec.DeleteLabelValues("POST", "200")
	fmt.Printf("Deleted POST 200: %t\n", deleted)

	// Reset all metrics in the vector
	counterVec.Reset()
	fmt.Println("CounterVec reset complete")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_golang/prometheus.CounterVec 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.CounterVec"
  ],
  "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 (
	"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.Fatalf("metric does not contain counter data")
	}
	return m.GetCounter().GetValue()
}

func TestCounterVec_IncrementAndAdd(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "Total HTTP requests.",
		},
		[]string{"method", "status"},
	)

	counter := vec.WithLabelValues("GET", "200")
	if val := getCounterValue(t, counter); val != 0.0 {
		t.Errorf("initial counter value = %v, want 0.0", val)
	}

	counter.Inc()
	if val := getCounterValue(t, counter); val != 1.0 {
		t.Errorf("counter value after Inc() = %v, want 1.0", val)
	}

	counter.Add(4.5)
	if val := getCounterValue(t, counter); val != 5.5 {
		t.Errorf("counter value after Add(4.5) = %v, want 5.5", val)
	}

	// Distinct label values track independent counters
	postCounter := vec.With(prometheus.Labels{"method": "POST", "status": "201"})
	postCounter.Add(10.0)
	if val := getCounterValue(t, postCounter); val != 10.0 {
		t.Errorf("postCounter value = %v, want 10.0", val)
	}
	if val := getCounterValue(t, counter); val != 5.5 {
		t.Errorf("original counter value changed: %v, want 5.5", val)
	}
}

func TestCounterVec_GetMetricWith(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "api_calls_total",
			Help: "Total API calls.",
		},
		[]string{"endpoint", "handler"},
	)

	// Valid label map returns counter without error
	counter, err := vec.GetMetricWith(prometheus.Labels{"endpoint": "/users", "handler": "GetUser"})
	if err != nil {
		t.Fatalf("GetMetricWith returned error: %v", err)
	}
	counter.Inc()
	if val := getCounterValue(t, counter); val != 1.0 {
		t.Errorf("counter value = %v, want 1.0", val)
	}

	// Inconsistent label set returns error
	_, err = vec.GetMetricWith(prometheus.Labels{"endpoint": "/users"})
	if err == nil {
		t.Errorf("GetMetricWith with missing label expected error, got nil")
	}

	_, err = vec.GetMetricWith(prometheus.Labels{"endpoint": "/users", "invalid_label": "foo"})
	if err == nil {
		t.Errorf("GetMetricWith with unknown label expected error, got nil")
	}

	// GetMetricWithLabelValues with wrong count returns error
	_, err = vec.GetMetricWithLabelValues("/users")
	if err == nil {
		t.Errorf("GetMetricWithLabelValues with wrong count expected error, got nil")
	}
}

func TestCounterVec_DeleteAndReset(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "events_total",
			Help: "Total events.",
		},
		[]string{"type"},
	)

	vec.WithLabelValues("login").Add(3.0)
	vec.WithLabelValues("logout").Add(2.0)

	// Delete existing label returns true
	if deleted := vec.DeleteLabelValues("login"); !deleted {
		t.Errorf("DeleteLabelValues('login') = false, want true")
	}

	// Delete non-existent label returns false
	if deleted := vec.DeleteLabelValues("non_existent"); deleted {
		t.Errorf("DeleteLabelValues('non_existent') = true, want false")
	}

	// Re-initializing deleted label starts from 0
	newLoginCounter := vec.WithLabelValues("login")
	if val := getCounterValue(t, newLoginCounter); val != 0.0 {
		t.Errorf("re-created counter value = %v, want 0.0", val)
	}

	// Delete using Labels map
	if deleted := vec.Delete(prometheus.Labels{"type": "logout"}); !deleted {
		t.Errorf("Delete(type=logout) = false, want true")
	}

	// Reset clears all metrics
	vec.WithLabelValues("a").Inc()
	vec.WithLabelValues("b").Inc()
	vec.Reset()

	if deleted := vec.DeleteLabelValues("a"); deleted {
		t.Errorf("DeleteLabelValues('a') after Reset() = true, want false")
	}
}

func TestCounterVec_CurryWith(t *testing.T) {
	vec := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "rpc_requests_total",
			Help: "Total RPC requests.",
		},
		[]string{"service", "method", "status"},
	)

	// Curry with service label
	curriedVec, err := vec.CurryWith(prometheus.Labels{"service": "auth"})
	if err != nil {
		t.Fatalf("CurryWith returned unexpected error: %v", err)
	}

	curriedCounter := curriedVec.WithLabelValues("Login", "200")
	curriedCounter.Add(5.0)

	// Access original vector with all labels to verify it points to the same counter
	originalCounter, err := vec.GetMetricWith(prometheus.Labels{
		"service": "auth",
		"method":  "Login",
		"status":  "200",
	})
	if err != nil {
		t.Fatalf("vec.GetMetricWith returned error: %v", err)
	}
	if val := getCounterValue(t, originalCounter); val != 5.0 {
		t.Errorf("original counter value = %v, want 5.0", val)
	}

	// Currying with invalid label name returns error
	_, err = vec.CurryWith(prometheus.Labels{"unknown_label": "value"})
	if err == nil {
		t.Errorf("CurryWith with unknown label expected error, got nil")
	}
}

Исходный сидер

аноним