CodeSampleX

Ejemplo

github.com/prometheus/common v0.71.0: expfmt

Muestra verificada para golang github.com/prometheus/common v0.71.0: expfmt. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.

sha256:bdfa918826eadeac66d43416cf605e0e637ecaf0577f17fa886de20c6a5b7e0f

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
1
Claves de firma que lo compilaron
1
Entorno declarado go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Entornos de las ejecuciones de verificación

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

Caso

HOW
Objetivo
verify github.com/prometheus/common/expfmt in pkg:golang/github.com/prometheus/common@v0.71.0
Paquetes
Símbolos
  • github.com/prometheus/common/expfmt
Entorno
go 1.26.6
Creado
2026-09-05T08:27:55Z

Contrato

  1. expfmt.Negotiate defaults to TypeTextPlain when Accept header is missing or unrecognized
  2. expfmt.NegotiateAccept negotiates format according to Accept header preferences
  3. expfmt.NewTextParser parses Prometheus exposition text into metric families
  4. expfmt.NewDecoder decodes stream metric families until EOF
  5. expfmt.NewFormat creates valid Format instance with expected FormatType

Archivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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/common/expfmt in pkg:golang/github.com/prometheus/common@v0.71.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/common@v0.71.0
Demonstrate these symbols/APIs:
  - github.com/prometheus/common/expfmt

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:362edaf89a05c375e00a9920cc09fc09e10da99eff5aa2f5ffd9672d2be7ab60","contract":["expfmt.Negotiate defaults to TypeTextPlain when Accept header is missing or unrecognized","expfmt.NegotiateAccept negotiates format according to Accept header preferences","expfmt.NewTextParser parses Prometheus exposition text into metric families","expfmt.NewDecoder decodes stream metric families until EOF","expfmt.NewFormat creates valid Format instance with expected FormatType"],"goal":"verify github.com/prometheus/common/expfmt in pkg:golang/github.com/prometheus/common@v0.71.0","kind":"HOW","packages":["pkg:golang/github.com/prometheus/common@v0.71.0"],"schemaVersion":1,"symbols":["github.com/prometheus/common/expfmt"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","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/common@v0.71.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/common@v0.71.0","symbols":["github.com/prometheus/common/expfmt"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	github.com/prometheus/client_model v0.6.2
	github.com/prometheus/common v0.71.0
)

require (
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	google.golang.org/protobuf v1.36.12 // indirect
)
go.sum
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_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.71.0 h1:9KDAKb7Mj3HEVKyFCK6Dc/HIwlBzZIN2l7/lrHl3KK8=
github.com/prometheus/common v0.71.0/go.mod h1:CLJ5H8TEsGX8bl31BdMkfhIZ+QmZ9tBPPotUxUbfcmk=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/model"
)

func main() {
	// Negotiate format from HTTP Accept header
	reqHeader := http.Header{}
	reqHeader.Set("Accept", "text/plain; version=0.0.4")
	format := expfmt.Negotiate(reqHeader)
	fmt.Printf("Negotiated format: %s\n", format)

	// Parse Prometheus metrics text into MetricFamilies
	metricsText := `# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="post",code="200"} 1027 1395066496465
`
	parser := expfmt.NewTextParser(model.LegacyValidation)
	metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(metricsText))
	if err != nil {
		panic(err)
	}

	for name, mf := range metricFamilies {
		fmt.Printf("Parsed metric family: %s (type: %s, metrics: %d)\n", name, mf.GetType(), len(mf.GetMetric()))
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/common/expfmt in pkg:golang/github.com/prometheus/common@v0.71.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/common@v0.71.0"
  ],
  "symbols": [
    "github.com/prometheus/common/expfmt"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/model"
)

func main() {
	// Assertion 1: expfmt.Negotiate defaults to TypeTextPlain when Accept header is missing or unrecognized
	{
		h := http.Header{}
		format := expfmt.Negotiate(h)
		if format.FormatType() != expfmt.TypeTextPlain {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected TypeTextPlain, got %v\n", format.FormatType())
			os.Exit(1)
		}

		h.Set("Accept", "application/unsupported")
		format = expfmt.Negotiate(h)
		if format.FormatType() != expfmt.TypeTextPlain {
			fmt.Fprintf(os.Stderr, "assertion 1 failed on unsupported: expected TypeTextPlain, got %v\n", format.FormatType())
			os.Exit(1)
		}
	}

	// Assertion 2: expfmt.NegotiateAccept negotiates format according to Accept header preferences
	{
		h := http.Header{}
		h.Set("Accept", "application/openmetrics-text; version=1.0.0; q=0.8, text/plain; version=0.0.4; q=0.5")
		accepted := []expfmt.Format{
			expfmt.FmtOpenMetrics_1_0_0,
			expfmt.FmtText,
		}
		format := expfmt.NegotiateAccept(h, accepted...)
		if format.FormatType() != expfmt.TypeOpenMetrics {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected TypeOpenMetrics, got %v\n", format.FormatType())
			os.Exit(1)
		}
	}

	// Assertion 3: expfmt.NewTextParser parses Prometheus exposition text into metric families
	{
		metricsText := `# HELP http_requests_total The total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="post",code="200"} 1027 1395066496465
http_requests_total{method="post",code="400"} 3 1395066496465
`
		parser := expfmt.NewTextParser(model.LegacyValidation)
		fams, err := parser.TextToMetricFamilies(strings.NewReader(metricsText))
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: parse error: %v\n", err)
			os.Exit(1)
		}
		mf, ok := fams["http_requests_total"]
		if !ok || mf == nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: missing metric family http_requests_total\n")
			os.Exit(1)
		}
		if mf.GetType() != dto.MetricType_COUNTER {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected COUNTER, got %v\n", mf.GetType())
			os.Exit(1)
		}
		if len(mf.GetMetric()) != 2 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected 2 metrics, got %d\n", len(mf.GetMetric()))
			os.Exit(1)
		}
	}

	// Assertion 4: expfmt.NewDecoder decodes stream metric families until EOF
	{
		metricsText := `# HELP process_cpu_seconds Total CPU time.
# TYPE process_cpu_seconds gauge
process_cpu_seconds 4.2
`
		dec := expfmt.NewDecoder(strings.NewReader(metricsText), expfmt.FmtText)
		var mf dto.MetricFamily
		if err := dec.Decode(&mf); err != nil {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: decode error: %v\n", err)
			os.Exit(1)
		}
		if mf.GetName() != "process_cpu_seconds" {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected name process_cpu_seconds, got %s\n", mf.GetName())
			os.Exit(1)
		}
		if mf.GetType() != dto.MetricType_GAUGE {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected GAUGE, got %v\n", mf.GetType())
			os.Exit(1)
		}
	}

	// Assertion 5: expfmt.NewFormat creates valid Format instance with expected FormatType
	{
		fmtPlain := expfmt.NewFormat(expfmt.TypeTextPlain)
		if fmtPlain.FormatType() != expfmt.TypeTextPlain {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected TypeTextPlain, got %v\n", fmtPlain.FormatType())
			os.Exit(1)
		}
		fmtOpenMetrics := expfmt.NewFormat(expfmt.TypeOpenMetrics)
		if fmtOpenMetrics.FormatType() != expfmt.TypeOpenMetrics {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected TypeOpenMetrics, got %v\n", fmtOpenMetrics.FormatType())
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

Seeder de origen

anónimo