carlos / platform Public

Go code audit 2026-11-16: ranked backlog open

Read-only audit of the Go code on 2026-11-16 at 5b6d5374. Four Fable 5.2 auditors (console; host family; activator and edge; root CLI and tooling) wrote reports, staticcheck v0.8.2 and govulncheck v1.8.0 ran once, and Astra verified the merged list against the code. Astra disproved two of Fable's bugs; they are left out below.

Overall the code is careful. The gaps are network calls with no deadline, holes in the CI gate, and a few oversized shapes.

First batch (Paul said go, 2026-11-16)

  1. AWS/S3 timeouts. rootaws.LoadDefaultConfig and release.newS3Store (internal/release/store.go:861) set no timeout; the SDK bounds only dial and TLS. About 20 host-agent loops pass context.Background() each pass, so one stalled response parks a loop until restart. Fix: per-operation deadlines, not one short client timeout (large transfers), plus one loop helper with a per-pass deadline.
  2. klauspost/compress v1.18.0 to v1.20.2. GO-2026-6865 (panic) is reachable from internal/moves/archive/archive.go:445.
  3. Request path. No IdleTimeout or ReadTimeout on the edge's public servers (edge.go:4808); remote tcpProxy dials have no timeout (edge.go:3528); a cancelled wake leaves a health probe running 30 to 120 s (backendexec.go:3699, backendunit.go:276); the throttled-log map is keyed on the request Host, so invented subdomains grow it without limit (plandisabled.go:80).
  4. Gate, stages 1 and 2. go vet with the rootrunner tag (111 test files, 34k lines, never compiled today), then staticcheck's bug checks, with existing findings fixed or baselined.

Later

  1. Console graceful shutdown: SIGTERM goes straight to os.Exit(0) (cmd/console/main.go:656). Medium: drain, workers and lease release need coordinating.
  2. Console request queries without a context, on a single SQLite connection (internal/console/store.go:118).
  3. Gate stages 3 and 4: govulncheck with GO-2026-6859 as an explicit exception under the 1.26.10 pin; gitleaks; a targeted -race job once racy test helpers are fixed (host/capspasstest.go:121, activator/wakecheck_test.go:586).
  4. Bugs: carlos ledger verify has no timeout and panics on a {} HEAD (cli.go:3808, :3813; internal/ledger/verify.go:55); carlos system update ignores decode errors (system.go:405, :453); "ops" substring match on delete errors (console/ownership.go:755); silent capacity-page failure (host/haplacement.go:17); unbounded staging-lease release (host/movescut.go:912, :917); escrow ALERT: prefix already missed when an error is joined first (activator/escrow.go:872); AGENTS.md:284 recommends a banned GOCACHE path.
  5. Tests: remove sleeps where seams exist (edge about 35 s, console 24 x 1.1 s, activator HA about 8 s, one 20 s host test); lease renewer tests to testing/synctest; add edge and activator to TEST_SPLIT.
  6. Structure, convert on touch: CLI commands return errors instead of log.Fatal (954 calls); a leaf package for the S3 Store interface (61 importers of internal/release link SQLite); a leaf for the names console takes from activator and edge; a census moved class before any root-graph file move; staged console split (widen 13 package-dir source guards first, then consoledb); split very long functions when next changed.

Not worth doing

A slog migration (tests, runbooks and release-note greps depend on log wording); a repo-wide %w or context sweep; moving the CLI to internal/cli; subpackages inside activator; mass-unexporting in host.

LLM

Fable audit plus Astra second read; first batch in progress

LLM

Correction: the audit read a local checkout of main at 5b6d5374, 159 commits behind amadan's main. Rechecked the first batch against 15b1ee6b:

  • Item 2 (klauspost/compress) is already fixed on main: 197cc40c moved it to v1.20.2 on 2026-11-09. Branch audit-compress-1202 deleted unused.
  • Items 1, 3 and 4 are still present on 15b1ee6b; line numbers have moved. Branches: audit-aws-timeouts, audit-request-path, audit-gate-vet-staticcheck.
  • The later items need the same recheck before anyone builds them.
Agent notes

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

  1. 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.
  2. *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.
  3. 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:369
  • os.ReadDir("."): claimroutestest.go:56
  • parser.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.

  1. 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).
  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.
  3. 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.
  4. 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.
Agent notes

Full Fable audit report: host (read against 5b6d5374; line numbers have moved since).

Audit: internal/host, internal/host* packages, instancectl, instanceexec, instancefs, lease

Method: grep, awk, go list, git log and reading. Nothing was built, tested or analysed. Counts are by grep over git ls-files, production files only unless a line says tests. Every file:line below was read. "Rows" means rows in internal/provision/testdata/census-base.tsv.

Slice size (production / test lines):

| package | prod | test | notes | |---|---|---|---| | internal/host | 124,928 | 255,912 | 505 prod files, 855 test files, 4,050 top-level tests | | internal/hostops | 14,522 | 14,031 | | | internal/instancectl | 11,970 | 17,505 | | | internal/hostbox | 9,514 | 10,508 | | | internal/hostclaim | 6,854 | 11,716 | | | internal/lease | 4,866 | 8,147 | plus leasetest, locktest | | the other 12 | under 3,500 each | | |

Only internal/host is over 20k lines. Only two files are over 2,000 lines: internal/host/agent.go (5,978) and internal/host/systemapply.go (2,414).

Summary

The three things most worth doing in this slice:

  1. Give the agent's loops one shape with a per-pass deadline and the agent's context (finding 5). About 20 loops in internal/host are for { time.Sleep(d); pass(context.Background()) }. The S3 store has no request timeout of its own, so one hung call parks a loop for the life of the process. The repo has already paid for this three times, one site at a time. Medium cost, cheap census class (body).
  2. Break up runAgent (1,089 lines, touched by 46 commits in the last month) inside agent.go, and teach census-propose a moved class before any file or package split (findings 6 and 7). Today every census unit is keyed by file path, so a pure move costs a removal plus a new row per unit, and the reviewer rule treats "moved rather than went" as a rejection. Until that exists, splits of internal/host are not worth their census cost.
  3. Stop exporting what nothing outside uses, then run a dead-code pass (finding 10a). internal/host exports 560 declarations; the root package uses 20 and three test packages use 3 more. Exported names hide unused code from staticcheck. One dead global turned up by eye (movingStatusNudged); there will be more.

Not worth doing in this slice: a slog migration (892 log.Printf in host, 49 test files and two operator runbooks match the text); a sleep-to-synctest sweep of internal/host (the measured suite is about 100 s of test time and one test is 20 s of it); mechanical %v to %w (no caller breaks today); splitting systemapply.go; chasing panic (three in the slice, all sound).

Findings

1. Static analysis gate

  • Verdict: do (small, rides the separate staticcheck pass)
  • Payoff: dead code and stale comments removed; fewer false leads in review.
  • Cost: S, Risk: low, Census-touching: yes (any byte in internal/host), class removed/envelope
  • Evidence: - Unused package variable with a comment describing a guard that now lives elsewhere: internal/host/movespass.go:1684 (var movingStatusNudged sync.Map). The live guard is the worker field at movespass.go:84, used at movespass.go:1572. No other reference in internal/. - _ = f() in the slice: 107 lines (host 61, instancectl 16, lease 8, instanceexec 6, hostops 5, hostbox 4, hostexec 3, instancefs 2, hostactors 1, hostenv 1). By callee: Remove/RemoveAll 19, fs.Parse 13, NewEncoder(...).Encode 13, Close 9, Set{Read,Write}Deadline 13. These are fine. The ones that matter are few: - internal/host/haplacement.go:17: a failed capacity page is dropped with no log line (see Bugs). - internal/host/systemapply.go:763: _ = a.record(req, reason); the result file is how the agent learns the outcome. The reason is still returned on the next line, so this is minor. - Sentinel compared with ==: 21 sites. 20 are err != io.EOF straight from json.Decoder (internal/hostclaim/store.go:32, internal/hostops/record.go:37, and so on), correct as written. One is a real sentinel: internal/host/claimrecovery_remote.go:108 (err == hostbox.ErrChanged). Guard.With (internal/hostguard/guard.go:151) returns the callback's error unwrapped today, so it works, but the retry silently becomes a failure the day anyone wraps. Change to errors.Is. - Redundant loop-variable copies (rt := rt), Go 1.22 made them dead: 4 sites, for example internal/host/agent.go:1530. Leave them unless the file is being edited anyway.
  • Proposal: delete movingStatusNudged; errors.Is at claimrecovery_remote.go:108; log at haplacement.go:17. Then finding 10a.

2. Error wrapping

  • Verdict: don't (as a sweep); fix two message bugs
  • Payoff: none today from a sweep. No caller in the slice does errors.Is or errors.As on any of these results, and there is no strings.Contains(err.Error(), ...) in production code in the slice (0 matches).
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: 52 fmt.Errorf(..., err) without %w (host 33, instancectl 16, hostfloor 2, instanceexec 1). They fall into three groups: - Operator-facing sentences for one-shot root commands, where the text is the product: internal/host/bootstrap.go:511,545,561,573,612,626,641,705, internal/host/boxpublish.go:134,138,147,154. - Deliberate flattening at a refusal boundary: internal/host/movesfloor.go:374,400, internal/host/seedsfloor.go:167,182, internal/host/systemapply.go:1279. - Would lose a context error if anyone ever checked for it: internal/host/movesfiles.go:722,748, internal/host/unitsettle.go:338, internal/instancectl/client.go:142. Nobody checks today.
  • Proposal: leave them. Fix movesfiles.go:721-722 and 747-748, which fold "not found" and "error" into one branch and print <nil> in the first case (see Bugs).

3. Sleep-based tests

  • Verdict: do later, three targeted fixes; don't sweep
  • Payoff: about 25 s off the gate and three fewer timing-margin tests. internal/host is not sleep-bound: .amadan/test-weights.tsv lists 99 host tests at 101 s in total, 18 of them at 1 s or more (67 s).
  • Cost: S each, Risk: low, Census-touching: no (test files only)
  • Evidence: 255 time.Sleep in the slice's tests (host 186, lease 32, instancectl 16, hostfiles 11, instanceexec 8). 93 of host's are outside the rootrunner build tag (104 files carry //go:build linux && rootrunner, so the 30 s and 65 s sleeps in internal/host/region_ha_g2_loss_root_linux_test.go:445,639,700 never run in the ordinary gate). Sampled classes: - "Sleep, then assert nothing happened" (the majority): for example internal/host/interactive_test.go:1880, internal/host/systemapply_test.go:2151, internal/host/rolloutdeclined_test.go:569. These can only pass falsely, never flake red, and cost 100 to 300 ms each. Leave them. - Waiting on a real second boundary because a timestamp has second resolution: internal/host/systemapply_test.go:259 and :1117 (1.1 s each, both tests are parallel), internal/lease/staging_test.go:267 (2.2 s, serial). An injected clock removes them; the fixture already carries f.now. - Waiting on a real timer in the code under test: internal/host/claim_ack_refresh_linux_test.go:533-543 waits for one real execlease.Renewal and is the slowest test in the package at 20.09 s (weights file). internal/lease/pause_test.go:71 (1.1 s) and :88 (2.5 s), internal/lease/release_test.go:168 (3 s), internal/lease/lease_test.go:302 (20 s against a live bucket, gated by liveConfig).
  • synctest candidates: internal/lease has 0 synctest uses and 0 t.Parallel. The renewer tests in pause_test.go, renew_attempt_test.go and checkpoint_test.go run against the in-memory lockStore (internal/lease/checkpoint_test.go:27), with timers and goroutines only, which is what synctest covers. The tests on leasetest.NewLockFixture (release_test.go:168) go through a real HTTP listener and cannot move. internal/host already uses synctest in three files (replicacoordinator_test.go, region_ha_g2_peer_test.go, suspects_test.go), so the pattern is known here.
  • Proposal: (a) put the in-memory renewer tests of internal/lease in synctest bubbles; (b) give TestClaimAckRefreshProductionClient a short renewal through the fixture, or accept it and keep it -short-skipped as it is; (c) use the fixture clock at systemapply_test.go:259,1117.

4. Data races and globals

  • Verdict: do later (one cheap guard now); the test discipline is good
  • Payoff: keeps the package able to run a -race shard and more parallel tests; removes the reason runAgent cannot be started twice in a process.
  • Cost: M, Risk: med, Census-touching: yes for production changes
  • Evidence: - Scale: internal/host declares about 296 package-level variables. About 60 are function-valued seams (for example internal/host/claimunit.go:20 readClaimUnitFile = os.ReadFile, internal/host/claimjournal_migration_linux.go:42 claimSystemctl, internal/host/claimunit_production.go:24 productionClaimUnitShapes). About 45 are process singletons set once by runAgent and read from loops: armed* and *Source atomics, for example internal/host/agent.go:4577-4607 (six atomic.Value sources), internal/host/group_admission.go:23, internal/host/movespass.go:244, internal/host/housekeeper.go:374, internal/host/rollout.go:60. - Test discipline holds. 610 t.Parallel() calls in 196 of 855 host test files. A scan of every top-level test that calls t.Parallel found none that assigns a package variable, and none that calls any of the 50 helper functions that swap one (plan9Fix2Systemctl, newAssemblyWorld, fastSweepRetries and so on). The scan is one call level deep; subtests and second-level helpers were not followed. - What blocks more parallelism is the environment and the logger, not the seams: 166 host test files use t.Setenv/os.Setenv because production code holds 248 os.Getenv references in 59 files (101 in agent.go), and 49 test files swap log.SetOutput (101 calls). - One latent race in a test helper: internal/host/caps_pass_test.go:121-129 captures the log into a bare bytes.Buffer and returns buf.String. Any goroutine still logging when the test reads it is a data race. internal/host/interactive_test.go:600-608 does the same job with a mutex. There are four more helpers of the first kind and 44 raw log.SetOutput(&buf) sites. - internal/lease keeps process state in globals that tests must reset: internal/lease/owed.go:74 (owed store), owed.go:81 (owedNow), internal/lease/self.go:12 (self), internal/lease/release.go:162 (finalSyncHook), internal/lease/health.go:62 (pauseLimitFor). That is why the package has no parallel tests.
  • Proposal: (a) now: one shared captureLog(t) with a mutex in a _test.go helper, used by all five helpers; (b) later, with finding 5: pass getenv down from runAgent (the package already does this in places: openDeployStoreEnv at internal/host/agent.go:5438); (c) do not try to remove the armed* singletons as a project. Fold a few into a struct only when runAgent is decomposed (finding 6). (d) When CI gets a -race run, start with internal/lease, internal/hostexec, internal/hostops and internal/instancectl: small, concurrent, cheap to run.

5. Context propagation and goroutine lifetimes

  • Verdict: do
  • Payoff: a hung store call stops stalling a box's convergence, heartbeat or metering until the next restart; loops become testable without sleeping; shutdown can wait for a pass instead of cutting it.
  • Cost: M, Risk: med, Census-touching: yes (body class for the loop functions that have rows: statusLoop, fastConvergeLoop, configGenLoop among agent.go's 63 rows)
  • Counts: 180 context.Background() in production code in the slice (host 157, lease 6, instancectl 6, hostexec 6, hostfiles 2, hostbox 1, hostguard 1, hostenv 1). No context.TODO(). agent.go has 30, rootrestart.go 16.
  • Fine, leave alone: - Process roots and one-shot commands: internal/host/agent.go:265 (agentCtx), internal/host/systemapply.go:131, internal/host/guardarm.go:86,90,102, internal/hostenv/cli.go:49, internal/instancectl/server.go:336. - Detached cleanup with its own bound: internal/host/claimstop_run.go:92,106 (30 s), internal/host/claimwakeassembly.go:314,338,554, internal/host/movescut.go:929 and :1504 (10 s), internal/lease/lease.go:235,583, internal/lease/release.go:227, internal/lease/ha.go:159 (5 s). - Deliberately independent cleanup: internal/hostexec/controller.go:115 and :282 (the comment at :112 says why: exclusion stays held until the cleanup joins, and the channel is buffered so the goroutine cannot leak). - The good idiom is already in the tree: internal/hostbox/renewing.go:85 uses context.WithTimeout(context.WithoutCancel(ctx), RequestLimit).
  • Wrong, class A: loops that run every pass on an unbounded context. Each is started with a bare go from runAgent (internal/host/agent.go:1030-1099) and can never be stopped or bounded (tunnel_client.go:46-48 gives its reason in a comment; the others do not): - adoptLoop, internal/host/agent.go:1702 (hourly release.Pass) - configSyncLoop, agent.go:1807 - configGenLoop, agent.go:2576 (every 3 s) - fastConvergeLoop, agent.go:3466 (the seconds-cadence converge) - domainsLoop, agent.go:4201 - instancesLoop, agent.go:4326 - retentionLoop, agent.go:4413 - statusLoop, agent.go:4719 (the heartbeat) - internal/host/usage_loop.go:65, internal/host/metrics_loop.go:892, internal/host/snapshot_loop.go:195, internal/host/steering_loop.go:230, internal/host/logship.go:52, internal/host/boxrecord.go:168, internal/host/memwatch.go:97, internal/host/edgesfile.go:1180 (edgesFileLoop), internal/host/housekeeper.go:472 (mintMeshKeyLoop), internal/host/tunnel_client.go:49 - agent.go:991: sd.runner.Start(context.Background()), with the comment "runs until the process ends, like every loop below".

Why it matters: release.newS3Store (internal/release/store.go:861, outside this slice) builds the client from the default config with no HTTP timeout, and nothing in internal/rootaws or internal/s3compat sets one. The code says so itself at internal/host/schedule_wiring.go:284-290: "a bucket that accepts a connection and then never answers would park the pass ... for as long as the process lives". That site got its own convergePassTimeout. The index poll got one at agent.go:3399 after amadan #336 finding 3 (internal/host/changeindex_test.go:382-386). The domains pass got one at agent.go:4236. The rest have none. Only three goroutines take agentCtx: agent.go:589, agent.go:1091 and the regional claims at agent.go:998.

  • Wrong, class B: callback signatures with no context, so the body reaches for Background() with no bound while taking a store lock: - internal/host/rootrestart.go:170,181,186,247 (checkedUnitRestart returns func(registry.Route) error; line 181 is s.Lock(...)), :315,335,356,358, :430,464,481,494,519, :548,566. The callers (release.Pass options) all hold a context. - internal/hostfiles/wake.go:85,96 (ImportWake has no ctx parameter and writes the registry). - internal/hostguard/admissionfence.go:40 (FenceView under Background() inside an admission check). - internal/host/systemapply.go:1364,1367 (layoutReversalReasons has no ctx; its caller chain starts from Run(ctx, ...) at :312). - internal/host/edgesfile.go:1272 (tick(context.Background()) on every timer tick).
  • Wrong, class C: inconsistent release. internal/host/movescut.go:912 and :917 release the staging lease with an unbounded context.Background(); the same lease is released with a 10 s bound at :929.
  • Related, the systemd seam has no context at all: internal/host/unitsettle.go:48-56 (unitSystem), implemented with bare exec.Command at unitsettle.go:61,105, internal/host/unitops.go:141,191,202, internal/host/agent.go:5190,5215,5337, internal/host/probes.go:45. 25 exec.Command against 19 exec.CommandContext in the slice. A systemctl that blocks holds whichever pass mutex its caller took (reconcileMu, configSyncMu, internal/host/agent.go:1834,2019).
  • Proposal, in order: 1. One helper, in internal/host: runLoop(ctx, name string, first, every func() time.Duration, budget time.Duration, pass func(context.Context) error). It derives a per-pass context.WithTimeout from the agent's context, logs a pass cut short, and returns when the context ends. Convert the class A loops one commit at a time, slowest cadence first. Budgets: copy convergePassTimeout's reasoning (minutes, far past a healthy bucket). 2. Pass agentCtx into them. Shutdown already has a deadline (agent.go:1295); cancelling the loops there is the same act. 3. Class B: add ctx as the first parameter of the restart callbacks when release's option types are next touched; until then wrap each body in one context.WithTimeout(context.Background(), ...) at the top instead of 16 separate Background() calls. 4. Class C: rel(context.WithoutCancel(ctx)) with the 10 s bound, as :929 does. 5. unitSystem: add ctx and use exec.CommandContext. Mechanical, about 30 call sites plus fakes.

6. Huge files

  • Verdict: agent.go do (inside the file first); systemapply.go don't
  • Payoff: fewer merge conflicts and smaller review diffs on the most-edited file in the repo. git log --since=2026-10-16: 349 commits repo-wide, 117 touch internal/host, 61 touch agent.go, 46 touch the lines of runAgent.
  • Cost: M, Risk: med, Census-touching: yes
  • Evidence: internal/host/agent.go:264, runAgent, is 1,089 lines. The next longest functions in the slice: edgesFileWriteClaims 468 (internal/host/edgesfile.go:567), ClaimWakeAssembly.Build 435 (internal/host/claimwakeassembly.go:186), runAdoptUnderRootRelease 353 (agent.go:5619). 153 functions are 100 lines or more, 21 are 200 or more.
  • Census constraint, which decides the plan: units are keyed by file path and unit name (checkRootReadDeclarations, internal/provision/plan14_root_reads_test.go:1790). agent.go has 63 base rows and appears in 35 overlays. Moving a row-bearing function to another file is a removal at the old key plus a new row at the new one, and AGENTS.md tells the reviewer to reject "if a removed or left unit moved rather than went". runAgent itself has no row, so cutting it into functions that stay in agent.go costs only the envelope re-pin.
  • Proposal: 1. Step one, no moves: cut runAgent into phase functions in agent.go, each taking and returning an explicit struct (line ranges approximate): openAgentState (registry, claims, judge: 264-430), buildActivator (430-860), startAgentSocket (860-930), startLoops (930-1100, the 25 go statements; this is where finding 5's helper lands), armEdge (the callback at 1176-1290), shutdownAgent (1292-1353). The struct replaces most of the closures over 1,000 lines of locals. 2. Step two, only after a moved class exists in census-propose (finding 7): split by concern. agent_config.go: configSyncLoop, syncExecSerialized*, pendingDirs, configAck*, genCache, genPollPass, configGenLoop, configGenTick (1796-2790). agent_fast.go: fastDeps and methods, fastTick, fastConvergeLoop, canary helpers (2791-3715). agent_status.go: the *Source atomics, statusLoop, statusTick (4538-5117). agent_restart.go: makeRestartRoute, systemctl*, agent*UnitRestart, bounceFn, wakeFn (5118-5415). agent_store.go: openDeployStore*, openStatusStore, resolveStatus* (5416-5593). adopt.go: RunAdopt and below (5594 to the end). What stays is runAgent and its phases, about 1,400 lines. 3. internal/host/systemapply.go (2,414 lines, 36 rows): leave it. It is one type (systemApplier) and one state machine, read top to bottom, and it is root's self-updater. A split buys nothing a reader needs and costs 36 unit moves.

7. Huge packages

  • Verdict: do later, and only behind a census moved class; do the small leaves first; do not start with moves
  • Payoff: internal/host is one compile unit of 125k lines importing 90 internal packages (154 imports in all; go list). A change to any of the 90 recompiles all of it and relinks a 256k-line test binary. Only the root package imports it. Subpackages would let an edit in moves* skip recompiling claim* and the reverse, and let the gate shard by package instead of by TEST_SPLIT (.amadan/test-gate.sh:36 deals ./internal/host=4). Not measured, since builds were out of bounds; expect the incremental test-binary build for a one-file change to drop roughly in proportion to the lines that leave.
  • Cost: L, Risk: high, Census-touching: yes, all of it. Every file of internal/host is in the root binary's graph, and so is every other package in this slice. internal/host holds 1,908 base rows.
  • Evidence, clusters by file-name prefix, with a token-level estimate of the boundary (top-level identifiers declared in one cluster and referenced from another; an estimate, not a type check):

| cluster | prod lines | files | base rows | idents it uses from outside | idents others use from it | |---|---|---|---|---|---| | moves | 31,523 | 57 | 402 | 96 (claim 46, core 20, system 12) | 96 (core 35, claim 25, relocat 21) | | claim | 26,841 | 157 | 512 | 96 (moves 25, root 23) | 202 (root 62, moves 46, relocat 46) | | root (not rootgeneration) | 9,414 | 63 | 226 | 132 (claim 62) | 98 | | relocat | 5,167 | 14 | 52 | 74 (claim 46, moves 21) | 15 | | rootgeneration | 3,629 | 19 | 96 | 30 | 15 | | ha | 2,747 | 10 | few | 15 (core 13) | 22 (core 16) | | run, interactive | 2,647 | 5 | 10 | 6 | 11 (core 10) | | metrics, alert, memwatch | 2,290 | 8 | 11 | 42 (core 34) | 22 | | demo | 2,113 | 10 | few | 7 | 12 (core 10) |

moves and claim reference each other (46 one way, 25 the other), so neither can leave without the other or without an interface layer between them. relocat sits on both.

  • Proposal: 1. First, tooling: add a moved class to make census-propose: when a unit's declaration digest is byte-identical at a new file key and absent at the old one, carry the row and its disposition, and print the pair on the card. Without it a 57-file move is 400 hand-written claims that the reviewer is instructed to reject. 2. Then the leaves, as a trial of the tooling, smallest boundary first: - internal/host/runs (run, interactive: 2.6k lines). API in: `New(cfg) Worker, Worker.Pass(ctx, recs), Shutdown(ctx). Needs from core: openDeployStore, dataDir, the judge. About 6 identifiers to inject or export. - internal/host/demo jobs (2.1k), same shape. - internal/host/hadeparture (ha*, 2.7k): Controller is already an exported type with ScanPass. 3. moves + relocat (36.7k lines, 454 rows) is the real prize and the real cost. It would need about 20 core helpers moved down into a small shared package (dataDir, readMachineID, writeFileDurable, syncDir, openBeneath, flockExclusiveNonblock, systemRootDir, systemPrevPath) and the claim boundary turned into the interfaces that already exist by name (ClaimMovesOwners, ClaimMoveReadAccess, MovesRecordReader). Do not schedule it until the leaves have shown what a move costs in census review rounds. 4. Not worth it: merging or re-cutting the 16 small host* packages. Their import graph is already a clean DAG (hostwrite, hostquarantine, hostfloor, instancefs at the bottom; hostops and hostrelocate at the top; nothing imports internal/host`).

8. Logging

  • Verdict: don't migrate; do add fixed keys only where a machine reads the line
  • Payoff of a migration: small. Cost: L, Risk: med, Census-touching: yes
  • Evidence: 924 log.Printf-style calls in the slice, 892 of them in internal/host; 2 slog references. What depends on the text: - 49 host test files capture the logger (101 log.SetOutput calls) and assert on substrings. - Operator runbooks published in the changelog grep for exact text: docs/site/changelog.json:5424 ('placement before exec failed') and :5808 ('agent: instance keys:', "must show 0 failed"). - The package has a de facto convention that works: a subsystem prefix (agent:, moves:, adopt:) and, where a line is meant for machines, a name code=value form (internal/host/agent.go:1298, ha_departure_stop code=deadline).
  • Proposal: keep log.Printf. When a line becomes an alert or runbook input, give it the name key=value form and pin it with a test, as the HA departure lines do. Fix the test helper race in finding 4 regardless.

9. panic and ignored errors

  • Verdict: don't (nothing to fix)
  • Evidence: 3 panic in production code in the slice. internal/hostops/effect_runner.go:219 and internal/hostops/ingest.go:87 re-raise a recovered panic after settling the journal, which is right. internal/instanceexec/probe.go:397 panics when crypto/rand fails, with a comment saying why a fallback would be worse. None is reachable by input.
  • log.Fatal: 123 in the slice, in entry points: internal/host/guardarm.go 37, agent.go 27, guardexec.go 13, claimstop_run.go 13. They are one-shot root commands and agent startup. Two in runAgent fire after defers are registered (agent.go:988, :999; the defer admission.Close() at :280 and defer cancelAgent() at :266 are skipped). Both are before the edge serves, so the cost is nil today. Worth knowing when runAgent is decomposed: have the phases return errors and let one place exit.

10a. Exported surface far larger than its use

  • Verdict: do
  • Payoff: staticcheck's unused check (U1000) skips exported names. With 560 exported declarations in internal/host and 23 used from outside, most of the package is invisible to it.
  • Cost: S to find, M to act, Risk: low, Census-touching: yes (renames change bytes; deletions are removed)
  • Evidence: the root package uses 20 names (host.RunAgent, host.RunAdopt, 13 other host.Run*, host.ResolveStatusBucket, host.BoxLabel, host.ReadPublicIP, host.ReadPlacementRegion, host.OpenDeployStore). Tests in internal/console, internal/edge and internal/sim/regionha use host.FleetBinding, host.WriteFleetBinding, host.ReconcileFleetBindings. go list shows no other importer.
  • Proposal: run deadcode ./... (golang.org/x/tools, whole-program reachability from main) once, in the same separate pass as staticcheck, and delete what it reports under internal/host. Do not mass-rename exported names to unexported: it changes every unit's bytes for no reader's benefit. Deleting dead units is the win.

10b. Repeated unix-socket client boilerplate

  • Verdict: do later
  • Payoff: one place to get deadlines, body limits and error text right.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: the same 15 lines (dial closure, one-shot http.Transport with DisableKeepAlives, NewRequestWithContext, client with no Timeout because the context carries it) appear at internal/host/claimlaunch_transport.go:43-58, internal/host/movesheldrelease.go:239-254, internal/host/rootexecution_transport.go:49-60, internal/host/claimstop_transport.go:148, internal/host/claimstop_writers.go:178, internal/host/claimretire_transport.go:281, internal/host/claimhandover_transport.go:155, and in a fuller form at internal/instancectl/client.go:85-128. All of them do bound the request through the context; no missing timeout was found. HTTP clients to the network all set Timeout (for example internal/host/agent.go:4130, internal/host/replicacoordinator.go:26).
  • Proposal: a small postUnixJSON(ctx, socket, path, in, out, limit) in one of the bottom packages, adopted as each transport is next edited.

10c. Manual lock and unlock on many return paths

  • Verdict: do later
  • Evidence: internal/host/movespaging.go:249-296 takes pageOutboxMu and releases it by hand on six paths, dropping and retaking it around delivery at :285-291; :394-431 has five. Every access to pageIndex that was checked is under the lock (:442, :490), so there is no bug today.
  • Proposal: split each into a locked inner function with defer and an unlocked delivery step. Small, and it removes the class of bug.

10d. Unbounded maps

  • Verdict: don't
  • Evidence: the log-once maps are keyed by host or alias and are deleted on recovery (internal/host/aliassocket.go:90, internal/host/edgesfile.go:773). Two only ever grow: internal/host/logship.go:229-243 (unshippableSeen, keyed by family and app) and internal/host/relocationsweep.go:25-28 (relocationStraySaid, keyed by path). Both are bounded by what one box hosts between restarts.

10e. Test files named after plans and fix rounds

  • Verdict: don't rename (census witnesses and J4 name them); note for new work
  • Evidence: 185 host test files (33,933 lines) are named plan9*, plan11*, plan14* and similar, for example internal/host/plan14_restart_consumption_test.go. A reader looking for the tests of rootrestart.go will not find them by name.
  • Proposal: name new test files after the production file they cover.

Bugs found along the way

  • internal/host/movesfiles.go:721-722 and :747-748: if err != nil || !found { return nil, fmt.Errorf("...: %v", err) }. When the manifest is simply absent (found == false, err == nil) the operator reads "the prepared files manifest k@v: <nil>". The two cases need two messages. It also flattens a context error with %v.
  • internal/host/haplacement.go:17: _ = page(...) for "Region needs more capacity". A failed page leaves no trace anywhere. The sibling at internal/host/agent.go:3953-3955 logs the failure. One log.Printf fixes it.
  • internal/host/movescut.go:912 and :917: the staging lease is released with context.Background() and no bound on the two error paths, while the normal path at :929 uses 10 s. A store that hangs at that moment hangs the cut's goroutine with the lease's renewer state behind it.
  • internal/host/movespass.go:1680-1684: movingStatusNudged is unused and its comment describes behaviour implemented by w.nudged (movespass.go:84, :1572). Misleading to a reader checking that the "one nudge per host per process" guard exists. Note the guard changed meaning in the move: it is now per worker and is cleared on completion (movespass.go:1646), which is the better behaviour.
  • internal/host/caps_pass_test.go:121-129: log capture into an unsynchronised bytes.Buffer, read with buf.String while background goroutines may still log. A real data race the day a -race run exists; internal/host/interactive_test.go:600-608 shows the fix.
  • internal/host/claimrecovery_remote.go:108: err == hostbox.ErrChanged drives a retry loop. Correct today, because nothing on the path wraps; other code in the same package does wrap this sentinel with %w (internal/host/movesfiles.go:718). Use errors.Is.
  • Not a bug, a gap to confirm outside this slice: internal/release/store.go:861-873 builds the S3 client with no HTTP or per-request timeout. Every unbounded context in finding 5 depends on that client returning. Whoever audits internal/release should confirm, and a default per-operation deadline there would shrink finding 5 to shutdown behaviour only.
Agent notes

Full Fable audit report: activator-edge (read against 5b6d5374; line numbers have moved since).

Audit: internal/activator, internal/edge and the small edge packages

Scope: internal/activator (43.9k production lines, 96.9k test lines, 1,836 tests), internal/edge (33.7k / 78.5k, 1,569 tests), and edgeguard (830), edgeproof (160), edgesfile (1.5k), assetcache (1.5k), certwarm (189), hairpin (769), lbhealth (200). No Go subpackages exist under activator or edge (only testdata). All nine packages are in the root binary's go list -deps . graph, so every change below is census-touching unless it is test-only.

Method: read-only, grep and reading. Nothing was built or run, so timing claims are sums of literal sleeps, not measurements. Every file:line below was read.

Summary

The code in this slice is careful. Context use, panics, error wrapping and static-analysis hygiene are in good shape, and most of the checklist comes back "leave it". The three things most worth doing:

  1. Harden the request path's HTTP plumbing (finding 10a-10d). The public servers have no IdleTimeout; every registry reload throws away every unix/TCP upstream connection pool; the unprobed TCP proxy dials remote upstreams with no timeout; the wake health wait leaks a polling goroutine for up to 30 s (120 s for rootfs) after a cancelled wake. Each is a few lines.
  2. Take about 35 s of pure sleeping out of the edge tests and shard the two packages (finding 3). Two seams already exist (Edge.watchTick, haFiles.platformEvery) and are not used by the slow tests; one constant (holderHeaderSuspectAfter) needs a seam. Neither package is in TEST_SPLIT or test-weights.tsv, and edge runs 1,538 of 1,569 tests serially.
  3. Move the handful of names the console needs out of activator and edge (finding 7). internal/console links 78k lines of activator + edge for two prefix helpers, two unit-name helpers, ConfigFromEnv, the layout classifier and FleetArmVerdict.

Not worth doing in this slice: a slog migration (finding 8), a mechanical %w sweep (finding 2), splitting activator into subpackages (finding 7), and any context "cleanup" of the 80 context.Background() sites in activator (finding 5), which are almost all deliberate and bounded.

One bug found: a throttled-log map keyed by a request-supplied hostname (see the last section).

Findings

1. Static analysis gate

  • Verdict: don't (nothing slice-specific to do beyond the repo-wide pass)
  • Payoff: small. This slice is clean by grep.
  • Cost: S, Risk: low, Census-touching: yes (any fix edits files in scope)
  • Evidence: - No ioutil, rand.Seed, strings.Title, .Temporary() in production code. 4 os.IsNotExist-style calls, 5 nolint comments, 2 init() (internal/edgeguard/catalogue.go:124, internal/edge/edge.go:4029). - 122 _ = f() lines and 15 _, _ =. The large groups are legitimate: 23 os.Remove, 18 a.persistGenerations (it logs and marks itself dirty for the sweep, internal/activator/generations_file.go:307-310), deadline setters and best-effort closes. - == against sentinel errors, 10 sites, all on errors that the standard library returns unwrapped: internal/edge/edge.go:4645, :4834, :4841 (http.ErrServerClosed), internal/edge/sse.go:44, :101, internal/edge/static.go:561, :1065, internal/edge/devboxfront.go:99, internal/edge/demo_banner.go:62, internal/activator/seedplace.go:530 (io.EOF). Correct today; switch to errors.Is only if a linter is turned on that demands it.
  • Proposal: nothing beyond whatever the separate staticcheck run reports.

2. Error wrapping

  • Verdict: do one small thing (the ALERT: prefix), don't sweep the rest
  • Payoff: removes one way to silently lose an alert classification.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: - 23 fmt.Errorf(... %v ..., err) in the slice. 14 are in the wildcard ACME order (internal/edge/wildcard.go:665, :669, :674, :691, :695, :699, :708, :711, :724, :760, :778, :781). No caller uses errors.Is/As on that path today: the retry at internal/edge/wildcard.go:549 only checks errNoZone. So nothing is broken. The latent cost: the per-host warm path classifies a CA rate limit with errors.As(err, &ae) (internal/edge/certwarm.go:614) and backs off harder; the wildcard path cannot, because %v has flattened the *acme.Error, so a rate-limited wildcard order retries hourly. - The others are leaf messages where the cause is deliberately a string: internal/edge/prober.go:531, :542 (the reason shown on the dashboard), internal/activator/backend_exec.go:3679, :2964, internal/activator/backend_unit.go:273, internal/edge/static.go:555, :565, internal/edge/headers.go:198, internal/edge/dns.go:127, internal/edgeguard/catalogue.go:240, internal/activator/hafiles.go:274. - String matching on error text, 2 sites, both the same idiom: strings.HasPrefix(err.Error(), "ALERT: ") at internal/activator/escrow.go:1364 and :1572. The errors are minted at internal/activator/escrow.go:496, :960 and :1235. Any future fmt.Errorf("x: %w", err) between mint and check turns an alert into an ordinary hourly-throttled line (:1572) or sends it down a different switch arm (:1364), with no test failing unless it covers that exact wrap.
  • Proposal: add type escrowAlert struct{ msg string } (or a sentinel wrapped with %w), mint the three errors through it, and replace both prefix checks with errors.As. Change internal/edge/wildcard.go:674, :695, :778, :781 to %w only when someone adds rate-limit handling to the wildcard retry; otherwise leave them.

3. Sleep-based tests

  • Verdict: do (the named offenders and the shard config); do later (a wider synctest move)
  • Payoff: roughly 35 s of serial wall time out of the edge package and 10 s out of activator from seven tests, plus whatever sharding buys. Fewer timing flakes on a loaded runner.
  • Cost: S for the named tests, S for sharding, L for a general synctest move. Risk: low. Census-touching: no for test-only edits; yes for the one production seam (holderHeaderSuspectAfter).
  • Evidence, counts: - time.Sleep in tests: activator 210, edge 113, assetcache 1, the other six packages 0. Literal sleeps sum to about 45 s in edge and 32 s in activator (static sum; loops and subtests multiply it, parallel tests divide it). - t.Parallel(): activator 461 of 1,836 tests; edge 31 of 1,569. Edge tests are held serial by process globals: 162 t.Setenv, 53 log.SetOutput. - testing/synctest is already used in four files: internal/edge/visitor_test.go, internal/edge/devboxfront_test.go, internal/edge/heldstream_sim_test.go, internal/activator/rootfsrelease_test.go. - .amadan/test-weights.tsv has rows for the root package, internal/console and internal/host only; .amadan/test-gate.sh:36 splits only those three. There is no measured per-test time for this slice.
  • Evidence, the slowest offenders I can identify: - internal/edge/lbhealth_test.go:301 and :333: time.Sleep(5 * time.Second) to let the 2 s registry watch tick a couple of times. wedgedProbe runs twice (:350, :356), so this is 15 s. The seam to drive ticks by hand already exists: Edge.watchTick (internal/edge/edge.go:439, read at :3411) and is used by internal/edge/reload_serial_test.go:185. Also :178 (1.2 s). - internal/edge/forwardha_service_test.go:59, :135 and internal/edge/forwardha_test.go:1532: time.Sleep(3200 * time.Millisecond), at least five executions counting subtests, plus internal/edge/forwardha_test.go:1593 (2.8 s). All wait out holderHeaderSuspectAfter, a const of 3 s at internal/edge/forwardha.go:332. About 19 s. - internal/activator/harelease_test.go:490, :495 (1.5 s each), :707 (1.2 s) and internal/activator/hasamebox_test.go:248 (1.2 s), :268 (0.5 s, five times): all wait for "the publisher's pass", which ticks at haPlatformEvery = time.Second (internal/activator/hafiles.go:42, ticker at :359). The interval is already a field that internal/activator/hafiles_test.go:268 sets to 100 ms. About 8 s. - internal/activator/wakecheck_test.go:586: a fake that sleeps 5 s inside a callback. The assertion ends at 400 ms, but the goroutine lives 5 s past the test. - internal/activator/rootfsrelease_test.go:1139 (1.5 s) and :2080, :2166, :2186, :2222 (0.3 s each); internal/activator/activator_test.go:4142 (0.7 s), :4252, :4344, :6563 (0.3 s each).
  • Classification of a sample of 40: - Negative waits ("nothing more happens for N ms"): the largest group in activator, for example internal/activator/heldstream_e2e_test.go:611, internal/edge/burst_notice_test.go:583. These slow the suite and can pass falsely on a slow box, but cannot be made faster without a fake clock. - Waiting for a real ticker or timer with a fixed sleep: the offenders above. Flake risk and slow. - Poll loops with a short sleep and a generous deadline (internal/edge/prober_test.go:20, internal/activator/activator_test.go:977): fine. Leave them.
  • synctest candidates: tests that use only fakes and timers. The held-stream simulator already does this. Good next candidates are the activator tests built on fakeBackend with no socket or subprocess (the wake wait bound, first-wake extension and sidecar join tests around internal/activator/wakecheck_test.go:577 and internal/activator/stop_returned_sidecar_test.go:95, :150). Not candidates: anything in edge that uses httptest.NewServer (239 uses), a unix socket, or exec.Command (51 uses in activator).
  • Proposal: 1. lbhealth_test.go: set e.watchTick and send two ticks instead of sleeping 5 s. Test-only. 2. Make holderHeaderSuspectAfter a field on the forwarder (or a package var with a shrink helper like clientGoneGrace, internal/edge/answered.go:76) and run the five tests at 100 ms. 3. In haServiceEntry-based tests, set platformEvery to 50 ms as hafiles_test.go:268 does. 4. Run .amadan/test-weights.sh over ./internal/activator and ./internal/edge, commit the rows, and add both to TEST_SPLIT (.amadan/test-gate.sh:36). Sharding by process sidesteps the t.Setenv/log.SetOutput globals that keep edge serial. 5. Later: move fake-only timing tests to synctest as they are touched.

4. Data races and globals

  • Verdict: do later
  • Payoff: lets a -race run and more t.Parallel be trusted in activator.
  • Cost: M, Risk: low, Census-touching: yes
  • Evidence: - Single-line package vars in production: activator 174, edge 57. Of those, 18 in activator and 12 in edge are durations or functions that exist to be swapped by tests, for example internal/activator/activator.go:1208 (wakeWaitBound), :943 (sidecarSettle), :1213 (wakeBoundExtended), internal/activator/wakecheck.go:56 (heldPoll), internal/activator/backend_exec.go:48 (spawnHealthTimeout), :484, :504, internal/activator/rootfs_service.go:380, :850, internal/activator/claimwake.go:405, internal/edge/assetcatch.go:39, :193, :198, internal/edge/certsync.go:251, :424, :429, :435, :1987, internal/edge/forwardha.go:148. - Tests swap them through about 20 shrink*/set* helpers with t.Cleanup restore (internal/activator/wakecheck_test.go:29, :39). About 40 direct assignments to these globals in activator tests. - I found no test that both calls t.Parallel() and a shrink helper, so the convention holds, but only by convention: nothing fails if someone adds t.Parallel() to a test that shrinks a global. The remaining race is a goroutine that outlives its test and reads the global while the cleanup writes it. The changelog records exactly that once (docs/site/changelog.json:1208, "shrinkFirstWake's cleanup races the first-wake watch goroutine under -race"). - Process-wide log.SetOutput in tests: 28 in activator, 53 in edge.
  • Proposal: when a seam is next touched, move it onto Config/Service (or Edge) as a field with the current value as default, as HeldTarget and platformEvery already are. Start with the four that parallel-capable wake tests need: wakeWaitBound, heldPoll, sidecarSettle, spawnHealthTimeout. Add a one-screen guard test that fails when a test function contains both t.Parallel() and a shrink* call, so the convention is enforced before a -race job exists.

5. Context propagation

  • Verdict: don't sweep; fix the two functions that have no context at all
  • Payoff: cancelled wakes stop doing work; shutdown is not held by sleeps.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence, the count: 80 context.Background() in activator production code, 27 in edge, 0 in the small packages.
  • Fine (the large majority, with reasons in place): - Stop, cleanup and release paths that must outlive the request that triggered them, each under its own timeout: about 60 sites of the form context.WithTimeout(context.Background(), actStopTimeout), for example internal/activator/activator.go:4381, :4912, :5031, internal/activator/opset.go:211, :215, internal/activator/claimwake.go:379, :483. - The wake, detached from the first requester on purpose and bounded by wakeCeilingFor (internal/activator/activator.go:2062-2072). - Settle proofs that "bound themselves" (internal/activator/cmd.go:248, internal/activator/rootfsworkers.go:502), and the shutdown-aware proof parent (internal/activator/containment.go:114-120). - Lifetime contexts and startup: internal/activator/activator.go:1660, internal/edge/prober.go:254, internal/edge/edge.go:4652, :4685, :4706, :4880, internal/edge/dns.go:69. - The replica key read looks unbounded at internal/activator/replicakey.go:132 but each read is wrapped in a 10 s timeout (internal/activator/instancekey.go:203, :217).
  • Worth changing: - waitHealthy and waitHealthyAddr take no context (internal/activator/backend_exec.go:3660, internal/activator/backend_unit.go:254). Their Ctx wrappers start a goroutine and abandon it on cancel (internal/activator/backend_exec.go:3699-3708, internal/activator/backend_unit.go:276-285). See finding 10d. - internal/activator/activator.go:4108: WakeWorker waits on a wake with context.Background() although it used a.lifeCtx twenty lines earlier for the startup wait (:4029). Bounded by the wake timer, so low value; use a.life() for consistency when next there. - Sleeps that ignore a context they hold: internal/edge/route53dns.go:206 and internal/edge/wildcard.go:1003 (time.Sleep(3 * time.Second) inside a loop that checks ctx.Err() only between sleeps). A cancelled issuer holding waits up to 3 s more. Replace with a select on ctx.Done() and a timer.
  • Proposal: thread ctx into the two health waits and the two DNS waits. Leave the rest.

6. Huge files

  • Verdict: do later, and only alongside real work in the file
  • Payoff: cheaper reviews and fewer merge conflicts in the three files most branches touch. No build or test win: same package.
  • Cost: M (see the census note), Risk: low, Census-touching: yes
  • Census note, the real cost: the census keys units as <file>:<unit> and pins whole file bytes. A pure move of a function to another file shows up as a removed unit plus a new unit, and the reviewer brief rejects "a removed or left unit moved rather than went" unless it is claimed and checked. So a split of activator.go or backend_exec.go is a census card with dozens of rows and a full review round, for no behaviour change. That is why this is "do later".
  • Evidence, files over 2,000 lines: internal/activator/activator.go (6,661), internal/activator/backend_exec.go (3,922), internal/edge/edge.go (4,975), internal/edge/certsync.go (2,083). Test files: internal/activator/activator_test.go (7,353).
  • Inside them, the functions are the larger problem: - Edge.ServeHTTP is about 800 lines (internal/edge/edge.go:1940-2740). - Edge.Reload is about 610 lines (internal/edge/edge.go:866-1479). - Service.doWakeOnce is about 900 lines (internal/activator/activator.go:2501-3400). - Service.sweepOnce is about 590 lines (internal/activator/activator.go:5432-6020). - Service.respawnWorkerLocked about 330 (:4297), Service.stop about 300 (:4727), Service.wake about 300 (:2058).
  • Proposal for internal/edge/edge.go (same package, by concern): - edge.go: Edge, options, New, Enable*, lookup helpers (lines 77 to 865 and 1479 to 1940). - reload.go: Reload, OnReload, runReloadHooks, Watch (866 to 1530, 3402 to 3477). - serve.go: ServeHTTP, unknownHost, httpFallbackHandler, held-mark helpers (1940 to 2870, 3294 to 3400). - cachepolicy.go: maybeStore, the Vary and Cache-Control parsers, recordingResponseWriter (2872 to 3293). These are pure functions and the cheapest, safest first cut. - proxies.go: unixProxy, tcpProxy, multiProxy, tunnelProxy, fleetProxy, dial retry (3489 to 4028, 4496 to 4505). - backhaul.go: the backhaul admission, transport and proxy (4029 to 4495). - run.go: Run*, enable*FromEnv, envOr (4506 to 4975).
  • Proposal for internal/activator/activator.go: - config.go: Config, ConfigFromEnv, HibernatePrefix (100 to 187). - interfaces.go: Backend, DueStore, Lease, Rep, Proc and the lease release retry (188 to 480). - entry.go: actState, actEntry (482 to 897; the struct alone is 410 lines). - sidecar.go: the sidecar stop, stray and replace code (902 to 1190, 3616 to 3830). - request.go: begin, beginRequest, awaitWake, releaseFunc, ServeHTTP, serve, serveWakeError (1738 to 2050, 6372 to 6660). - wake.go: wake, doWake, doWakeOnce (2058 to 3400). - worker.go: WakeWorker through setWorkerToken (3938 to 4726). - stop.go: stop, finishStop, pending-stop retry (4727 to 5340). - sweep.go: Start, sweepOnce, RetireExcept (5341 to 6126). - shutdown.go: Shutdown and the exit logs (6127 to 6371).
  • Proposal for internal/activator/backend_exec.go: exec_strict.go (556 to 793), exec_restore.go (816 to 1126), exec_seed.go (1127 to 1939), exec_gen.go (2136 to 3007), exec_env.go (3027 to 3293), exec_sidecar.go (3294 to 3640), health.go (3645 to 3708).
  • internal/edge/certsync.go: leave it. It is one concern (the certificate mirror) and barely over the line.
  • Before any split: break doWakeOnce and ServeHTTP into named steps in place. That is where review time goes, and it needs the same census card the split would.

7. Huge packages

  • Verdict: do (a small leaf package for what the console needs); do later (lift the certificate cluster out of edge); don't (subpackages inside activator)
  • Cost and risk per part below. Census-touching: yes, all of it.
  • 7a. Console's dependency on activator and edge. Verdict: do. Cost M, risk low. - Evidence: internal/console imports activator and edge directly and reaches activator again through internal/dbreads and internal/layout. What it actually uses: - activator.UnitName, activator.ExecName (internal/console/metricsview.go:889-890, internal/console/usageattrib.go:143, :146), defined as one-liners at internal/activator/backend_unit.go:71 and :78. - activator.ConfigFromEnv (cmd/console/main.go:1819, internal/ops/ops.go:276), activator.HibernatePrefix and activator.MovesPrefix (internal/activator/activator.go:167, internal/activator/backend_exec.go:3800). - internal/layout uses activator.Classify and the Layout* names, all from the 128-line internal/activator/layout.go:19-95. - edge.FleetArmVerdict and edge.FleetServed (internal/console/apiinstances.go:283, :426), defined at internal/edge/fleetforward.go:230 and :261. - So the console's largest-in-repo test package (87 weighted tests, 8 shards) compiles and links 78k lines, the ACME client, the Route 53 SDK and x/net/http2, and has its test cache invalidated by every activator or edge change, for about ten small names. - Proposal: a leaf package (say internal/actnames) holding Config, ConfigFromEnv, HibernatePrefix, MovesPrefix, UnitName, ExecName, and the layout classifier; and move FleetArmVerdict with its types into a small package beside edgesfile (it takes routes and owners and returns a verdict; check its helpers first, in particular foldPlatformAliases). Keep type aliases in activator and edge so no caller outside console changes. Nothing new becomes exported that is not exported today. - Win: internal/console, internal/dbreads, internal/layout, internal/ops stop depending on activator and edge. Console test binaries get smaller and stay cached across activator/edge-only branches. I cannot put a number on it without a build.
  • 7b. The certificate cluster in edge. Verdict: do later. Cost L, risk med. - Evidence: certsync.go, wildcard.go, certwarm.go, certsweep.go, certsettle.go, dns.go, route53dns.go are 4,990 production and 8,338 test lines. They have 6 methods on *Edge between them and read about ten Edge fields (issuer, homes, staticStore, contends, deploymentHosts, steeringHost, reg, lbHealth). dns.go and route53dns.go reference Edge not at all. - API of an edgecert package: a constructor taking an interface with DeploymentHosts() []string, Homes(), the issuer gate and the store; it returns the autocert.Cache wrapper, the GetCertificate function and the challenge handler that RunWithActivatorReady wires today (internal/edge/edge.go:4708-4803). - Win: 8k lines of tests run as their own package beside the edge package instead of inside its serial run, and the Route 53 SDK leaves the edge package's own compile. Sharding (finding 3) gets most of the test win for far less work, so do that first. - Other files with no reference to Edge that could leave cheaply but are too small to matter: prober.go (613), redirects.go (482), compress.go (351), static_trees.go (274), sse.go (134).
  • 7c. Subpackages inside activator. Verdict: don't. - Evidence: 396 methods on *Service and 293 on *ExecBackend. The clusters by file prefix are large (ha: 17 files, 5.4k lines; rootfs: 7 files, 4.3k lines with 20.8k test lines; swap 1.6k; wake 1.6k) but they are not separable: the ha files hold 42 Service and 54 ExecBackend methods and take a.mu 24 times; rootfs 67 and 20, and a.mu 32 times. Everything shares one mutex and the 410-line actEntry (internal/activator/activator.go:490-897). - A split would mean exporting the entry, the lock discipline and dozens of methods, in the package with the most census units. High risk, no behaviour gain. - What is separable is small: escrow*.go (1.9k lines, 40 ExecBackend methods, 2 Service methods, no a.mu) and leaf files with no reference to either struct (hacache.go 511, coordinator.go 322, servingretry.go 285, admintoken.go 265, logsink.go 250). Not worth a census round on their own.

8. Logging

  • Verdict: don't migrate; do later for a few machine-read lines
  • Payoff of a migration: low. Cost: L. Risk: med. Census-touching: yes.
  • Evidence: - 326 log.Print* calls in activator, 166 in edge, 16 in edgesfile, 1 in edgeproof. One slog use (internal/edge/storedoor.go). - Log text is load-bearing here. 81 log.SetOutput captures across the two test suites assert on wording. Operator instructions quote lines verbatim: docs/region-ha-runbook.md:51 ("edge: wildcard certs on, serve only ..."), and release notes tell operators to grep the journal for exact phrases (docs/site/changelog.json:5424, :5808). Six test files outside the slice match activator:/edge: lines, for example internal/host/region_ha_g2_pool_root_linux_test.go and internal/rollout/rootfs_release_outcomes_test.go. - The lines are written as sentences for a person reading journalctl, with the reason and the next step in them. That is worth more to this project's operators than key=value pairs, and there is no log pipeline in infra/ that parses them (no metric filters; I looked for filter_pattern and metric_filter and found none).
  • Proposal: keep log.Printf. If a consumer appears that needs fields (wake timing, the "woke in" line), emit that one event as a second structured line or through the existing event sink (emitEvent) and leave the prose alone.

9. panic and ignored errors

  • Verdict: don't
  • Payoff: none; all 11 are correct.
  • Cost: n/a, Risk: n/a, Census-touching: n/a
  • Evidence: - Build-time invariants over embedded data, run from init or a package-level initialiser, covered by the package's own tests: internal/edgeguard/catalogue.go:127, :130, :134, :138, internal/edge/plandisabled.go:52, internal/edge/pending.go:154. - panic(http.ErrAbortHandler), the standard way to abort a response: internal/edge/assetcatch.go:581, internal/edge/demo_traffic.go:532, internal/edge/storedoor.go:270. - Re-panics after cleanup in a recover: internal/edge/assetcatch.go:736, internal/edge/demo_traffic.go:246. - None is reachable from request input other than as the intended abort. - The one place a proxy runs off the server's own goroutine has a recover (internal/edge/heldstream.go:611-618). - 14 log.Fatal* in production, all in Run* startup or listener failure (internal/edge/edge.go:4545-4660, :4816-4842). Fine.

10. Other: the request path's HTTP plumbing

10a. Public servers have no IdleTimeout

  • Verdict: do
  • Payoff: idle keep-alive and idle HTTP/2 connections stop being held open for as long as the client likes. Today a client can complete one request and then hold the connection, its goroutine and its TLS state indefinitely; ReadHeaderTimeout only starts once the next request's first byte arrives.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: internal/edge/edge.go:4808-4809 (the :80 and :443 servers), :4630 (dev), internal/edge/door.go:201, internal/edge/devbox.go:225-233 set only ReadHeaderTimeout. With IdleTimeout and ReadTimeout both zero, net/http applies no idle limit. The comments explain why ReadTimeout/WriteTimeout are off (WebSockets); that reasoning does not apply to IdleTimeout, which never touches a hijacked or in-flight connection.
  • Proposal: IdleTimeout: 120 * time.Second on the public and door servers (keep it under the load balancer's own idle timeout where there is one). Add ReadHeaderTimeout to the control listener at internal/edge/purge.go:159, which has no timeouts at all (unix socket, local callers, so low priority).

10b. Every reload rebuilds every upstream transport

  • Verdict: do
  • Payoff: a registry change for one route stops costing every other route on the box its connection pool. Fewer re-dials after each reload, and no pile of orphaned pools waiting out their 90 s idle timeout.
  • Cost: S to M, Risk: med (reload is delicate), Census-touching: yes
  • Evidence: Reload builds a new httputil.ReverseProxy with a new http.Transport for every socket and address route on every pass: internal/edge/edge.go:1098 (unixProxy), :1130, :1143 (tcpProxy), :1150 (multiProxy); the transports are constructed at :3505-3514 and :3528-3532. Nothing reuses the previous map's proxy and nothing calls CloseIdleConnections on the ones dropped; the only such calls in the package are for the prober and the generation pools (internal/edge/prober.go:471, internal/edge/genproxy.go:178, :194). The comment at :3509-3511 shows the leak was noticed and bounded with IdleConnTimeout, not removed. Watch reloads on any fingerprint change (internal/edge/edge.go:3438-3449).
  • Also: unixProxy and tcpProxy set MaxIdleConns: 32 but leave MaxIdleConnsPerHost at the default 2, and each has exactly one host. The backhaul transport's own comment describes this limit and sets 32 for itself (internal/edge/edge.go:4380-4389). A tenant with more than two concurrent requests re-dials its socket constantly.
  • Proposal: keep a map[key]*http.Transport on Edge keyed by socket path or address, as backhaulTransports and genPools already do; reuse on reload; call CloseIdleConnections on transports whose key left the map. Set MaxIdleConnsPerHost equal to MaxIdleConns on both.

10c. The unprobed TCP proxy dials remote upstreams with no timeout

  • Verdict: do
  • Payoff: a black-holed remote upstream fails in seconds instead of the kernel's connect timeout (about two minutes on Linux), during which every request to that route holds a goroutine and a client connection.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: internal/edge/edge.go:3528-3532 sets DialContext: hold.dialer, which is nil in production (the comment at :3525-3526 says so), so the transport falls back to a zero net.Dialer. The retry wrapper is applied only for a local upstream (:3533-3543). Compare multiProxy, which bounds each attempt with multiDialTimeout (:3702-3708), and the backhaul, which uses backhaulDialTimeout (:4359).
  • Proposal: default to (&net.Dialer{Timeout: multiDialTimeout}).DialContext in tcpProxy when hold.dialer is nil.

10d. The wake health wait leaks a polling goroutine and a connection

  • Verdict: do
  • Payoff: a cancelled or timed-out wake stops probing. Today the probe keeps sending GET / to the instance's socket path every 50 ms for up to 30 s (spawnHealthTimeout, internal/activator/backend_exec.go:48) or 120 s for a rootfs row (internal/release/rootfs.go:47 via internal/activator/rootfs_service.go:38-43), and a retried wake binds the same path, so the stale prober's requests land on the new process.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: - waitHealthyCtx runs waitHealthy in a goroutine and returns on ctx.Done() without stopping it (internal/activator/backend_exec.go:3699-3708). Its own comment says the opposite: "so an aborted wake doesn't keep probing a socket nobody wants anymore" (:3697-3698). waitHealthyAddrCtx is the same (internal/activator/backend_unit.go:276-285). - The loops sleep with time.Sleep(poll) and build requests with client.Get, so there is nothing to cancel (internal/activator/backend_exec.go:3664-3678, internal/activator/backend_unit.go:259-272). - socketClient builds a new http.Transport per call with keep-alives on and no IdleConnTimeout (internal/activator/backend_exec.go:3645-3654). Each health wait and each NextDueVia call (internal/activator/backend_exec.go:1965) leaves one idle connection and its two goroutines open until the instance closes its end.
  • Proposal: give waitHealthy/waitHealthyAddr a ctx, use http.NewRequestWithContext, and replace the sleep with a select on ctx.Done(); delete the two wrappers. Set DisableKeepAlives: true in socketClient (one request per client is the only use).

10e. God structs

  • Verdict: don't act on it directly; it is the reason for 6 and 7c
  • Evidence: Edge is a 325-line struct (internal/edge/edge.go:116-440), Service 365 lines (internal/activator/activator.go:1269-1634), actEntry 410 lines (:490-897), ExecBackend 335 lines (internal/activator/backend_exec.go:79-414). The field comments are thorough, which is what keeps them workable.
  • Proposal: when a concern is next extended, group its fields into a named sub-struct (as e.held, e.probers, e.genPools already are) instead of adding top-level fields.

Bugs found along the way

  1. A throttled-log key is built from the request's Host, so a remote party can grow the map and the journal without bound. internal/edge/plandisabled.go:80 calls e.logThrottled("plan-disabled "+host, ...). host is the request's own host (internal/edge/edge.go:1944, passed at :2369), not the route's. A one-label catch-all route matches any label under its parent (internal/edge/edge.go:1693-1696), and the predicate answers true for every such host once the route's own host is disabled (internal/host/plans_pass.go:255-256) or the *.parent entry is (:265-266). So for an account turned off after a lapse that has a catch-all, each distinct invented subdomain adds a permanent map entry and writes one journal line (the first occurrence always logs, internal/edge/edge.go:1524). logThrottled's own contract forbids this: "Keys must be built from values the box itself controls ... never from remote input" (internal/edge/edge.go:1513-1515). Low severity (it needs a disabled account with a catch-all), cheap fix: key on rt.Host.
  1. waitHealthyCtx does not do what its comment says. See 10d: internal/activator/backend_exec.go:3697-3708 and internal/activator/backend_unit.go:276-285. The probe outlives a cancelled wake by up to 30 s (120 s for rootfs) and can hit the next wake's process on the same socket path.
  1. Escrow alerts are recognised by string prefix. See finding 2: internal/activator/escrow.go:1364 and :1572 match "ALERT: " at the start of err.Error(). Not wrong today; one wrap away from being wrong.
  1. A test goroutine sleeps 5 s past its test. internal/activator/wakecheck_test.go:586. Harmless to correctness, but it is a goroutine that reads package globals after the test's cleanup has restored them, which is the shape of the race recorded at docs/site/changelog.json:1208.
Agent notes

Full Fable audit report: root-repo (read against 5b6d5374; line numbers have moved since).

Audit: root package main, cmd/*, repo-wide organisation and tooling

Measured on main at 5b6d5374, 2026-11-16. Read-only: go list, grep, wc, git log. No builds, tests or analysers were run. Every file:line below was read.

Summary

The three things most worth doing:

  1. Widen the gate at almost no cost. 114 test files (33,956 lines, 109 of them in internal/host) carry //go:build linux && rootrunner and nothing in Makefile or .amadan/ ever compiles or vets them. Adding the tag to the existing go vet ./... type-checks them for free. Then add staticcheck (bug checks only, with a baseline), govulncheck, gitleaks and a small targeted -race step, as the sibling rastrillo repo already does, plus a toolchain pin so laptop and CI agree.
  2. Make CLI commands return errors instead of calling log.Fatal. The root package has 954 log.Fatal and 110 os.Exit calls in production code; 223 of 235 run* commands return nothing. That is why tests re-execute themselves, shell out 142 times, and cannot observe refusals in process. Nine commands already use the right shape (runXWithSession(ctx, sess, args, out) error). Make that the rule and convert on touch.
  3. Split the bucket store out of internal/release. release is 23,597 lines and is imported by 61 packages, most of which want only the 5-method Store interface. Because release imports registry (SQLite), every one of them links SQLite, the registry and the adoption pass. A leaf store package fixes the largest layering problem in the repo.

Not worth doing:

  • Moving the CLI from the root package into internal/cli. No build or test win by itself, a large census bill, and the premise (the e2e tests compile the binary many times) is no longer true. Details in A1.
  • A slog migration, threading context through the CLI or the registry, and chasing %w in CLI error text. None has a caller that benefits today.

Import cycles are not being dodged with globals or callbacks. They are dodged with small leaf packages and with hand-copied "twins" pinned by tests (10.3). That is disciplined, but the twins point at where a shared leaf package is missing.

Findings

A1. Moving the CLI out of package main into internal/cli

  • Verdict: don't
  • Payoff: none measurable. A package moved whole is still one compile unit of the same size, and the binary still has to be built from the module root for the e2e tests.
  • Cost: L, Risk: high, Census-touching: yes (all of it)
  • Evidence: - The premise is stale. The binary is built once per test process, lazily, behind a sync.Once: auth_e2e_test.go:33 ("linking it takes seconds and about 135 tests wanted it"), build at auth_e2e_test.go:104, shared with package main_test through export_test.go:9. Makefile:17 still says the tests "compile the carlos binary many times over"; that comment should be corrected. The gate runs the root package as 5 shards plus the cutover-witness job (.amadan/test-gate.sh:36, :175), so about 6 builds per gate run, each from a warm compile cache. - Root's measured test time is 299 s across 71 weighted tests (.amadan/test-weights.tsv), and 165 s of that is three DB-forward tests that wait in real time (see 3). Compiling is not the bottleneck. - Census: every root file is in the . envelope, and 110 census units live in 34 root files (30 in cli.go alone; internal/provision/testdata/census-base.tsv). A move turns each into a removed plus a new unit, and AGENTS.md tells the reviewer to reject when "a removed or left unit moved rather than went". 134 of the 249 commits since 2026-10-26 already touch the census testdata; a 311-file move would collide with most open branches. - internal/docsite/cliscan.go:11 parses main.go's dispatch switch to check docs/site/cli.md. It would need rewriting. - 196 root test files (70,714 lines) use unexported helpers. - The "thin main" guidance exists so other programs can import the logic and so main is testable. Nothing else needs to import the CLI, and testability is blocked by log.Fatal, not by the package name (A2).
  • Proposal: leave the package where it is. Do A2 and A3 instead. If a slice is ever extracted, the only one with a second consumer is the console HTTP client (A4).

A2. CLI commands exit the process instead of returning errors

  • Verdict: do, incrementally (on touch, plus the worst files)
  • Payoff: refusals become testable in process; fewer subprocess tests (faster, and no more "one fatal takes the whole package down with no named failure"); commands stop writing to a global stdout, which is what keeps root's 1,631 tests serial.
  • Cost: M per large file, S per command. Risk: low (exit codes and text can stay byte-identical). Census-touching: yes for the 34 files with units.
  • Evidence: - 954 log.Fatal* and 110 os.Exit( in root production code. Worst: cli.go 186, appconfig_cli.go 70, deploy.go 47, accounts.go 47, instances_cli.go 41. - 223 run* functions return nothing, 9 return error, 3 return int. - The tests say what it costs: accounts_resolve_test.go:70 ("The refusals themselves are log.Fatal (os.Exit, unobservable in-process)"); auth_e2e_test.go:698 (a 429 "takes the whole package down with no named failure", so the test logs in a second time to avoid it); appconfig_cli_fleet_test.go:217 and :275, system_roles_test.go:33, cli_add_rootfs_test.go:92 re-execute the test binary to observe one exit. AGENTS.md records a week of red CI from the same mechanism ("A known-failing test is a defect in its own right"). - captureStdout swaps the package global stdout (cli.go:49, apimode_test.go:37) and is called 182 times. Only 22 t.Parallel() calls exist in root, in 4 files. - The target shape already exists: accounts_plan.go:96 (runAccountsPlanWithSession(ctx, sess, args, out) error) with a 5-line wrapper at accounts_plan.go:88; store.go:406 likewise.
  • Proposal: adopt one rule in AGENTS.md: a command is func runX(ctx, args, out io.Writer) error, and only main.go's switch turns an error into log.Fatal. Convert when a command is next changed; convert cli.go's runRoute and runShip deliberately because they have the most refusals. Do not do it as one sweep: each file is a census card.

A3. Huge files in root (checklist 6)

  • Verdict: do for apimode.go and cli.go; the rest are fine
  • Payoff: cheaper reviews and fewer merge conflicts. apimode.go had 43 commits and cli.go 22 since 2026-10-01 (of 537).
  • Cost: S each (pure moves within the package). Risk: low. Census-touching: yes, but a same-package file move changes no unit body; check with make census-card whether it reports only envelope and site changes before committing to it.
  • Evidence and proposal: - apimode.go (5,852 lines, 204 functions) is the console API client, one resource after another. Split by resource: - api_session.go: apiSession, resolveMode (apimode.go:118), account and app resolution, getJSON/sendJSON/putJSON/deleteJSON, error types (lines 1 to about 990, plus 2883 to 2934 and 3256). - api_releases.go: promote (994) to releases (1810), ship (4985) and its echo checks. - api_apps.go: createApp, trashApp, restoreApp, temporary apps, appList (1094 to 2155). - api_store.go: store, antivirus, scan, relay, ledger (2155 to 2883). - api_config.go: config and pipeline (2934 to 3256). - api_instances.go: instancesEnable (3342, itself 236 lines) to sidecarWake (4485). - api_domains.go: 4552 to 4985. - api_fleets.go: fleets, services, assets, env (5197 to end). - cli.go (4,249 lines, 94 functions): - route_cli.go: runRoute (793, 725 lines in one function), the runRoute* verbs and their rails (793 to about 2310). - ship_cli.go: runShip (2474) to printAPIShipped (2922). - promote_cli.go: runPromote, runChannels, runVersionTarget, runReleases, runRollback (2938 to 3510). - ledger_cli.go: RunLedger (3511) to runKeygen (3836). - status_live.go: RunStatus (3942) to the end. - cli.go keeps runAdd, runRemove, runInstances and the shared helpers. - deploy.go (1,957) is under the bar, but runDeploy (deploy.go:133) is 479 lines; extract its first-run resolution when it is next touched.

A4. Extracting the console API client

  • Verdict: do later, and only if a second consumer appears
  • Payoff: the client would compile separately and could be used by cmd/console tests and probes without a subprocess.
  • Cost: M, Risk: med, Census-touching: yes (apimode.go holds 6 units, auth.go 5)
  • Evidence: apiSession mixes transport with terminal prompts (offerLogin at apimode.go:287, offerSaveProjectDefaults at :713) and per-invocation flag state (shipSwap, shipAssets, deferSaves at apimode.go:85 to :93). A clean package boundary needs those separated first, which A2 and A3 do as a side effect.
  • Proposal: after A3, if api_session.go plus the resource files no longer reference prompts or log.Fatal, they are movable. Not before.

A5. cmd/*

  • Verdict: do later (cmd/console), don't (the rest)
  • Payoff: console start-up configuration becomes testable and listable.
  • Cost: M, Risk: low, Census-touching: no (cmd/console is outside the root graph)
  • Evidence: - cmd/console/main.go is 2,107 lines; serve (cmd/console/main.go:315) is one 575-line function, and the file reads the environment 86 times through dozens of small helper functions. - The store-open helper exists three times: cli.go:2338, cli.go:4046 (deploymentStoreFromEnv, the only one that returns an error) and cmd/console/main.go:933, whose comment says it is "duplicated here because cmd/console cannot import package main". - cmd/moveprobe (1,036 lines, 1,388 of tests), cmd/rootfswitness, cmd/zddprobe, cmd/changelog, cmd/pricebook-export are small, tested and out of the root graph. Nothing to do.
  • Proposal: move deploymentStoreFromEnv into internal/release (or the new store package, B1) as OpenFromEnv(ctx, getenv) (Store, error) and delete the other two. For serve, parse the environment once into a serveConfig struct with one test that lists every variable; leave the wiring as is.

B1. internal/release is two layers in one package (checklist 7, layering)

  • Verdict: do (step 1), do later (step 2)
  • Payoff: about 15 small packages stop linking SQLite, the registry and the adoption pass into their test binaries; an edit to the adoption pass stops invalidating 61 packages; the "release cannot import X" twins (10.3) lose their cause.
  • Cost: M (step 1), L (step 2). Risk: low with type aliases. Census-touching: yes: release has 39 units, and every importer whose import line changes is an envelope re-pin.
  • Evidence: - 23,597 production lines in 107 files; fan-in 61, the highest in the repo. - Outside the package, release.Store is named 1,397 times and release.ErrCASConflict 263 times; the next identifier is at 197. - Nine packages use nothing but Store, ErrCASConflict and NewDirStore (apperr, boxid, boxvolumes, dbverify, edgeproof, hostevidence, hostguard, metrics, usage); six more add one validator or key helper (analytics, plans, telemetry, seeds, park, lease). - internal/release/store.go imports only rootaws, safefile, s3compat and the AWS SDK (store.go:24 to :31). The Store interface is at store.go:50, ErrCASConflict at store.go:37. - 16 of the 107 files reference registry (6,726 lines: adopt.go, materialize*.go, pins.go, restartscope.go, rollback.go, roothistory_pass.go, updatetarget.go and others). adopt.go:24 imports it; internal/registry/registry.go:25 imports modernc.org/sqlite. Those 16 files are the box-side adoption pass. The other 91 are bucket-side shapes, signing and the store.
  • Proposal: - Step 1: a new leaf package (say internal/bucket) holding Store, ErrCASConflict, DirStore, S3Store, prefixStore, KeyETag, DeleteIfMatch, CreateExact and the open-from-env helper. release keeps type Store = bucket.Store and the like, so no caller has to change on day one. Leaf packages then switch import path one branch at a time. Nothing new has to be exported; these names already are. - Step 2: move the 16 registry-using files to internal/release/adopt (the box-side pass). release then no longer imports registry. This needs adoptHost and friends to reach some unexported release helpers, so expect to export a dozen or so; size it properly before starting. - Build win, honestly stated: compile results are cached, so the gain is in link time and in how much is invalidated by one edit. I did not measure it (no builds allowed). It is a layering fix first and a speed fix second.

B2. internal/provision: record shapes and the reconciler are one package

  • Verdict: do later; do the small leaf extraction now
  • Payoff: appconfig, instancectl, hostclaim, hostbox, regionlabel, moves and edge stop depending on the reconciler and its imports (demo, demobuild, democlaim, domains, ratelimit, runs, seeds).
  • Cost: S (leaf), L (full split). Risk: med. Census-touching: yes (49 units).
  • Evidence: - 16,851 lines; provision.go (3,350) is record types, validators and path helpers; reconcile.go (3,545) is the box-side pass. - Importers that want only the shape half: internal/appconfig/syncexec.go:67 and :76 (NestedDBPath, NestedSocket, InstanceDir, three uses in total); instancectl (InstanceID 23 times, ValidHostShape 16); hostclaim (4 identifiers); regionlabel (state constants only). - internal/edge imports it for validators and one Reconcile call. - internal/registry/aliassocket.go:28 to :40 re-implements provision.InstanceID and MaxInstanceID because "this package cannot import" provision.
  • Proposal: now, move InstanceID, MaxInstanceID, InstanceDir, SocketDir, NestedSocket, NestedDBPath to a leaf (say internal/instancepath), with forwarding functions left in provision. That deletes the registry twin and two import edges. Later, split provision into records (provision) and the pass (provision/reconcile).

B3. Very long functions in the root binary's hot paths (checklist 6 and 10)

  • Verdict: do later, one at a time, when a change is already planned there
  • Payoff: narrower census cards and reviews. A census unit is a function; with a 1,266-line function every edit anywhere in it re-freezes the same unit and the reviewer has to reason about all of it.
  • Cost: M each, Risk: med (these are the functions that move production routes), Census-touching: yes
  • Evidence: - internal/provision/reconcile.go:1423 Reconcile: 1,266 lines. The file had 33 commits since 2026-10-01. - internal/release/adopt.go:1402 adoptHost: 832 lines; adopt.go:550 PassFilter: 752 lines. - cli.go:793 runRoute: 725 lines. - internal/appconfig/syncexec.go:104 SyncExecWithCallbacks: 658 lines. - cmd/console/main.go:315 serve: 575 lines.
  • Proposal: extract phases as named functions taking a small pass-state struct. Do not do this as a standalone refactor; attach it to the next feature that edits the function, so the census review happens once.

B4. internal/registry and internal/appconfig

  • Verdict: don't restructure; two small items
  • Payoff: small.
  • Cost: S, Risk: low, Census-touching: yes (registry holds 183 units, the third most in the repo; appconfig 38)
  • Evidence: - registry.go is 4,605 lines and 115 functions, almost all methods on one Registry type over one SQLite file. It imports only six leaf packages. It is big but coherent, and with 183 census units a split by file is all that is affordable: schema and migrations (to about line 1000), route CRUD, policy and channels, aliases and paths. Do it only if conflicts on the file become a problem. - Eight migrations detect an existing column by matching error text: internal/registry/registry.go:806, :896, :899, internal/registry/fleets.go:156, :163, :176, internal/registry/claimrows.go:45, internal/registry/importjournal.go:74 (strings.Contains(err.Error(), "duplicate column")). The same package already does it properly with pragma_table_info at internal/registry/ha_identity_history.go:26. One addColumnIfMissing helper would remove the dependency on modernc's wording across an upgrade. - appconfig (7,360 lines) imports provision for three path helpers (B2) and relay for ParseConfig. objstore imports appconfig, and release cannot import objstore, which is why release/trash.go:267 parses store.json with its own struct. B1 does not fix that one; it is pinned by a test and can stay.
  • Proposal: the addColumnIfMissing helper, next time a migration is added.

B5. The gate compared with a strong Go project (checklist 1 and 4)

  • Verdict: do
  • Payoff: catches bugs and rot the gate cannot see today.
  • Cost: S each. Risk: low. Census-touching: no, if the steps live in .amadan/ci.d/ and Makefile (but note the Makefile's warning that every .sh in the tree is a census unit; keep new logic in Makefile or the existing scripts).
  • Evidence: today the gate is go build ./..., go vet ./..., gofmt -l ., go test -count=1 sharded (.amadan/test-gate.sh:138 to :175), five cross-compiles with a binary size ceiling (.amadan/ci.d/20-cross@5:55, :91), and the MinIO contract. There is no staticcheck.conf, no .gitleaks.toml, no -race, no vulnerability scan and no toolchain pin in go.mod (it says go 1.26.0) or the Makefile. Rastrillo's Makefile has all five (GOTOOLCHAIN at line 39, staticcheck 219, govulncheck 232, gitleaks 251, race 297).
  • Proposal, in order of value per CPU second: 1. Vet the tagged tests. go vet ./... at .amadan/test-gate.sh:139 sees neither rootrunner (114 files, 33,956 lines) nor carlos_cutover_witness (2 files). Neither tag has a negated counterpart, so go vet -tags rootrunner,carlos_cutover_witness ./... is a strict superset of today's run at the same cost. The only thing that compiles the rootrunner tests today is a witness script (scripts/region_ha_g2_witness.py:456), so a refactor in internal/host can break them and stay green. 2. Pin the toolchain in the Makefile as rastrillo does (export GOTOOLCHAIN = go1.26.10), or with a toolchain line in go.mod. The pin currently lives only on the runner. govulncheck needs it to give the same answer on a laptop and in CI. 3. staticcheck, pinned with go run ...@version (no tool directive needed), starting with the SA bug checks only and a baseline of today's findings, so the first run is green and only new findings fail. The separate repo-wide pass will say how long the baseline is. Run it as its own job in test-gate.sh beside vet, with the same tags. 4. govulncheck as its own ci.d step, not inside make test: it reads a live database and can go red with no change in the tree, which should be visible as a separate red step and not as a failed test run. The root binary links 103 AWS SDK packages, pion DTLS/TURN/STUN (from internal/relay/server.go:14), litestream, and prometheus/client_golang v1.17.0 (indirect, 2023). 5. gitleaks over HEAD's history, as its own step, with an allowlist for the test keys. The repo is mirrored to GitHub. 6. A targeted -race step, CGO_ENABLED=1, on a short list of packages with real concurrency and fast tests, as its own ci.d step so its CPU cost is bounded and visible. internal/edge/race_on_test.go and internal/relay/race_on_test.go already exist behind //go:build race, so someone runs it by hand today. From my slice: internal/registry (the remote worker, remote.go:257), internal/release (change watch) and internal/provision (the caches). The other auditors will name theirs. Never the whole tree: the root and console packages would take many minutes. 7. Later: GOOS=darwin go vet . in the darwin cross shard. The cross step builds but does not vet, so test files tagged darwin or windows, and every !linux test file, are never type-checked. The CLI is the part people run on Macs.
  • Also: -shuffle=on on the unsplit rest job would surface order-dependent tests cheaply. Leave root and console out until A2 reduces the shared globals.

B6. Package granularity and naming

  • Verdict: don't rename or merge; fix the direction of a few edges
  • Payoff: smaller rebuilds and test binaries for the packages named below.
  • Cost: S each, Risk: low, Census-touching: yes (each is a small move)
  • Evidence: - 156 packages under internal/: 42 under 200 lines, 58 between 200 and 1,000, 40 between 1,000 and 5,000, 11 between 5,000 and 20,000, and 5 over 20,000 holding 388,172 of 609,372 production lines (64%). So the granularity is bimodal, and the small host* packages (18 of them) are the result of carving pieces off internal/host, which is still 124,928 lines and imports 90 internal packages. - The tiny packages are mostly deliberate: controlsock exists to break a cycle and says so (internal/controlsock/controlsock.go:3 to :7); hostops/fencerelease (7 lines) restricts who can construct a token; controlname (8 lines) forwards to the launchctx module. Merging them would recreate the cycles. Leave them. - internal/host is imported only by the root package, so it is the top of the graph and its size costs compile and test time but not layering. That is the other auditors' slice. - Edges where a small package imports a giant for one or two names: - internal/dbreads/read.go:166 and internal/ops/hibernate_verify.go:90 import activator (43,862 lines, 81 internal packages behind it) for HibernatePrefix, a string helper. ops also uses activator.Config (internal/ops/ops.go:276). - internal/tsidentity/whois.go:26 imports edge (33,676 lines) for the Visitor struct, which is three strings (internal/edge/visitor.go:14). tsidentity is 86 lines with 58 internal packages behind it. - internal/stopevidence/evidence.go:27 imports activator for one type. - internal/layout/plan.go:24 imports release for two constants. - internal/devbox imports edge for ExtractSite and RuleFileLimit. - Naming: internal/layout reads as a low-level path package but is the layout migration pass (it imports activator, hostbox, instancectl, provision). internal/objstore is tenant object storage, not the deployment bucket, which is release.Store. Neither is worth a rename.
  • Proposal: move HibernatePrefix beside the other key helpers (the store package from B1), and Visitor/VisitorIdentity to a leaf (tsidentity itself can own them, with edge importing it). Each is a 20-line change that removes dozens of packages from a small package's dependency set.

B7. Size of the root binary's dependency graph

  • Verdict: don't change; one watch item
  • Payoff: none available without splitting the artifact.
  • Cost: n/a
  • Evidence: GOOS=linux GOARCH=amd64 go list -deps . gives 656 packages: 221 standard library, 126 of this module's 166 (AGENTS.md line 319 says "106 of 134", which is out of date), 103 aws-sdk-go-v2 across 15 services, 43 smithy, 35 pion, about 26 protobuf and 9 prometheus (through litestream), and modernc SQLite. The stripped linux/arm64 binary has a 64 MB ceiling (.amadan/ci.d/20-cross@5:91); the unstripped test build is about 120 MB (auth_e2e_test.go:94). main.go:1 states the design: edge, host agent and CLI in one artifact. Someone running the CLI on a Mac therefore links the host agent, the edge, DTLS/TURN and SQLite. That is a product decision, the size tripwire already guards it, and a second CLI-only binary would double the release and census surface.
  • Proposal: correct the count in AGENTS.md. Nothing else.

1. Static analysis in this slice

  • Verdict: covered by B5; nothing to fix by hand first
  • Evidence: root has 18 _ = f() lines; most are closes and deadlines. The ones that matter are the ignored json.Unmarshal results on console replies: system.go:332, :405, :453, :638, system_geoip.go:133, :277, apimode.go:5679, system_activation.go:54. See the bug list for system.go:405. I found no err == comparisons against sentinel errors in root with a simple grep; the two != io.EOF checks (domains_buy_cli.go:222, history_cli.go:145) are on json.Decoder.Decode, which returns io.EOF unwrapped, so they are correct.

2. Error wrapping

  • Verdict: don't in root; do later in release
  • Payoff: none in root today.
  • Cost: S, Risk: low, Census-touching: yes
  • Evidence: root has 31 fmt.Errorf(..., err) without %w. All are final user-facing messages on their way to log.Fatal (for example instances_updates.go:165, apps_policy.go:268, system.go:443); no caller inspects them. One string match exists: deploy.go:1281 matches "unreachable:" in text produced at deploy.go:1807 and :1814, 500 lines away in the same file. release has 46 without %w (for example internal/release/buildstate.go:73, pipeline.go:223, adopt.go:1168); provision and registry have none.
  • Proposal: replace the deploy.go string match with a small error type when that code is next touched. In release, use %w in new code; a sweep is not worth 46 census-visible edits unless a caller needs errors.Is.

3. Sleep-based tests

  • Verdict: don't convert; one optional speed-up
  • Payoff: at most about 60 s off one root shard.
  • Cost: M, Risk: low, Census-touching: no (tests only)
  • Evidence: root has 39 time.Sleep in tests; release 12, provision 2, registry 1, appconfig 1. The time goes to three real-time acceptance tests through the real CLI binary, the real edge and the real console server: TestDBForwardPrintsNothingForABadAnswer 67 s (its "no result" case waits for the console's one-minute grace, dbforward_e2e_test.go:682 to :686), TestDBForwardThroughTheBackhaulHop 55 s and TestDBForwardLongRequestThroughTheEdge 43 s (a 20 s scripted restore, dbforward_e2e_test.go:571). These cross process boundaries and real sockets, so testing/synctest cannot cover them. The backhaul helper also compiles internal/edge's test binary inside the test (dbforward_e2e_test.go:736).
  • Proposal: leave them. If root's wall clock ever becomes the gate's floor, make the console's grace configurable for the "no result" case and run the three sub-cases in parallel.

4. Globals and data races

  • Verdict: covered by A2 and B5
  • Evidence: root has few seams and they are plain: stdout (cli.go:49), shipNow (cli.go:2412), boxLabelForAdd (cli.go:266), interactiveTerminal and chooserIn (account_choose.go:47, :53), dbPullSpoolWrite (dbforward.go:512), checkPause (ship_check.go:54), sleepFn (mail_cli.go:1510), watchOrigin (deploy.go:1684). They are swapped by serial tests, so they do not race today, but they are why root cannot use t.Parallel. Repo-wide there are no exported function-valued package variables and only 7 init() functions.

5. Context propagation

  • Verdict: don't
  • Evidence: root has 252 context.Background(), and exactly one sits inside a function that already has a ctx: devbox_cli.go:995, a drain timeout that must outlive the cancelled parent, which is correct. The rest start a command. Long-running commands already use signal.NotifyContext (db.go:442, relay.go:117, instances_import.go:157, fleets_managed.go:35). registry has 15, because the Registry API takes no context (internal/registry/timers.go:63, aliassocket.go:112); it is a local SQLite file, and threading ctx through 115 methods and 183 census units buys nothing.

8. Logging

  • Verdict: don't
  • Evidence: root has 7 log.Print* calls and no slog; a CLI prints, it does not log. provision has 300 log.Printf calls, all prefixed provision: (143 in reconcile.go), and 6 of its test files capture log output (26 log.SetOutput uses), so a move to slog would be a rewrite of those assertions on top of a census card per file. main.go routes the standard logger through a colouring writer for log.Fatal.

9. Panics

  • Verdict: nothing to do
  • Evidence: root has 3: interactive_cli.go:262 and :339 re-panic after restoring the terminal, mail_cli.go:1659 is a write to a bytes.Buffer. release and provision have one each; registry and appconfig none.

10.3 How import cycles are dodged

  • Verdict: mostly fine; B1 and B2 remove the common cause
  • Evidence: not with globals or late-bound callbacks. Three mechanisms: 1. Leaf packages made for the purpose (controlsock, rolloutwords, updatewords, boxid/internal/signtest, lease/locktest). 2. Function fields on config structs, wired by internal/host (internal/activator/backend_exec.go:103 to :109, RawInstanceDir, because the activator "cannot import" layout). That is ordinary dependency injection. 3. Twins: the same rule written twice and held together by a test. internal/registry/aliassocket.go:28 (provision's InstanceID); internal/provision/provision.go:1595 and internal/moves/ids.go:17 (move id shapes); internal/release/pins.go:228 to :239 (BuildStateKept, the activator's rule restated); internal/lease/tombstone.go:49 (MaxTombstoneTTL, equal to the moves package's); internal/apppolicy/apppolicy.go:31 (cgroup size names); internal/release/trash.go:267 with internal/objstore/objstore.go:128 (two parsers of store.json).
  • Assessment: every twin I read has a pinning test named beside it, so the bug risk is low. The cost is that identifiers, shapes and path rules live in the operational packages (provision, moves, activator) and not in a leaf both sides can import. B2's instancepath removes one twin; a small internal/ids for the move and rollback id shapes would remove two more.

10.4 Documentation drift in the build instructions

  • Verdict: do (two lines)
  • Evidence: AGENTS.md:284 tells agents to use GOCACHE=/tmp/claude-1001/gocache, which the machine policy forbids (the default cache is the rule, and /tmp is a shared RAM disk). Makefile:17 and AGENTS.md:319 are stale as noted above.
  • Proposal: delete the GOCACHE advice, fix the two comments.

Bugs found along the way

  • cli.go:3808: carlos ledger verify uses http.DefaultClient with context.Background() (cli.go:3809), so there is no timeout at all. A status host that accepts the connection and stalls hangs the command forever. Every other client in root sets a timeout (for example auth.go:537, deploywatch.go:706).
  • system.go:405: the reply to carlos system update is decoded with the error discarded, then started.Job is passed straight to watchSystemJob. A reply without a job id (an older console, a proxy's HTML) polls /api/cli/system/jobs/ with an empty id and reports a confusing "job :" error for a promote that may have started. Check for an empty job id and say so. system.go:453 has the same shape inside the poll loop: a body that does not decode is treated as "no steps, not done" and polled for 15 minutes.
  • .amadan/test-gate.sh:139: not a code bug, but a hole. The 114 rootrunner test files are never compiled by the gate (B5 item 1).
  • AGENTS.md:284: instructs a cache path that the machine policy bans (10.4).
Agent notes

Astra second read of the merged backlog (against 5b6d5374).

Verification

Reviewed HEAD 5b6d53741b4aac7e6b557b3b2b526512d5917acc and the supplied reports. No edits, builds, tests, analysers or delegates. The existing go.mod changes only alter direct/indirect classification.

  1. AWS/S3 timeouts — CONFIRMED; implementation scope understated. rootaws/config.go:38 and release/store.go:861 supply no overall timeout. S3Store.Get also reads the response body without another bound at line 923. The cited host loops use background contexts; the fast loop’s serial read is an explicit unbounded operation at agent.go:3183. Existing index and edge-IP deadlines protect individual operations, not whole loops.

Add operation-specific deadlines first. A shared short http.Client.Timeout would also interrupt legitimate large transfers; a response-header timeout alone would leave stalled bodies unbounded. Converting all loops, cancellation and shutdown ownership is medium work.

  1. Request-path plumbing — mixed:

| Claim | Verdict | |---|---| | Public servers lack IdleTimeout | CONFIRMED. Both servers omit it and ReadTimeout: edge.go:4808. | | Every reload drops upstream pools | OVERSTATED. Ordinary Unix and unprobed TCP proxies are rebuilt at edge.go:1098 and line 1130. Their abandoned idle connections expire after 90 seconds. Generation-managed sockets already reuse GenPools; multiProxy deliberately disables pooling at edge.go:3753. Narrow the finding and preserve these distinctions. | | Remote tcpProxy dial has no timeout | CONFIRMED. Its transport receives a nil production dialer, and the bounded retry applies only to local upstreams: edge.go:3528. | | Cancelled health waits leave probing goroutines | CONFIRMED. backend_exec.go:3699 abandons a context-free polling loop; backend_unit.go:276 does likewise. This is bounded lingering work, not a permanent goroutine leak. An outstanding three-second request can extend the nominal polling deadline. |

  1. Compression dependency upgrade — CONFIRMED at dependency/reachability level. go.mod pins v1.18.0; archive.go:445 really calls zstd.Encoder.Close. The supplied govulncheck output identifies v1.20.2 as fixed. That supports upgrading; it does not establish an exploitable application input by itself.
  1. Widening the gate — CONFIRMED gaps, with corrections. - The ordinary vet job has no tags: test-gate.sh:139. I count 111 tracked rootrunner test files, 33,866 lines, not 114/33,956. - The cutover-witness tag is compiled and tested separately at line 175; the root report overstates that gap. - No staticcheck, govulncheck, gitleaks or race job appears in the current gate. Their proposed costs are unmeasured; tagged vet is additional work, not “free.” - The supplied vulnerability scan reports the standard-library issue as affected. The referenced pin discussions were not supplied, so I cannot verify the exception’s authorization or terms. An exception should identify that advisory explicitly and retain a visible remediation obligation.
  1. Console shutdown — CONFIRMED; closer to medium than small. main.go:656 handles the signal with capacity cancellation, lease release and os.Exit(0), without draining HTTP. Workers started at line 754 retain background contexts. Fixing this requires coordinating HTTP drain, worker completion and lease release; adding Shutdown alone is insufficient.
  1. Bug batch — individual verdicts:

| Finding | Verdict and evidence | |---|---| | Request-host log key | CONFIRMED. plandisabled.go:80 inserts request hosts into the permanent logN map. Wildcard lookup at edge.go:1693 and disabled-route matching at plans_pass.go:255 establish the reachable case. Key by the resolved route. | | Ledger verification timeout | CONFIRMED. cli.go:3808 combines http.DefaultClient with context.Background(); ledger.HTTPGetter adds no deadline. | | System-update decode errors | CONFIRMED. system.go:405 permits an empty job ID. Line 453 discards poll-response decoding errors, potentially continuing until the fifteen-minute deadline. | | "ops" substring | CONFIRMED classifier defect. ownership.go:755 classifies arbitrary returned database errors by substring. This can misreport the reason; it does not bypass deletion checks. | | Zero-incarnation panic | WRONG as a current reachable bug. apiinstances.go:2513 replaces rec with the successful lifetime-create result. lifetimes_create.go:116 rejects exhaustion, then assigns base+1 at line 123. Host-claim consoles do not enter lifetime admission. The cited panic constructor exists, but this path establishes its precondition. | | Two "<nil>" manifest errors | WRONG as reachable failures. Both calls use exactBytesStore with precisely ManifestKey(prefix). movesfiles.go:971 therefore returns bytes successfully; manifest.go:144 returns found=false, err=nil only for a missing key. Malformed supplied bytes return a nonnil error. | | Dropped capacity-page error | CONFIRMED. haplacement.go:17 discards delivery errors. Sink failure counters may still record them, so “no trace anywhere” is too strong; the caller supplies no diagnostic. | | Unbounded staging-lease release | CONFIRMED. movescut.go:912 and line 917 pass background contexts and discard errors. Production supplies Held.Release, whose remote release uses that context at lease.go:326. The renewer is stopped first. | | Sentinel == | OVERSTATED as a bug. claimrecovery_remote.go:108 receives direct sentinel returns; Guard.With propagates callback errors unchanged. errors.Is is sensible defensive maintenance, not a demonstrated retry failure. | | Escrow "ALERT: " prefix | CONFIRMED, with stronger evidence than reported. escrow.go:872 already joins another error before the alert. Consequently the prefix checks at lines 1364 and 1572 miss it today. The unreadable-error sentinel still refuses the launch, and escrowConflictFound logs directly, so this does not prove unsafe launch or total alert loss. Use a typed classification. | | Forbidden cache advice | CONFIRMED. AGENTS.md:284 explicitly recommends the machine-policy-forbidden cache path. |

Ranking

  • Keep immediate priority: the compression upgrade, attacker-controlled log growth, unbounded network operations, public idle timeout, cancelled health probes and console shutdown. Include the ledger validation defect below.
  • Promote narrow CLI error-return conversions from item 9 above transport-pool optimisation and cosmetic diagnostics. Existing tests explicitly work around process termination: authe2etest.go:698. Convert commands being fixed now using the established accounts_plan.go:96 pattern.
  • Recover the console database-context work omitted from the merged backlog. The console report raised it. A single connection at store.go:118, combined with context-free request queries such as AccountBySqid at line 1316, permits abandoned requests to remain queued. Target those request paths before package extraction; “context sweeps aren’t worth doing” should not bury this.
  • Stage the gate additions. Tagged compilation/vet and reviewed staticcheck findings come first. Add bounded race jobs after repairing their helpers. Treat vulnerability and secret scanning as separate checks with explicit exceptions.
  • Defer pool reuse until its benefit is measured. It is narrower than reported and touches routing lifetimes. It is not equivalent in urgency to an unbounded request-host map.
  • Remove the two disproved bugs from item 6. Keep sentinel hardening and error-message classification below demonstrated failures. Avoid coupling unrelated root, storage, edge and console changes into one supposedly small branch.
  • Reject item 15’s mass-unexporting prerequisite. The host report itself ultimately recommends whole-program dead-code analysis and explicitly rejects mass renaming. Renaming hundreds of declarations incurs census churn without establishing that anything can be deleted.
  • Keep broad package splits deferred. Their dependency arguments are plausible, but compile/link savings remain unmeasured. None presently outranks the confirmed availability fixes.

Missed

  1. Validate ledger wire data before returning successful verification. A HEAD body of {} or null decodes successfully at verify.go:55, skips the walk and returns success at line 98. The CLI then panics on HeadSHA256[:12] at cli.go:3813. Define and enforce valid head/count/digest combinations, including any supported empty-ledger representation, before returning success. Add malformed-head cases alongside the existing chain tests. This is a concrete counterexample to dismissing input-dependent panics wholesale.
  1. Bound cold-restore memory before reading the selected chain. restore.go:349 reads each entire LTX object before checking its declared size, and line 416 retains every object in memory. Normalisation can temporarily hold another encoded copy. Memory therefore scales with the complete selected chain. Enforce byte budgets before allocation and use verified disk-backed staging for large chains, preserving the existing verification-before-install ordering. This is on the claim-wake path; assess its activation status before prioritising implementation.
  1. Carry cancellation through webhook delivery’s function type. Sinks.Page(ctx, …) accepts a context, but alerting.go:57 defines Post without one, and alerting.go:267 uses client.Post. A cancelled page can still send and wait five seconds. Make the delivery function accept context.Context and construct the request with it, retaining the existing redirect refusal and secret-safe errors.
LLM

First batch done, merged, not released:

  • Item 1, AWS/S3 stall bounds: audit-aws-timeouts, merged as 0374ac2. Follow-ups in #1143.
  • Item 2, compress bump: already on main (197cc40c).
  • Item 3, request path: audit-request-path, merged as 958ff2e. The prober's unbounded dial is a follow-up (comment in internal/edge/upstreamdial.go).
  • Item 4, gate: audit-gate-vet-staticcheck, merged as b064b14. The 40-staticcheck step is green on main. SA1012 (177), SA1019 (70) and SA4006 (70) are excluded until follow-ups fix them.

Found along the way: #1141 (subdomain lost-race answers "unreadable") and #1142 (flaky root dbforward e2e tests).

LLM

Recheck of the later backlog items against main at c4b44c34 (2026-11-16, after the first batch merged).

| # | Item | Holds? | Evidence on c4b44c34 | |---|---|---|---| | 5 | Console SIGTERM drops in-flight requests | Yes | cmd/console/main.go:704-709 stops capacity, releases the policy lease, then os.Exit(0); no HTTP Shutdown | | 6 | Console queries without a context on one connection | Yes | store.go:122 SetMaxOpenConns(1); 459 context-free s.db.Query/QueryRow/Exec calls in 49 non-test files (store.go alone: 132 against 8 with Context) | | 7 | govulncheck, gitleaks, -race in CI | Not there | ci.d has 10-gate, 20-cross, 30-minio, 40-staticcheck. govulncheck today: only GO-2026-6859 (net/http, under the 1.26.10 pin, ruled unreachable in #904). Racy helpers still in place: host/capspasstest.go:121 captureLog, activator/wakechecktest.go:586 5 s sleep | | 8a | ledger verify: no timeout, {} HEAD panics | Yes | cli.go:3827 http.DefaultClient; cli.go:3832 HeadSHA256[:12] | | 8b | system update ignores decode errors | Yes | system.go:461-462 (empty job id to watchSystemJob), :509 in the poll loop | | 8c | "ops" substring on delete errors | Yes | console/ownership.go:721 | | 8d | Silent capacity-page failure | Yes | host/haplacement.go:17 | | 8e | Escrow alerts matched by "ALERT: " prefix | Yes | activator/escrow.go:1438, :1653 | | 8f | AGENTS.md recommends a banned GOCACHE | Yes | AGENTS.md:296 | | 9a | Edge test sleeps | Yes | lbhealthtest.go:301, :333 (5 s each), :178 (1.2 s); forwardhatest waits on the 3 s holderHeaderSuspectAfter const (forwardha.go:509) | | 9b | Console whole-second sleeps | Yes | 24 x time.Sleep(1100 ms) | | 9c | Host 20 s test | Yes | TestClaimAckRefreshProductionClient waits on a real lease renewal (claimackrefreshlinuxtest.go:533-543) | | 9d | Edge and activator not sharded | No, wrong | test-gate.sh:59 TESTSPLIT already has edge=4 and activator=4, and both are in test-weights.tsv | | 10a | CLI log.Fatal / os.Exit | Yes, grown | 999 log.Fatal and 120 os.Exit in root production files (audit: 954 / 110) | | 10b | internal/release pulls the registry into its importers | Yes, grown | 67 packages import it (audit: 61); it imports internal/registry | | 10c | Console links activator and edge | Yes | internal/console imports both | | 10d | Census "moved" class | Not there | | | 10e | Console package-dir source guards | Yes, 15 | (audit: 13) | | 10f | Long functions | Yes, grown | Reconcile 1,274 lines, runAgent 1,221, handleAPIInstanceCreate 1,246 |

Total test sleeps are now 1,019 (audit: 872).

LLM

The plan is merged as 295fe89: docs/superpowers/plans/2026-11-16-go-code-health.md (fix, hold, improve). Batch 2 is merged (40d5273, b530ec0, 7412166, fdc912b). Batch 3 has started with the code-health ratchet on branch code-health-ratchet.

LLM

Code-health ratchet merged as 7e50962 (plan Part 2): 60-code-health and 61-code-health-record run in CI, AGENTS.md has Writing Go here. First counts: fatal 1,091 at 473 sites, test sleeps 1,006 at 812, db calls without a context 935 at 751, host context.Background 169 at 124, 46 functions over 300 code lines, 8 files over 3,000, 65 packages importing internal/release. Next from batch 3: console request cancellation in place, and bounded systemctl/journalctl plus the edge prober dial.

LLM

Batch 3 so far: c855db5 console request contexts on signed-in paths (db-no-context in console 629 to 591), 61ed548 bounded systemctl queries through internal/systemd, plus the prober dial. Follow-ups #1214 (job-verb bounds and outcome reconciliation; ratchet wrapper blind spot). Still to come in batch 3: #1143, the staticcheck SA family burn-down, racy test helpers then -race, gitleaks.