Files
coder/scripts/metricsdocgen/main.go
T
Nick Vigilante 72e31ffb4c fix: prevent Prometheus metrics reference drift (#29314)
## Summary

The Prometheus metrics reference merged scanner output with a
hand-maintained file, and changes to the hand-maintained half could not
fail CI. 66 of the 76 static families had no scanner coverage: four
files sat in a skip list pending `WrapRegistererWithPrefix` support, and
the `aibridge/` tree was outside the scan roots entirely. Rename or add
a metric in any of them and `make gen` regenerated the page unchanged,
so `check_unstaged.sh` passed while the published table quietly went
wrong.

The scanner now resolves the prefixes a registerer applies:

- Indexes `WrapRegistererWithPrefix` and `NewMetricAliasRegisterer` call
sites, resolving the prefix from a string literal or an imported
constant.
- Maps that prefix to the package whose constructor receives the wrapped
registerer, covering the two shapes the codebase uses: a constructor
that **forwards** its registerer to another package
(`aibridge.NewMetrics` to `aibridge/metrics.NewMetrics`), and a
collector **registered directly** against the wrapped registerer
(`gatewayRegisterer.MustRegister(keypool.NewStateCollector(...))`).
- Indexes only the canonical prefix of an alias registerer. The legacy
`coder_aibridged_` and `coder_aibridgeproxyd_` aliases are deprecated
per AIGOV-447 and should not be taught in the reference.

With prefixes resolved: skip list deleted, `aibridge` added to the scan
roots, and all 29 `coder_ai_gateway_*` families removed from the static
file, which now holds only genuine externals (`go_*`, `process_*`, and
metrics built dynamically). `enterprise/scaletest/agentfake` is excluded
deliberately: its fake-agent metrics are not part of a deployment's
surface, so documenting them would send operators looking for series
they will never see.

**Also fixes two extraction and merge gaps.** Label lists written as
`append(baseLabels, "status", "route")` now resolve, and any
unresolvable element returns no labels rather than a partial list.
Static runtime-label overrides now replace generated labels only:
generated name, type, and HELP remain authoritative.

## Verification

The prefix-scanning refactor itself preserves the existing AI Gateway
rows. However, the page is **not byte-identical** to `main` because this
round fixes two already-published stale HELP strings. Its SHA-256
changes from
`7ced1e7e9f2d4caf5e3b5e484ef4af14f955b8b4cd1a14fe81360bbdd49bb150` to
`a68774275a3b21d5bae65024cc8ee65b52c51e52786c9aea45e3981e4e7f1643`.

| Metric | Before | After |
| --- | --- | --- |
| `coderd_agentstats_connection_median_latency_seconds` | The median
agent connection latency | The median agent connection latency in
seconds |
| `coderd_agentstats_startup_script_seconds` | The number of seconds the
startup script took to execute. | Amount of time taken to run the
startup script in seconds. |

- `go test ./scripts/metricsdocgen/...` covers prefix resolution from a
literal and imported constant, alias-registerer argument selection,
collector registration, forwarder propagation, scan-to-emit prefix
application, all-or-nothing label extraction, static-label merging, and
the exclusion predicate.
- `golangci-lint run ./scripts/metricsdocgen/...` and full `make
pre-commit` pass.

## What this does not fix

Ten metrics are still skipped for having no `HELP` text, with a warning
to stderr rather than an error. Making that fatal means writing accurate
descriptions for ten metrics in the agent and SSH server packages, which
is a behavioral claim I would rather not guess at. Follow-up filed as
DOCS-906.

The scanner still uses package-level syntactic prefix inference. Broader
validation of prefix scan roots, mixed registration within a package,
and parameter-passed registerers belongs in DOCS-908 rather than this
focused drift fix.

<details>
<summary>Local pre-push note</summary>

The pre-push hook cannot run in this workspace: GNU Make 4.4.1 segfaults
on the repo's `.SHELLFLAGS = $@ -ceu` configuration for a target named
`test`, tracked in DOCS-903 with a minimal reproduction. I verified with
the package tests, `golangci-lint`, and full pre-commit, and disabled
the hook for this worktree only through its documented `git config
coder.pre-push` knob, restoring it right after the push. No
`--no-verify`.

</details>

---

Generated with Coder Agents on behalf of @nickvigilante. Linear:
[DOCS-897](https://linear.app/codercom/issue/DOCS-897/metricsdocgen-static-metrics-file-can-go-stale-without-failing-ci)
2026-10-01 16:06:32 -04:00

223 lines
6.3 KiB
Go

package main
import (
"bytes"
"errors"
"flag"
"io"
"log"
"os"
"sort"
"strings"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"golang.org/x/xerrors"
"google.golang.org/protobuf/proto"
"github.com/coder/coder/v2/coderd/util/maps"
"github.com/coder/coder/v2/scripts/atomicwrite"
)
var (
staticMetricsFile string
prometheusDocFile string
generatedMetricsFile string
dryRun bool
generatorPrefix = []byte("<!-- Code generated by 'make docs/admin/integrations/prometheus.md'. DO NOT EDIT -->")
generatorSuffix = []byte("<!-- End generated by 'make docs/admin/integrations/prometheus.md'. -->")
)
func main() {
flag.StringVar(&staticMetricsFile, "static-metrics", "scripts/metricsdocgen/metrics", "Path to static metrics file (manually maintained)")
flag.StringVar(&generatedMetricsFile, "generated-metrics", "scripts/metricsdocgen/generated_metrics", "Path to generated metrics file (from scanner)")
flag.StringVar(&prometheusDocFile, "prometheus-doc-file", "docs/admin/integrations/prometheus.md", "Path to Prometheus doc file")
flag.BoolVar(&dryRun, "dry-run", false, "Dry run")
flag.Parse()
metrics, err := readAndMergeMetrics(generatedMetricsFile, staticMetricsFile)
if err != nil {
log.Fatal("can't read metrics: ", err)
}
doc, err := readPrometheusDoc()
if err != nil {
log.Fatal("can't read Prometheus doc: ", err)
}
doc, err = updatePrometheusDoc(doc, metrics)
if err != nil {
log.Fatal("can't update Prometheus doc: ", err)
}
if dryRun {
log.Println(string(doc))
return
}
err = writePrometheusDoc(doc)
if err != nil {
log.Fatal("can't write updated Prometheus doc: ", err)
}
}
// readMetricsFromFile reads metrics from a single Prometheus text format file.
func readMetricsFromFile(path string) ([]*dto.MetricFamily, error) {
f, err := os.Open(path)
if err != nil {
return nil, xerrors.Errorf("can't open metrics file %s: %w", path, err)
}
defer f.Close()
var metrics []*dto.MetricFamily
decoder := expfmt.NewDecoder(f, expfmt.NewFormat(expfmt.TypeTextPlain))
for {
var m dto.MetricFamily
err = decoder.Decode(&m)
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, xerrors.Errorf("decoding metrics from %s: %w", path, err)
}
metrics = append(metrics, &m)
}
return metrics, nil
}
// readAndMergeMetrics returns generated metrics with any runtime-only static
// labels added. Generated metadata is authoritative when a metric appears in
// both inputs; static-only metrics, such as go_* and process_*, pass through.
// The scanner emits exactly one sample per metric family, so this merge updates
// the first sample's labels before the renderer unions labels across samples.
func readAndMergeMetrics(generatedPath, staticPath string) ([]*dto.MetricFamily, error) {
generatedMetrics, err := readMetricsFromFile(generatedPath)
if err != nil {
return nil, xerrors.Errorf("reading generated metrics: %w", err)
}
staticMetrics, err := readMetricsFromFile(staticPath)
if err != nil {
return nil, xerrors.Errorf("reading static metrics: %w", err)
}
// Merge metrics, using a map to deduplicate by name.
metricsByName := make(map[string]*dto.MetricFamily)
// Add generated metrics first.
for _, m := range generatedMetrics {
metricsByName[*m.Name] = m
}
// Static metrics override only their labels, which may depend on runtime
// configuration. Generated source metadata remains authoritative.
for _, m := range staticMetrics {
generated, ok := metricsByName[*m.Name]
if !ok {
metricsByName[*m.Name] = m
continue
}
if len(m.Metric) == 0 || len(generated.Metric) == 0 {
continue
}
merged := proto.CloneOf(generated)
merged.Metric[0].Label = mergeLabels(generated.Metric[0].Label, m.Metric[0].Label)
metricsByName[*m.Name] = merged
}
// Convert back to slice and sort.
var metrics []*dto.MetricFamily
for _, m := range metricsByName {
metrics = append(metrics, m)
}
sort.Slice(metrics, func(i, j int) bool {
return *metrics[i].Name < *metrics[j].Name
})
return metrics, nil
}
// mergeLabels returns labels from generated and static metadata, deduplicated
// by name. Source-declared labels remain documented when runtime metadata adds
// labels the scanner cannot observe.
func mergeLabels(generated, static []*dto.LabelPair) []*dto.LabelPair {
labels := make([]*dto.LabelPair, 0, len(generated)+len(static))
seen := make(map[string]struct{}, len(generated)+len(static))
for _, source := range [][]*dto.LabelPair{generated, static} {
for _, label := range source {
name := label.GetName()
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
labels = append(labels, label)
}
}
return labels
}
func readPrometheusDoc() ([]byte, error) {
doc, err := os.ReadFile(prometheusDocFile)
if err != nil {
return nil, err
}
return doc, nil
}
func updatePrometheusDoc(doc []byte, metricFamilies []*dto.MetricFamily) ([]byte, error) {
i := bytes.Index(doc, generatorPrefix)
if i < 0 {
return nil, xerrors.New("generator prefix tag not found")
}
tableStartIndex := i + len(generatorPrefix) + 1
j := bytes.Index(doc[tableStartIndex:], generatorSuffix)
if j < 0 {
return nil, xerrors.New("generator suffix tag not found")
}
tableEndIndex := tableStartIndex + j
var buffer bytes.Buffer
_, _ = buffer.Write(doc[:tableStartIndex])
_ = buffer.WriteByte('\n')
_, _ = buffer.WriteString("| Name | Type | Description | Labels |\n")
_, _ = buffer.WriteString("| - | - | - | - |\n")
for _, mf := range metricFamilies {
_, _ = buffer.WriteString("| ")
_, _ = buffer.Write([]byte("`" + *mf.Name + "`"))
_, _ = buffer.WriteString(" | ")
_, _ = buffer.Write([]byte(strings.ToLower(mf.Type.String())))
_, _ = buffer.WriteString(" | ")
if mf.Help != nil {
_, _ = buffer.Write([]byte(*mf.Help))
}
_, _ = buffer.WriteString(" | ")
labels := map[string]struct{}{}
metrics := mf.GetMetric()
for _, m := range metrics {
for _, label := range m.Label {
labels["`"+*label.Name+"`"] = struct{}{}
}
}
if len(labels) > 0 {
_, _ = buffer.WriteString(strings.Join(maps.SortedKeys(labels), " "))
}
_, _ = buffer.WriteString(" |\n")
}
_ = buffer.WriteByte('\n')
_, _ = buffer.Write(doc[tableEndIndex:])
return buffer.Bytes(), nil
}
func writePrometheusDoc(doc []byte) error {
return atomicwrite.File(prometheusDocFile, doc)
}