Files
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

65 lines
1.7 KiB
Go

package main
import (
"os"
"path/filepath"
"testing"
)
func TestReadAndMergeMetrics(t *testing.T) {
t.Parallel()
dir := t.TempDir()
generatedPath := filepath.Join(dir, "generated_metrics")
staticPath := filepath.Join(dir, "metrics")
if err := os.WriteFile(generatedPath, []byte(`# HELP requests_total Generated help.
# TYPE requests_total counter
requests_total{generated=""} 0
`), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(staticPath, []byte(`# HELP requests_total Static help.
# TYPE requests_total gauge
requests_total{generated="",runtime=""} 0
# HELP go_goroutines Goroutines that currently exist.
# TYPE go_goroutines gauge
go_goroutines 0
`), 0o600); err != nil {
t.Fatal(err)
}
metrics, err := readAndMergeMetrics(generatedPath, staticPath)
if err != nil {
t.Fatalf("readAndMergeMetrics: %v", err)
}
if len(metrics) != 2 {
t.Fatalf("got %d metrics, want 2", len(metrics))
}
metric := metrics[1]
if got, want := metric.GetHelp(), "Generated help."; got != want {
t.Errorf("HELP = %q, want %q", got, want)
}
if got, want := metric.GetType().String(), "COUNTER"; got != want {
t.Errorf("TYPE = %q, want %q", got, want)
}
labels := map[string]bool{}
for _, label := range metric.Metric[0].Label {
labels[label.GetName()] = true
}
for _, label := range []string{"generated", "runtime"} {
if !labels[label] {
t.Errorf("labels = %v, missing %q", labels, label)
}
}
staticOnly := metrics[0]
if got, want := staticOnly.GetName(), "go_goroutines"; got != want {
t.Errorf("static-only metric name = %q, want %q", got, want)
}
if got, want := staticOnly.GetHelp(), "Goroutines that currently exist."; got != want {
t.Errorf("static-only HELP = %q, want %q", got, want)
}
}