From d031680ff2beff4e69661ebd682ae2c312b0c29e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Tue, 6 Oct 2026 14:53:20 -0400 Subject: [PATCH] fix(scripts/metricsdocgen/scanner): normalize package keys to slash paths (#30360) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the Windows failures in `TestBuildPrefixIndex` and `TestExcluded` (ENG-3443). The scanner keyed package directories with `filepath.Dir`, which uses `\` on Windows, but compared them against keys derived from Go import paths and against `excludeDirs`, which always use `/`. Prefixes never reached imported packages, and excluded subtrees weren't skipped. Each parsed file now records its directory once in slash form (`packageDir`), and the `prefixIndex` doc states the key rule. `excluded` normalizes its input because `scanDirectory` passes it native `filepath.WalkDir` paths. Generated output on Linux is unchanged. PR CI only runs `./cli/... ./enterprise/cli/... ./agent/...` on Windows, so I dispatched [`nightly-gauntlet` on this branch](https://github.com/coder/coder/actions/runs/37316261411). On `windows-2022`, both `scripts/metricsdocgen` and `scripts/metricsdocgen/scanner` pass. That run tested `c5462169cd`. The only later commit drops an unused field and rewords comments, so the result still applies.
Unrelated failures in the gauntlet run The Windows job still fails on `TestWorkspaceToolsGolden`, `TestEditMessageCancelsToolCallsOnAgent`, and `TestTools/WorkspaceExecute`. These fail the same way in [main's 2026-10-05 nightly](https://github.com/coder/coder/actions/runs/37262889155), together with the scanner failures this PR fixes. `TestAcquirer_MatchTags` also failed once, in provisioner code that this PR doesn't touch.
--- 🤖 Generated by Coder Agents on behalf of @nickvigilante. --- scripts/metricsdocgen/scanner/prefix.go | 24 +++++++++++++------ scripts/metricsdocgen/scanner/scanner.go | 8 ++++--- scripts/metricsdocgen/scanner/scanner_test.go | 24 ++++++++++++++++++- 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/scripts/metricsdocgen/scanner/prefix.go b/scripts/metricsdocgen/scanner/prefix.go index ecca008a201..4e6477b20c4 100644 --- a/scripts/metricsdocgen/scanner/prefix.go +++ b/scripts/metricsdocgen/scanner/prefix.go @@ -26,6 +26,11 @@ const modulePath = "github.com/coder/coder/v2/" // caller to wrap the registerer, so the declaration alone does not spell the // published metric name. Scanning those files without the prefix would emit // names that no deployment ever exposes, which is worse than omitting them. +// +// Keys are slash-separated on every OS because they are matched against +// directories derived from import paths. Build keys from file paths with +// packageDir. The constant map built by collectPrefixInputs follows the same +// rule. type prefixIndex map[string][]string // prefixFuncs are the registerer wrappers that prepend to every metric name @@ -81,13 +86,12 @@ func propagateThroughForwarders(index prefixIndex, files []parsedFile) { for round := range maxRounds { changed := false for _, pf := range files { - dir := filepath.Dir(pf.path) - prefixes, ok := index[dir] + prefixes, ok := index[pf.dir] if !ok { continue } for _, target := range forwardedPackages(pf) { - if target == dir { + if target == pf.dir { continue } for _, prefix := range prefixes { @@ -172,10 +176,16 @@ func isPrometheusRegisterer(expr ast.Expr) bool { return ok && pkg.Name == "prometheus" } +// packageDir returns the directory of a file path in the key form used by +// prefixIndex and the constant map. +func packageDir(path string) string { + return filepath.ToSlash(filepath.Dir(path)) +} + // parsedFile is a parsed Go file plus the import information needed to resolve // a selector back to a package directory. type parsedFile struct { - path string + dir string // packageDir of the file's path file *ast.File imports map[string]string // local name -> package directory } @@ -201,11 +211,11 @@ func collectPrefixInputs(roots []string) (map[string]string, []parsedFile, error return xerrors.Errorf("parsing %s: %w", path, err) } - dir := filepath.Dir(path) + dir := packageDir(path) for name, value := range stringConsts(file, func(string) bool { return true }, decodedStringLiteral) { consts[dir+"."+name] = value } - files = append(files, parsedFile{path: path, file: file, imports: fileImports(file)}) + files = append(files, parsedFile{dir: dir, file: file, imports: fileImports(file)}) return nil }) if err != nil { @@ -348,7 +358,7 @@ func constString(expr ast.Expr, pf parsedFile, consts map[string]string) (string return resolveStringReference( expr, func(name string) (string, bool) { - value, ok := consts[filepath.Dir(pf.path)+"."+name] + value, ok := consts[pf.dir+"."+name] return value, ok }, func(pkg, name string) (string, bool) { diff --git a/scripts/metricsdocgen/scanner/scanner.go b/scripts/metricsdocgen/scanner/scanner.go index eee84c57ff5..23614cea804 100644 --- a/scripts/metricsdocgen/scanner/scanner.go +++ b/scripts/metricsdocgen/scanner/scanner.go @@ -48,10 +48,12 @@ var excludeDirs = []string{ "enterprise/scaletest/agentfake", } -// excluded reports whether a path lies under an excluded subtree. +// excluded reports whether a path lies under an excluded subtree. The path may +// use either OS-native or slash separators. func excluded(path string) bool { + path = filepath.ToSlash(path) for _, dir := range excludeDirs { - if path == dir || strings.HasPrefix(path, dir+string(filepath.Separator)) { + if path == dir || strings.HasPrefix(path, dir+"/") { return true } } @@ -189,7 +191,7 @@ func scanDirectory(root string, prefixes prefixIndex, packageStrings map[string] return nil } - fileMetrics, err := scanFile(path, prefixes[filepath.Dir(path)], packageStrings) + fileMetrics, err := scanFile(path, prefixes[packageDir(path)], packageStrings) if err != nil { return xerrors.Errorf("scanning %s: %w", path, err) } diff --git a/scripts/metricsdocgen/scanner/scanner_test.go b/scripts/metricsdocgen/scanner/scanner_test.go index 81c90499375..1d76033b11f 100644 --- a/scripts/metricsdocgen/scanner/scanner_test.go +++ b/scripts/metricsdocgen/scanner/scanner_test.go @@ -63,6 +63,24 @@ const PrometheusMetricPrefix = "coder_ai_gateway_" writeGoFile(t, root, "server/costcontrol", "metrics.go", "package costcontrol\n") writeGoFile(t, root, "gateway/keypool", "collector.go", "package keypool\n") writeGoFile(t, root, "proxy", "metrics.go", "package proxy\n") + // A prefix resolved through a constant declared in the wrapping file's own + // package. + writeGoFile(t, root, "server/cmd", "run.go", `package cmd + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/coder/coder/v2/server/local" +) + +const localPrefix = "coder_local_" + +func run(registry *prometheus.Registry) { + reg := prometheus.WrapRegistererWithPrefix(localPrefix, registry) + local.NewMetrics(reg) +} +`) + writeGoFile(t, root, "server/local", "metrics.go", "package local\n") index, err := buildPrefixIndex([]string{"cli", "gateway", "server"}) if err != nil { @@ -81,6 +99,8 @@ const PrometheusMetricPrefix = "coder_ai_gateway_" {"gateway/keypool", []string{"coder_ai_gateway_"}}, // Alias registerer indexes only the canonical prefix. {"proxy", []string{"coder_ai_gateway_proxy_"}}, + // Prefix resolved through a same-package constant. + {"server/local", []string{"coder_local_"}}, } for _, tc := range cases { if got := index[tc.dir]; !slices.Equal(got, tc.want) { @@ -161,7 +181,7 @@ var requests = prometheus.NewCounter(prometheus.CounterOpts{ `) metrics, err := scanDirectory(filepath.Join(root, "metrics"), prefixIndex{ - filepath.Dir(path): {"coder_ai_gateway_"}, + packageDir(path): {"coder_ai_gateway_"}, }, make(map[string]map[string]string)) if err != nil { t.Fatalf("scanDirectory: %v", err) @@ -243,6 +263,8 @@ func TestExcluded(t *testing.T) { "enterprise/scaletest": false, "enterprise/scaletestextra/metrics.go": false, "coderd/prometheusmetrics/metrics.go": false, + // Paths from filepath.WalkDir use OS-native separators. + filepath.Join("aibridge", "keypool", "state_collector.go"): true, } for path, want := range cases { if got := excluded(path); got != want {