carlos / platform Public

usage-attribution-390: usage and billing attribute every box's readings by instance record, not the console box's registry

Statements, the census, the economics page and `carlos status --instances`
joined fleet-wide readings to the console box's own registry, so an
instance on any other box was charged to the ops account, and the hourly
statement re-sweep moved a moved instance's earlier hours to ops too.

A reading now belongs to the tenant its instance or sidecar record names,
for an hour that began after the record was created, wherever the box is.
A host some record names is decided by its records alone, so a hostname
reused across accounts never hands the predecessor's hours over. Hosts with
no record fall back to the sampling box's report, then the console box's
route. An instance whose tenant cannot be established is counted against
no account and logged; `status --instances` marks it unattributed. A live
reading its box tagged with a tenant uses the tag. The census counts
records plus console-box routes no record covers.

Console only; the root package's CLI printer changed too (census overlay).
No backfill: the open month corrects itself at the next statements pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 902e12c9312e5cfbff3a5a0cf961defd6ce8ef11 parent 78c2365
17 files changed, +1,082 −182
  • docs/site/cli.md +5 −5
  • docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md +67 −0
  • docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md +13 −0
  • docs/superpowers/notes/census-proposal-usage-attribution-390.md +11 −0
  • internal/console/apistatusinstances.go +38 −26
  • internal/console/economicspass.go +115 −86
  • internal/console/economicspass_test.go +17 −22
  • internal/console/economicsview.go +43 −27
  • internal/console/metricsview.go +11 −0
  • internal/console/remoteinstances.go +13 −0
  • internal/console/remoteinstances_round5_test.go +1 −1
  • internal/console/usageattrib.go +319 −0
  • internal/console/usageattrib_test.go +379 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv +3 −0
  • status_instances.go +27 −8
  • status_instances_test.go +19 −7

CI cancelled — superseded by a newer push — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 3df4506f6..6d3dbca32 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2305,11 +2305,11 @@ not a secret — a wrong-method request gets a 405 from the router, like every
other route here — but the answer is, because it names other people's
accounts.
-Two things it cannot see, both printed under the table. A sleeping instance
-has no process and so no reading, so it does not appear. And the readings are
-fleet-wide while the account each one is attributed to comes from the
-console's own box's route registry, so on a multi-box deployment an instance
-running elsewhere can show up under `(platform)` rather than under its tenant.
+A sleeping instance has no process or reading, so it does not appear. A note
+under the table explains this. Each reading belongs to the account and app
+named by its instance record, wherever the instance runs. An instance with no
+record or box report showing its owner appears as `(unattributed)`. Its usage
+counts against no account, including the platform.
`--layout` shows which layout each instance is on, box by box. `flat` is the
shared `/data` every instance used to live in. `nested` is the instance's own
diff --git a/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md
new file mode 100644
index 000000000..281ba1596
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md
@@ -0,0 +1,67 @@
+# Copy review brief: usage attribution across boxes (#390)
+
+Paul delegates copy review for platform CLI, console and docs copy to you. You
+are the copy editor; your edits will be applied as approved copy.
+
+## What changed
+
+Until now `carlos status --instances` and the console's usage statements
+decided whose a box's CPU and memory readings were by looking only at the
+console's own box. An instance on any other box was filed under the
+platform. Now each reading belongs to the account and app its instance
+record names, on any box. A reading that nothing can be shown to belong to
+(no instance record, no box report naming its owner) is shown as
+unattributed and is counted against no account, the platform's included.
+
+## The strings (draft text is yours to change; ids are fixed)
+
+Readers: platform operators. `carlos status --instances` is operator-only
+and lists every awake instance on every box, one row per instance, columns
+BOX REGION HOST ACCOUNT APP CPU MEM.
+
+- UA-1, the APP cell of an instance whose owner cannot be established (the
+ ACCOUNT cell prints `-`). It sits beside the existing `(platform)` cell,
+ which marks the platform's own services. Draft: `(unattributed)`
+- UA-2, a note printed in muted text under the table, only when at least one
+ UA-1 row is present. The existing note above it reads `(awake instances
+ only — a hibernating instance has no process to measure)` (older copy, not
+ in scope). Draft: `(unattributed: no record or box report says whose this
+ instance is, so its usage counts against no account)`
+- UA-3, the console's refusal to `carlos status --instances` when it could not
+ read the instance records (transient; retrying usually works). The CLI
+ prints it after `status --instances: `. Draft: `could not read the instance
+ records. Try again.`
+- UA-4, a warning banner on the operator-only economics page when the
+ instance records could not be read; `%v` is a Go error string. Draft:
+ `instance records: %v; no instance's usage is attributed to an account this
+ sweep`
+- UA-5, a docs paragraph in docs/site/cli.md, `--instances` section, after a
+ paragraph about who may call it. Draft:
+
+ > A sleeping instance has no process and so no reading, so it does not
+ > appear, and a note under the table says so. Each reading belongs to the
+ > account and app its instance record names, on whichever box the instance
+ > runs. An instance that no record or box report accounts for shows as
+ > `(unattributed)`, and its usage counts against no account, the
+ > platform's included.
+
+## House rules (Paul's, all binding)
+
+- No em dashes, ever. Use a full stop and a new sentence; in CLI and API
+ error strings the new sentence continues in lower case (`could not provision
+ the store. re-run ...`).
+- Plain words. No jargon a reader would not know. Short.
+- Human text only. If a string is not human text, flag it rather than edit it.
+- Neutral names only (shop, example.com). Never a tenant's name.
+- Keep every placeholder exactly (`%v`) and keep UA-1's parentheses (it sits
+ beside `(platform)`).
+- Do not change the facts a string states. If a fact looks wrong or two rows
+ disagree, flag it.
+
+## Output
+
+Markdown, in this shape:
+
+1. A table of changes only: `id | current | new | why` (a few words in why).
+2. A list of flagged rows: `id | problem`.
+3. One line of counts: changed, flagged, left alone.
diff --git a/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md
new file mode 100644
index 000000000..d55f2c82f
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md
@@ -0,0 +1,13 @@
+| id | current | new | why |
+|---|---|---|---|
+| UA-1 | `(platform)` | `(unattributed)` | Distinguishes unknown ownership from platform services. |
+| UA-2 | `(accounts are joined against the console's own box's route registry; an instance on another box in a fleet can land under (platform))` | `(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)` | Explains the actual condition briefly. |
+| UA-3 | `could not read the route registry — try again` | `could not read the instance records. try again.` | Names the failed read and follows CLI sentence style. |
+| UA-4 | None | `instance records: %v. No instance's usage is attributed to an account this sweep.` | States the warning and its effect clearly. |
+| UA-5 | Existing paragraph about sleeping instances and the console box's route registry | A sleeping instance has no process or reading, so it does not appear. A note under the table explains this. Each reading belongs to the account and app named by its instance record, wherever the instance runs. An instance with no record or box report showing its owner appears as `(unattributed)`. Its usage counts against no account, including the platform. | Removes obsolete behavior and uses shorter, clearer sentences. |
+
+Flagged rows:
+
+None.
+
+changed: 5, flagged: 0, left alone: 0
\ No newline at end of file
diff --git a/docs/superpowers/notes/census-proposal-usage-attribution-390.md b/docs/superpowers/notes/census-proposal-usage-attribution-390.md
new file mode 100644
index 000000000..6c7606183
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-usage-attribution-390.md
@@ -0,0 +1,11 @@
+# Census approval: usage-attribution-390
+
+Ruling `census-ruling-usage-attribution-390`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision.
+
+Seal: `125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd` → `125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/apistatusinstances.go b/internal/console/apistatusinstances.go
index 5577e207c..e5d71607b 100644
--- a/internal/console/apistatusinstances.go
+++ b/internal/console/apistatusinstances.go
@@ -31,23 +31,17 @@
// outright: this is an operator's view of the whole fleet, and no app-scoped
// machine token has any business holding it.
//
-// SCOPE: the two halves of the join do not reach equally far, and the answer
-// is only as fleet-wide as the shorter one. The READINGS are fleet-wide —
-// every box writes metrics/boxes/<box>/ and LoadMetrics sweeps all of it —
-// but the ROUTES they are attributed against come from openPassRegistry,
-// which opens this console's OWN box-local registry file. On a multi-box
-// deployment a unit sampled on any other box therefore matches no route
-// here, falls through routeForUnit's unmatched case, and lands in the answer
-// as platform overhead charged to the ops account: a whole box's tenants
-// read as the platform's own, which is the opposite of what an operator
-// asking "who is using what" would take from it. sweepUsage
-// (economicspass.go) carries this same trap and the same reasoning — both
-// production deployments are single-box today, so it is inert, and the
-// structural fix is routes-as-bucket-records (PR #137, unmerged), which
-// would give every pass a registry view spanning boxes instead of one box's
-// local file. Until that lands the CLI prints the limit beside the answer,
-// the way `carlos routes` does, rather than letting a short list read as the
-// whole fleet.
+// SCOPE: the readings are fleet-wide — every box writes metrics/boxes/<box>/
+// and LoadMetrics sweeps all of it — and so is the join (#390). Each reading
+// is attributed the way the economics passes attribute it
+// (usageattrib.go): a reading its box tagged with a tenant is that tenant's;
+// otherwise an instance's unit goes to the tenant its record names, wherever
+// the box is; a host with no record to the tenant the sampling box's report
+// names, then to the console box's route. An instance's unit none of those
+// can place is shown as unattributed, never as the platform's: until #390
+// a whole remote box's tenants read as platform overhead charged to the ops
+// account, the opposite of what an operator asking "who is using what"
+// would take from it.
//
// The other limit is by design rather than a defect: an instance that is
// ASLEEP has no cgroup and therefore no sample, so it is not here at all.
@@ -64,9 +58,9 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-// apiStatusInstance is one awake instance. Account and app are joined on from
-// the registry through routeForUnit — the same matching rule the economics
-// pass attributes cost with, deliberately shared rather than reimplemented.
+// apiStatusInstance is one awake instance. Account and app are joined on
+// through usageAttribution — the same rule the economics passes attribute
+// cost with, deliberately shared rather than reimplemented.
type apiStatusInstance struct {
Box string `json:"box"`
Unit string `json:"unit"`
@@ -91,8 +85,19 @@ type apiStatusInstance struct {
// operator asking what is on the box wants the box's own overhead in the
// picture, clearly labelled rather than silently dropped.
Platform bool `json:"platform,omitempty"`
+ // Unattributed marks an instance's unit whose owner cannot be
+ // established: no tag from its box, no record that existed when the
+ // reading was taken, no report or console-box route for a host with no
+ // record. Account and App are empty; Host is the unit's. The economics
+ // passes count such a reading against no account.
+ Unattributed bool `json:"unattributed,omitempty"`
}
+// statusInstancesRecordsUnread refuses the answer when the instance records
+// cannot be read: every instance's owner comes from them. Copy: Luna pass,
+// 2026-10-26 (UA-3).
+const statusInstancesRecordsUnread = "could not read the instance records. try again."
+
func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request) {
addr, ok := s.cliUser(w, r)
if !ok {
@@ -125,6 +130,12 @@ func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request
jsonError(w, http.StatusBadGateway, "could not read the route registry — try again")
return
}
+ attrib := s.newUsageAttribution(r.Context(), routes)
+ if attrib.recordsErr != nil {
+ log.Printf("console: api status instances: instance records: %v", attrib.recordsErr)
+ jsonError(w, http.StatusBadGateway, statusInstancesRecordsUnread)
+ return
+ }
boxes, _, err := s.LoadMetrics(r.Context())
if err != nil {
log.Printf("console: api status instances: metrics: %v", err)
@@ -138,13 +149,14 @@ func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request
for _, u := range b.Units {
row := apiStatusInstance{Box: b.Box, Unit: u.Unit, CPU: u.CPUFrac, Mem: u.MemBytes}
row.Region, row.RegionName = s.boxRegion(b.Box)
- // unitOwner's two cases, taken off the match already in hand
- // rather than by walking the whole route list a second time —
- // same rule, same answers, one pass.
- if rt, ok := routeForUnit(routes, u.Unit); ok {
- row.Host, row.App, row.Account = rt.Host, rt.App, release.RouteAccount(rt)
- } else {
+ who := attrib.attribute(r.Context(), b.Box, u.Unit, b.At, b.latestOwner(u))
+ switch who.class {
+ case unitTenant:
+ row.Host, row.Account, row.App = who.host, who.owner.Account, who.owner.App
+ case unitPlatform:
row.Platform, row.Account = true, release.OpsAccount
+ default:
+ row.Unattributed, row.Host = true, who.host
}
if want != "" && row.Account != want {
continue
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index db4dd18ca..c7a79dcd5 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -18,10 +18,10 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
- "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/economics"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/usage"
@@ -96,6 +96,16 @@ func (s *Server) openPassRegistry() (consoleRegistry, error) {
// a route with no account (Route.Account == "") to release.OpsAccount, the
// deployment operator's built-in account — so pre-accounts routes land in
// one place instead of scattering under "".
+//
+// What it counts (#390): every instance record, wherever its box is, plus
+// every console-box route no record covers (a hand route, an apex mint, a
+// sidecar row), one per host. Until #390 it counted the console box's
+// routes alone, so an account whose instances all ran on other boxes
+// dropped out of the census. Left out: records of an app in the Trash (its
+// routes are withdrawn while the record waits out the restore window), and
+// records placed on a customer fleet (fleet boxes are metered by
+// fleetMeters, and their routes were never counted here). Both reads must
+// succeed: the day is create-only, so a partial read would be permanent.
func (s *Server) censusPass(ctx context.Context, date string) error {
key := usage.CensusDayKey(date)
if _, _, err := s.cfg.Releases.Get(ctx, key); err == nil {
@@ -109,26 +119,67 @@ func (s *Server) censusPass(ctx context.Context, date string) error {
if err != nil {
return err
}
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ recs, _, err := provision.ListAllRecordsStrictJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ return fmt.Errorf("console: census pass: instance records: %w", err)
+ }
+ trashed, err := s.trashedApps()
+ if err != nil {
+ return fmt.Errorf("console: census pass: %w", err)
+ }
accounts := map[string]usage.CensusAccount{}
apps := map[string]map[string]bool{}
- for _, rt := range routes {
- acct := release.RouteAccount(rt)
+ counted := map[string]bool{}
+ count := func(host, acct, app string) {
+ if counted[host] {
+ return
+ }
+ counted[host] = true
c := accounts[acct]
c.Routes++
if apps[acct] == nil {
apps[acct] = map[string]bool{}
}
- if rt.App != "" && !apps[acct][rt.App] {
- apps[acct][rt.App] = true
+ if app != "" && !apps[acct][app] {
+ apps[acct][app] = true
c.Apps++
}
accounts[acct] = c
}
+ for _, rec := range recs {
+ if _, fleet := registry.FleetPlacement(rec.Region); fleet || trashed[rec.Account+"/"+rec.App] {
+ continue
+ }
+ count(rec.Host, rec.Account, rec.App)
+ }
+ for _, rt := range routes {
+ count(rt.Host, release.RouteAccount(rt), rt.App)
+ }
day := usage.CensusDay{V: 1, Date: date, Accounts: accounts}
_, err = usage.CreateDayObject(ctx, s.cfg.Releases, key, day)
return err
}
+// trashedApps is every app in the Trash, as "<sqid>/<app>".
+func (s *Server) trashedApps() (map[string]bool, error) {
+ accts, err := s.store.Accounts()
+ if err != nil {
+ return nil, err
+ }
+ out := map[string]bool{}
+ for _, a := range accts {
+ apps, err := s.store.TrashedAppsIn(a.ID)
+ if err != nil {
+ return nil, err
+ }
+ for _, t := range apps {
+ out[a.Sqid+"/"+t.App] = true
+ }
+ }
+ return out, nil
+}
+
// storagePass sizes every app's deployment-bucket prefix, plus its tenant
// object store when one is provisioned, create-only per day. Requires the
// bucket to support sized listings (release.SizeLister); a store that
@@ -214,45 +265,6 @@ func (s *Server) storagePass(ctx context.Context, date string) error {
return err
}
-// unitOwner attributes a sampled systemd unit (or exec-child cgroup name) to
-// its route's account/app. Matching mirrors OwnerAppMetrics (metricsview.go
-// ~698-730): rather than parse a host back out of the unit string, it builds
-// each route's OWN expected unit names — activator.UnitName/ExecName for a
-// unit-backed or exec-backed instance route, plus the route's stamped Unit
-// column (#110's bespoke unit) — and compares those forward against the
-// sampled name. (Read first per the brief: neither UnitName nor ExecName
-// systemd-escapes the host — activator.UnitName is a bare string
-// concatenation and cgroup.ExecName likewise — so there is no unescaping
-// helper to reuse; building the expected name forward, the same direction
-// OwnerAppMetrics does it, is what keeps a hyphenated or dotted host correct
-// with no separate escaping step.) A unit matching no route — the console's
-// own unit, system units — attributes to release.OpsAccount, app "": platform
-// overhead.
-func unitOwner(routes []registry.Route, unit string) (acct, app string, ok bool) {
- rt, ok := routeForUnit(routes, unit)
- if !ok {
- return release.OpsAccount, "", false
- }
- return release.RouteAccount(rt), rt.App, true
-}
-
-// routeForUnit is the matching rule itself, split out of unitOwner so that a
-// second reader of the same sampled units — `carlos status --instances`,
-// which needs the route's HOST and not only its owner — cannot end up with a
-// private second notion of which route a cgroup belongs to. The comment above
-// unitOwner is the rationale for the rule; this is the rule.
-func routeForUnit(routes []registry.Route, unit string) (registry.Route, bool) {
- for _, rt := range routes {
- if rt.Unit != "" && rt.Unit == unit {
- return rt, true
- }
- if rt.Host != "" && (unit == activator.UnitName(rt.Host) || unit == activator.ExecName(rt.Host)) {
- return rt, true
- }
- }
- return registry.Route{}, false
-}
-
// usageSweep is sweepUsage's result: the box- and account-shaped meters
// accumulated by reading metrics and edge days over [from, to], plus enough
// coverage bookkeeping for callers to label a total honestly. It deliberately
@@ -284,16 +296,16 @@ type usageSweep struct {
// by statementsPass (whole month to date, create-or-replace statements) and
// Task 11's LoadEconomics (arbitrary period, priced live under a scenario).
//
-// routes is the registry snapshot unitOwner attributes sampled units
-// against — the CALLER resolves it, deliberately not sweepUsage itself,
-// because the two callers need opposite failure behaviour on a
-// missing/unmounted registry: statementsPass (a WRITE pass) must refuse
-// outright rather than write a permanent all-zero day off an empty
-// registry.Open (openPassRegistry's own doc comment), while LoadEconomics
-// (a READ path) degrades instead — see loadRoutesForEconomics
-// (economicsview.go). A nil/empty routes therefore isn't an error here:
-// every sampled unit simply falls through unitOwner's unmatched-unit case
-// to release.OpsAccount, same as any other unmatched unit.
+// attrib says whose each sampled unit's hour is (usageattrib.go, #390): an
+// instance's hour goes to the tenant its record names, if the record existed
+// when the hour began, wherever the box was; a platform unit's to
+// release.OpsAccount; and an instance's hour whose tenant cannot be
+// established to no account at all, tallied and logged once per sweep. The
+// CALLER builds it, deliberately not sweepUsage itself, because the two
+// callers need opposite failure behaviour: statementsPass (a WRITE pass)
+// refuses outright when the console box's registry or the records cannot be
+// read (passAttribution), while LoadEconomics (a READ path) degrades with a
+// warning (loadAttributionForEconomics, economicsview.go).
//
// Storage and census are deliberately NOT accumulated here: storage's
// account attribution needs a ValidAccount guard with pass-scoped dedup
@@ -304,18 +316,7 @@ type usageSweep struct {
// sweep and nothing else is still a covered day, exactly as before this
// function existed, even though the bytes themselves are read again by
// foldStorageAndCensus.
-//
-// unitOwner attributes a sampled unit against routes, which — for both
-// current callers — is this CONSOLE's own box-local registry, while this
-// sweep iterates units published by every box under metrics/boxes/. On a
-// multi-box deployment a unit sampled on a box other than this console's own
-// can fail to match any route in this registry and silently fall to
-// release.OpsAccount, indistinguishable from the intended platform-overhead
-// fallback. Both production deployments are single-box today, so this is
-// currently inert; the structural fix is routes-as-bucket-records (PR #137,
-// unmerged), which would give every pass a registry view that spans boxes
-// instead of one box's local file.
-func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []registry.Route) (*usageSweep, error) {
+func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) {
metricsBoxes, err := s.cfg.Releases.ListDirs(ctx, metricsBoxesPrefix)
if err != nil {
return nil, fmt.Errorf("console: sweep usage: %w", err)
@@ -355,6 +356,9 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re
return bl
}
+ unattributed := unattributedUsage{}
+ defer unattributed.log(from, to)
+
fromDay := from.UTC().Truncate(24 * time.Hour)
toDay := to.UTC().Truncate(24 * time.Hour)
for d := fromDay; !d.After(toDay); d = d.AddDate(0, 0, 1) {
@@ -376,24 +380,44 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re
sweep.BoxDays[box]++
bl := boxLoad(box)
bl.Hours += float64(len(roll.Hours))
- for _, hour := range roll.Hours {
+ for hourKey, hour := range roll.Hours {
+ // The hour's start: a record vouches for an hour only if it
+ // existed when the hour began. An unparsable key vouches for
+ // nothing (the zero time precedes every record).
+ at, _ := time.Parse("2006-01-02T15", date+"T"+hourKey)
for unit, um := range hour.Units {
- acct, _, _ := unitOwner(routes, unit)
- mm := touch(acct)
var instN int
var cpuCoreHours, memGBHours float64
- if cpu, ok := um["cpu"]; ok {
+ cpu, hasCPU := um["cpu"]
+ if hasCPU {
cpuCoreHours = cpu.Avg * float64(cpu.N) / 60
- mm[usage.MeterCPUCoreHours] += cpuCoreHours
instN = cpu.N
}
- if mem, ok := um["mem_bytes"]; ok {
+ mem, hasMem := um["mem_bytes"]
+ if hasMem {
memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9
- mm[usage.MeterMemGBHours] += memGBHours
if instN == 0 {
instN = mem.N
}
}
+ who := attrib.attribute(ctx, box, unit, at, nil)
+ var acct string
+ switch who.class {
+ case unitTenant:
+ acct = who.owner.Account
+ case unitPlatform:
+ acct = release.OpsAccount
+ default:
+ unattributed.add(box, unit, float64(instN)/60)
+ continue
+ }
+ mm := touch(acct)
+ if hasCPU {
+ mm[usage.MeterCPUCoreHours] += cpuCoreHours
+ }
+ if hasMem {
+ mm[usage.MeterMemGBHours] += memGBHours
+ }
mm[usage.MeterInstanceHours] += float64(instN) / 60
al := bl.ByAccount[acct]
al.CPUCoreHours += cpuCoreHours
@@ -614,7 +638,7 @@ func hasDeviceTag(tags string) bool {
//
// Deliberately a SECOND bounded read over metrics day objects, not an
// extension of sweepUsage's single pass: sweepUsage iterates every box under
-// metrics/boxes/ once and attributes by UNIT (unitOwner), which has no
+// metrics/boxes/ once and attributes by UNIT (usageAttribution), which has no
// concept of a fleet box at all — a fleet box's day rollup carries no units
// most of the time (see rollupPresenceHours's doc comment), only a host
// aggregate, so folding this in there would mean threading a
@@ -652,9 +676,9 @@ func hasDeviceTag(tags string) bool {
// bucket-backed box publishing straight to the platform root, or one an
// operator hand-configured with CARLOS_STATUS_PREFIX="" — is invisible to
// this meter: its rollups never appear under fleets/<fleet>/, so it
-// contributes zero fleet box-hours, and its sampled units (if any) fall
-// through unitOwner's unmatched case to release.OpsAccount like any other
-// unrecognized unit, same as a platform box's stray unit would. This
+// contributes zero fleet box-hours, and its sampled units (if any) are
+// attributed like any platform box's (usageAttribution): an instance's
+// to the tenant its record names, anything else to release.OpsAccount. This
// closes itself once the box (re)publishes under its fleet prefix — no
// separate migration is needed.
// - fleetMeters failing makes statementsPass itself fail (see
@@ -731,9 +755,10 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// census, for app_months, and fleet box-hours, for fleet_box_hours_server/
// device) into one usage.Statement per account, create-or-replace via
// usage.UpsertStatement — safe to run repeatedly as new days' objects
-// appear. It is a thin caller: open the registry (refusing early — see
-// openPassRegistry — since this is the WRITE pass), sweep the whole month to
-// date (sweepUsage), fold in storage/census meters (foldStorageAndCensus),
+// appear. It is a thin caller: build the attribution (passAttribution:
+// refusing early when the console box's registry is missing — see
+// openPassRegistry — or the instance records cannot be read, since this is
+// the WRITE pass), sweep the whole month to date (sweepUsage), fold in storage/census meters (foldStorageAndCensus),
// fold in fleet meters (fleetMeters — a union merge, since an account with
// ONLY fleet usage and no platform routes at all must still get every meter
// key it's owed), then upsert.
@@ -744,6 +769,14 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// deletion onward — the account's last statement object simply stops moving
// forward, rather than the month closing it out explicitly.
//
+// Every run re-attributes the whole month (#390): an hour belongs to the
+// tenant whose record existed when it began, not to whoever routes the host
+// today, so a move leaves an instance's earlier hours with it and a
+// hostname reused across accounts never hands the predecessor's hours to
+// the successor. An instance whose record is deleted mid-month has no
+// record left to vouch for its hours, so the next run counts them against
+// no account and logs them.
+//
// fleetMeters failing (a bad registry read, a bucket hiccup under a fleet
// prefix) makes this WHOLE pass return an error rather than upsert
// statements missing that account's fleet hours — deliberate (review, fix
@@ -756,11 +789,7 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// economics page over it is not, the same asymmetry sweepUsage's own doc
// comment draws between its two callers.
func (s *Server) statementsPass(ctx context.Context, now time.Time) error {
- reg, err := s.openPassRegistry()
- if err != nil {
- return fmt.Errorf("console: statements pass: %w", err)
- }
- routes, err := reg.List()
+ attrib, err := s.passAttribution(ctx)
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
@@ -771,7 +800,7 @@ func (s *Server) statementsPass(ctx context.Context, now time.Time) error {
month := usage.MonthOf(nowUTC)
monthStart := time.Date(y, mo, 1, 0, 0, 0, 0, time.UTC)
- sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, routes)
+ sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, attrib)
if err != nil {
return fmt.Errorf("console: statements pass: %w", err)
}
diff --git a/internal/console/economicspass_test.go b/internal/console/economicspass_test.go
index 4a6819b99..3502b0b66 100644
--- a/internal/console/economicspass_test.go
+++ b/internal/console/economicspass_test.go
@@ -424,31 +424,26 @@ func TestStatementsPassZeroUsageAccountListed(t *testing.T) {
}
}
-// TestUnitOwnerUnmatchedFallsToOpsAccount pins the correction over the
-// brief's literal text: the fallback is release.OpsAccount ("bab"), never
-// the bare string "ops".
-func TestUnitOwnerUnmatchedFallsToOpsAccount(t *testing.T) {
- acct, app, ok := unitOwner(nil, "console.service")
- if ok {
- t.Fatalf("unitOwner matched an empty route list: acct=%q app=%q", acct, app)
- }
- if acct != release.OpsAccount {
- t.Fatalf("unmatched unit acct = %q, want release.OpsAccount (%q)", acct, release.OpsAccount)
- }
- if app != "" {
- t.Fatalf("unmatched unit app = %q, want empty", app)
+// TestAttributionPlatformUnitFallsToOpsAccount pins the correction over the
+// brief's literal text: a unit that is not an instance's is platform
+// overhead, charged to release.OpsAccount ("bab"), never the bare string
+// "ops".
+func TestAttributionPlatformUnitFallsToOpsAccount(t *testing.T) {
+ a := &usageAttribution{}
+ if who := a.attribute(context.Background(), "box1", "console.service", time.Now(), nil); who.class != unitPlatform || who.owner != (metrics.Owner{}) {
+ t.Fatalf("console.service = %+v, want platform overhead", who)
}
}
-// TestUnitOwnerMatchesStampedUnitColumn: a route with a non-empty Unit
-// column matches that exact unit name, independent of Host.
-func TestUnitOwnerMatchesStampedUnitColumn(t *testing.T) {
- routes := []registry.Route{
- {Host: "bespoke.example.com", App: "bespoke", Unit: "carlos-bespoke.service"},
- }
- acct, app, ok := unitOwner(routes, "carlos-bespoke.service")
- if !ok || app != "bespoke" || acct != release.OpsAccount {
- t.Fatalf("unitOwner(stamped unit) = %q %q %v", acct, app, ok)
+// TestAttributionMatchesStampedUnitColumn: a console-box route with a
+// non-empty Unit column matches that exact unit name, independent of Host.
+func TestAttributionMatchesStampedUnitColumn(t *testing.T) {
+ a := &usageAttribution{stamped: map[string]registry.Route{
+ "carlos-bespoke.service": {Host: "bespoke.example.com", App: "bespoke", Unit: "carlos-bespoke.service"},
+ }}
+ who := a.attribute(context.Background(), "box1", "carlos-bespoke.service", time.Now(), nil)
+ if who.class != unitTenant || who.owner.App != "bespoke" || who.owner.Account != release.OpsAccount {
+ t.Fatalf("stamped unit = %+v", who)
}
}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index bb6c0ac25..2dbeec26f 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -46,10 +46,11 @@ type EconomicsView struct {
// not be loaded/parsed/validated — never set when active.json is simply
// absent (a fresh deployment, not a fault; see loadActiveScenario).
ScenarioWarning string
- // Warning is set when the SWEEP itself degraded — currently only "no
- // registry configured/reachable", which makes every sampled unit
- // attribute to release.OpsAccount instead of its real account (see
- // loadRoutesForEconomics). Distinct from ScenarioWarning: the two can
+ // Warning is set when the SWEEP itself degraded: no registry
+ // configured/reachable (stamped units and console-box hand routes go
+ // unmatched), instance records unreadable (no instance's usage is
+ // attributed to an account), or fleet meters unavailable (see
+ // loadAttributionForEconomics). Distinct from ScenarioWarning: the two can
// both be set at once and Task 13 renders them as separate notices.
Warning string
Scenarios []string // names under economics/scenarios/
@@ -409,9 +410,9 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
// comment for why this must be the full month, not PeriodDays.
daysInMonth := time.Date(now.Year(), now.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
- routes, warning := s.loadRoutesForEconomics(sweepCtx)
+ attrib, warning, recordsWarning := s.loadAttributionForEconomics(sweepCtx)
- sweep, err := s.sweepUsage(sweepCtx, from, to, routes)
+ sweep, err := s.sweepUsage(sweepCtx, from, to, attrib)
if err != nil {
return nil, fmt.Errorf("console: load economics: %w", err)
}
@@ -429,18 +430,18 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
// fleetMeters error — see that function's doc comment), THIS is a READ
// path: a bad registry read or a bucket hiccup under a fleet prefix
// degrades to "no fleet meters this render" plus a visible Warning,
- // never a failed dashboard — the same asymmetry loadRoutesForEconomics
+ // never a failed dashboard — the same asymmetry loadAttributionForEconomics
// already draws for the registry itself. Called once per
// buildEconomicsView call, which is already the unit the 60s
// stale-while-revalidate cache (economicsCacheTTL) bounds — no separate
// throttling needed here. A registry-less console would otherwise show
- // TWO banners for the SAME missing registry (loadRoutesForEconomics's
+ // TWO banners for the SAME missing registry (loadAttributionForEconomics's
// and this one, since fleetMeters opens that identical registry) — see
// the warning=="" guard below, which keeps it to one banner, one cause.
if fleetMM, ferr := s.fleetMeters(sweepCtx, from, to); ferr != nil {
log.Printf("console: load economics: fleet meters unavailable: %v", ferr)
// Suppress a second banner when routes are ALREADY degraded
- // (warning != "" here can only mean loadRoutesForEconomics found no
+ // (warning != "" here can only mean loadAttributionForEconomics found no
// usable registry, the one thing that precedes this call): fleetMeters
// opens that exact same registry, so its failure here is the same
// root cause restated, not a second independent fault. One banner,
@@ -461,6 +462,16 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom
}
}
+ // The records warning is its own cause, so it is added after the fleet
+ // meters' one-banner rule above, which reads warning as "the registry
+ // is missing" only.
+ if recordsWarning != "" {
+ if warning != "" {
+ warning += "; "
+ }
+ warning += recordsWarning
+ }
+
sc, scenarioWarning := s.loadActiveScenario(sweepCtx)
scenarioNames, err := s.listScenarioNames(sweepCtx)
@@ -714,28 +725,33 @@ func poolTopupAccrual(from, to time.Time, topupUSD float64) float64 {
return total
}
-// loadRoutesForEconomics resolves the routes sweepUsage needs to attribute
-// sampled units to accounts, DEGRADING rather than failing when the
-// registry is missing or unreadable — the opposite of openPassRegistry's
-// refusal, and deliberately so: that refusal protects a WRITE pass from
-// reading registry.Open's freshly-created empty sqlite as "zero routes" and
-// writing a permanent, uncorrectable all-zero day. This is a READ path —
-// there is nothing to protect by refusing. A nil routes list simply means
-// unitOwner falls every sampled unit through to release.OpsAccount
-// (indistinguishable from platform overhead, same as any other unmatched
-// unit), and the dashboard still renders with a visible warning rather than
-// a blank 500 — precedent: commit 0958fa3, instances health degrading on a
-// console with no registry rather than failing the page.
-func (s *Server) loadRoutesForEconomics(ctx context.Context) (routes []registry.Route, warning string) {
+// loadAttributionForEconomics builds the attribution sweepUsage needs
+// (usageattrib.go), DEGRADING rather than failing when the console box's
+// registry or the instance records cannot be read — the opposite of
+// passAttribution's refusal, and deliberately so: that refusal protects a
+// WRITE pass from writing numbers it could not attribute. This is a READ
+// path — there is nothing to protect by refusing. With no registry, stamped
+// units and console-box hand routes go unmatched; with no records, no
+// instance's reading is attributed to any account. Either way the dashboard
+// still renders, with a visible warning rather than a blank 500 —
+// precedent: commit 0958fa3, instances health degrading on a console with
+// no registry rather than failing the page. registryWarning and
+// recordsWarning are returned apart because the fleet meters' one-banner
+// rule (buildEconomicsView) concerns the registry only.
+func (s *Server) loadAttributionForEconomics(ctx context.Context) (attrib *usageAttribution, registryWarning, recordsWarning string) {
+ var routes []registry.Route
reg, err := s.openPassRegistry()
if err != nil {
- return nil, fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", err)
+ registryWarning = fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", err)
+ } else if routes, err = reg.List(); err != nil {
+ routes = nil
+ registryWarning = fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", err)
}
- routes, err = reg.List()
- if err != nil {
- return nil, fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", err)
+ attrib = s.newUsageAttribution(ctx, routes)
+ if attrib.recordsErr != nil {
+ recordsWarning = fmt.Sprintf("instance records: %v. No instance's usage is attributed to an account this sweep.", attrib.recordsErr) // Luna pass 2026-10-26 (UA-4)
}
- return routes, ""
+ return attrib, registryWarning, recordsWarning
}
// loadActiveScenario resolves economics.ActiveKey -> named scenario ->
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go
index 5e6142844..e9b2ca80c 100644
--- a/internal/console/metricsview.go
+++ b/internal/console/metricsview.go
@@ -85,6 +85,17 @@ func (v BoxMetricsView) ownerIndex(tenant metrics.Owner) int32 {
return -1
}
+// latestOwner is the tenant the box tagged u's latest reading with (the
+// reading UnitRow carries), nil when it tagged none.
+func (v BoxMetricsView) latestOwner(u UnitRow) *metrics.Owner {
+ n := len(u.owner)
+ if n == 0 || n != len(v.times) || u.owner[n-1] < 0 || int(u.owner[n-1]) >= len(v.owners) {
+ return nil
+ }
+ o := v.owners[u.owner[n-1]]
+ return &o
+}
+
// AlertRow is one currently-firing rule on one box. LoadMetrics only ever
// returns firing rules — a quiet rule has nothing to show.
type AlertRow struct {
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index 2b3a4c77b..f992c3679 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -337,6 +337,19 @@ func (f appFacts) host(rec provision.Record) *hostReport {
// complete is whether every box's report was read.
func (f appFacts) complete() bool { return f.reports.complete }
+// tenantOn is the tenant box's own fresh report names for host, whatever
+// app the facts were read for. Usage attribution asks it about a host no
+// record names (usageattrib.go): only the box that took a reading can say
+// whose process it ran.
+func (f appFacts) tenantOn(box, host string) (metrics.Owner, bool) {
+ for _, r := range f.reports.byHost[host] {
+ if r.box == box && r.tenantKnown {
+ return metrics.Owner{Account: r.account, App: r.app}, true
+ }
+ }
+ return metrics.Owner{}, false
+}
+
// seen reports whether any fresh box report names host at all, whoever it
// says the host belongs to: a host some box serves is not "not minted
// anywhere", even when nothing about it can be joined.
diff --git a/internal/console/remoteinstances_round5_test.go b/internal/console/remoteinstances_round5_test.go
index 974f061ce..916122237 100644
--- a/internal/console/remoteinstances_round5_test.go
+++ b/internal/console/remoteinstances_round5_test.go
@@ -29,7 +29,7 @@ func TestRemoteFactsOneAccessor(t *testing.T) {
allowed := map[string]map[string]bool{
"foldFleetReports": {"remoteFacts": true},
"pageBoxReports": {"remoteFacts": true, "handleApp": true},
- "byHost": {"foldFleetReports": true, "host": true, "seen": true, "unrecorded": true},
+ "byHost": {"foldFleetReports": true, "host": true, "seen": true, "unrecorded": true, "tenantOn": true},
}
files, err := filepath.Glob("*.go")
if err != nil {
diff --git a/internal/console/usageattrib.go b/internal/console/usageattrib.go
new file mode 100644
index 000000000..33f9f86ae
--- /dev/null
+++ b/internal/console/usageattrib.go
@@ -0,0 +1,319 @@
+package console
+
+// Usage attribution (#390): whose is a sampled unit's reading?
+//
+// The readings are fleet-wide: every box writes metrics/boxes/<box>/ and the
+// sweeps read all of it. Until #390 the owner of each reading came from the
+// console box's own registry, so an instance on any other box matched no
+// route and was charged to the ops account as platform overhead, and the
+// statements pass, which re-sweeps the whole month against today's routes,
+// moved an instance's earlier hours to ops as soon as it left the console's
+// box.
+//
+// The owner now comes from region-neutral sources, in this order:
+//
+// 1. A unit stamped on a console-box route (#110's bespoke unit): that
+// route's account and app, as before.
+// 2. Anything that is not an instance's unit (carlos-exec@<host> or
+// carlos-app@<host>.service) is the platform's own: the ops account.
+// 3. A live reading its box tagged with a tenant (metrics.UnitSample.Owner,
+// remote-instance-metrics) is that tenant's. Day rollups carry no tag,
+// so this applies to the live view only.
+// 4. The host's instance or sidecar record: its account and app, for a
+// reading taken in an hour that starts at or after the record's
+// created_at. A host some record names is decided by its records alone,
+// so a hostname reused across accounts never hands the predecessor's
+// hours to the successor. Records survive a move unchanged, so an
+// instance's hours on the box it left stay its own.
+// 5. A host no record names (a hand route, an apex mint): the tenant the
+// sampling box's own fresh report names for it, then the console box's
+// route for it when the console's box took the sample.
+// 6. Otherwise the reading's tenant cannot be established. It is counted
+// against no account, the platform's included, and the sweep logs it.
+//
+// Records are read once per pass through the record view when it is armed
+// (recordWalkStore), so a pass on a deployment with the change index adds
+// no bucket requests. Box reports are read only when a host has no record,
+// through remoteFacts and its 60-second cache.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// unitClass is what a sampled unit is, for usage.
+type unitClass int
+
+const (
+ // unitPlatform is not an instance's unit: the platform's own overhead,
+ // charged to release.OpsAccount.
+ unitPlatform unitClass = iota
+ // unitTenant is an instance whose tenant is established.
+ unitTenant
+ // unitUnknown is an instance's unit whose tenant cannot be established.
+ // It is counted against no account.
+ unitUnknown
+)
+
+// unitOwnership is one reading's owner.
+type unitOwnership struct {
+ class unitClass
+ host string
+ owner metrics.Owner
+}
+
+// recordTenant is one record's tenant and when the record was created.
+type recordTenant struct {
+ owner metrics.Owner
+ created time.Time
+}
+
+// usageAttribution answers unitOwnership for every reading of one pass. It is
+// built once per pass (newUsageAttribution) and used from one goroutine.
+type usageAttribution struct {
+ // stamped is the console box's routes with a stamped unit, by unit.
+ stamped map[string]registry.Route
+ // local is the console box's routes by host, and box the console's own
+ // box label: a local route vouches only for a reading that box took.
+ // With no label known, any box's (a single-box deployment).
+ local map[string]registry.Route
+ box string
+
+ // records is every instance record's tenant by host. recordsErr is set
+ // when the records could not be read, and then no instance reading is
+ // attributed at all: with the records unknown, nothing can show that a
+ // host has no record. unreadable is a host whose record did not decode.
+ records map[string][]recordTenant
+ unreadable map[string]bool
+ recordsErr error
+
+ // src is the store the records were read from, for sidecar records,
+ // and sidecars their memo by host.
+ src release.Store
+ sidecars map[string]sidecarLookup
+
+ // facts reads the box reports, once, when a host with no record needs
+ // them.
+ facts func(context.Context) appFacts
+ factsLoaded bool
+ fleetFacts appFacts
+}
+
+type sidecarLookup struct {
+ tenants []recordTenant
+ err error
+}
+
+// newUsageAttribution reads what attribution needs: routes is the console
+// box's registry (nil when it has none), and the records are read here. A
+// failed record read is kept in recordsErr, for the caller to refuse (a
+// write pass) or degrade (a read).
+func (s *Server) newUsageAttribution(ctx context.Context, routes []registry.Route) *usageAttribution {
+ a := &usageAttribution{
+ stamped: map[string]registry.Route{},
+ local: map[string]registry.Route{},
+ box: s.cfg.BoxLabel,
+ records: map[string][]recordTenant{},
+ unreadable: map[string]bool{},
+ sidecars: map[string]sidecarLookup{},
+ facts: func(ctx context.Context) appFacts { return s.remoteFacts(ctx, "", "") },
+ }
+ for _, rt := range routes {
+ if rt.Unit != "" {
+ a.stamped[rt.Unit] = rt
+ }
+ if rt.Host != "" {
+ a.local[rt.Host] = rt
+ }
+ }
+ if s.cfg.Releases == nil {
+ a.recordsErr = errors.New("no deployment bucket")
+ return a
+ }
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ a.src = src
+ recs, unreadable, err := provision.ListAllRecordsStrictJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ a.recordsErr = err
+ return a
+ }
+ for _, rec := range recs {
+ a.records[rec.Host] = append(a.records[rec.Host], recordTenant{
+ owner: metrics.Owner{Account: rec.Account, App: rec.App},
+ created: rec.CreatedAt,
+ })
+ }
+ a.unreadable = unreadable
+ return a
+}
+
+// passAttribution is newUsageAttribution for a pass that writes: the console
+// box's registry must open (openPassRegistry: never an empty one created in
+// its place) and the records must read, or the pass writes nothing.
+func (s *Server) passAttribution(ctx context.Context) (*usageAttribution, error) {
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return nil, err
+ }
+ routes, err := reg.List()
+ if err != nil {
+ return nil, err
+ }
+ a := s.newUsageAttribution(ctx, routes)
+ if a.recordsErr != nil {
+ return nil, fmt.Errorf("instance records: %w", a.recordsErr)
+ }
+ return a, nil
+}
+
+// instanceHost is the host of an instance's unit: carlos-exec@<host> (an
+// exec-backed or nested instance, or a sidecar) or carlos-app@<host>.service
+// (a unit-backed one). Anything else is not an instance's.
+func instanceHost(unit string) (string, bool) {
+ const app = "carlos-app@"
+ switch {
+ case strings.HasPrefix(unit, "carlos-exec@"):
+ host := strings.TrimPrefix(unit, "carlos-exec@")
+ return host, host != "" && activator.ExecName(host) == unit
+ case strings.HasPrefix(unit, app) && strings.HasSuffix(unit, ".service"):
+ host := strings.TrimSuffix(strings.TrimPrefix(unit, app), ".service")
+ return host, host != "" && activator.UnitName(host) == unit
+ }
+ return "", false
+}
+
+// attribute is the owner of the reading of unit that box took at (the start
+// of a rollup's hour, or a live sample's time). tag is the tenant the box
+// tagged the reading with, nil for none or for a rollup.
+func (a *usageAttribution) attribute(ctx context.Context, box, unit string, at time.Time, tag *metrics.Owner) unitOwnership {
+ if rt, ok := a.stamped[unit]; ok {
+ return unitOwnership{class: unitTenant, host: rt.Host, owner: metrics.Owner{Account: release.RouteAccount(rt), App: rt.App}}
+ }
+ host, ok := instanceHost(unit)
+ if !ok {
+ return unitOwnership{class: unitPlatform}
+ }
+ unknown := unitOwnership{class: unitUnknown, host: host}
+ if tag != nil && tag.Account != "" && tag.App != "" {
+ return unitOwnership{class: unitTenant, host: host, owner: *tag}
+ }
+ if a.recordsErr != nil || a.unreadable[host] {
+ return unknown
+ }
+ tenants, err := a.recordsFor(ctx, host)
+ if err != nil {
+ return unknown
+ }
+ if len(tenants) > 0 {
+ var who *metrics.Owner
+ for _, r := range tenants {
+ if r.created.IsZero() || r.created.After(at) {
+ continue
+ }
+ if who != nil && *who != r.owner {
+ return unknown
+ }
+ o := r.owner
+ who = &o
+ }
+ if who == nil {
+ return unknown
+ }
+ return unitOwnership{class: unitTenant, host: host, owner: *who}
+ }
+ if o, ok := a.reported(ctx, box, host); ok {
+ return unitOwnership{class: unitTenant, host: host, owner: o}
+ }
+ if rt, ok := a.local[host]; ok && (a.box == "" || box == a.box) {
+ return unitOwnership{class: unitTenant, host: host, owner: metrics.Owner{Account: release.RouteAccount(rt), App: rt.App}}
+ }
+ return unknown
+}
+
+// recordsFor is the tenants of host's records: its instance records, or for
+// a sidecar's synthetic host (provision.SidecarHost) its sidecar record.
+func (a *usageAttribution) recordsFor(ctx context.Context, host string) ([]recordTenant, error) {
+ if !strings.HasSuffix(host, provision.SidecarSuffix) {
+ return a.records[host], nil
+ }
+ if l, ok := a.sidecars[host]; ok {
+ return l.tenants, l.err
+ }
+ var l sidecarLookup
+ parts := strings.Split(strings.TrimSuffix(host, provision.SidecarSuffix), ".")
+ if len(parts) == 3 && provision.ValidSidecarName(parts[0]) && release.ValidApp(parts[1]) && release.ValidAccount(parts[2]) {
+ rec, err := provision.GetSidecarRecord(ctx, a.src, parts[2], parts[1], parts[0])
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ case err != nil:
+ l.err = err
+ case rec.Host != host:
+ l.err = fmt.Errorf("sidecar record %s/%s/%s names host %q", parts[2], parts[1], parts[0], rec.Host)
+ default:
+ l.tenants = []recordTenant{{owner: metrics.Owner{Account: rec.Account, App: rec.App}, created: rec.CreatedAt}}
+ }
+ }
+ a.sidecars[host] = l
+ return l.tenants, l.err
+}
+
+// reported is the tenant box's fresh report names for host.
+func (a *usageAttribution) reported(ctx context.Context, box, host string) (metrics.Owner, bool) {
+ if !a.factsLoaded {
+ a.fleetFacts, a.factsLoaded = a.facts(ctx), true
+ }
+ return a.fleetFacts.tenantOn(box, host)
+}
+
+// unattributedUsage tallies the instance-hours a sweep counted against no
+// account, by box and unit, for one log line per sweep.
+type unattributedUsage map[[2]string]float64
+
+func (u unattributedUsage) add(box, unit string, hours float64) { u[[2]string{box, unit}] += hours }
+
+// log writes the sweep's one line about readings it could attribute to no
+// account, naming the ten largest.
+func (u unattributedUsage) log(from, to time.Time) {
+ if len(u) == 0 {
+ return
+ }
+ keys := make([][2]string, 0, len(u))
+ var total float64
+ for k, h := range u {
+ keys = append(keys, k)
+ total += h
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ if u[keys[i]] != u[keys[j]] {
+ return u[keys[i]] > u[keys[j]]
+ }
+ return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1]
+ })
+ var b strings.Builder
+ for i, k := range keys {
+ if i == 10 {
+ fmt.Fprintf(&b, "; and %d more", len(keys)-10)
+ break
+ }
+ if i > 0 {
+ b.WriteString("; ")
+ }
+ fmt.Fprintf(&b, "%s on box %s %.2f h", k[1], k[0], u[k])
+ }
+ log.Printf("console: usage attribution %s..%s: %.2f instance-hours on %d units counted against no account (no record, box report or console-box route establishes their tenant): %s",
+ usageDay(from), usageDay(to), total, len(keys), b.String())
+}
+
+func usageDay(t time.Time) string { return t.UTC().Format("2006-01-02") }
diff --git a/internal/console/usageattrib_test.go b/internal/console/usageattrib_test.go
new file mode 100644
index 000000000..a2f9f77e2
--- /dev/null
+++ b/internal/console/usageattrib_test.go
@@ -0,0 +1,379 @@
+package console
+
+// Usage attribution across boxes (#390). The fixture is
+// remoteinstances_test.go's: two boxes and one bucket, instances created and
+// deleted through the console's doors, minted by each box's real reconcile
+// pass, reported by each box's real status snapshot. Each box's hourly
+// rollups are written by the box's own code (metrics.RollupHour over raw
+// samples, then metrics.UpsertRollup), and the passes under test are the
+// console's real statementsPass, censusPass and status door.
+
+import (
+ "context"
+ "encoding/json"
+ "math"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// rollHour writes one hour of a box's day rollup the way the box's metrics
+// loop does: n one-minute samples of unit, rolled up by metrics.RollupHour
+// and stored by metrics.UpsertRollup. Units already in the hour are kept.
+func rollHour(t *testing.T, rel release.Store, box string, hour time.Time, units map[string]metrics.UnitSample, n int) {
+ t.Helper()
+ ctx := context.Background()
+ var samples []metrics.Sample
+ for i := 0; i < n; i++ {
+ us := map[string]metrics.UnitSample{}
+ for name, u := range units {
+ us[name] = u
+ }
+ samples = append(samples, metrics.Sample{At: hour.Add(time.Duration(i) * time.Minute), Units: us})
+ }
+ agg := metrics.RollupHour(samples)
+ raw, _, err := rel.Get(ctx, metrics.DayKey(box, hour.UTC().Format("2006-01-02")))
+ if err == nil {
+ var day metrics.DayRollup
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ if prev, ok := day.Hours[hour.UTC().Format("15")]; ok {
+ for name, u := range prev.Units {
+ if _, mine := agg.Units[name]; !mine {
+ agg.Units[name] = u
+ }
+ }
+ }
+ }
+ if err := metrics.UpsertRollup(ctx, rel, box, hour, agg); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// busy is one full minute of an instance: half a core and 1 GB, so an hour of
+// 60 samples is 1 instance-hour, 0.5 core-hours and 1 GB-hour.
+func busy() metrics.UnitSample {
+ return metrics.UnitSample{CPUFrac: p(0.5), MemBytes: pi64(1e9)}
+}
+
+// hoursAfter is n whole UTC hours, the first starting after t, all in one
+// calendar month: a statement covers one month, so a window that would
+// cross into the next starts at that month's first hour instead.
+func hoursAfter(t time.Time, n int) []time.Time {
+ first := t.UTC().Truncate(time.Hour).Add(time.Hour)
+ if last := first.Add(time.Duration(n) * time.Hour); last.Month() != first.Month() {
+ y, m, _ := last.Date()
+ first = time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
+ }
+ out := make([]time.Time, n)
+ for i := range out {
+ out[i] = first.Add(time.Duration(i) * time.Hour)
+ }
+ return out
+}
+
+// statement runs the real statements pass at now and reads acct's month.
+func statement(t *testing.T, fx *consoleFixture, now time.Time, acct string) map[string]float64 {
+ t.Helper()
+ if err := fx.srv.statementsPass(context.Background(), now); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), usage.StatementKey(acct, usage.MonthOf(now)))
+ if err != nil {
+ t.Fatalf("statement %s %s: %v", acct, usage.MonthOf(now), err)
+ }
+ var st usage.Statement
+ if err := json.Unmarshal(raw, &st); err != nil {
+ t.Fatal(err)
+ }
+ return st.Meters
+}
+
+func near(t *testing.T, what string, got, want float64) {
+ t.Helper()
+ if math.Abs(got-want) > 1e-9 {
+ t.Fatalf("%s = %v, want %v", what, got, want)
+ }
+}
+
+func recordOf(t *testing.T, fx *consoleFixture, acct, app, host string) provision.Record {
+ t.Helper()
+ recs, _, err := provision.ListRecords(context.Background(), fx.rel, acct, app, 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range recs {
+ if r.Host == host {
+ return r
+ }
+ }
+ t.Fatalf("no record of %s in %s/%s", host, acct, app)
+ return provision.Record{}
+}
+
+// TestUsageTwoBoxTenant: one account with an instance on the console's box
+// and one on box B. Both boxes' hours are the account's, in the statement,
+// the census and `carlos status --instances`; the platform's own unit stays
+// with the ops account. On main the remote instance's hours went to ops.
+func TestUsageTwoBoxTenant(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ tb.setUp(t, true)
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
+
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt
+ if l := recordOf(t, fx, tb.sqid, "shop", localHost).CreatedAt; l.After(created) {
+ created = l
+ }
+ hours := hoursAfter(created, 3)
+ rollHour(t, fx.rel, boxA, hours[0], map[string]metrics.UnitSample{execUnit(localHost): busy()}, 60)
+ rollHour(t, fx.rel, boxB, hours[0], map[string]metrics.UnitSample{execUnit(remoteHost): busy(), "carlos-edge.service": busy()}, 60)
+ // A unit-backed instance is never tagged by its box; the record still
+ // names its tenant.
+ rollHour(t, fx.rel, boxB, hours[1], map[string]metrics.UnitSample{activator.UnitName(remoteHost): busy()}, 60)
+
+ ours := statement(t, fx, hours[2], tb.sqid)
+ near(t, "instance_hours", ours[usage.MeterInstanceHours], 3)
+ near(t, "cpu_core_hours", ours[usage.MeterCPUCoreHours], 1.5)
+ near(t, "mem_gb_hours", ours[usage.MeterMemGBHours], 3)
+ ops := statement(t, fx, hours[2], release.OpsAccount)
+ near(t, "ops instance_hours (the edge on B)", ops[usage.MeterInstanceHours], 1)
+
+ date := usage.DayOf(hours[2])
+ if err := fx.srv.censusPass(context.Background(), date); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), usage.CensusDayKey(date))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var day usage.CensusDay
+ if err := json.Unmarshal(raw, &day); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := day.Accounts[tb.sqid], (usage.CensusAccount{Apps: 1, Routes: 2}); got != want {
+ t.Fatalf("census %s = %+v, want %+v (both instances, one on each box)", tb.sqid, got, want)
+ }
+
+ // The live view: B's unit is the account's, not the platform's.
+ if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ tb.fresh()
+ rows := statusInstanceRows(t, fx, tb.token, "?account="+tb.sqid)
+ got := map[string]apiStatusInstance{}
+ for _, r := range rows {
+ got[r.Unit] = r
+ }
+ r, ok := got[execUnit(remoteHost)]
+ if !ok || r.Box != boxB || r.Host != remoteHost || r.App != "shop" || r.Platform || r.Unattributed {
+ t.Fatalf("status --instances for %s = %+v, want B's unit as the account's shop instance", tb.sqid, rows)
+ }
+}
+
+// TestUsageReusedHostname: another account ran the hostname on box B and
+// deleted it, and this account created it again. Nothing B sampled before
+// this account's record existed is this account's, even though the record,
+// B's registry row and B's report all name this account now. The rival's
+// record is gone, so its hours are counted nowhere, and logged. The hour in
+// which the record was created is not this account's either: part of it may
+// be the predecessor's.
+func TestUsageReusedHostname(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ ctx := context.Background()
+ now := time.Now()
+ const rivalID int64 = 6363
+ rival := accountSqid(rivalID)
+ if err := fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteAccountManifest(ctx, fx.rel, rivalID, rival, "Rival", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ shipAndPromote(t, fx, rival, "shop", "v3", "stable")
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-usage-reuse-bob")
+ fx.setUser("paul@keymail.dev")
+
+ tb.create(t, bob, rival, "shop", remoteHost, "uk", "")
+ tb.reconcile(t, "v3")
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(fx, rival, "shop")+"/"+remoteHost, bob, ""); code/100 != 2 {
+ t.Fatalf("rival delete = %d %s", code, out)
+ }
+ tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "")
+ if err := tb.regB.Delete(remoteHost); err != nil {
+ t.Fatal(err)
+ }
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != tb.sqid {
+ t.Fatalf("fixture: B's row = %+v, want this account's", rt)
+ }
+ report(t, fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ tb.fresh()
+
+ boxB := status.Label("box-b")
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt
+ creationHour := created.UTC().Truncate(time.Hour)
+ // The rival's era: the hour before, and the hour the new record was
+ // created in. This account's: the two whole hours after.
+ rivalEra := []time.Time{creationHour.Add(-time.Hour), creationHour}
+ oursEra := []time.Time{creationHour.Add(time.Hour), creationHour.Add(2 * time.Hour)}
+ for _, h := range append(append([]time.Time{}, rivalEra...), oursEra...) {
+ rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(remoteHost): busy()}, 60)
+ }
+
+ logs := captureLog(t)
+ attrib, err := fx.srv.passAttribution(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := fx.srv.sweepUsage(ctx, rivalEra[0], oursEra[1], attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 2)
+ near(t, "the rival's instance_hours", sweep.PerAccount[rival][usage.MeterInstanceHours], 0)
+ near(t, "ops instance_hours", sweep.PerAccount[release.OpsAccount][usage.MeterInstanceHours], 0)
+ if !strings.Contains(logs.String(), execUnit(remoteHost)) || !strings.Contains(logs.String(), "counted against no account") {
+ t.Fatalf("the unattributed hours were not logged:\n%s", logs.String())
+ }
+}
+
+// TestStatementRerunAcrossAMove: an instance runs on the console's box, its
+// record is re-homed to another region and box B mints it (the console's box
+// drops its route). The statement is re-run over the whole month after the
+// move, and keeps the hours from before it: the record, not today's routes,
+// says whose they were. On main the re-run moved them to ops.
+func TestStatementRerunAcrossAMove(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ ctx := context.Background()
+ tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "")
+ tb.reconcile(t, "v3")
+ regA, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rt, _ := regA.Get(localHost); rt == nil {
+ t.Fatal("fixture: the console's box did not mint the ie instance")
+ }
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
+ hours := hoursAfter(recordOf(t, fx, tb.sqid, "shop", localHost).CreatedAt, 6)
+ for _, h := range hours[:3] {
+ rollHour(t, fx.rel, boxA, h, map[string]metrics.UnitSample{execUnit(localHost): busy()}, 60)
+ }
+ near(t, "before the move", statement(t, fx, hours[3], tb.sqid)[usage.MeterInstanceHours], 3)
+
+ if err := provision.SetRecordRegion(ctx, fx.rel, tb.sqid, "shop", localHost, "uk"); err != nil {
+ t.Fatal(err)
+ }
+ tb.reconcile(t, "v3")
+ if rt, _ := regA.Get(localHost); rt != nil {
+ t.Fatalf("fixture: the console's box still routes the moved instance: %+v", rt)
+ }
+ if rt, _ := tb.regB.Get(localHost); rt == nil {
+ t.Fatal("fixture: box B did not mint the moved instance")
+ }
+ for _, h := range hours[3:5] {
+ rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(localHost): busy()}, 60)
+ }
+ ours := statement(t, fx, hours[5], tb.sqid)
+ near(t, "after the move, re-run", ours[usage.MeterInstanceHours], 5)
+ near(t, "cpu after the move", ours[usage.MeterCPUCoreHours], 2.5)
+ near(t, "ops after the move", statement(t, fx, hours[5], release.OpsAccount)[usage.MeterInstanceHours], 0)
+}
+
+// TestUsageUnknownInstanceCountsNowhere: an instance unit no record, box
+// report or console-box route names is nobody's. It is not platform overhead,
+// so it is not charged to ops either; it is logged. A unit a box reports for
+// a host with no record is that tenant's.
+func TestUsageUnknownInstanceCountsNowhere(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ tb.setUp(t, false)
+ boxB := status.Label("box-b")
+ // A hand route on B (no record) that B's report names.
+ if err := tb.regB.Upsert(registry.Route{Host: "hand.example.com", Kind: "instance", Status: "ready",
+ Account: "cdef", App: "widgets", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ report(t, fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ tb.fresh()
+ // A console-box hand route does not vouch for another box's sample.
+ fx.addRoute(t, registry.Route{Host: "local-only.example.com", Kind: "instance", Status: "ready", App: "kass", Account: fx.sqid})
+
+ hours := hoursAfter(time.Now(), 2)
+ rollHour(t, fx.rel, boxB, hours[0], map[string]metrics.UnitSample{
+ execUnit("stray.example.com"): busy(),
+ execUnit("local-only.example.com"): busy(),
+ execUnit("hand.example.com"): busy(),
+ }, 60)
+ logs := captureLog(t)
+ ops := statement(t, fx, hours[1], release.OpsAccount)
+ near(t, "ops instance_hours", ops[usage.MeterInstanceHours], 0)
+ near(t, "the hand route's tenant", statement(t, fx, hours[1], "cdef")[usage.MeterInstanceHours], 1)
+ for _, u := range []string{execUnit("stray.example.com"), execUnit("local-only.example.com")} {
+ if !strings.Contains(logs.String(), u) {
+ t.Fatalf("%s was not logged as unattributed:\n%s", u, logs.String())
+ }
+ }
+}
+
+// TestStatusInstancesAcrossBoxes: the live view joins each sample to its
+// owner from the records and the boxes' tags. A sample its box tagged names
+// its tenant; an instance unit nobody can be shown to own is marked
+// unattributed rather than charged to the platform.
+func TestStatusInstancesAcrossBoxes(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ fx.srv.cfg.BoxLabel = status.Label("box-a")
+ tb.setUp(t, true)
+ if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ boxB := status.Label("box-b")
+ at := time.Now().UTC()
+ writeSamples(t, fx.rel, boxB, metrics.Sample{At: at, Units: map[string]metrics.UnitSample{
+ execUnit(remoteHost): {CPUFrac: p(0.2)},
+ execUnit("tagged.example.com"): {CPUFrac: p(0.3), Owner: &metrics.Owner{Account: "cdef", App: "widgets"}},
+ execUnit("nobodys.example.com"): {CPUFrac: p(0.4)},
+ "carlos-edge.service": {CPUFrac: p(0.1)},
+ }})
+ tb.fresh()
+ got := map[string]apiStatusInstance{}
+ for _, r := range statusInstanceRows(t, fx, tb.token, "") {
+ got[r.Unit] = r
+ }
+ if r := got[execUnit(remoteHost)]; r.Account != tb.sqid || r.App != "shop" || r.Host != remoteHost || r.Platform || r.Unattributed {
+ t.Errorf("remote instance = %+v, want this account's shop", r)
+ }
+ if r := got[execUnit("tagged.example.com")]; r.Account != "cdef" || r.App != "widgets" || r.Host != "tagged.example.com" || r.Unattributed {
+ t.Errorf("tagged sample = %+v, want the tenant its box vouched for", r)
+ }
+ if r := got[execUnit("nobodys.example.com")]; !r.Unattributed || r.Account != "" || r.Platform || r.Host != "nobodys.example.com" {
+ t.Errorf("unknown instance = %+v, want it unattributed, not the platform's", r)
+ }
+ if r := got["carlos-edge.service"]; !r.Platform || r.Account != release.OpsAccount {
+ t.Errorf("edge = %+v, want platform overhead", r)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 60ffb8106..a8709b815 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -6,3 +6,4 @@ plan14-root-reads-remote-instance-metrics.tsv ed0d770a827bdb37a87d21e5c8efb259ca
plan14-root-reads-edge-asset-cache-3.tsv f723ddc14e3c03c0d55b6f0c949567a2c9325e0b5d491e0649fe548b2c0c282d
plan14-root-reads-remote-metrics-nested.tsv e923841657499fc729713abdd750cbd2d6019fc4db677b540be0fab4d2a160e4
plan14-root-reads-region-ha-p1a.tsv 125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd
+plan14-root-reads-usage-attribution-390.tsv 125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd
diff --git a/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
new file mode 100644
index 000000000..42478266b
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
@@ -0,0 +1,3 @@
+# Census overlay usage-attribution-390, written by census-propose (#369). census-ruling-usage-attribution-390, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-usage-attribution-390.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . 3c7b62e753b67528cea531850257bd22cba6ad4db4d2116797cf1dab235ee6ee
diff --git a/status_instances.go b/status_instances.go
index b6b2b04d6..cef383b0d 100644
--- a/status_instances.go
+++ b/status_instances.go
@@ -42,6 +42,9 @@ type statusInstanceRow struct {
CPU *float64 `json:"cpu"`
Mem *int64 `json:"mem_bytes"`
Platform bool `json:"platform"`
+ // Unattributed is an instance whose owner the console cannot establish
+ // (#390); Account and App are empty. Absent from an older console.
+ Unattributed bool `json:"unattributed"`
// Region and RegionName are the box's placement code and label (region
// labels spec §4); "" from an older console or for a box it cannot name.
Region string `json:"region"`
@@ -117,6 +120,12 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string)
// overhead in the picture.
host, app = r.Unit, "(platform)"
}
+ if r.Unattributed {
+ // An instance whose owner the console cannot establish: named
+ // by its host, with the reason under the table, rather than
+ // filed under the platform.
+ app = statusInstancesCopy.Unattributed
+ }
fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
r.Box, statusRegionCell(r.Region, r.RegionName), dashIfEmpty(host), dashIfEmpty(r.Account), dashIfEmpty(app),
cpuCell(r.CPU), memCell(r.Mem))
@@ -129,14 +138,24 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string)
// it does not exist. The question this verb answers is "right now", and
// that limit belongs next to the answer.
mutedf(w, "(awake instances only — a hibernating instance has no process to measure)")
- // The readings are fleet-wide, but the console joins them against its own
- // box's route registry, so a unit on any other box matches nothing and
- // lands under (platform) rather than under its tenant. Inert on a
- // single-box deployment and fixed structurally by PR #137; until then an
- // operator reading this for "who is using what" has to be told, the same
- // way `carlos routes` says whose routes it is showing.
- mutedf(w, "(accounts are joined against the console's own box's route registry; "+
- "an instance on another box in a fleet can land under (platform))")
+ // Said only when it applies: since #390 the console joins every box's
+ // readings to the instance records, so an instance on another box is
+ // its tenant's. What is left is an instance nothing can be shown to own.
+ for _, r := range rows {
+ if r.Unattributed {
+ mutedf(w, "%s", statusInstancesCopy.UnattributedNote)
+ break
+ }
+ }
+}
+
+// statusInstancesCopy is `carlos status --instances`' new copy (#390; Luna
+// pass 2026-10-26, docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md).
+var statusInstancesCopy = struct {
+ Unattributed, UnattributedNote string
+}{
+ Unattributed: "(unattributed)",
+ UnattributedNote: "(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)",
}
// statusLayoutRow is one host's layout, as the console answers it
diff --git a/status_instances_test.go b/status_instances_test.go
index d9dfea623..fa2a98c94 100644
--- a/status_instances_test.go
+++ b/status_instances_test.go
@@ -19,12 +19,12 @@ import (
// (platform) rather than as two blank cells a reader would take for missing
// data.
//
-// And the table is followed, every time, by the two ways it misleads: a
-// hibernating instance has no process and so no reading, and the readings are
-// fleet-wide while the account each is attributed to comes from the console's
-// own box's registry. Neither caveat is conditional, because both are ways a
-// SHORT list reads as a complete one, and short is exactly when nobody thinks
-// to ask.
+// And the table is followed, every time, by the way it misleads: a
+// hibernating instance has no process and so no reading. Not conditional,
+// because a SHORT list reads as a complete one, and short is exactly when
+// nobody thinks to ask. An instance whose owner cannot be established
+// (#390) prints by its host with (unattributed), and the note saying what
+// that means follows the table only when such a row is there.
func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) {
rows := []statusInstanceRow{
{Box: "box-a", Host: "app.example.com", Account: "cdef", App: "widgets",
@@ -39,12 +39,24 @@ func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) {
"app.example.com", "cdef", "widgets", "0.250", "1MB",
"console.service", "(platform)",
"awake instances only",
- "console's own box's route registry",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in:\n%s", want, out)
}
}
+ if strings.Contains(out, statusInstancesCopy.UnattributedNote) {
+ t.Errorf("the unattributed note printed with no unattributed row:\n%s", out)
+ }
+
+ rows = append(rows, statusInstanceRow{Box: "box-b", Unit: "carlos-exec@stray.example.com", Host: "stray.example.com", Unattributed: true})
+ buf.Reset()
+ printStatusInstances(&buf, rows, "")
+ out = buf.String()
+ for _, want := range []string{"stray.example.com", statusInstancesCopy.Unattributed, statusInstancesCopy.UnattributedNote} {
+ if !strings.Contains(out, want) {
+ t.Errorf("missing %q in:\n%s", want, out)
+ }
+ }
}
// TestPrintStatusLayoutRendersSortedAndMarksStale pins the CLI table for