Full Fable audit report: console (read against 5b6d5374; line numbers have moved since).
Audit: internal/console, cmd/console and console-only packages
Scope: internal/console (446 production files, 162,109 lines; 649 test files, 269,508 lines; 5,809 top-level tests; one package), cmd/console (main.go is 2,107 lines), and the packages only the console binary links: internal/billing, billingstripe, compute, dnsrec, domainreg, fleetstore, mail, perf, registrar/openprovider, zonehost, zonehost/route53zones (from go list -deps ./cmd/console minus GOOS=linux go list -deps .).
Method: grep, go list, and a regex-based reference count over the package (top-level declarations per file, then who refers to them). The coupling numbers in item 7 are approximate: identifiers are matched by name, not by type. Nothing was built or run. Every file:line below was read.
Summary
- The package cannot be split by moving files. 313 of 446 files (127,739 lines) define methods on one
*Server (2,099 methods, 197 fields); only 38 files (3,263 lines) are leaves that touch neither Server nor Store. A split is still worth doing, but in a fixed order: the database layer first (Store, one-directional, cheap with type aliases), then five features that have few inbound references and no record-write census rows (billing, alerts, operator pages, architecture view, PDF), each as its own struct. Map in item 7. - *Thirteen in-package source guards glob `.go
in the package directory.** Any file that moves leaves their view silently. They have to be widened before the first move, not after. Also 150 record-write census rows in internal/provision` name console files by path. - Cheap wins that need no restructuring: 24 sleeps of 1.1 s that exist only to cross a whole-second timestamp (about 27 s of serial test time), 15 migrations that detect "duplicate column" by error text, and no graceful shutdown (SIGTERM ends in
os.Exit(0) with requests in flight).
Not worth doing in this slice: a slog migration (1,705 log.Printf lines, 45 test files capture the standard logger, nothing consumes the text by machine); chasing _ = lines (the ones I read are deliberate and the callee logs); a %w sweep (9 sites, none breaks a caller today); splitting out the copy maps or other small leaves for build time (under 2% of the package).
The code itself is careful: rows.Err() is checked after all 95 rows.Next() loops, maps keyed by caller input are bounded, HTTP clients have timeouts or request contexts, detached contexts carry a comment saying why. The problem in this slice is shape, not sloppiness.
Findings
7. Huge package: internal/console (the main item)
- Verdict: do, in stages. Stage 0 and 1 now; stage 2 one feature at a time; stage 3 only if stage 2 pays.
- Payoff: targeted test runs stop compiling 432k lines per edit; CI gets package-level parallelism without the hand-kept shard weights; reviews and census-style guards get a real boundary to check instead of a file name convention.
- Cost: L overall (S for stage 0, M for stage 1, M per feature in stage 2). Risk: med. Census-touching: no for the root-read census, yes for the record-write census (see "What the census says").
What is there today
| Measure | Value | |---|---| | Production files / lines | 446 / 162,109 | | Test files / lines / tests | 649 / 269,508 / 5,809, all package console | | *Server methods / lines in them | 2,099 / about 71,000 | | Server struct | server.go:1000-1574, 197 fields, 36 func-typed seams, 18 locks | | Config struct | server.go:533-999, about 100 fields | | page view model | server.go:2454-2925, 188 fields, shared by every HTML page | | *Store methods | 523 (383 exported) across 60 files, about 9,350 lines | | Files with Server methods | 313 (127,739 lines) | | Files with neither Server nor Store methods | 102 (21,072 lines) | | Leaf-closed files (no Server/Store reference, all deps also leaves) | 38 (3,263 lines) | | Route table | 159 registerRoute calls in NewServer (server.go:1916-2234), plus registerCLIRoutes (authcli.go:545, 647 lines) | | Shared test fixture | newConsoleFixture (server_test.go:45), 1,120 uses; tests reach 411 distinct unexported Server members through fx.srv (3,574 uses) | | Test files that use no server fixture | 174 (51,730 lines) |
The file-name prefixes (claim, demo, lifetimes_, billing, plan, alert) are real clusters of topic, but each is 23% to 67% Server methods and calls 9 to 66 Server methods defined elsewhere. They are chapters of one struct, not modules.
Approximate coupling per cluster (out = distinct methods defined outside the cluster that it calls; in = outside files that refer to it; rows = record-write census rows in internal/provision naming its files):
| Cluster (prefixes) | Files | Prod | Test | Server-method share | Out: Server / Store | In: files | Exclusive Server fields | Rows | |---|---|---|---|---|---|---|---|---| | sqlgate (storegate, claimsql) | 8 | 2,988 | 1,313 | 0% | 0 / 2 | few (see below) | 0 | 0 | | arch (arch) | 5 | 2,015 | 2,458 | 5% | 9 / 0 | 2 | 1 | 0 | | operator (op, accountreview, auditdetail) | 13 | 2,771 | 5,347 | 13% | 8 / 6 | 14 | 0 | 0 | | geoip (geoip, apisystemgeoip, apigeo) | 8 | 1,568 | 1,621 | 15% | 8 / 0 | 27 | 0 | 3 | | alerts (alert) | 11 | 5,624 | 5,770 | 23% | 9 / 8 | 42 | 7 | 0 | | pdf (pdf) | 4 | 672 | 1,392 | 26% | 3 / 2 | 5 | 4 | 0 | | mail (mail, sesevents, apimail, consolemail) | 8 | 4,684 | 5,620 | 43% | 21 / 8 | 16 | 5 | 0 | | billing (billing, apibilling) | 21 | 8,312 | 11,322 | 46% | 18 / 13 | 11 | 0 | 0 | | plans (plan, accountplans, apiaccountplan) | 22 | 4,474 | 9,754 | 44% | 14 / 13 | 50 | 4 | 3 | | scan (scan, apiscan) | 8 | 2,867 | 4,939 | 55% | 12 / 0 | 7 | 4 | 1 | | lifetimes (+materialize, expirypass) | 13 | 4,945 | 10,384 | 46% | 27 / 16 | 72 | 3 | 15 | | moves (apiinstancemove*, movesrecovery) | 5 | 4,583 | 8,400 | 53% | 20 / 12 | 32 | 6 | 6 | | claim + hostclaim (not sqlgate) | 37 | 6,676 | 15,384 | 36% | 66 / 20 | 314 | 8 | 8 | | demo (demo_, apidemo) | 29 | 9,564 | 19,340 | 67% | 64 / 22 | 32 | 13 | 6 | | fleets (managed, fleet, hostsused) | 28 | 9,900 | 17,478 | 53% | 57 / 11 | 94 | 11 | - | | regions/placement | 30 | 7,303 | 16,712 | 41% | 50 / 13 | 69 | 9 | - | | everything else ("core") | 69+ | 36,758+ | 57,616+ | 43% | - | - | 36 | 89 |
Reading the table: billing, alerts, operator, arch and pdf are the candidates. Few outside files refer to them, they call a short list of Server helpers, and they carry no record-write census rows. claim_, despite 37 files, is the worst candidate: registerRoute (claim_routes.go:68) wraps every route in the process, and 314 files refer into the cluster. demo* looks isolated from the outside (32 files) but needs 64 Server methods and reaches s.store.db directly 60 times (democlaimtransfer.go 21, demoexpiry.go 14, demopublish.go 11, demo_jobs.go 7); it becomes movable only after stage 1.
What the census says
- AGENTS.md:317 puts "the console binary's own packages (
cmd/console, internal/console and its templates)" out of root-read census scope. GOOS=linux go list -deps . confirms the root binary links none of internal/console, and TestRootBinaryLinksNoConsoleOrMail (internal/provision/rootbinarydeps_test.go:18) pins it. Every move proposed here stays inside packages only cmd/console links, so none needs a root-read census card. A new directory under internal/console/ is out of scope automatically, because scope is computed from the dependency list. - The trap is the opposite direction. If logic is "pushed down" into a package the root binary already links (
internal/release, provision, registry, hostops, moves, demo, alerting, geoip), that code enters census scope. Keep new packages under internal/console/. - AGENTS.md:397: the record-write census "is unchanged". It walks the whole repo (internal/provision/plan9b8censustest.go:217) and keys each row on
File, Unit, Class, Kinds, Digest (plan9b8censustest.go:43). 150 distinct (file, unit) pairs across 74 console files are named in 67 inventory files under internal/provision. Moving a file changes File; turning Server.x into billing.Service.x changes Unit. The body digest survives a pure move. Each moved writer is a mechanical row edit that a reviewer has to see. The five candidates above have zero rows; lifetimes (15), seed/import (16) and "core" (89) are where this cost sits.
The guard that goes blind
Thirteen tests in the package enforce "nothing else in the package does X" by scanning the directory. After a split they still pass and no longer see the moved files, which is the "rule stated as an absence" failure AGENTS.md describes:
filepath.Glob("*.go"): billinglinttest.go:32 and :271, claimauthoritycensustest.go:148, claimsqlcensustest.go:41, hostsusedwriterstest.go:465, jobstest.go:396, lifetimesstoretest.go:331, recordwritelocktest.go:120, remoteinstancesround5test.go:34, planlapsetest.go:153, rootfsmovetest.go:369os.ReadDir("."): claimroutestest.go:56parser.ParseDir(fset, "."): svcroutes_test.go:837
21 test files in the package parse Go source in some form (11,068 lines). Outside the package, 18 root tests, 2 in cmd/console and a handful elsewhere name internal/console/<file>.go paths (the approved-copy tests among them).
Proposed map
cmd/console
internal/console composition root: Config, NewServer,
| route table, worker registry, and the
| not-yet-extracted handlers
+- console/billing stage 2
+- console/alerts stage 2
+- console/operator stage 2
+- console/archview stage 2
+- console/pdfdoor stage 2
| (each imports web, never console)
+- console/web stage 2 prerequisite: the kernel
| +- console/consoledb stage 1: Store, Account, migrations
| +- console/sqlgate stage 1: the driver-level SQL gate
+- console/srcguard stage 0: one shared "walk every
console package" helper for the guards
Dependencies point one way: console imports features, features import web, web imports consoledb. NewServer registering a feature's routes is why features cannot import console itself.
Stage 0: make the guards split-proof (S, low risk, do now). Replace the thirteen directory scans with one helper that walks internal/console/... (every production Go file under the tree), and have each guard state which packages it expects to cover. No production code moves. This is worth doing even if nothing else is: it turns "the guard only sees one directory" from an accident into a statement.
Stage 1: consoledb and sqlgate (M, low-med risk).
- What moves:
store.go, store_gate.go, storelock.go, the *_store.go files (alertstore, authstore, billingstore, domainstore, doorkeysstore, emailsigninstore, hostsusedstore, lifetimesstore, managedstore, opstore, plangracestore, planlapsestore, signinmethodsstore, tempstore, demostore, democlaimstore, democlaimbrowserstore, apppolicystore), pending.go, mailevents.go, pdfrenders.go, the claim_sql_* files, and the Store-method halves of the 29 mixed files (billingops.go 12 methods, mailpush.go 16, svcprincipal.go 12, demo_store.go 12, stepup.go 7, billinglate.go 7 are the large ones). About 9,350 lines of Store methods plus their types and schema: roughly 15k to 18k production lines. - Why it is clean: nothing in the
Store files calls a Server method (0 in the count). The dependency already runs one way. - Why it is cheap: 383 of 523
Store methods are already exported, and console can keep type Store = consoledb.Store, type Account = consoledb.Account, var Open = consoledb.Open, so the thousands of s.store.X(...) call sites and cmd/console do not change. - What has to become exported: the 140 unexported
Store methods that Server code calls (planExempt, withMailAppSQL, withAutoAppSQL, pruneMailAppRows, claimGated, ed25519Key are the busy ones), the row types they return, and hashToken/randomToken (store.go:2880, :2885), which Server code uses as free functions. - What has to stop: 104 direct
s.store.db uses in 25 Server files. Each becomes a named Store method. This is the real work of the stage and the real gain: today the SQL lives on both sides of the line. sqlgate inside it: store_gate.go (1,971 lines) and claim_sql_instance/identity/outer/receipts.go are a database/sql driver wrapper (types at storegate.go:840-1603) with 0% Server methods and two outbound references (Account, newStore). API: Gate, Connector, OuterDB, BoundDB, Scope, Table, Handle (today sqlHandle, storegate.go:110), the grant constructors. The Store methods that drive it (withClaimSQL, storegate.go:1779; WithAppMutation, claimsqlgrants.go:50) stay with Store. This is the security boundary for host-claimed apps, so it should move last in the stage, behind the stage 0 helper, with claimsqlcensustest.go watched to fail first.- Tests that move with it: the fixture-free store tests. 174 test files (51,730 lines) use no server fixture; the store-facing subset of those moves. Tests that build a
Server stay. - Census: no root-read card. Record-write rows: the inventories name no
Store.* unit in a console file today, so this stage edits none.
Stage 2: web kernel, then features one at a time (M each, med risk).
A feature package cannot hold *Server. It holds a small struct of its own and a *web.Kernel (or a few interfaces). The kernel is what every feature already calls. From the reference count, the helpers the five candidates need are:
- gates:
session, account, owner, operatorOnly, requireFreshAuth, stepUpGate, apiAccountApp, cliUser, clientIP - rendering:
render, renderMessage, basePage, accountPage, opPage, setFlash, takeFlash, consoleName, storeFormCSRF - JSON:
jsonError (1,463 call sites package-wide), writeJSON, readJSON, readJSONStrictLimit - cross-cutting:
lockAccount/lockApp (keyedLocks, applocks.go:12), jobFailed, audit, registerRoute, registerClaimWorker
That is about 30 methods plus keyedLocks, the rate limiter (authcli.go:198) and the job registry. It is the right first cut of Server whether or not any feature ever moves, because it names the console's actual internal API.
Two shared structures block HTML features and have to be dealt with in the kernel:
page (server.go:2454, 188 fields): every feature adds its view fields to one struct. A feature package needs web.Page{Chrome; Body any} with its own body type. Templates that read .BillingX become .Body.X. This is the largest mechanical change in stage 2 and touches the 64 templates.templates (server.go:80): one template set with one FuncMap that closes over feature data (billingText reads billingCopy, server.go:84). The kernel owns the base set and chrome; a feature registers its templates and funcs at construction.
Per feature:
| Package | Files | Prod / test lines | Own state today | API it exposes | Needs from kernel | |---|---|---|---|---|---| | console/archview | arch.go | 2,015 / 2,458 | infraRefreshing | Build(...) View, two handlers (handleArchitecture, handleArchitectureRefresh) | operatorOnly, opPage, render, flash, loadInventory, infraPass | | console/operator | op.go, accountreview.go, auditdetail.go | 2,771 / 5,347 | opNow | 7 page handlers, the op* template helpers (opPill, opTabs, opHeader, used by 13 outside files: these belong in web) | operatorOnly, render, boxRegion; Store.Accounts/Members | | console/pdfdoor | apipdf.go, pdflimit.go, pdf_copy.go, planpdf.go | 672 / 1,392 | pdfLimiter, pdfTimeout, pdfIdleTimeout, recordPDF | Handler, Limits, ParseLimits | apiAccountApp, jsonError, plan cap check | | console/alerts | alert.go | 5,624 / 5,770 | alertEngine, alertClock, alertHTTP, alertHTTPOnce, alertPassBudget, alertSeal, alertTests | Engine with Start, Due, RecordSeen, Recipients; 13 handlers; FiringAlert | operatorOnly, render, opPage, consoleName; Store.Members/Operators/AlertSigningKey/AlertSeen | | console/billing | billing.go, apibilling*.go | 8,312 / 11,322 | none exclusive (uses memberLocks with plans) | Service with Hold, Team, Clock, StartSyncPass, ReconcileSeats, RetireForDeletion; 14 handlers; Config (today BillingConfig) | flash/render/accountPage, requireFreshAuth, stepUpGate, lockMembers; Store.AccountByID/planExempt/MemberCount/AccountPlan |
Order: archview (proves the page/template mechanics on the smallest case), operator, pdfdoor, alerts, billing. Billing is the largest win (19.6k lines out of the main compile unit) and has the fewest inbound files (11), but it is entangled with plans (billingstore.go and billingusage.go refer into plan files about 80 times), so decide first whether plans moves with it or the plan rows move to consoledb.
Tests: each feature's tests currently use newConsoleFixture. They can keep doing that from an external test package only if the fixture is exported (console/consoletest) and they stop reading unexported Server members. Expect to rewrite the white-box half. That is the main cost per feature and the reason to go one feature at a time.
Stage 3: the rest (L, decide later). demo (28.9k lines with tests), lifetimes, moves, seed/import, fleets, regions. All have 50+ Server methods out or 70+ files in, and they hold the record-write census rows. Do not start these until stage 2 has shown what a feature extraction costs in practice. claim_* stays in the root console package: it is the route and worker registry.
Not proposed: a console/copy package for the *_copy.go maps (about 970 lines, referred to from 74 files, pinned by path in the root approved-copy tests); icons.go/countrynames.go; emailsignin_limits. They are leaves, but moving them buys nothing measurable.
Build and test win (estimates, not measured)
I could not build, so these are reasoned, not timed. One go test -c ./internal/console with -debug-actiongraph on the CI runner would replace them with numbers; do that before committing to stage 2.
- Today any edit to any console file, production or test, recompiles the test variant of the package: 432k lines in one compile unit, then links it. Type-checking is serial per package, so cores do not help much. A targeted
go test ./internal/console -run TestX pays that whole cost each iteration. The memory rule "targeted tests only" does not avoid it. - After stage 1, an edit in
consoledb recompiles 15k to 18k lines plus its own tests for a store-only test run; an edit above it no longer recompiles the store. The main unit drops by roughly 10% production and whatever store tests move. - After stage 2 (all five features): about 19.4k production and 26.3k test lines leave the main unit (about 11% of the 432k). A billing-only iteration compiles about 20k lines instead of 432k.
- CI:
.amadan/test-gate.sh:11 records that the package took about 440 s on 32 cores before sharding, and line 36 splits it 8 ways by weights kept in .amadan/test-weights.tsv. Separate packages run in parallel without that file. The top weights are few tests (two at about 60 s, one at 30 s: TestALapsedWriterCannotOverwriteTheNextWritersRevoke, TestClaimConsoleMutationInvariant, TestPolicyWriterLeaseIsOneConsolePerBucket), so the split will not shorten the CI wall clock much by itself. The CI win is small; the win is in local iteration and in review. - 22 root-package test files, 7 in
internal/host, 1 in internal/edge and 1 in internal/provision import internal/console. They need the whole server, so they gain nothing from the split.
6. Huge files
- Verdict: do for server.go and the two giant handlers; do later for the rest.
- Payoff: review cost and merge conflicts. server.go is touched by nearly every feature (it holds the struct, the config, the route table and the view model), so parallel branches collide in it.
- Cost: S per file (same package, no renames). Risk: low, except that record-write census rows name files (89 "core" rows;
NewServer in server.go is named in many inventories, for example internal/provision/analyticslivecensus_test.go:14). A same-package file split changes File for every unit that moves. Census-touching: record-write only. - Evidence and proposal:
| File | Lines | Split | |---|---|---| | server.go | 7,015 | templates.go (FuncMap, :80-524), config.go (Config, :533-999), server.go (struct, NewServer body without routes), routes.go (the 159 registerRoute lines, :1916-2234), page.go (page, render, cookies, flash, :2454-3100), accounts_pages.go (home, new account, invites, :3103-3870), signin_pages.go (:3867-4120), app_pages.go (app tabs, logs, settings, :4247-5300), appclaim.go (claimApp*, :5329-5720), release_pages.go (promote, rollback, production, fast track, canary, :5853-6975). Leave NewServer in server.go so its census rows keep their File. | | apiinstances.go | 3,572 | instancehealth.go (:299-915), instancejoin.go (box and rollout joins, :915-1231), apiinstances.go (list/get), apiinstancecreate.go, apiinstanceupdate.go, apiinstancedelete.go (delete, token, enable) | | store.go | 3,320 | store_schema.go (migrate, :163-860), store_accounts.go (:1177-1850), store_apps.go (:1853-2630), store_sessions.go (:2860-3060), store_movelog.go (:2737-2860), store_keys.go (:3166-3260) | | apicli.go | 2,688 | apiprincipal.go (:46-380), apiapps.go, apipromote.go (:878-1440), apiship.go (:1868-2688) | | authcli.go | 2,103 | ratelimit.go (:198-420), cliroutes.go (registerCLIRoutes, :545-1208), jsonio.go (:1258-1350), authcli.go (device flow, tokens) | | cmd/console/main.go | 2,107 | serve.go (serve, :315-889), env.go (the 40-odd env readers, :962-1700), main.go |
- Functions, not just files. 136 functions are over 100 lines, 24 over 200, 5 over 400: -
handleAPIInstanceCreate, apiinstances.go:1524, 1,081 lines - registerCLIRoutes, authcli.go:545, 647 lines (a table; fine) - Store.migrate, store.go:163, 569 lines (a table; fine) - serve, cmd/console/main.go:315, 569 lines - handleAPIShip, apicli.go:2055, 568 lines - NewServer, server.go:1769, 517 lines - handleAPIInstanceUpdate, apiinstances.go:2803, 376 lines
handleAPIInstanceCreate and handleAPIShip are the two worth breaking up: each is a single handler that validates, admits, writes and undoes in one body. Split into a parse/validate step returning a request struct, an admit step, and the write. That is a behaviour- preserving refactor of code with census rows, so it needs its own reviewed branch; do it when either handler next needs a feature.
3. Sleep-based tests
- Verdict: do the 1.1 s sleeps; leave the poll loops.
- Payoff: about 27 s of serial test time removed (24 sleeps of 1,100 ms plus one of 2,100 ms), and a class of second-boundary flakes.
- Cost: S. Risk: low. Census-touching: yes if the clock goes into
internal/release (root binary links it); no if the tests backdate the pointer instead. - Evidence: 123
time.Sleep in console tests. Three kinds: 1. Sleeping across a whole-second timestamp (24 sites). release.PromoteSystem stamps time.Now().UTC().Truncate(time.Second) (internal/release/systempointer.go:203 and :336) and SystemPromoteOptions (systempointer.go:275) has no clock, so tests sleep to order two promotions: apisystemupdatetest.go:442, :456, :563, :603, :612, :638, :685, :694; layoutguardtest.go:90, :120, :196, :203; fleetfloortest.go:596, :651, :660; apisystemoperatorstest.go:58, :78; remoteinstancesround4test.go:171, :173; remoteinstancesround2test.go:175 ("createdat is whole seconds"); apiclitest.go:2925 ("PromotedAt is truncated to the second"); apiinstancemovej4test.go:80; plan9btest.go:156; statusrowsg3test.go:120; demojobstest.go:800 (2,100 ms). 2. Sleep, then assume a goroutine has arrived (flake risk, and the right testing/synctest candidates because the code under test is in-memory): reqmemoprefetchtest.go:99, :132, :138; analyticslivetest.go:223, :238; apirunsboxtest.go:595 (300 ms to assert nothing happened); apiinteractivetest.go:1061, :1064 (real websocket deadlines, not a synctest candidate). 3. Poll loops with a deadline (fine): apidbforwardtest.go:877, :931; apirunsboxtest.go:215, :508; storelocktest.go:121; sealkeytest.go:436, :646; hostsusedactive_test.go:335. Leave them. - Proposal: for kind 1, give the console tests a helper that promotes and then rewrites the pointer's
PromotedAt/ReleasedAt one second back (test-only, no census). An At time.Time on SystemPromoteOptions would be cleaner but is a census card. For kind 2, move the reqmemo and analyticslive tests into synctest.Test bubbles; apipdf_test.go already uses synctest, so the pattern is in the package.
5. Context propagation
- Verdict: do later, as part of stage 1. The handler-level misuse is small; the store-level gap is the real one.
- Payoff: a request that the client abandoned stops waiting for the database. The store has one connection:
db.SetMaxOpenConns(1) (store.go:118, and store_gate.go:1912 for the gated store), so every query queues behind every other, and database/sql only lets a waiter give up through its context. - Cost: M. Risk: low. Census-touching: no.
- Evidence: 86
context.Background() in production console code, 52 in cmd/console/main.go. - Fine, with reasons in place: startup in main; the 35 workers started at cmd/console/main.go:754-848; detached jobs that must outlive the request (apisystemgeoip.go:78, apirunsbox.go:259, apiinteractive.go:273 and :552, emailsignin.go:140, authcli.go:1532, storenotify.go:87 and :96, apidbforward.go:255, policylease.go:204 and :371); the database/sql/driver methods that have no context parameter (storegate.go:1010, :1016, :1504, :1508; claimsqlreceipts.go:164-227). demoClaimEnabled (democlaimauth.go:26) passes Background into a check that uses context.WithoutCancel anyway (democlaimready.go:68). - Wrong, context dropped by signature while every caller has one: - withRecordLock, recordlock.go:22 (callers at appsettings.go:1171, :1298, domainattach.go:276, replicacoordinator.go:104, :179 all have ctx) - demoMutationRefusal, demodomains.go:21 (6 callers) - configuredPlacementGuidance, apiplacements.go:1044 (calls s.edgeIPs(context.Background()), which can fold edge files) - movable, fleetbox.go:178; replicaNext, replicaplacement.go:102; replicaAction, replicaplacement.go:198 - The larger gap: 94 of 523 Store methods take a context. 520 call sites use Exec/Query/QueryRow/Begin without one, against 352 with. The package has grown twin methods to bridge it: RecordEvent calls RecordEventContext(context.Background(), ...) (store.go:3272; same shape at store.go:3262, :3282, :3292, :3302, :3312, tempstore.go:218-258, authstore.go:730, :781, :815, doorkeys_store.go:236-266, pending.go:387, :398, svcprincipal.go:689, :699). - Proposal: fix the six signatures now (S). When
Store moves to consoledb, make the context variant the only one for anything a handler calls, and delete the twins. busy_timeout=5000 (store.go:122) bounds a lock wait, not a wait for the single connection.
10. Other: shutdown, god structs, single connection
No graceful shutdown.
- Verdict: do. Cost: S-M. Risk: low. Census-touching: no.
- Evidence: cmd/console/main.go:656-664 handles SIGTERM by stopping the capacity observer, releasing the policy lease and calling
os.Exit(0). httpSrv.Serve (main.go:882) is never shut down, and the workers at main.go:754-848 all run on context.Background(). A console roll therefore cuts in-flight requests (a ship upload, a promote) and any pass mid-write. The journaled doors are built to survive that, so this is about client-visible errors during rolls, not corruption. - Proposal: one
signal.NotifyContext root context passed to every worker; on signal call httpSrv.Shutdown with a bound (the systemd stop timeout minus a margin), then release the lease, then exit. NewHTTPServer (httpserver.go:17) deliberately has no WriteTimeout; keep that.
Server, Config and page as shared mutable structure.
- Verdict: addressed by item 7 stage 2; do not treat separately.
- Evidence:
Server 197 fields (server.go:1000-1574), of which the count finds about 115 used by one non-core cluster only (demo 13, fleets 11, regions 9, claim 8, alerts 7, moves 6). 127 tests build &Server{} literals and set unexported fields, which is what keeps every field package-visible. - Cheap step that pays now: group each cluster's exclusive fields into a named sub-struct on
Server (s.alerts.clock, s.demo.jobs). It shrinks the struct to something reviewable and is the first half of any later extraction. S per cluster, same package, no census rows unless a writer's body text changes (it will, where s.field becomes s.group.field: the digest covers the body, so check the rows for the cluster first; alerts, billing and operator have none).
One SQLite connection for reads and writes.
- Verdict: don't, here. It is already tracked (read-only connections, #514). Noted because it is what makes the context gap in item 5 matter.
Console-only packages. internal/billing, billingstripe, compute, dnsrec, domainreg, fleetstore, perf, registrar/openprovider, zonehost, route53zones: no context.Background(), no unwrapped errors, no error-text matching, HTTP clients with timeouts (internal/billingstripe/client.go:142-143). Nothing to do. internal/mail (6,868 lines) has one large file, walk.go (2,227 lines), and 16 log.Printf; not worth a finding.
2. Error wrapping and error-text matching
- Verdict: do the migrations helper; do later for the advice functions; don't sweep
%w. - Payoff: boot-time migrations stop depending on a driver's wording; four user-facing messages stop depending on log text.
- Cost: S. Risk: low. Census-touching: no for the console side; the sentinel for
release errors would be (root binary links it). - Evidence: -
fmt.Errorf with err and no %w: 9 sites (alertstore.go:415, keymail.go:409, controlplane.go:378, :389, lifetimesmigrate.go:508, store.go:3174, :3178, :3228, :3232). None is inspected with errors.Is/As by a caller I could find; they end in a log line or a flash message. Not worth a change. - err == sql.ErrNoRows / io.EOF with ==: 45 sites (store.go:1321 and 14 more in that file, alertstore.go:606, :1079, :1167, authstore.go:491, :560, mailpush.go:313, :601). Correct today because these come straight from database/sql and io; staticcheck does not flag sql.ErrNoRows comparisons by default. Leave. - Error-text matching, 29 sites, in three groups: 1. "duplicate column" in migrations, 15 sites: store.go:645, :738; authstore.go:279; billingstore.go:148, :207, :219, :249; democlaimstore.go:65; domainstore.go:117; emailsigninstore.go:92; opstore.go:32; storegate.go:1889, :1895. 81 ALTER TABLE statements run on every boot and rely on the driver's English. One helper, addColumn(db, table, column, def), that reads `pragmatable_info first removes all 15 and makes a driver upgrade safe. 2. **Advice from a sibling's error text**: ownership.go:734 ("last owner"), :741 ("not a member"), :744 ("already"), :751 ("still holds"), :755 ("ops"); appsettings.go:1769 ("already claims"); authstore.go:443 ("UNIQUE"). The errors are made a few lines away (ownership.go:770, :781, :821, :833; store.go:1601). Sentinels (errLastOwner, errNotMember, errOpsAccount, errHoldsApps) cost a few lines. :755 matches the bare substring "ops" in any error DeleteAccount returns, including a database error; see Bugs. 3. **Text from another package**: ownership.go:683, :687, :691 and apicli.go:1914 match release errors; apifeatures.go:144 matches "at most" from release.UpdateFeatures; apimail.go:1314 and :1445 match mail errors. mail is console-only, so add mail.ErrFromNotVerified and mail.ErrBadCredentialName freely. The release` ones need sentinels in a census-scoped package: worth one card for all four, not four cards.
4. Globals, seams and t.Parallel
- Verdict: don't, beyond two small fixes.
- Payoff: little. The package mostly does this right: clocks and hooks are
Server fields (36 func-typed fields, for example alertClock, movesClock, relayNow, opNow), not package globals. - Cost: S. Risk: low. Census-touching: no.
- Evidence: 315 package-level
var lines, almost all tables, copy maps and compiled regexps. Mutable seams that tests write: pageDomainPurchase (domainbuy.go:847, 12 writes in 5 test files), pageNoCapacity (nocapacity.go:103, 3), lifetimesNow (lifetimescutover.go:63), lifetimesPage (lifetimesfloor.go:42), geoipVerifyExec (geoipverify.go:81), followerExpired (geoipfollower.go:22), hostsTripwireRetry (hostsusedtripwire.go:28), apiShipMaxBytesRootfs (apishiprootfs.go:28), hostReportProcReadFile and hostReportPIDNamespace (hostreportsprocesslinux.go:14, :37), geoipCommitDelay (apisystemgeoip.go:31). Process-wide atomic hooks: lifetimeLockHook (lifetimes.go:173, 32 test Store calls), instanceCreateHook (apiinstances.go:82), capabilityDoorHook (apidomains.go:832), fleetKeyHook (fleetsecretskey.go:50), teamScopedHook (teamdoors.go:104). - What blocks
t.Parallel is not these. It is log.SetOutput (118 calls in 45 test files) and t.Setenv (83). Only 15 test files use t.Parallel at all. The suite gets its parallelism from process shards, and that works. - Proposal: move
pageDomainPurchase and pageNoCapacity onto Server like the other pagers (they are the only seams with many writers). The five atomic hooks are race-safe; leave them. A -race run is worth having once per release on the two concurrency-heavy areas (reqmemo.go, interactivehub.go), not on the whole package.
8. Logging
- Verdict: don't.
- Payoff: none that is tangible today.
- Cost: L. Risk: med. Census-touching: no.
- Evidence: 1,724
log.Printf-family calls in the package (1,705 start with the literal "console: "), 90 in cmd/console/main.go, one slog call (hostreports.go:100). log.SetFlags(0) (cmd/console/main.go:173): systemd adds the timestamp. 45 test files capture the standard logger with log.SetOutput (helper captureLog, claimlogging_test.go:15) and assert on text. I found no infra metric filter or alert rule that matches console log text; alerts go through alerting.Page and jobFailed, which are structured already. Runbooks under docs/superpowers tell operators to journalctl -u the unit and read sentences. - The logs are written as sentences for a person and that is how they are used. A
slog move would rewrite 1,700 lines and 45 test files to gain keys nothing reads. If a need appears (per-account log search), add it at the two choke points that already exist, jobFailed and the audit path, not package-wide.
9. panic and ignored errors
- Verdict: don't, except the two data-dependent ones.
- Cost: S. Risk: low. Census-touching: no.
- Evidence: 30 non-test
panics. - Programming-error or startup invariants (fine): route registration (authcli.go:453, :473; teamdoors.go:78; claimroutes.go:27, :52; claimworkers.go:63), embedded assets and copy ids (assets.go:49, :70; signincopy.go:85, :88; democlaimpage.go:28), test-only switches (claimsqlinstance.go:102; cutoverwitnesscontrols.go:23, :34, :43), crypto/rand failure (billingportal.go:22, billingchange.go:87, billingcheckout.go:88, interactivehub.go:171, relayops.go:160). - Re-panics of a recovered value across a goroutine (fine): hotreads.go:71, :346; reqmemo.go:118, :127; claimsqlgrants.go:124; apipdf.go:93. - panic(http.ErrAbortHandler) (apipdf.go:236, :242): the documented way to abort a response. - Reachable from stored data: retireExpectETag (lifetimesretire.go:63) panics on an empty ETag and is fed ETags read from the object store (apiinstanceimport.go:1109, lifetimespurge.go:126, seedfinish.go:142); retireExpectIncarnation (lifetimesretire.go:72) panics on 0 and is fed rec.Incarnation at apiinstances.go:2561 with no check (the call at lifetimespurge.go:128 does check). In a handler net/http recovers and the request dies; in a worker jobs.go:234 recovers. Either way the retirement is skipped silently from the caller's point of view. Return an error instead; both callers already handle one. _ = f(): 92 lines. The ones I read are deliberate: 14 jobs.Run, 21 deadline setters on connections, 10 json.NewEncoder(w).Encode, and the lifetimes recovery pass (lifetimesrecovery.go:125, :132, :134, :180), where the callee logs and calls jobFailed itself (lifetimescreate.go:555-561). Nothing to fix.
1. Static analysis gate
- Verdict: nothing console-specific to add to the separate staticcheck run.
- Likely findings when it runs: the 45
== comparisons against sql.ErrNoRows/io.EOF only if the errorlint-style check is on (staticcheck proper does not flag them); the twin Foo/FooContext methods in item 5 may show as unused once callers move to the context form. - Cost: S. Risk: low. Census-touching: no.
Bugs found along the way
Few, and none severe.
- ownership.go:755,
deletionAdvice matches the substring "ops". It is meant to recognise "console: the ops account cannot be deleted" (ownership.go:821), but it is applied to whatever DeleteAccount returns (ownership.go:247-249), including a transaction or constraint error. Any such error whose text contains "ops" tells the owner "The ops account is the platform's own and cannot be deleted", after the account has already been retired in the bucket (the comment at ownership.go:244). Low probability, wrong message at a bad moment. Fix with a sentinel (item 2). - apiinstances.go:2561, unchecked incarnation into a panicking constructor.
retireExpectIncarnation(rec.Incarnation) panics when the value is 0 (lifetimesretire.go:72). The sibling call site guards it (lifetimespurge.go:127-128); this one relies on the create path always having stamped an incarnation when lifetimesUnit(ctx) is true. If that ever does not hold, the undo of a just-created record is skipped by a recovered panic and the duplicate-apex record stays. Guard it or return an error. - cmd/console/main.go:656-664, SIGTERM exits without draining. Not a correctness bug given the journaled doors, but every roll drops in-flight requests. See item 10.
- Flake candidates, not bugs: reqmemoprefetchtest.go:99, :132, :138 and analyticslive_test.go:223, :238 sleep 20 to 50 ms and assume a goroutine has reached a blocking point. On a loaded shared runner that is a race the test loses now and then.