codehealth: Astra R1 fixes: moves, aliases, literals, both arches
Astra round 1 (READY AFTER FIXES, no P1) found four P2s; all fixed. Each new fixture failed on 27ff9263 and passes here. 1. Several MOVE pairs from one site could each spend its allowance (A allows 3; MOVE='A:B;A:C' with B 2, C 2 wrote 4). lower now totals every destination by source and checks them, with what the old site keeps, through conserved(), the one transfer rule checkAgainstBase also uses. Old sites are looked up in the record as it was. TestRecordMoveSeveralDestinations: a valid two-way split, and two over-allocations. 2. The classifier missed aliases inside types (*Row for type Row = sql.Row). typeString writes types by identity at every depth (aliases resolved, named types by path, byte/rune as uint8/int32, empty interface as any). Fixtures: store.aliasQueryer and, after a move, consoledb.rowQueryer through store.Row. 3. Function literals escaped func-lines. They are measured now: a literal assigned to a variable is named by it (run, F.helper), any other by its place in its function or var initializer (F.func1, table.func1). Fixtures in testdata/lines, comment exclusion included. 4. Architecture-specific Linux files were skipped. The scan now loads linux/amd64 and linux/arm64, each untagged and with the gate's tags, occurrences deduplicated by position; archNeutral is gone. Fixtures: main_amd64.go, main_arm64.go and a linux && arm64 && rootrunner file are all counted. The record, regenerated from today's tree by a throwaway generator test (deleted), gains two lines, both from fix 3, both function literals in internal/host tests over 300 code lines: func-lines internal/host TestPlan12RecoveryRestoreSourceDatabase.func1 329 func-lines internal/host plan14TimerIntention.func1 311 The tree has no architecture-specific files, so fix 4 adds none; the alias form does not occur, so fix 2 adds none. Timing at nice, GOMAXPROCS=4: 174 s cold (the arm64 half was uncached here), 35 s warm, up from 165 s and 18 s. It stays its own step, 60-code-health; README and the step header say so.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+399
−158
.amadan/README.md+7 −6.amadan/ci.d/60-code-health+7 −5.amadan/code-health.tsv+9 −5Makefile+2 −2internal/codehealth/codehealth_test.go+3 −3internal/codehealth/fixtures_test.go+35 −20internal/codehealth/ratchet_test.go+32 −0internal/codehealth/record_test.go+52 −22internal/codehealth/scan_test.go+166 −93internal/codehealth/testdata/fixture/consoledb/consoledb.go+8 −1internal/codehealth/testdata/fixture/internal/host/probe_arm64.go+8 −0internal/codehealth/testdata/fixture/main_amd64.go+6 −0internal/codehealth/testdata/fixture/main_arm64.go+2 −1internal/codehealth/testdata/fixture/store/store.go+10 −0internal/codehealth/testdata/lines/lines.go+52 −0
CI passed — run details
diff --git a/.amadan/README.md b/.amadan/README.md| index 7cc1b2a90..9f559c4de 100644 |
| --- a/.amadan/README.md |
| +++ b/.amadan/README.md |
| @@ -99,12 +99,13 @@ go down: |
| old site's allowance. So a raise is always a visible, reviewed edit. |
| The scan is its own step, not part of `make test`, because of its cost. |
| -It type-checks every package and its tests twice, with no tags and with |
| -the gate's tags. The untagged half reuses the compiles `make test` |
| -already does. The tagged half compiles every package and its test |
| -variant again: on a cold cache the scan took 165 s at `GOMAXPROCS=4`, |
| -against 20 s warm. `make test` still runs the package's fixture tests |
| -and checks the record's syntax. |
| +It type-checks every package and its tests four times: for linux/amd64 |
| +and linux/arm64, each with no tags and with the gate's tags. Only the |
| +untagged load for the runner's own architecture reuses the compiles |
| +`make test` already does. The other three compile every package and its |
| +test variant again: on a cold cache the scan took 174 s at |
| +`GOMAXPROCS=4`, against 35 s warm. `make test` still runs the package's |
| +fixture tests and checks the record's syntax. |
| The record step needs main's history, which the runner's shallow clone |
| lacks. It fetches main from `origin` (readable without credentials) and, |
diff --git a/.amadan/ci.d/60-code-health b/.amadan/ci.d/60-code-health| index 47d7036b3..f4e173ea6 100755 |
| --- a/.amadan/ci.d/60-code-health |
| +++ b/.amadan/ci.d/60-code-health |
| @@ -14,11 +14,13 @@ |
| # itself only went down. |
| # |
| # Its own step rather than part of 10-gate's `make test`: the scan |
| -# type-checks every package with its tests under no tags and under the |
| -# gate's tags. The untagged half reuses the gate's own compiles, but the |
| -# tagged half compiles every package and its test variant again, which on |
| -# a cold cache took 165 s on a 4-core budget (20 s warm). `make test` |
| -# still runs the package's fixture tests and checks the record's syntax. |
| +# type-checks every package with its tests for linux/amd64 and |
| +# linux/arm64, each under no tags and under the gate's tags. Only the |
| +# untagged load for the runner's own architecture reuses the gate's |
| +# compiles; the other three compile every package and its test variant |
| +# again, which on a cold cache took 174 s on a 4-core budget (35 s warm). |
| +# `make test` still runs the package's fixture tests and checks the |
| +# record's syntax. |
| set -eu |
| . .amadan/go-toolchain.sh |
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 455f4bec7..8141a502a 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -9,11 +9,13 @@ |
| # (blank and comment-only lines not counted). release-importers is one total. |
| # |
| # The scan covers this module and launchctx with type information, for |
| -# GOOS=linux, twice: with no tags and with the gate's (rootrunner and the |
| -# cutover witnesses'). A site seen in both counts once. Generated files, |
| -# testdata and files built only for other systems or architectures are not |
| -# scanned; make code-health lists them, with every count and the line |
| -# metrics' physical lengths. |
| +# linux/amd64 and linux/arm64, each with no tags and with the gate's |
| +# (rootrunner and the cutover witnesses'). A site seen in several counts |
| +# once. Functions include function literals: a literal assigned to a |
| +# variable is named by it ("run", "F.helper"), any other by its place |
| +# ("F.func1"). Generated files, testdata and files built only for other |
| +# systems are not scanned; make code-health lists them, with every count and |
| +# the line metrics' physical lengths. |
| # |
| # - The gate (make code-health, CI's 60-code-health step) fails when the |
| # code has more at a site than its line allows, or an offence at a site |
| @@ -2222,6 +2224,7 @@ func-lines internal/edge TestTunnelWebSocketEndToEnd - 327 |
| func-lines internal/host (*ClaimWakeAssembly).Build - 421 |
| func-lines internal/host TestPagingIsRateLimited - 509 |
| func-lines internal/host TestPlan12RecoveryRestoreSourceDatabase - 334 |
| +func-lines internal/host TestPlan12RecoveryRestoreSourceDatabase.func1 - 329 |
| func-lines internal/host TestRootEgressKernelProof - 371 |
| func-lines internal/host TestRootG2PoolIngress - 302 |
| func-lines internal/host TestRootInstanceStopExecStop - 441 |
| @@ -2231,6 +2234,7 @@ func-lines internal/host newColdRootHarness - 340 |
| func-lines internal/host plan14InstalledClaimLaunch - 870 |
| func-lines internal/host plan14RequiredArtifactsRootRunner - 374 |
| func-lines internal/host plan14TimerIntention - 315 |
| +func-lines internal/host plan14TimerIntention.func1 - 311 |
| func-lines internal/host rootFilesSeedIsolatedWitness - 308 |
| func-lines internal/host runAgent - 685 |
| func-lines internal/host runFilesSeedPreparationWithLive - 390 |
diff --git a/Makefile b/Makefile| index 33a69c13e..5eda80ea5 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -137,8 +137,8 @@ census-propose: |
| # scans the tree and fails where the code is above .amadan/code-health.tsv, |
| # naming the site. It prints every count, the sites below the record, the |
| # line metrics' physical lengths and the files it did not scan. Not part |
| -# of `make test`: on a cold build cache the scan's tagged half compiles |
| -# every package again under the gate's tags. The test skips without |
| +# of `make test`: on a cold build cache the scan's other architecture and |
| +# tag set compile every package again. The test skips without |
| # CODEHEALTH_GATE, and a skipped test exits 0, so its PASS line must show. |
| code-health: |
| @out=$$(mktemp "$${TMPDIR:-/tmp}/code-health.XXXXXX") || exit 1; \ |
diff --git a/internal/codehealth/codehealth_test.go b/internal/codehealth/codehealth_test.go| index a0c7a0216..1a962acee 100644 |
| --- a/internal/codehealth/codehealth_test.go |
| +++ b/internal/codehealth/codehealth_test.go |
| @@ -59,7 +59,7 @@ func report(w io.Writer, res *scanResult, listSkipped bool) { |
| } |
| fmt.Fprintf(w, "release-importers: %s\n", strings.Join(res.importers, " ")) |
| if !listSkipped { |
| - fmt.Fprintf(w, "not scanned: %d files built only for other systems, architectures or tags, or generated\n"+ |
| + fmt.Fprintf(w, "not scanned: %d files built only for other systems or tags, or generated\n"+ |
| "(make code-health lists them)\n", len(res.skipped)) |
| return |
| } |
| @@ -94,8 +94,8 @@ func TestRecordFile(t *testing.T) { |
| // both. |
| // |
| // It runs only under make code-health (CI's 60-code-health step), not in |
| -// make test: on a cold build cache the scan's second tag set costs a |
| -// compile of every package, which is more than the gate should carry. |
| +// make test: on a cold build cache the scan's other architecture and tag |
| +// set cost compiles of every package, more than the gate should carry. |
| func TestCodeHealth(t *testing.T) { |
| if os.Getenv("CODEHEALTH_GATE") != "1" { |
| t.Skip("run by make code-health (CI's 60-code-health)") |
diff --git a/internal/codehealth/fixtures_test.go b/internal/codehealth/fixtures_test.go| index 952d07b3b..c20a94ccd 100644 |
| --- a/internal/codehealth/fixtures_test.go |
| +++ b/internal/codehealth/fixtures_test.go |
| @@ -58,6 +58,10 @@ func TestScanFixture(t *testing.T) { |
| k("fatal", ".", "main", "(*log.Logger).Fatalln"): 1, |
| k("fatal", ".", "main", "os.Exit"): 1, |
| k("fatal", ".", "run", "log.Fatal"): 2, |
| + // Files built only for one Linux architecture count on any machine: |
| + // both linux/amd64 and linux/arm64 are scanned (R1 P2 4). |
| + k("fatal", ".", "amd64Only", "log.Fatal"): 1, |
| + k("fatal", ".", "arm64Only", "log.Fatal"): 1, |
| // Test files only, an alias included, an external test package |
| // under its own name; production sleeps and a local sleep do not. |
| @@ -72,6 +76,8 @@ func TestScanFixture(t *testing.T) { |
| k("host-context", "internal/host", "queue", "context.Background"): 1, |
| k("host-context", "internal/host", "queue", "context.TODO"): 1, |
| k("host-context", "internal/host/sub", "Run", "context.Background"): 1, |
| + // linux && arm64 && rootrunner: only one of the four configurations. |
| + k("host-context", "internal/host", "armProbe", "context.TODO"): 1, |
| // The database classifier: database/sql's DB, Tx and Stmt, a |
| // promoted *sql.DB method, console's sqlQueryer.QueryRow and |
| @@ -89,10 +95,15 @@ func TestScanFixture(t *testing.T) { |
| k("db-no-context", "store", "Calls", "store.Queryer.QueryRow"): 1, |
| k("db-no-context", "store", "Calls", "store.handle.Begin"): 1, |
| k("db-no-context", "store", "Calls", "store.oldStyle.Exec"): 1, |
| - // The same calls after a move to another package still count. |
| + // An alias behind a pointer (*Row for *sql.Row) is the same |
| + // signature (R1 P2 2). |
| + k("db-no-context", "store", "Aliased", "store.aliasQueryer.QueryRow"): 1, |
| + // The same calls after a move to another package still count, the |
| + // alias from the old package included. |
| k("db-no-context", "consoledb", "Get", "(*sql.DB).QueryRow"): 1, |
| k("db-no-context", "consoledb", "Get", "consoledb.sqlQueryer.QueryRow"): 1, |
| k("db-no-context", "consoledb", "Get", "store.Queryer.QueryRow"): 1, |
| + k("db-no-context", "consoledb", "Get", "consoledb.rowQueryer.QueryRow"): 1, |
| // imp/a, imp/b (aliased, two files) and release's own subpackage; |
| // not imp/c, which imports it only in a test. |
| @@ -102,22 +113,15 @@ func TestScanFixture(t *testing.T) { |
| if got := strings.Join(res.importers, " "); got != "imp/a imp/b internal/release/sub" { |
| t.Errorf("importers %q", got) |
| } |
| - for file, why := range map[string]string{ |
| + // Exactly these are not scanned; every file some configuration builds |
| + // (queue_default.go, queue_rootrunner.go, main_amd64.go, main_arm64.go, |
| + // probe_arm64.go) is. |
| + want2 := map[string]string{ |
| "gen.go": "generated", |
| "main_darwin.go": "built only for other systems or tags", |
| - // On amd64 the go command leaves it out; on arm64 the scanner |
| - // does. Either way it is not counted, and it is listed. |
| - "main_arm64.go": "", |
| - } { |
| - got, ok := res.skipped[file] |
| - if !ok || (why != "" && got != why) { |
| - t.Errorf("skipped[%s] = %q, want %q", file, got, why) |
| - } |
| } |
| - for file := range res.skipped { |
| - if strings.Contains(file, "queue_") { |
| - t.Errorf("%s is listed as not scanned, but one configuration reads it", file) |
| - } |
| + if fmt.Sprint(res.skipped) != fmt.Sprint(want2) { |
| + t.Errorf("not scanned: %v, want %v", res.skipped, want2) |
| } |
| } |
| @@ -131,16 +135,27 @@ func TestScanLines(t *testing.T) { |
| {"func-lines", ".", "(*T).Long", "-"}: 6, |
| {"func-lines", ".", "G.Long", "-"}: 6, |
| {"func-lines", ".", "TestLong", "-"}: 6, |
| - // lines.go has 33 code lines; lines_test.go is short. |
| - {"file-lines", ".", "lines.go", "-"}: 33, |
| + // Function literals are measured too (R1 P2 3): a package-level |
| + // function value by its variable, one inside a package-level |
| + // initializer and an unnamed callback by their ordinal, an assigned |
| + // one by its variable. short, 5 code lines among comments, is not. |
| + {"func-lines", ".", "run", "-"}: 6, |
| + {"func-lines", ".", "callbacks", "-"}: 15, |
| + {"func-lines", ".", "callbacks.func1", "-"}: 6, |
| + {"func-lines", ".", "callbacks.helper", "-"}: 6, |
| + {"func-lines", ".", "table.func1", "-"}: 6, |
| + // lines.go has 68 code lines; lines_test.go is short. |
| + {"file-lines", ".", "lines.go", "-"}: 68, |
| } |
| sameCounts(t, res.counts, want) |
| // Physical length is reported beside code lines, never compared. |
| - if p := res.physical[siteKey{"func-lines", ".", "long", "-"}]; p != 7 { |
| - t.Errorf("long's physical length %d, want 7", p) |
| + for name, p := range map[string]int{"long": 7, "run": 8} { |
| + if got := res.physical[siteKey{"func-lines", ".", name, "-"}]; got != p { |
| + t.Errorf("%s's physical length %d, want %d", name, got, p) |
| + } |
| } |
| - if p := res.physical[siteKey{"file-lines", ".", "lines.go", "-"}]; p <= 33 { |
| - t.Errorf("lines.go's physical length %d, want more than its 33 code lines", p) |
| + if p := res.physical[siteKey{"file-lines", ".", "lines.go", "-"}]; p <= 68 { |
| + t.Errorf("lines.go's physical length %d, want more than its 68 code lines", p) |
| } |
| } |
diff --git a/internal/codehealth/ratchet_test.go b/internal/codehealth/ratchet_test.go| index 392501d57..5f42b7184 100644 |
| --- a/internal/codehealth/ratchet_test.go |
| +++ b/internal/codehealth/ratchet_test.go |
| @@ -143,6 +143,38 @@ func TestRecordMove(t *testing.T) { |
| } |
| } |
| +// Several MOVE pairs from one site share its allowance: together they and |
| +// what the old site keeps can never exceed it (R1 P2 1). |
| +func TestRecordMoveSeveralDestinations(t *testing.T) { |
| + r := rec(at(dbOld, 3), at(release, 65)) |
| + moves, err := parseMoves(dbOld.String() + ":" + dbNew.String() + "; " + dbOld.String() + ":" + dbOther.String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // A valid split across two destinations: 2 + 1 of 3. |
| + out, err := lower(r, map[siteKey]int{dbNew: 2, dbOther: 1, release: 65}, moves) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + from := "# moved-from: " + dbOld.String() |
| + if _, ok := out[dbOld]; ok || out[dbNew] != at(dbNew, 2, from) || out[dbOther] != at(dbOther, 1, from) { |
| + t.Fatalf("split to %v", out) |
| + } |
| + if problems, _ := checkAgainstBase(r, out); len(problems) > 0 { |
| + t.Fatalf("CI refuses what the command wrote: %v", problems) |
| + } |
| + // Over-allocated: each pair alone fits in 3, together they take 4. And |
| + // with the old site keeping one, 2 + 1 + 1. |
| + for name, counts := range map[string]map[siteKey]int{ |
| + "two destinations take 4": {dbNew: 2, dbOther: 2, release: 65}, |
| + "two destinations and a kept": {dbOld: 1, dbNew: 2, dbOther: 1, release: 65}, |
| + } { |
| + if out, err := lower(r, counts, moves); err == nil { |
| + t.Errorf("%s: wrote %v", name, out) |
| + } |
| + } |
| +} |
| + |
| // The CI step: added or raised lines need a new raised comment or a valid |
| // transfer; lowered and dropped lines need nothing. |
| func TestRecordAgainstBaseRules(t *testing.T) { |
diff --git a/internal/codehealth/record_test.go b/internal/codehealth/record_test.go| index ae103be20..971047a46 100644 |
| --- a/internal/codehealth/record_test.go |
| +++ b/internal/codehealth/record_test.go |
| @@ -24,11 +24,13 @@ const recordHeader = `# The code-health ratchet's record (internal/codehealth; t |
| # (blank and comment-only lines not counted). release-importers is one total. |
| # |
| # The scan covers this module and launchctx with type information, for |
| -# GOOS=linux, twice: with no tags and with the gate's (rootrunner and the |
| -# cutover witnesses'). A site seen in both counts once. Generated files, |
| -# testdata and files built only for other systems or architectures are not |
| -# scanned; make code-health lists them, with every count and the line |
| -# metrics' physical lengths. |
| +# linux/amd64 and linux/arm64, each with no tags and with the gate's |
| +# (rootrunner and the cutover witnesses'). A site seen in several counts |
| +# once. Functions include function literals: a literal assigned to a |
| +# variable is named by it ("run", "F.helper"), any other by its place |
| +# ("F.func1"). Generated files, testdata and files built only for other |
| +# systems are not scanned; make code-health lists them, with every count and |
| +# the line metrics' physical lengths. |
| # |
| # - The gate (make code-health, CI's 60-code-health step) fails when the |
| # code has more at a site than its line allows, or an offence at a site |
| @@ -212,10 +214,14 @@ func lower(rec record, counts map[siteKey]int, moves []move) (record, error) { |
| for k, l := range rec { |
| out[k] = l |
| } |
| + // transfers holds each old site's moved lines. Old sites are looked up |
| + // in the record as it was, so a move cannot start from a line another |
| + // pair just wrote. |
| + transfers := map[siteKey][]recordLine{} |
| for _, mv := range moves { |
| var old recordLine |
| found := false |
| - for k, l := range out { |
| + for k, l := range rec { |
| if k.String() == strings.Join(strings.Fields(mv.old), " ") { |
| old, found = l, true |
| break |
| @@ -234,15 +240,18 @@ func lower(rec record, counts map[siteKey]int, moves []move) (record, error) { |
| if _, exists := out[newKey]; exists { |
| return nil, fmt.Errorf("MOVE: %s already has a line; a move goes to a site with none", newKey) |
| } |
| - moved, left := counts[newKey], counts[old.key] |
| + moved := counts[newKey] |
| if moved == 0 { |
| return nil, fmt.Errorf("MOVE: the code has no %s offence at %s", old.key.metric, newKey) |
| } |
| - if moved+left > old.count { |
| - return nil, fmt.Errorf("MOVE: %s would hold %d and %s keeps %d, more than the %d %s allows; a move never raises", |
| - newKey, moved, old.key, left, old.count, old.key) |
| - } |
| out[newKey] = recordLine{key: newKey, count: moved, comment: "# moved-from: " + old.key.String()} |
| + transfers[old.key] = append(transfers[old.key], out[newKey]) |
| + } |
| + // Every pair from one site together, with what the old site keeps. |
| + for _, old := range sortedSites(transfers) { |
| + if err := conserved(old, rec[old].count, counts[old], transfers[old]); err != nil { |
| + return nil, fmt.Errorf("MOVE: %v", err) |
| + } |
| } |
| for k, l := range out { |
| if n := counts[k]; n < l.count { |
| @@ -313,7 +322,7 @@ func checkAgainstBase(base, head record) (problems, notes []string) { |
| problems = append(problems, what+": needs \"# raised: <reason>\" or a moved-from transfer") |
| } |
| } |
| - for _, old := range slices.SortedFunc(maps.Keys(transfers), func(a, b siteKey) int { return cmp.Compare(a.String(), b.String()) }) { |
| + for _, old := range sortedSites(transfers) { |
| lines := transfers[old] |
| b, ok := base[old] |
| if !ok { |
| @@ -322,18 +331,39 @@ func checkAgainstBase(base, head record) (problems, notes []string) { |
| } |
| continue |
| } |
| - total := head[old].count |
| - var names []string |
| - for _, l := range lines { |
| - total += l.count |
| - names = append(names, fmt.Sprintf("%s (%d)", l.key, l.count)) |
| - } |
| - if total > b.count { |
| - problems = append(problems, fmt.Sprintf("%s %s: allowed %d at the merge base, but it keeps %d and %s took %d between them; a move never raises", |
| - old.metric, old, b.count, head[old].count, strings.Join(names, ", "), total-head[old].count)) |
| + if err := conserved(old, b.count, head[old].count, lines); err != nil { |
| + problems = append(problems, err.Error()+" (the merge base's allowance)") |
| continue |
| } |
| - notes = append(notes, fmt.Sprintf("%s %s moved to %s (allowed %d at the merge base)", old.metric, old, strings.Join(names, ", "), b.count)) |
| + notes = append(notes, fmt.Sprintf("%s %s moved to %s (allowed %d at the merge base)", old.metric, old, lineNames(lines), b.count)) |
| } |
| return problems, notes |
| } |
| + |
| +// conserved is the transfer rule, the one place it lives, for both |
| +// make code-health-record and the CI step: what the old site keeps plus |
| +// every line moved from it may not exceed what it was allowed. Pairs are |
| +// judged together, so two moves cannot each spend the same allowance. |
| +func conserved(old siteKey, allowed, kept int, moved []recordLine) error { |
| + total := kept |
| + for _, l := range moved { |
| + total += l.count |
| + } |
| + if total > allowed { |
| + return fmt.Errorf("%s %s: allowed %d, but it keeps %d and %s took %d between them; a move never raises", |
| + old.metric, old, allowed, kept, lineNames(moved), total-kept) |
| + } |
| + return nil |
| +} |
| + |
| +func lineNames(lines []recordLine) string { |
| + var names []string |
| + for _, l := range lines { |
| + names = append(names, fmt.Sprintf("%s (%d)", l.key, l.count)) |
| + } |
| + return strings.Join(names, ", ") |
| +} |
| + |
| +func sortedSites(m map[siteKey][]recordLine) []siteKey { |
| + return slices.SortedFunc(maps.Keys(m), func(a, b siteKey) int { return cmp.Compare(a.String(), b.String()) }) |
| +} |
diff --git a/internal/codehealth/scan_test.go b/internal/codehealth/scan_test.go| index 8ffec1f75..1cac00539 100644 |
| --- a/internal/codehealth/scan_test.go |
| +++ b/internal/codehealth/scan_test.go |
| @@ -12,10 +12,8 @@ |
| package codehealth |
| import ( |
| - "bytes" |
| "fmt" |
| "go/ast" |
| - "go/build/constraint" |
| "go/scanner" |
| "go/token" |
| "go/types" |
| @@ -76,12 +74,19 @@ type limits struct{ fn, file int } |
| var treeLimits = limits{fn: 300, file: 3000} |
| -// The two build configurations, both GOOS=linux: what production builds |
| -// (no tags) and the gate's tags, so a `!rootrunner` production file and |
| -// the rootrunner tests are both seen. A site seen in both is counted once. |
| +// The configurations: GOOS=linux on both architectures the fleet runs, |
| +// each with no tags (what production builds) and with the gate's tags, so a |
| +// `!rootrunner` production file, the rootrunner tests and a file built for |
| +// one architecture are all seen. A site seen in several is counted once. |
| // The second tag is spelled in two halves: TestCutoverWitnessControlsAreTagged |
| // allows its full name only in the files that build with it. |
| -var tagSets = [][]string{nil, {"rootrunner", "carlos_cutover" + "_witness"}} |
| +var ( |
| + goarches = []string{"amd64", "arm64"} |
| + tagSets = [][]string{nil, {"rootrunner", "carlos_cutover" + "_witness"}} |
| +) |
| + |
| +// loadsAtOnce bounds how many loads hold their packages in memory at once. |
| +const loadsAtOnce = 4 |
| // A tree is what one scan covers: modules (directories holding a go.mod, |
| // relative to root) and the limits for the line metrics. |
| @@ -98,75 +103,78 @@ type scanResult struct { |
| // a report and never compared. |
| physical map[siteKey]int |
| // skipped names each file the scan did not read and why: built only for |
| - // other systems, architectures or tags, or generated. |
| + // other systems or tags, or generated. |
| skipped map[string]string |
| // importers lists the packages counted by release-importers. |
| importers []string |
| } |
| -// scanTree loads every module under both configurations and counts. |
| +// scanTree loads every module under every configuration and counts. |
| func scanTree(tr tree) (*scanResult, error) { |
| - type job struct { |
| - module string |
| - tags []string |
| - pkgs []*packages.Package |
| - err error |
| - } |
| - var jobs []*job |
| - for _, mod := range tr.modules { |
| - for _, tags := range tagSets { |
| - jobs = append(jobs, &job{module: mod, tags: tags}) |
| - } |
| - } |
| sqlSigs, err := loadSQLSignatures(tr.root) |
| if err != nil { |
| return nil, err |
| } |
| - var wg sync.WaitGroup |
| - for _, j := range jobs { |
| - wg.Go(func() { j.pkgs, j.err = load(filepath.Join(tr.root, j.module), j.tags) }) |
| - } |
| - wg.Wait() |
| - |
| s := &scanState{ |
| tree: tr, |
| sqlSigs: sqlSigs, |
| result: &scanResult{counts: map[siteKey]int{}, physical: map[siteKey]int{}, skipped: map[string]string{}}, |
| seen: map[string]bool{}, |
| - lengths: map[string]int{}, |
| importers: map[string]bool{}, |
| scanned: map[string]bool{}, |
| ignored: map[string]bool{}, |
| } |
| - for _, j := range jobs { |
| - if j.err != nil { |
| - return nil, fmt.Errorf("loading %s with tags %v: %w", j.module, j.tags, j.err) |
| - } |
| - modPath := "" |
| - for _, p := range j.pkgs { |
| - if p.Module != nil && p.Module.Main { |
| - modPath = p.Module.Path |
| - break |
| + // Loads run side by side, loadsAtOnce at a time; each is counted as it |
| + // finishes, under mu, and then let go. |
| + var ( |
| + wg sync.WaitGroup |
| + mu sync.Mutex |
| + errs []error |
| + sem = make(chan struct{}, loadsAtOnce) |
| + ) |
| + for _, mod := range tr.modules { |
| + for _, arch := range goarches { |
| + for _, tags := range tagSets { |
| + wg.Go(func() { |
| + sem <- struct{}{} |
| + defer func() { <-sem }() |
| + pkgs, err := load(filepath.Join(tr.root, mod), arch, tags) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("loading %s for linux/%s with tags %v: %w", mod, arch, tags, err)) |
| + return |
| + } |
| + modPath := "" |
| + for _, p := range pkgs { |
| + if p.Module != nil && p.Module.Main { |
| + modPath = p.Module.Path |
| + break |
| + } |
| + } |
| + for _, p := range pkgs { |
| + s.pkg(p, modPath) |
| + } |
| + }) |
| } |
| } |
| - for _, p := range j.pkgs { |
| - s.pkg(p, modPath, j.tags) |
| - } |
| + } |
| + wg.Wait() |
| + if len(errs) > 0 { |
| + return nil, errs[0] |
| } |
| s.finish() |
| return s.result, nil |
| } |
| -// load is one go/packages load: tests included, with types, for linux. |
| -// GOARCH is left as it is; files whose inclusion depends on it are skipped |
| -// (archNeutral), so amd64 and arm64 machines count the same. |
| -func load(dir string, tags []string) ([]*packages.Package, error) { |
| +// load is one go/packages load: tests included, with types, for linux/arch. |
| +func load(dir, arch string, tags []string) ([]*packages.Package, error) { |
| cfg := &packages.Config{ |
| Mode: packages.NeedName | packages.NeedFiles | packages.NeedSyntax | packages.NeedTypes | |
| packages.NeedTypesInfo | packages.NeedImports | packages.NeedModule, |
| Dir: dir, |
| Tests: true, |
| - Env: append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0", "GOWORK=off"), |
| + Env: append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0", "GOWORK=off"), |
| } |
| if len(tags) > 0 { |
| cfg.BuildFlags = []string{"-tags=" + strings.Join(tags, ",")} |
| @@ -250,7 +258,7 @@ func dbOpWithoutContext(fn *types.Func, sqlSigs map[string][]string) bool { |
| // signatureString writes a signature's parameter and result types, with |
| // full package paths and without names or receiver, so two signatures |
| -// compare equal as text. `interface{}` is written as `any`. |
| +// compare equal as text. Type spelling does not matter (typeString). |
| func signatureString(sig *types.Signature) string { |
| var b strings.Builder |
| tuple := func(t *types.Tuple, variadic bool) { |
| @@ -263,7 +271,7 @@ func signatureString(sig *types.Signature) string { |
| b.WriteString("...") |
| typ = typ.(*types.Slice).Elem() |
| } |
| - b.WriteString(strings.ReplaceAll(types.TypeString(types.Unalias(typ), nil), "interface{}", "any")) |
| + b.WriteString(typeString(typ)) |
| } |
| } |
| b.WriteString("(") |
| @@ -274,17 +282,60 @@ func signatureString(sig *types.Signature) string { |
| return b.String() |
| } |
| +// typeString writes a type by identity, not spelling: aliases are resolved |
| +// at every depth (*Row for `type Row = sql.Row` is *database/sql.Row), a |
| +// named type is its package path and name, byte and rune are uint8 and |
| +// int32, and the empty interface is any. |
| +func typeString(t types.Type) string { |
| + switch t := t.(type) { |
| + case *types.Alias: |
| + return typeString(types.Unalias(t)) |
| + case *types.Basic: |
| + return types.Typ[t.Kind()].Name() |
| + case *types.Pointer: |
| + return "*" + typeString(t.Elem()) |
| + case *types.Slice: |
| + return "[]" + typeString(t.Elem()) |
| + case *types.Array: |
| + return fmt.Sprintf("[%d]%s", t.Len(), typeString(t.Elem())) |
| + case *types.Map: |
| + return "map[" + typeString(t.Key()) + "]" + typeString(t.Elem()) |
| + case *types.Chan: |
| + return [...]string{"chan ", "chan<- ", "<-chan "}[t.Dir()] + typeString(t.Elem()) |
| + case *types.Signature: |
| + return "func" + signatureString(t) |
| + case *types.Named: |
| + s := t.Obj().Name() |
| + if pkg := t.Obj().Pkg(); pkg != nil { |
| + s = pkg.Path() + "." + s |
| + } |
| + if args := t.TypeArgs(); args.Len() > 0 { |
| + var parts []string |
| + for i := range args.Len() { |
| + parts = append(parts, typeString(args.At(i))) |
| + } |
| + s += "[" + strings.Join(parts, ", ") + "]" |
| + } |
| + return s |
| + case *types.Interface: |
| + if t.Empty() { |
| + return "any" |
| + } |
| + } |
| + // Structs, non-empty interfaces and type parameters: no database/sql |
| + // signature holds one. |
| + return types.TypeString(t, nil) |
| +} |
| + |
| // scanState is one scan in progress. |
| type scanState struct { |
| tree tree |
| sqlSigs map[string][]string |
| result *scanResult |
| // seen holds each occurrence already counted (metric, file, offset), so |
| - // a file read in both configurations, or in a package and its test |
| + // a file read in several configurations, or in a package and its test |
| // variant, counts once. |
| - seen map[string]bool |
| - // lengths holds each line-metric occurrence's length by the same key. |
| - lengths map[string]int |
| + seen map[string]bool |
| importers map[string]bool |
| scanned map[string]bool // files read |
| ignored map[string]bool // files a load left out |
| @@ -311,7 +362,7 @@ func (s *scanState) add(m string, file string, offset int, key siteKey, n, physi |
| } |
| // pkg scans one loaded package. |
| -func (s *scanState) pkg(p *packages.Package, modPath string, tags []string) { |
| +func (s *scanState) pkg(p *packages.Package, modPath string) { |
| for _, f := range p.IgnoredFiles { |
| s.ignored[f] = true |
| } |
| @@ -345,10 +396,6 @@ func (s *scanState) pkg(p *packages.Package, modPath string, tags []string) { |
| s.result.skipped[rel] = "generated" |
| continue |
| } |
| - if !archNeutral(file, src, tags) { |
| - s.result.skipped[rel] = "built only for some architectures" |
| - continue |
| - } |
| s.scanned[file] = true |
| s.file(p, f, file, rel, src, dir, name, modPath) |
| } |
| @@ -382,13 +429,29 @@ func (s *scanState) file(p *packages.Package, f *ast.File, file, rel string, src |
| } |
| } |
| + // measure records a function, declared or literal, over the limit. |
| + measure := func(node ast.Node, name string) { |
| + from, to := fset.Position(node.Pos()).Line, fset.Position(node.End()).Line |
| + if n := count(from, to); n > s.tree.limits.fn { |
| + s.add("func-lines", file, tf.Offset(node.Pos()), siteKey{"func-lines", pkgName, name, "-"}, n, to-from+1) |
| + } |
| + } |
| for _, decl := range f.Decls { |
| fn := "package-level" |
| - if fd, ok := decl.(*ast.FuncDecl); ok { |
| - fn = funcName(fd) |
| - from, to := fset.Position(fd.Pos()).Line, fset.Position(fd.End()).Line |
| - if n := count(from, to); n > s.tree.limits.fn { |
| - s.add("func-lines", file, tf.Offset(fd.Pos()), siteKey{"func-lines", pkgName, fn, "-"}, n, to-from+1) |
| + switch d := decl.(type) { |
| + case *ast.FuncDecl: |
| + fn = funcName(d) |
| + measure(d, fn) |
| + for lit, name := range funcLitNames(d, fn) { |
| + measure(lit, name) |
| + } |
| + case *ast.GenDecl: |
| + for _, spec := range d.Specs { |
| + if vs, ok := spec.(*ast.ValueSpec); ok && len(vs.Names) > 0 { |
| + for lit, name := range funcLitNames(vs, vs.Names[0].Name) { |
| + measure(lit, name) |
| + } |
| + } |
| } |
| } |
| ast.Inspect(decl, func(n ast.Node) bool { |
| @@ -529,40 +592,50 @@ func codeLines(src []byte) map[int]bool { |
| return lines |
| } |
| -// arches are the GOARCH values a file name can end in. |
| -var arches = []string{"386", "amd64", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", |
| - "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "wasm"} |
| - |
| -// archNeutral reports whether file is built the same on amd64 and arm64 |
| -// under linux and tags. The scan leaves GOARCH as the machine has it, so a |
| -// file that depends on it would count differently on a laptop and in CI; |
| -// such files are skipped and listed instead. There are none today. |
| -func archNeutral(file string, src []byte, tags []string) bool { |
| - base := strings.TrimSuffix(strings.TrimSuffix(filepath.Base(file), ".go"), "_test") |
| - for _, a := range arches { |
| - if strings.HasSuffix(base, "_"+a) { |
| - return false |
| - } |
| - } |
| - var expr constraint.Expr |
| - for line := range bytes.Lines(src) { |
| - text := strings.TrimSpace(string(line)) |
| - if strings.HasPrefix(text, "package ") { |
| - break |
| - } |
| - if constraint.IsGoBuild(text) { |
| - expr, _ = constraint.Parse(text) |
| - break |
| +// funcLitNames names the function literals in root (a function declaration |
| +// or a package-level var spec, whose name is base) for func-lines. A |
| +// literal assigned to a variable is named by it: "run" for a package-level |
| +// `var run = func() {...}`, "F.helper" for `helper := func() {...}` in F. |
| +// Any other literal is base and its place among them: "F.func1", or |
| +// "table.func1" for a callback in a var's initializer. |
| +func funcLitNames(root ast.Node, base string) map[*ast.FuncLit]string { |
| + assigned := map[*ast.FuncLit]string{} |
| + ast.Inspect(root, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.AssignStmt: |
| + if len(n.Lhs) == len(n.Rhs) { |
| + for i, r := range n.Rhs { |
| + lit, ok := r.(*ast.FuncLit) |
| + if id, isID := n.Lhs[i].(*ast.Ident); ok && isID && id.Name != "_" { |
| + assigned[lit] = base + "." + id.Name |
| + } |
| + } |
| + } |
| + case *ast.ValueSpec: |
| + for i, v := range n.Values { |
| + if lit, ok := v.(*ast.FuncLit); ok && i < len(n.Names) && n.Names[i].Name != "_" { |
| + if n == root { |
| + assigned[lit] = n.Names[i].Name |
| + } else { |
| + assigned[lit] = base + "." + n.Names[i].Name |
| + } |
| + } |
| + } |
| } |
| - } |
| - if expr == nil { |
| return true |
| - } |
| - on := func(arch string) func(string) bool { |
| - return func(tag string) bool { |
| - return tag == "linux" || tag == "unix" || tag == "gc" || tag == arch || |
| - strings.HasPrefix(tag, "go1.") || slices.Contains(tags, tag) |
| + }) |
| + names := map[*ast.FuncLit]string{} |
| + ordinal := 0 |
| + ast.Inspect(root, func(n ast.Node) bool { |
| + if lit, ok := n.(*ast.FuncLit); ok { |
| + if name, ok := assigned[lit]; ok { |
| + names[lit] = name |
| + } else { |
| + ordinal++ |
| + names[lit] = fmt.Sprintf("%s.func%d", base, ordinal) |
| + } |
| } |
| - } |
| - return expr.Eval(on("amd64")) == expr.Eval(on("arm64")) |
| + return true |
| + }) |
| + return names |
| } |
diff --git a/internal/codehealth/testdata/fixture/consoledb/consoledb.go b/internal/codehealth/testdata/fixture/consoledb/consoledb.go| index 00750f115..cf6269ed5 100644 |
| --- a/internal/codehealth/testdata/fixture/consoledb/consoledb.go |
| +++ b/internal/codehealth/testdata/fixture/consoledb/consoledb.go |
| @@ -12,8 +12,15 @@ type sqlQueryer interface { |
| QueryRow(query string, args ...any) *sql.Row |
| } |
| -func Get(db *sql.DB, q sqlQueryer, sq store.Queryer) { |
| +// rowQueryer names its result through store's alias, from another package: |
| +// still database/sql's QueryRow. |
| +type rowQueryer interface { |
| + QueryRow(query string, args ...any) *store.Row |
| +} |
| + |
| +func Get(db *sql.DB, q sqlQueryer, sq store.Queryer, rq rowQueryer) { |
| db.QueryRow("q") // counted here as it was in store |
| q.QueryRow("q") // its own narrow interface: counted |
| sq.QueryRow("q") // store's interface, from another package: counted |
| + rq.QueryRow("q") // an alias behind a pointer, after the move: counted |
| } |
diff --git a/internal/codehealth/testdata/fixture/internal/host/probe_arm64.go b/internal/codehealth/testdata/fixture/internal/host/probe_arm64.go| new file mode 100644 |
| index 000000000..dc4ec72e4 |
| --- /dev/null |
| +++ b/internal/codehealth/testdata/fixture/internal/host/probe_arm64.go |
| @@ -0,0 +1,8 @@ |
| +//go:build linux && arm64 && rootrunner |
| + |
| +package host |
| + |
| +import "context" |
| + |
| +// Only linux/arm64 with the gate's tags builds this: counted. |
| +func armProbe() context.Context { return context.TODO() } |
diff --git a/internal/codehealth/testdata/fixture/main_amd64.go b/internal/codehealth/testdata/fixture/main_amd64.go| new file mode 100644 |
| index 000000000..705de5199 |
| --- /dev/null |
| +++ b/internal/codehealth/testdata/fixture/main_amd64.go |
| @@ -0,0 +1,6 @@ |
| +package main |
| + |
| +import "log" |
| + |
| +// Built only for linux/amd64: counted, on any machine. |
| +func amd64Only() { log.Fatal("amd64") } |
diff --git a/internal/codehealth/testdata/fixture/main_arm64.go b/internal/codehealth/testdata/fixture/main_arm64.go| index 62269d3b0..2d7334773 100644 |
| --- a/internal/codehealth/testdata/fixture/main_arm64.go |
| +++ b/internal/codehealth/testdata/fixture/main_arm64.go |
| @@ -2,4 +2,5 @@ package main |
| import "log" |
| -func arm64Only() { log.Fatal("built only for arm64: not scanned on any machine, listed") } |
| +// Built only for linux/arm64: counted, on any machine. |
| +func arm64Only() { log.Fatal("arm64") } |
diff --git a/internal/codehealth/testdata/fixture/store/store.go b/internal/codehealth/testdata/fixture/store/store.go| index 540d20145..5c318ab09 100644 |
| --- a/internal/codehealth/testdata/fixture/store/store.go |
| +++ b/internal/codehealth/testdata/fixture/store/store.go |
| @@ -25,6 +25,14 @@ type oldStyle interface { |
| Exec(query string, args ...interface{}) (sql.Result, error) |
| } |
| +// Row is an alias of sql.Row. Behind a pointer, *Row is still *sql.Row, so |
| +// aliasQueryer's QueryRow is database/sql's: counted. |
| +type Row = sql.Row |
| + |
| +type aliasQueryer interface { |
| + QueryRow(query string, args ...any) *Row |
| +} |
| + |
| // shell has an Exec and a Query that are not database/sql's: not counted. |
| type shell struct{} |
| @@ -34,6 +42,8 @@ func (shell) Query(q string) []string { return nil } |
| // Store embeds *sql.DB, so its promoted methods are *sql.DB's. |
| type Store struct{ *sql.DB } |
| +func Aliased(a aliasQueryer) { a.QueryRow("q") } |
| + |
| func Calls(ctx context.Context, db *sql.DB, tx *sql.Tx, stmt *sql.Stmt, conn *sql.Conn, q Queryer, h handle, o oldStyle, s Store) { |
| db.Query("q") |
| db.QueryRow("q") |
diff --git a/internal/codehealth/testdata/lines/lines.go b/internal/codehealth/testdata/lines/lines.go| index e9f913665..523d87406 100644 |
| --- a/internal/codehealth/testdata/lines/lines.go |
| +++ b/internal/codehealth/testdata/lines/lines.go |
| @@ -53,3 +53,55 @@ func (g G[K]) Long() int { |
| a++ |
| return a |
| } |
| + |
| +// run is a package-level function literal of 6 code lines: counted as run. |
| +// The comment and the blank line inside it are not counted. |
| +var run = func() int { |
| + a := 1 |
| + // not code |
| + |
| + a++ |
| + a++ |
| + return a |
| +} |
| + |
| +// short is a literal of 5 code lines among comments: not counted. |
| +var short = func() int { |
| + // one |
| + a := 1 |
| + // two |
| + a++ |
| + return a |
| +} |
| + |
| +func register(f func() int) int { return f() } |
| + |
| +// callbacks is 15 code lines: counted. Its two literals are 6 each and |
| +// counted too: the unnamed callback by its ordinal (callbacks.func1), the |
| +// assigned one by its variable (callbacks.helper). |
| +func callbacks() { |
| + register(func() int { |
| + a := 1 |
| + a++ |
| + a++ |
| + return a |
| + }) |
| + helper := func() int { |
| + a := 1 |
| + a++ |
| + a++ |
| + return a |
| + } |
| + _ = helper |
| +} |
| + |
| +// table holds a callback in a package-level initializer: table.func1, 6 |
| +// code lines, counted. |
| +var table = map[string]func() int{ |
| + "x": func() int { |
| + a := 1 |
| + a++ |
| + a++ |
| + return a |
| + }, |
| +} |