CodeSampleX

Пример

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

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

sha256:d49e37638e17d0ab4e980f097b309fa1304ac9cde4e7ade03cdc2ff6617cc8b5

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

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

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

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

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

Окружение Контракт Этапы Запуск
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.CounterOpts in pkg:golang/github.com/prometheus/client_golang@v1.19.1
Пакеты
Символы
  • github.com/prometheus/client_golang/prometheus.CounterOpts
Создан
2026-08-26T13:04:32Z

Контракт

  1. prometheus.CounterOpts configures namespace, subsystem, name, and help for a standalone counter
  2. prometheus.CounterOpts supports ConstLabels applied to all metric instances
  3. prometheus.CounterOpts configures labeled CounterVec metrics partitioned by label values

Файлы

  • PROMPT.md
  • counter.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.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.CounterOpts 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.CounterOpts
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.
counter.go
package sample

import (
	"github.com/prometheus/client_golang/prometheus"
)

// Metrics holds prometheus counter collectors configured via CounterOpts.
type Metrics struct {
	Registry       *prometheus.Registry
	RequestCounter prometheus.Counter
	HTTPRequests   *prometheus.CounterVec
}

// NewMetrics creates and registers Prometheus counters using CounterOpts.
func NewMetrics() *Metrics {
	reg := prometheus.NewRegistry()

	// Direct counter with namespace, subsystem, name, help, and const labels via CounterOpts
	singleOpts := prometheus.CounterOpts{
		Namespace:   "myapp",
		Subsystem:   "worker",
		Name:        "jobs_processed_total",
		Help:        "Total number of worker jobs processed.",
		ConstLabels: prometheus.Labels{"version": "1.0.0"},
	}
	singleCounter := prometheus.NewCounter(singleOpts)

	// Vector counter with CounterOpts
	vecOpts := prometheus.CounterOpts{
		Namespace: "myapp",
		Subsystem: "http",
		Name:      "requests_total",
		Help:      "Total HTTP requests by handler and status.",
	}
	vecCounter := prometheus.NewCounterVec(vecOpts, []string{"handler", "code"})

	reg.MustRegister(singleCounter, vecCounter)

	return &Metrics{
		Registry:       reg,
		RequestCounter: singleCounter,
		HTTPRequests:   vecCounter,
	}
}
csx.json
{"case":{"caseId":"case:sha256:a657983e0c3e23b322856d3e59f317ebf4e72b97145d6611fd6695fc187b8ee0","contract":["prometheus.CounterOpts configures namespace, subsystem, name, and help for a standalone counter","prometheus.CounterOpts supports ConstLabels applied to all metric instances","prometheus.CounterOpts configures labeled CounterVec metrics partitioned by label values"],"goal":"verify github.com/prometheus/client_golang/prometheus.CounterOpts 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.CounterOpts"]},"contractCommand":["go","run","./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.CounterOpts"],"verifierAdapter":"golang@1"}
go.mod
module sample

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/client_golang/prometheus.CounterOpts 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.CounterOpts"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"fmt"
	"os"

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

func main() {
	m := sample.NewMetrics()
	if m == nil || m.Registry == nil {
		fmt.Fprintf(os.Stderr, "failed to initialize metrics\n")
		os.Exit(1)
	}

	// 1. Increment standalone counter
	m.RequestCounter.Inc()
	m.RequestCounter.Add(4)

	// 2. Increment counter vector instances
	m.HTTPRequests.WithLabelValues("login", "200").Inc()
	m.HTTPRequests.WithLabelValues("login", "500").Add(2)

	// 3. Gather metrics from the registry
	mfs, err := m.Registry.Gather()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Gather failed: %v\n", err)
		os.Exit(1)
	}

	if len(mfs) != 2 {
		fmt.Fprintf(os.Stderr, "expected 2 metric families, got %d\n", len(mfs))
		os.Exit(1)
	}

	familyMap := make(map[string]*dto.MetricFamily)
	for _, mf := range mfs {
		familyMap[mf.GetName()] = mf
	}

	// Check single counter metric family: myapp_worker_jobs_processed_total
	jobsMF, ok := familyMap["myapp_worker_jobs_processed_total"]
	if !ok {
		fmt.Fprintf(os.Stderr, "missing myapp_worker_jobs_processed_total metric family\n")
		os.Exit(1)
	}
	if jobsMF.GetType() != dto.MetricType_COUNTER {
		fmt.Fprintf(os.Stderr, "expected COUNTER type, got %v\n", jobsMF.GetType())
		os.Exit(1)
	}
	if len(jobsMF.GetMetric()) != 1 {
		fmt.Fprintf(os.Stderr, "expected 1 metric instance, got %d\n", len(jobsMF.GetMetric()))
		os.Exit(1)
	}
	jobMetric := jobsMF.GetMetric()[0]
	if jobMetric.GetCounter().GetValue() != 5.0 {
		fmt.Fprintf(os.Stderr, "expected counter value 5.0, got %f\n", jobMetric.GetCounter().GetValue())
		os.Exit(1)
	}
	// Check const labels
	hasVersion := false
	for _, lbl := range jobMetric.GetLabel() {
		if lbl.GetName() == "version" && lbl.GetValue() == "1.0.0" {
			hasVersion = true
			break
		}
	}
	if !hasVersion {
		fmt.Fprintf(os.Stderr, "missing expected const label version=1.0.0\n")
		os.Exit(1)
	}

	// Check vector counter metric family: myapp_http_requests_total
	httpMF, ok := familyMap["myapp_http_requests_total"]
	if !ok {
		fmt.Fprintf(os.Stderr, "missing myapp_http_requests_total metric family\n")
		os.Exit(1)
	}
	if httpMF.GetType() != dto.MetricType_COUNTER {
		fmt.Fprintf(os.Stderr, "expected COUNTER type, got %v\n", httpMF.GetType())
		os.Exit(1)
	}
	if len(httpMF.GetMetric()) != 2 {
		fmt.Fprintf(os.Stderr, "expected 2 vector metric instances, got %d\n", len(httpMF.GetMetric()))
		os.Exit(1)
	}

	fmt.Println("All prometheus.CounterOpts contract assertions passed.")
}

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

аноним