carlos / platform Public

gate: fix SA1026 and the code-health ratchet for instance usage

Tag EdgeFlush.Instances json:"-" (struct-keyed map, in memory only).
Move the branch's additions and a few cohesive neighbours out of the
over-record files: startPostClaimWork (cmd/console), newUsageMeter
(host/instance_usage.go), apimode_limit.go, canary_count.go,
console/hostnorm.go. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f097f2e307381bb23d3b3c8b5d249833fbfa7ab5 parent b0280ed
10 files changed, +216 −161
  • .superpowers/sdd/2026-11-29-instance-usage/gate-fix-report.md +14 −0
  • apimode.go +0 −42
  • apimode_limit.go +52 −0
  • cmd/console/main.go +19 −14
  • internal/console/hostnorm.go +43 −0
  • internal/console/server.go +0 −37
  • internal/host/agent.go +1 −67
  • internal/host/canary_count.go +70 −0
  • internal/host/instance_usage.go +14 −0
  • internal/usage/edge.go +3 −1
diff --git a/.superpowers/sdd/2026-11-29-instance-usage/gate-fix-report.md b/.superpowers/sdd/2026-11-29-instance-usage/gate-fix-report.md
new file mode 100644
index 000000000..a610b42c3
--- /dev/null
+++ b/.superpowers/sdd/2026-11-29-instance-usage/gate-fix-report.md
@@ -0,0 +1,14 @@
+# Gate fix report
+
+SA1026: `usage.EdgeFlush.Instances` is tagged `json:"-"` (in memory only). No other code marshals EdgeFlush expecting Instances. `make staticcheck` is clean.
+
+Code-health moves (final count / record):
+- cmd/console `serve` 358 / 362: the fleet backfills plus the RunUsageFrom start moved into `startPostClaimWork` (cmd/console/main.go). The switch call stays in `serve`, because TestServeAppliesTheInstanceUsageSwitchFromTheEnvironment requires it.
+- internal/host `runAgent`: meter creation and the box switch moved into `newUsageMeter` (internal/host/instance_usage.go), one line in place of two. The ratchet passes.
+- apimode.go 4128 / 4147: the bounded GET reader (`getJSONDefaultLimit`, `errResponseTooLarge`, `getJSONLimit`, `getJSONHeaderLimit`) moved to apimode_limit.go.
+- internal/host/agent.go 3175 / 3204: `isCanaryRoute` and `countExpiredCanaries` moved to canary_count.go (one statusLoop line of the branch's own stays, so a pre-existing cohesive chunk had to go).
+- internal/console/server.go 4177 / 4191: `normalizeSteeringHost` and `normalizeDelegationZone` moved to hostnorm.go, for the same reason (Config field and embed are 2 code lines of the branch's own).
+
+Records not lowered.
+
+Tests: host (InstanceFlush|UsageFlush|Agent|Canary, -short), cmd/console (full), root (Usage|GetJSON), internal/usage, internal/console (Usage|Mint|Rotate|Steering|Delegation) all pass. go vet, gofmt clean. `make code-health` passes.
diff --git a/apimode.go b/apimode.go
index 92b076beb..82023b9ba 100644
--- a/apimode.go
+++ b/apimode.go
@@ -802,48 +802,6 @@ func (s *apiSession) getJSONHeader(ctx context.Context, path string) (int, http.
return s.getJSONHeaderLimit(ctx, path, getJSONDefaultLimit)
}
-// getJSONDefaultLimit is how much of an answer getJSON reads.
-const getJSONDefaultLimit = 1 << 20
-
-// errResponseTooLarge is an answer longer than the caller's limit: never a
-// truncated body handed back as if it were whole.
-var errResponseTooLarge = errors.New("the console's answer is larger than this command reads")
-
-// getJSONLimit is getJSON for an answer that can pass 1 MiB: it reads at
-// most limit bytes and fails with errResponseTooLarge past them.
-func (s *apiSession) getJSONLimit(ctx context.Context, path string, limit int64) (int, []byte, error) {
- status, _, body, err := s.getJSONHeaderLimit(ctx, path, limit)
- return status, body, err
-}
-
-// getJSONHeaderLimit is the one GET reader: it reads limit+1 bytes so an
-// answer of exactly limit bytes is whole and one byte more is an error.
-func (s *apiSession) getJSONHeaderLimit(ctx context.Context, path string, limit int64) (int, http.Header, []byte, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.c.base+path, nil)
- if err != nil {
- return 0, nil, nil, err
- }
- if s.c.token != "" {
- req.Header.Set("Authorization", "Bearer "+s.c.token)
- }
- res, err := s.c.httpc.Do(req)
- if err != nil {
- return 0, nil, nil, err
- }
- defer res.Body.Close()
- if merr := consoleMoved(s.c.base, res.StatusCode, res.Header.Get("Location")); merr != nil {
- return res.StatusCode, res.Header, nil, offerConsoleMoved(merr)
- }
- body, err := io.ReadAll(io.LimitReader(res.Body, limit+1))
- if err != nil {
- return res.StatusCode, res.Header, nil, err
- }
- if int64(len(body)) > limit {
- return res.StatusCode, res.Header, nil, errResponseTooLarge
- }
- return res.StatusCode, res.Header, body, nil
-}
-
// sendJSON runs one JSON request over the given method and hands back the
// status and raw body without interpreting a non-200 as an error itself —
// the one request-building body postJSON/putJSON/patchJSON share (Task 8
diff --git a/apimode_limit.go b/apimode_limit.go
new file mode 100644
index 000000000..cbd4f64b5
--- /dev/null
+++ b/apimode_limit.go
@@ -0,0 +1,52 @@
+package main
+
+// The bounded GET reader behind getJSON, getJSONHeader and getJSONLimit.
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+)
+
+// getJSONDefaultLimit is how much of an answer getJSON reads.
+const getJSONDefaultLimit = 1 << 20
+
+// errResponseTooLarge is an answer longer than the caller's limit: never a
+// truncated body handed back as if it were whole.
+var errResponseTooLarge = errors.New("the console's answer is larger than this command reads")
+
+// getJSONLimit is getJSON for an answer that can pass 1 MiB: it reads at
+// most limit bytes and fails with errResponseTooLarge past them.
+func (s *apiSession) getJSONLimit(ctx context.Context, path string, limit int64) (int, []byte, error) {
+ status, _, body, err := s.getJSONHeaderLimit(ctx, path, limit)
+ return status, body, err
+}
+
+// getJSONHeaderLimit is the one GET reader: it reads limit+1 bytes so an
+// answer of exactly limit bytes is whole and one byte more is an error.
+func (s *apiSession) getJSONHeaderLimit(ctx context.Context, path string, limit int64) (int, http.Header, []byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.c.base+path, nil)
+ if err != nil {
+ return 0, nil, nil, err
+ }
+ if s.c.token != "" {
+ req.Header.Set("Authorization", "Bearer "+s.c.token)
+ }
+ res, err := s.c.httpc.Do(req)
+ if err != nil {
+ return 0, nil, nil, err
+ }
+ defer res.Body.Close()
+ if merr := consoleMoved(s.c.base, res.StatusCode, res.Header.Get("Location")); merr != nil {
+ return res.StatusCode, res.Header, nil, offerConsoleMoved(merr)
+ }
+ body, err := io.ReadAll(io.LimitReader(res.Body, limit+1))
+ if err != nil {
+ return res.StatusCode, res.Header, nil, err
+ }
+ if int64(len(body)) > limit {
+ return res.StatusCode, res.Header, nil, errResponseTooLarge
+ }
+ return res.StatusCode, res.Header, body, nil
+}
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 363d82288..8f301ca44 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -886,20 +886,7 @@ func serve() {
// the placement column from routes, for apps placed before the column
// existed. Not before the first seal: sealKeyFor reads the same routes
// until it lands.
- work.Go("fleetBackfills", func(ctx context.Context) {
- ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
- defer cancel()
- srv.RunFleetOwnerBackfill(ctx)
- srv.RunAppPlacementBackfill(ctx)
- })
- // The instance usage attribution start (instance usage design §4):
- // checked now and every minute until usage/instances/@from.json is
- // held, then done. After LoadHostsMode above, whose held state it
- // reads, and after ConfigureClaimRuntime, so it never races that
- // swap of cfg.Releases. Only with the switch on.
- if cfg.InstanceUsage {
- work.Go("RunUsageFrom", srv.RunUsageFrom)
- }
+ startPostClaimWork(work, cfg, srv)
// Each claim worker runs on work's context under its own name.
startClaimWorker := func(name string) {
work.Go(name, func(ctx context.Context) { srv.RunClaimWorker(ctx, name) })
@@ -2308,6 +2295,24 @@ func applyMovesSwitch(cfg *console.Config, getenv func(string) string) {
cfg.MovesEnabled = moves.Enabled(getenv)
}
+// startPostClaimWork starts the workers that must follow ConfigureClaimRuntime
+// (it swaps cfg.Releases, so these never race that swap): the fleet owner and
+// app placement backfills, bounded, and then, with the instance usage switch
+// on, the attribution start (instance usage design §4), checked now and every
+// minute until usage/instances/@from.json is held. That one also reads
+// LoadHostsMode's held state.
+func startPostClaimWork(work *workers, cfg console.Config, srv *console.Server) {
+ work.Go("fleetBackfills", func(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
+ defer cancel()
+ srv.RunFleetOwnerBackfill(ctx)
+ srv.RunAppPlacementBackfill(ctx)
+ })
+ if cfg.InstanceUsage {
+ work.Go("RunUsageFrom", srv.RunUsageFrom)
+ }
+}
+
// applyInstanceUsageSwitch sets console.Config.InstanceUsage from
// CONSOLE_INSTANCE_USAGE (instance usage design §12): exactly "true" is on,
// anything else, unset included, is off.
diff --git a/internal/console/hostnorm.go b/internal/console/hostnorm.go
new file mode 100644
index 000000000..cec95a14a
--- /dev/null
+++ b/internal/console/hostnorm.go
@@ -0,0 +1,43 @@
+package console
+
+import (
+ "log"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// normalizeSteeringHost lowercases, trims and shape-validates the steering
+// hostname (Config.SteeringHost). Same posture as normalizeDelegationZone
+// below and for the same reason: a value that is not a legal hostname
+// degrades to "" — guidance keeps the A-record form, which always works —
+// rather than being pasted verbatim into a sentence every member of this
+// deployment is shown. Loud, because a deployment that armed steering and
+// typo'd the variable would otherwise mislead silently.
+func normalizeSteeringHost(raw string) string {
+ h := strings.ToLower(strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(raw), ".")))
+ if h != "" && !provision.ValidHostShape(h) {
+ log.Printf("console: steering hostname %q is not a valid domain — custom-domain guidance keeps the A-record form", raw)
+ return ""
+ }
+ return h
+}
+
+// normalizeDelegationZone lowercases, trims, and shape-validates raw (from
+// CARLOS_ACME_DELEGATION_ZONE): a value that isn't a legal hostname degrades
+// to "" — delegation off — rather than being handed to lookupCNAME verbatim
+// or failing boot. Mirrors the edge's own validation of the same variable
+// (internal/edge/wildcard.go's newWildcardFromEnv), so a zone the edge would
+// refuse never gets ACCEPTED here only to make every wildcard-enable request
+// dial a garbage DNS query. "" already has a well-defined, honest answer —
+// every enable request refuses with "deployment has no delegation zone
+// configured" — so a badly-typed zone gets exactly that, not a crash or a
+// distinguishable error.
+func normalizeDelegationZone(raw string) string {
+ zone := strings.ToLower(strings.TrimSpace(raw))
+ if zone != "" && !provision.ValidHostShape(zone) {
+ log.Printf("console: CARLOS_ACME_DELEGATION_ZONE %q is not a valid domain — delegation off, wildcard-enable requests refuse with \"no delegation zone configured\" until it's fixed", raw)
+ return ""
+ }
+ return zone
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 10104fa7b..550724f92 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1113,8 +1113,6 @@ type Server struct {
// hosts is the hostname history's mode, read once (hostsused.go).
hosts hostsHistory
- // The instance usage read's clock, attribution start and memo
- // (usagefrom.go, apiusage.go).
instanceUsageState
// lapseBeforeConverge, when set (tests only), runs inside the account's
@@ -1967,41 +1965,6 @@ func (s *Server) realFoldEdgeIPs(ctx context.Context) []string {
return ips
}
-// normalizeSteeringHost lowercases, trims and shape-validates the steering
-// hostname (Config.SteeringHost). Same posture as normalizeDelegationZone
-// below and for the same reason: a value that is not a legal hostname
-// degrades to "" — guidance keeps the A-record form, which always works —
-// rather than being pasted verbatim into a sentence every member of this
-// deployment is shown. Loud, because a deployment that armed steering and
-// typo'd the variable would otherwise mislead silently.
-func normalizeSteeringHost(raw string) string {
- h := strings.ToLower(strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(raw), ".")))
- if h != "" && !provision.ValidHostShape(h) {
- log.Printf("console: steering hostname %q is not a valid domain — custom-domain guidance keeps the A-record form", raw)
- return ""
- }
- return h
-}
-
-// normalizeDelegationZone lowercases, trims, and shape-validates raw (from
-// CARLOS_ACME_DELEGATION_ZONE): a value that isn't a legal hostname degrades
-// to "" — delegation off — rather than being handed to lookupCNAME verbatim
-// or failing boot. Mirrors the edge's own validation of the same variable
-// (internal/edge/wildcard.go's newWildcardFromEnv), so a zone the edge would
-// refuse never gets ACCEPTED here only to make every wildcard-enable request
-// dial a garbage DNS query. "" already has a well-defined, honest answer —
-// every enable request refuses with "deployment has no delegation zone
-// configured" — so a badly-typed zone gets exactly that, not a crash or a
-// distinguishable error.
-func normalizeDelegationZone(raw string) string {
- zone := strings.ToLower(strings.TrimSpace(raw))
- if zone != "" && !provision.ValidHostShape(zone) {
- log.Printf("console: CARLOS_ACME_DELEGATION_ZONE %q is not a valid domain — delegation off, wildcard-enable requests refuse with \"no delegation zone configured\" until it's fixed", raw)
- return ""
- }
- return zone
-}
-
// NewServer wires a server over an opened Store, loading (or minting) the
// console's Keymail signing key.
func NewServer(cfg Config, st *Store) (*Server, error) {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index c3ede15be..386b5c544 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1404,14 +1404,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// commits, instead of waiting for the 2s registry poll.
reload := func() { _ = e.Reload() }
layoutReload.Store(&reload)
- m := edge.NewUsageMeter()
- // The per-instance family's box switch: off, the meter keeps no
- // per-instance counts and the usage loop arms no flusher.
- instancesOff := instanceUsageOff(os.Getenv)
- if instancesOff {
- m.DisableInstances()
- log.Printf("agent: instance usage off (CARLOS_INSTANCE_USAGE=off)")
- }
+ m, instancesOff := newUsageMeter(os.Getenv)
e.EnableUsage(m)
// The plan rate ceiling (#358): the same plans snapshot the
// activator's idle hook reads, so a box without a plan catalog gets
@@ -3990,65 +3983,6 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu
}
}
-// isCanaryRoute reports whether rt follows a canary/* channel — the same
-// two-segment convention bake.go's DefaultHolds wildcard matches (a bare
-// "canary" with no slash is NOT covered, same as bake.go: it falls through
-// to the unknown-channel default there, so it shouldn't fast-poll here
-// either).
-func isCanaryRoute(rt registry.Route) bool {
- return strings.HasPrefix(rt.Channel, "canary/")
-}
-
-// countExpiredCanaries counts routes (this box's own, platform aliases
-// excluded — same convention as CollectBox) on a canary/* channel whose
-// pointer has passed release.CanaryTTL, for the fleet status page's §5
-// count (internal/status Probes.ExpiredCanaries). A canary route whose
-// pointer can't be resolved at all — store unavailable, pubkey unusable, or
-// the specific channel won't verify — nils the WHOLE count rather than
-// undercounting: "we couldn't check" and "there are none" are different
-// claims, and this function only ever makes the second one when it's sure.
-// No canary routes at all is a confident, known 0 — it needs no store to
-// answer "none" about routes that don't exist.
-//
-// Pointers are resolved at most once per distinct (account, app, channel)
-// among the routes given (the local `cache` map below), mirroring adopt.go's
-// Pass — this function is called once per 5-minute status tick
-// (statusLoop), so N routes on this box following the same canary channel
-// cost exactly ONE release.Channel() store read for that tick, not N
-// (2026-08-03 review: confirmed and pinned by
-// TestCountExpiredCanariesReadsEachChannelOnce). The cache is local to one
-// call/one tick — nothing persists across ticks, which is fine at a
-// 5-minute cadence.
-func countExpiredCanaries(ctx context.Context, routes []registry.Route, store release.Store, pub ed25519.PublicKey, now time.Time) *int {
- type key struct{ acct, app, channel string }
- cache := map[key]*release.ChannelPointer{}
- n := 0
- for _, rt := range routes {
- // A forward row keeps Channel for display only; the fleet box runs
- // the canary and counts it (fleet public routes spec §4.15).
- if rt.Platform || rt.IsForward() || !isCanaryRoute(rt) {
- continue
- }
- if store == nil || len(pub) != ed25519.PublicKeySize {
- return nil // a canary route exists but nothing here can resolve its pointer
- }
- k := key{release.RouteAccount(rt), rt.App, rt.Channel}
- ptr, cached := cache[k]
- if !cached {
- p, err := release.Channel(ctx, store, pub, k.acct, k.app, k.channel)
- if err != nil {
- return nil // this route's own pointer won't verify — unknown, not zero
- }
- ptr = p
- cache[k] = ptr
- }
- if release.CanaryExpired(ptr, now) {
- n++
- }
- }
- return &n
-}
-
// peekAcmeCache pre-parses the agent args for -acme-cache the same way
// peekRegistryPath peeks -registry: the edge does the authoritative parse,
// this just lets the domains loop stamp cert expiry from the SAME cache dir
diff --git a/internal/host/canary_count.go b/internal/host/canary_count.go
new file mode 100644
index 000000000..600c0224c
--- /dev/null
+++ b/internal/host/canary_count.go
@@ -0,0 +1,70 @@
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// isCanaryRoute reports whether rt follows a canary/* channel — the same
+// two-segment convention bake.go's DefaultHolds wildcard matches (a bare
+// "canary" with no slash is NOT covered, same as bake.go: it falls through
+// to the unknown-channel default there, so it shouldn't fast-poll here
+// either).
+func isCanaryRoute(rt registry.Route) bool {
+ return strings.HasPrefix(rt.Channel, "canary/")
+}
+
+// countExpiredCanaries counts routes (this box's own, platform aliases
+// excluded — same convention as CollectBox) on a canary/* channel whose
+// pointer has passed release.CanaryTTL, for the fleet status page's §5
+// count (internal/status Probes.ExpiredCanaries). A canary route whose
+// pointer can't be resolved at all — store unavailable, pubkey unusable, or
+// the specific channel won't verify — nils the WHOLE count rather than
+// undercounting: "we couldn't check" and "there are none" are different
+// claims, and this function only ever makes the second one when it's sure.
+// No canary routes at all is a confident, known 0 — it needs no store to
+// answer "none" about routes that don't exist.
+//
+// Pointers are resolved at most once per distinct (account, app, channel)
+// among the routes given (the local `cache` map below), mirroring adopt.go's
+// Pass — this function is called once per 5-minute status tick
+// (statusLoop), so N routes on this box following the same canary channel
+// cost exactly ONE release.Channel() store read for that tick, not N
+// (2026-08-03 review: confirmed and pinned by
+// TestCountExpiredCanariesReadsEachChannelOnce). The cache is local to one
+// call/one tick — nothing persists across ticks, which is fine at a
+// 5-minute cadence.
+func countExpiredCanaries(ctx context.Context, routes []registry.Route, store release.Store, pub ed25519.PublicKey, now time.Time) *int {
+ type key struct{ acct, app, channel string }
+ cache := map[key]*release.ChannelPointer{}
+ n := 0
+ for _, rt := range routes {
+ // A forward row keeps Channel for display only; the fleet box runs
+ // the canary and counts it (fleet public routes spec §4.15).
+ if rt.Platform || rt.IsForward() || !isCanaryRoute(rt) {
+ continue
+ }
+ if store == nil || len(pub) != ed25519.PublicKeySize {
+ return nil // a canary route exists but nothing here can resolve its pointer
+ }
+ k := key{release.RouteAccount(rt), rt.App, rt.Channel}
+ ptr, cached := cache[k]
+ if !cached {
+ p, err := release.Channel(ctx, store, pub, k.acct, k.app, k.channel)
+ if err != nil {
+ return nil // this route's own pointer won't verify — unknown, not zero
+ }
+ ptr = p
+ cache[k] = ptr
+ }
+ if release.CanaryExpired(ptr, now) {
+ n++
+ }
+ }
+ return &n
+}
diff --git a/internal/host/instance_usage.go b/internal/host/instance_usage.go
index 6002b52fb..3d779480b 100644
--- a/internal/host/instance_usage.go
+++ b/internal/host/instance_usage.go
@@ -14,6 +14,7 @@ import (
"sync/atomic"
"time"
+ "github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/usage"
)
@@ -235,6 +236,19 @@ func instanceUsageOff(getenv func(string) string) bool {
return getenv("CARLOS_INSTANCE_USAGE") == "off"
}
+// newUsageMeter is the box's usage meter with the box switch applied: off,
+// the meter keeps no per-instance counts and the usage loop arms no
+// flusher. It reports whether the family is off.
+func newUsageMeter(getenv func(string) string) (*edge.UsageMeter, bool) {
+ m := edge.NewUsageMeter()
+ off := instanceUsageOff(getenv)
+ if off {
+ m.DisableInstances()
+ log.Printf("agent: instance usage off (CARLOS_INSTANCE_USAGE=off)")
+ }
+ return m, off
+}
+
// activeInstanceFlusher is the usage loop's flusher, for the status tick's
// dropped-bytes count. nil until the loop arms one, and while switched off.
var activeInstanceFlusher atomic.Pointer[instanceFlusher]
diff --git a/internal/usage/edge.go b/internal/usage/edge.go
index 839a50afe..3ca9ecfb5 100644
--- a/internal/usage/edge.go
+++ b/internal/usage/edge.go
@@ -116,7 +116,9 @@ type EdgeFlush struct {
Guard map[string]GuardDelta
// Instances is the per-instance meter's drain. UpsertEdgeDay ignores it:
// it belongs to the usage/instances/ family, not the old day file.
- Instances map[InstanceBucket]InstanceCount
+ // Instances is in memory only, never serialised: the instance family has
+ // its own object shape.
+ Instances map[InstanceBucket]InstanceCount `json:"-"`
}
// SetOwner labels the row with the route's current account and app. When