CodeSampleX

샘플

github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Histogram

검증된 샘플 — golang github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9: Histogram. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:8c4192eb5d1162d35d2acc2db71347a50a856929c63db9e736cf5d2337c38496

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

검증 실행 환경

환경 컨트랙트 단계 실행일
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-02

케이스

HOW
목표
verify Histogram in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
패키지
심벌
  • Histogram
환경
go 1.26.6
생성일
2026-09-02T20:58:45Z

컨트랙트

  1. metrics.NewHistogram constructs a Histogram using a Sample reservoir
  2. Histogram.Update records integer samples and accurately updates Count, Min, Max, and Sum
  3. Histogram.Mean, Variance, and StdDev compute statistical distribution properties over recorded values
  4. Histogram.Percentile and Percentiles calculate sample quantiles via linear interpolation
  5. Histogram.Snapshot creates an immutable read-only copy that preserves statistics and panics on Update or Clear
  6. Histogram.Clear resets the histogram and sample statistics back to zero
  7. metrics.NewRegisteredHistogram and GetOrRegisterHistogram register and retrieve a Histogram in a Registry

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • 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 Histogram in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9
Demonstrate these symbols/APIs:
  - Histogram

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:3783aa7a902982fb3cdb5613c5b974f76dc063a391b3f88098111d9318d0ad6b","contract":["metrics.NewHistogram constructs a Histogram using a Sample reservoir","Histogram.Update records integer samples and accurately updates Count, Min, Max, and Sum","Histogram.Mean, Variance, and StdDev compute statistical distribution properties over recorded values","Histogram.Percentile and Percentiles calculate sample quantiles via linear interpolation","Histogram.Snapshot creates an immutable read-only copy that preserves statistics and panics on Update or Clear","Histogram.Clear resets the histogram and sample statistics back to zero","metrics.NewRegisteredHistogram and GetOrRegisterHistogram register and retrieve a Histogram in a Registry"],"goal":"verify Histogram in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9","kind":"HOW","packages":["pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"],"schemaVersion":1,"symbols":["Histogram"]},"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/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"],"schemaVersion":1,"subject":"pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9","symbols":["Histogram"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.24

require github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9
go.sum
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
main.go
package main

import (
	"fmt"

	"github.com/rcrowley/go-metrics"
)

func main() {
	sample := metrics.NewUniformSample(100)
	histogram := metrics.NewHistogram(sample)

	values := []int64{10, 20, 30, 40, 50}
	for _, v := range values {
		histogram.Update(v)
	}

	fmt.Printf("Count: %d\n", histogram.Count())
	fmt.Printf("Min: %d\n", histogram.Min())
	fmt.Printf("Max: %d\n", histogram.Max())
	fmt.Printf("Mean: %.2f\n", histogram.Mean())
	fmt.Printf("Median: %.2f\n", histogram.Percentile(0.5))

	snapshot := histogram.Snapshot()
	fmt.Printf("Snapshot Count: %d\n", snapshot.Count())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Histogram in pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/rcrowley/go-metrics@v0.0.0-20250401214520-65e299d6c5c9"
  ],
  "symbols": [
    "Histogram"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"math"
	"os"

	"github.com/rcrowley/go-metrics"
)

func main() {
	// Assertion 1: metrics.NewHistogram constructs a Histogram using a Sample reservoir
	sample := metrics.NewUniformSample(100)
	h := metrics.NewHistogram(sample)
	if h == nil {
		fmt.Fprintln(os.Stderr, "FAIL: NewHistogram returned nil")
		os.Exit(1)
	}
	if h.Sample() == nil {
		fmt.Fprintln(os.Stderr, "FAIL: h.Sample() is nil")
		os.Exit(1)
	}

	// Assertion 2: Histogram.Update records integer samples and accurately updates Count, Min, Max, and Sum
	values := []int64{10, 20, 30, 40, 50}
	for _, v := range values {
		h.Update(v)
	}
	if h.Count() != 5 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Count 5, got %d\n", h.Count())
		os.Exit(1)
	}
	if h.Min() != 10 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Min 10, got %d\n", h.Min())
		os.Exit(1)
	}
	if h.Max() != 50 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Max 50, got %d\n", h.Max())
		os.Exit(1)
	}
	if h.Sum() != 150 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Sum 150, got %d\n", h.Sum())
		os.Exit(1)
	}

	// Assertion 3: Histogram.Mean, Variance, and StdDev compute statistical distribution properties over recorded values
	if math.Abs(h.Mean()-30.0) > 1e-9 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Mean 30.0, got %f\n", h.Mean())
		os.Exit(1)
	}
	if math.Abs(h.Variance()-200.0) > 1e-9 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Variance 200.0, got %f\n", h.Variance())
		os.Exit(1)
	}
	expectedStdDev := math.Sqrt(200.0)
	if math.Abs(h.StdDev()-expectedStdDev) > 1e-9 {
		fmt.Fprintf(os.Stderr, "FAIL: expected StdDev %f, got %f\n", expectedStdDev, h.StdDev())
		os.Exit(1)
	}

	// Assertion 4: Histogram.Percentile and Percentiles calculate sample quantiles via linear interpolation
	median := h.Percentile(0.5)
	if math.Abs(median-30.0) > 1e-9 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Percentile(0.5) 30.0, got %f\n", median)
		os.Exit(1)
	}
	ps := h.Percentiles([]float64{0.0, 0.5, 1.0})
	if len(ps) != 3 || math.Abs(ps[0]-10.0) > 1e-9 || math.Abs(ps[1]-30.0) > 1e-9 || math.Abs(ps[2]-50.0) > 1e-9 {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected Percentiles result: %v\n", ps)
		os.Exit(1)
	}

	// Assertion 5: Histogram.Snapshot creates an immutable read-only copy that preserves statistics and panics on Update or Clear
	snap := h.Snapshot()
	if snap.Count() != 5 || snap.Min() != 10 || snap.Max() != 50 || snap.Sum() != 150 {
		fmt.Fprintf(os.Stderr, "FAIL: snapshot does not match histogram statistics\n")
		os.Exit(1)
	}

	var updatePanicked bool
	func() {
		defer func() {
			if r := recover(); r != nil {
				updatePanicked = true
			}
		}()
		snap.Update(60)
	}()
	if !updatePanicked {
		fmt.Fprintln(os.Stderr, "FAIL: HistogramSnapshot.Update did not panic")
		os.Exit(1)
	}

	var clearPanicked bool
	func() {
		defer func() {
			if r := recover(); r != nil {
				clearPanicked = true
			}
		}()
		snap.Clear()
	}()
	if !clearPanicked {
		fmt.Fprintln(os.Stderr, "FAIL: HistogramSnapshot.Clear did not panic")
		os.Exit(1)
	}

	// Assertion 6: Histogram.Clear resets the histogram and sample statistics back to zero
	h.Clear()
	if h.Count() != 0 || h.Min() != 0 || h.Max() != 0 || h.Sum() != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: after Clear, statistics not reset: count=%d, min=%d, max=%d, sum=%d\n",
			h.Count(), h.Min(), h.Max(), h.Sum())
		os.Exit(1)
	}
	if h.Mean() != 0.0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected Mean 0.0 after Clear, got %f\n", h.Mean())
		os.Exit(1)
	}

	// Assertion 7: metrics.NewRegisteredHistogram and GetOrRegisterHistogram register and retrieve a Histogram in a Registry
	reg := metrics.NewRegistry()
	registeredHist := metrics.NewRegisteredHistogram("latency", reg, metrics.NewUniformSample(50))
	if registeredHist == nil {
		fmt.Fprintln(os.Stderr, "FAIL: NewRegisteredHistogram returned nil")
		os.Exit(1)
	}
	registeredHist.Update(100)

	retrievedHist := metrics.GetOrRegisterHistogram("latency", reg, metrics.NewUniformSample(50))
	if retrievedHist == nil {
		fmt.Fprintln(os.Stderr, "FAIL: GetOrRegisterHistogram returned nil")
		os.Exit(1)
	}
	if retrievedHist.Count() != 1 || retrievedHist.Max() != 100 {
		fmt.Fprintf(os.Stderr, "FAIL: retrieved histogram does not match registered instance: count=%d\n", retrievedHist.Count())
		os.Exit(1)
	}

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

오리진 시더

익명