Exemple
github.com/prometheus/common v0.48.0: Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
Échantillon vérifié pour golang github.com/prometheus/common v0.48.0: Parse Prometheus text exposition format metrics into metric families using…
sha256:11620403c1eb9826ec622c9bde16e3b997e0be7caf94a945ce54a87e42a7cdb7
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
go linux x64 go go go
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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-23 |
Cas
HOW- Objectif
- Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
- Symboles
-
- github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies
- Environnement
- go
- Créé
- 2026-08-23T17:04:07Z
Contrat
- TextParser.TextToMetricFamilies parses Prometheus text format exposition input into a map of MetricFamily pointers keyed by metric family name.
- HELP and TYPE comments are correctly parsed into MetricFamily Help and Type metadata (such as MetricType_COUNTER and MetricType_GAUGE).
- Parsed metrics contain label name and value pairs as well as numeric counter or gauge sample values and optional millisecond timestamps.
- Exposition input streams with multiple distinct metric families are parsed into separate map entries.
- Malformed metric exposition input produces a non-nil parse error.
Fichiers
- NOTES.md
- PROMPT.md
- csx.json
- go.mod
- go.sum
- parser_test.go
- spec.json
Code source
# github.com/prometheus/common/expfmt Exposition Parser
## Prior Knowledge Search
A query to search known solutions for `pkg:golang/github.com/prometheus/common@v0.48.0` returned `NO_SAFE_MATCH`. This sample establishes verified coverage for parsing Prometheus text exposition formats into metric families.
## Pinned Release
- `github.com/prometheus/common`: `v0.48.0`
- `github.com/prometheus/client_model`: `v0.5.0`
- `google.golang.org/protobuf`: `v1.32.0`
## Proven Behaviors and Semantics
### 1. Parsing Counter and Gauge Metrics into MetricFamily Maps
`expfmt.TextParser.TextToMetricFamilies` reads an `io.Reader` of Prometheus exposition text and produces a map of `*dto.MetricFamily` keyed by the metric family name.
- HELP and TYPE metadata lines are parsed into `MetricFamily.Help` and `MetricFamily.Type`.
- Individual sample lines are parsed into elements of `MetricFamily.Metric`, with labels parsed into `[]*dto.LabelPair`.
- Numeric values and timestamps (when provided) are correctly populated in the metric's typed payload (`Counter.Value`, `Gauge.Value`, `TimestampMs`).
### 2. Multi-Metric and Multi-Family Parsing
A single exposition input stream containing multiple distinct metric families (e.g., counters and gauges) is parsed into separate map entries corresponding to each family name.
### 3. Syntax Error Detection
Malformed metric input (such as unquoted label values or invalid syntax) produces a non-nil parse error rather than silent corruption or panic.
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: Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/github.com/prometheus/common@v0.48.0
Demonstrate these symbols/APIs:
- github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies
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.
{"case":{"caseId":"case:sha256:dd1a55602fd64c50df04d68fb85d817563f74d1e6e2de81025648038ec906d25","contract":["TextParser.TextToMetricFamilies parses Prometheus text format exposition input into a map of MetricFamily pointers keyed by metric family name.","HELP and TYPE comments are correctly parsed into MetricFamily Help and Type metadata (such as MetricType_COUNTER and MetricType_GAUGE).","Parsed metrics contain label name and value pairs as well as numeric counter or gauge sample values and optional millisecond timestamps.","Exposition input streams with multiple distinct metric families are parsed into separate map entries.","Malformed metric exposition input produces a non-nil parse error."],"goal":"Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser","kind":"HOW","packages":["pkg:golang/github.com/prometheus/common@v0.48.0"],"schemaVersion":1,"symbols":["github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/prometheus/common@v0.48.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/common@v0.48.0","symbols":["github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"],"verifierAdapter":"golang@1"}
module example.com/csx-prometheus-common-test
go 1.26.5
require (
github.com/prometheus/client_model v0.5.0
github.com/prometheus/common v0.48.0
)
require google.golang.org/protobuf v1.32.0 // indirect
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_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=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
package main
import (
"strings"
"testing"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
)
func TestTextToMetricFamiliesCounter(t *testing.T) {
input := `# HELP http_requests_total The total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="post",code="200"} 1027 1395066363000
http_requests_total{method="post",code="400"} 3 1395066363000
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error parsing counter metrics: %v", err)
}
mf, exists := metricFamilies["http_requests_total"]
if !exists {
t.Fatalf("expected metric family 'http_requests_total' not found")
}
if mf.GetName() != "http_requests_total" {
t.Errorf("expected name 'http_requests_total', got %q", mf.GetName())
}
if mf.GetHelp() != "The total number of HTTP requests." {
t.Errorf("expected help text 'The total number of HTTP requests.', got %q", mf.GetHelp())
}
if mf.GetType() != dto.MetricType_COUNTER {
t.Errorf("expected metric type COUNTER, got %v", mf.GetType())
}
metrics := mf.GetMetric()
if len(metrics) != 2 {
t.Fatalf("expected 2 metrics in family, got %d", len(metrics))
}
// Verify first metric
m0 := metrics[0]
if m0.GetCounter().GetValue() != 1027 {
t.Errorf("expected counter value 1027, got %v", m0.GetCounter().GetValue())
}
if m0.GetTimestampMs() != 1395066363000 {
t.Errorf("expected timestamp 1395066363000, got %v", m0.GetTimestampMs())
}
labels := m0.GetLabel()
if len(labels) != 2 {
t.Fatalf("expected 2 labels on metric 0, got %d", len(labels))
}
labelMap := make(map[string]string)
for _, l := range labels {
labelMap[l.GetName()] = l.GetValue()
}
if labelMap["method"] != "post" || labelMap["code"] != "200" {
t.Errorf("unexpected label map: %v", labelMap)
}
}
func TestTextToMetricFamiliesGauge(t *testing.T) {
input := `# HELP node_memory_bytes Node memory usage in bytes.
# TYPE node_memory_bytes gauge
node_memory_bytes{type="free"} 1048576.5
node_memory_bytes{type="used"} 2097152
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error parsing gauge metrics: %v", err)
}
mf, exists := metricFamilies["node_memory_bytes"]
if !exists {
t.Fatalf("expected metric family 'node_memory_bytes' not found")
}
if mf.GetType() != dto.MetricType_GAUGE {
t.Errorf("expected metric type GAUGE, got %v", mf.GetType())
}
metrics := mf.GetMetric()
if len(metrics) != 2 {
t.Fatalf("expected 2 metrics, got %d", len(metrics))
}
if metrics[0].GetGauge().GetValue() != 1048576.5 {
t.Errorf("expected gauge value 1048576.5, got %v", metrics[0].GetGauge().GetValue())
}
if metrics[1].GetGauge().GetValue() != 2097152 {
t.Errorf("expected gauge value 2097152, got %v", metrics[1].GetGauge().GetValue())
}
}
func TestTextToMetricFamiliesMultipleFamilies(t *testing.T) {
input := `# HELP rpc_duration_seconds A summary of the RPC duration in seconds.
# TYPE rpc_duration_seconds gauge
rpc_duration_seconds{service="auth"} 0.012
# HELP app_version_info Application version info.
# TYPE app_version_info counter
app_version_info{version="1.0.0"} 1
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(metricFamilies) != 2 {
t.Fatalf("expected 2 metric families, got %d", len(metricFamilies))
}
if _, ok := metricFamilies["rpc_duration_seconds"]; !ok {
t.Errorf("expected family 'rpc_duration_seconds' missing")
}
if _, ok := metricFamilies["app_version_info"]; !ok {
t.Errorf("expected family 'app_version_info' missing")
}
}
func TestTextToMetricFamiliesSyntaxError(t *testing.T) {
invalidInput := `http_requests_total{method="post",code=200} 1027
`
var parser expfmt.TextParser
_, err := parser.TextToMetricFamilies(strings.NewReader(invalidInput))
if err == nil {
t.Fatalf("expected parse error for unquoted label value, got nil")
}
}
{
"schemaVersion": 1,
"goal": "Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser",
"kind": "HOW",
"packages": [
"pkg:golang/github.com/prometheus/common@v0.48.0"
],
"symbols": [
"github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
Seeder d'origine
anonyme