CodeSampleX

Пример

github.com/prometheus/procfs v0.6.0: Meminfo

Проверенный пример — golang github.com/prometheus/procfs v0.6.0: Meminfo. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:23912ed829c6a096d02ac9909488cbb8287fa8ee578fc30de61916eebd6e1c5e

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

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

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

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

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

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

Кейс

HOW
Цель
verify github.com/prometheus/procfs.Meminfo in pkg:golang/github.com/prometheus/procfs@v0.6.0
Пакеты
Символы
  • github.com/prometheus/procfs.Meminfo
Создан
2026-09-05T02:54:17Z

Контракт

  1. procfs.FS.Meminfo parses memory statistics including MemTotal, MemFree, Buffers, and Cached from procfs mount
  2. procfs.FS.Meminfo parses swap and paging metrics including SwapTotal, SwapFree, SwapCached, Dirty, and Writeback
  3. procfs.FS.Meminfo returns an error when reading from a non-existent proc mount
  4. procfs.FS.Meminfo returns an error when parsing malformed meminfo content

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • meminfo.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 github.com/prometheus/procfs.Meminfo in pkg:golang/github.com/prometheus/procfs@v0.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/procfs@v0.6.0
Demonstrate these symbols/APIs:
  - github.com/prometheus/procfs.Meminfo

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:3d63bbe6f2cac245b247b7e0b0e17695c3d77bcaa224ecbcc5388f8e1d96a0f2","contract":["procfs.FS.Meminfo parses memory statistics including MemTotal, MemFree, Buffers, and Cached from procfs mount","procfs.FS.Meminfo parses swap and paging metrics including SwapTotal, SwapFree, SwapCached, Dirty, and Writeback","procfs.FS.Meminfo returns an error when reading from a non-existent proc mount","procfs.FS.Meminfo returns an error when parsing malformed meminfo content"],"goal":"verify github.com/prometheus/procfs.Meminfo in pkg:golang/github.com/prometheus/procfs@v0.6.0","kind":"HOW","packages":["pkg:golang/github.com/prometheus/procfs@v0.6.0"],"schemaVersion":1,"symbols":["github.com/prometheus/procfs.Meminfo"]},"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/procfs@v0.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/procfs@v0.6.0","symbols":["github.com/prometheus/procfs.Meminfo"],"verifierAdapter":"golang@1"}
go.mod
module example.com/meminfo-sample

go 1.26.6

require github.com/prometheus/procfs v0.6.0

require golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c // indirect
go.sum
github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4=
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
meminfo.go
package meminfosample

import (
	"fmt"

	"github.com/prometheus/procfs"
)

// MemorySummary holds computed byte-level summary of system memory.
type MemorySummary struct {
	TotalBytes     uint64
	FreeBytes      uint64
	AvailableBytes uint64
	UsedBytes      uint64
}

// ReadMeminfo reads and returns procfs.Meminfo from the specified proc mount point.
func ReadMeminfo(mountPoint string) (procfs.Meminfo, error) {
	fs, err := procfs.NewFS(mountPoint)
	if err != nil {
		return procfs.Meminfo{}, fmt.Errorf("failed to open procfs at %s: %w", mountPoint, err)
	}

	info, err := fs.Meminfo()
	if err != nil {
		return procfs.Meminfo{}, fmt.Errorf("failed to read meminfo: %w", err)
	}

	return info, nil
}

// GetMemorySummary reads Meminfo from the given proc mount point and computes a summary in bytes.
func GetMemorySummary(mountPoint string) (*MemorySummary, error) {
	info, err := ReadMeminfo(mountPoint)
	if err != nil {
		return nil, err
	}

	var total, free, avail uint64
	if info.MemTotal != nil {
		total = *info.MemTotal * 1024
	}
	if info.MemFree != nil {
		free = *info.MemFree * 1024
	}
	if info.MemAvailable != nil {
		avail = *info.MemAvailable * 1024
	}

	var used uint64
	if total >= free {
		used = total - free
	}

	return &MemorySummary{
		TotalBytes:     total,
		FreeBytes:      free,
		AvailableBytes: avail,
		UsedBytes:      used,
	}, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/prometheus/procfs.Meminfo in pkg:golang/github.com/prometheus/procfs@v0.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/procfs@v0.6.0"
  ],
  "symbols": [
    "github.com/prometheus/procfs.Meminfo"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"path/filepath"

	meminfosample "example.com/meminfo-sample"
	"github.com/prometheus/procfs"
)

func main() {
	// Setup temporary directory for offline mock procfs testing
	tmpDir, err := os.MkdirTemp("", "mockproc-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to create temp dir: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tmpDir)

	mockProcDir := filepath.Join(tmpDir, "proc")
	if err := os.Mkdir(mockProcDir, 0755); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to create mock proc dir: %v\n", err)
		os.Exit(1)
	}

	mockMeminfoContent := `MemTotal:       16384000 kB
MemFree:         4096000 kB
MemAvailable:    8192000 kB
Buffers:         1024000 kB
Cached:          2048000 kB
SwapCached:       512000 kB
Active:          4000000 kB
Inactive:        2000000 kB
SwapTotal:       2097152 kB
SwapFree:        1048576 kB
Dirty:               128 kB
Writeback:             0 kB
`
	meminfoPath := filepath.Join(mockProcDir, "meminfo")
	if err := os.WriteFile(meminfoPath, []byte(mockMeminfoContent), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to write mock meminfo file: %v\n", err)
		os.Exit(1)
	}

	// Assertion 1: procfs.FS.Meminfo parses memory statistics including MemTotal, MemFree, Buffers, and Cached
	fs, err := procfs.NewFS(mockProcDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - failed to initialize procfs: %v\n", err)
		os.Exit(1)
	}

	meminfo, err := fs.Meminfo()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - failed to read meminfo: %v\n", err)
		os.Exit(1)
	}

	if meminfo.MemTotal == nil || *meminfo.MemTotal != 16384000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - unexpected MemTotal: %v\n", meminfo.MemTotal)
		os.Exit(1)
	}
	if meminfo.MemFree == nil || *meminfo.MemFree != 4096000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - unexpected MemFree: %v\n", meminfo.MemFree)
		os.Exit(1)
	}
	if meminfo.MemAvailable == nil || *meminfo.MemAvailable != 8192000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - unexpected MemAvailable: %v\n", meminfo.MemAvailable)
		os.Exit(1)
	}
	if meminfo.Buffers == nil || *meminfo.Buffers != 1024000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - unexpected Buffers: %v\n", meminfo.Buffers)
		os.Exit(1)
	}
	if meminfo.Cached == nil || *meminfo.Cached != 2048000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1 - unexpected Cached: %v\n", meminfo.Cached)
		os.Exit(1)
	}

	// Assertion 2: procfs.FS.Meminfo parses swap and paging metrics including SwapTotal, SwapFree, and SwapCached
	if meminfo.SwapTotal == nil || *meminfo.SwapTotal != 2097152 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected SwapTotal: %v\n", meminfo.SwapTotal)
		os.Exit(1)
	}
	if meminfo.SwapFree == nil || *meminfo.SwapFree != 1048576 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected SwapFree: %v\n", meminfo.SwapFree)
		os.Exit(1)
	}
	if meminfo.SwapCached == nil || *meminfo.SwapCached != 512000 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected SwapCached: %v\n", meminfo.SwapCached)
		os.Exit(1)
	}
	if meminfo.Dirty == nil || *meminfo.Dirty != 128 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected Dirty: %v\n", meminfo.Dirty)
		os.Exit(1)
	}
	if meminfo.Writeback == nil || *meminfo.Writeback != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected Writeback: %v\n", meminfo.Writeback)
		os.Exit(1)
	}

	// Verify package helper functions
	summary, err := meminfosample.GetMemorySummary(mockProcDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - GetMemorySummary failed: %v\n", err)
		os.Exit(1)
	}
	if summary.TotalBytes != 16384000*1024 || summary.FreeBytes != 4096000*1024 || summary.AvailableBytes != 8192000*1024 {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected summary values: %+v\n", summary)
		os.Exit(1)
	}
	expectedUsed := (16384000 - 4096000) * 1024
	if summary.UsedBytes != uint64(expectedUsed) {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 - unexpected used bytes: got %d, want %d\n", summary.UsedBytes, expectedUsed)
		os.Exit(1)
	}

	// Assertion 3: procfs.FS.Meminfo returns an error when reading from a non-existent proc mount
	emptyProcDir := filepath.Join(tmpDir, "emptyproc")
	if err := os.Mkdir(emptyProcDir, 0755); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3 - failed to create empty proc dir: %v\n", err)
		os.Exit(1)
	}
	emptyFS, err := procfs.NewFS(emptyProcDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3 - unexpected error opening empty procfs: %v\n", err)
		os.Exit(1)
	}
	if _, err := emptyFS.Meminfo(); err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3 - expected error when meminfo file does not exist, got nil\n")
		os.Exit(1)
	}

	// Assertion 4: procfs.FS.Meminfo returns an error when parsing malformed meminfo content
	malformedProcDir := filepath.Join(tmpDir, "badproc")
	if err := os.Mkdir(malformedProcDir, 0755); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4 - failed to create bad proc dir: %v\n", err)
		os.Exit(1)
	}
	badMeminfoPath := filepath.Join(malformedProcDir, "meminfo")
	if err := os.WriteFile(badMeminfoPath, []byte("MemTotal: not_a_number kB\n"), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4 - failed to write bad meminfo file: %v\n", err)
		os.Exit(1)
	}
	badFS, err := procfs.NewFS(malformedProcDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4 - unexpected error opening bad procfs: %v\n", err)
		os.Exit(1)
	}
	if _, err := badFS.Meminfo(); err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4 - expected error when meminfo has invalid number, got nil\n")
		os.Exit(1)
	}

	fmt.Println("PASS: procfs.Meminfo contract passed")
}

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

аноним