carlos / platform Public

usage-attribution-390: Astra round 1 fixes. attribute by box tag or the hostname's account namespace only; census refuses undecodable records, covers excluded hosts, counts sidecars

Round 1 (NOT READY, three P1s in the tenant-identity family): a record's
created_at, a box's report and a console-box route say who holds a host
now, not who ran it in an earlier hour, and a stamped unit name is no
identity on another box. A reading is now an account's only on evidence
that holds for the whole reading: the box's tag (live readings), or a host
under <name>.<sqid>.<apps domain> or a sidecar's synthetic host, for a live
account. Anything else that is a tenant's workload, including units
stamped on a tenant's console-box route, is counted nowhere and logged.
Billing no longer reads records at all.

P2s: the census refuses a day when a record will not decode, marks Trash
and fleet-placed record hosts covered before counting console-box routes,
and counts sidecar records. Sidecar GET failures in billing are gone with
the record reads.

Record-write census: handleAPIStatusInstances re-pinned (no write added).
Copy: second Luna pass for the changed note and docs paragraph.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 75ec5e139f722416fa85ee1d3ec2a2e908092072 parent acdda11
17 files changed, +703 −433
  • docs/site/cli.md +6 −4
  • docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md +64 −0
  • docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md +9 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md +47 −0
  • internal/console/apistatusinstances.go +27 −14
  • internal/console/apistatusinstances_test.go +17 −11
  • internal/console/economicspass.go +95 −56
  • internal/console/economicspass_test.go +26 −16
  • internal/console/economicsview.go +24 −36
  • internal/console/remoteinstances.go +0 −13
  • internal/console/remoteinstances_round5_test.go +1 −1
  • internal/console/usageattrib.go +123 −183
  • internal/console/usageattrib_test.go +229 −95
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv +1 −1
  • internal/provision/usage_attribution_390_census_test.go +31 −0
  • status_instances.go +2 −2
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 6d3dbca32..19b3cf000 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2306,10 +2306,12 @@ other route here — but the answer is, because it names other people's
accounts.
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.
+under the table explains this. Each reading belongs to the account whose own
+platform domain the instance's hostname is under
+(`<name>.<account>.<apps domain>`), wherever the instance runs, or to the
+owner its box recorded with the reading. An instance with neither, such as one
+on a custom domain, 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-R2.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md
new file mode 100644
index 000000000..d19c08bfa
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md
@@ -0,0 +1,64 @@
+# Copy review brief: usage attribution across boxes (#390), second pass
+
+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. Your first
+pass is `docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md`. A code
+review then changed the facts, so two of those strings changed and one is new.
+UA-1 `(unattributed)` stands. UA-3 and UA-4 were dropped.
+
+## The new facts
+
+A box's CPU and memory reading of an instance now belongs to an account only
+on evidence that holds for the whole time the reading covers:
+
+- the instance's hostname is under that account's own platform domain
+ (`<name>.<account>.<apps domain>`, for example `shop.bdx.oncarlos.com`;
+ only that account can ever hold such a name), or
+- the box recorded the owner with the reading itself (live readings only).
+
+Instance records and box reports no longer decide it: they say who holds a
+hostname now, not who ran it last week. An instance with neither, such as an
+instance an operator put on a custom domain, is unattributed and its usage
+counts against no account, the platform's included.
+
+## The strings (draft text is yours to change; ids are fixed)
+
+- UA-2, a muted note printed under the `carlos status --instances` table,
+ only when at least one row's APP reads `(unattributed)`. Draft:
+ `(unattributed: neither its box nor its hostname shows whose instance this
+ is, so its usage counts against no account)`
+- UA-5, the docs paragraph in docs/site/cli.md, `--instances` section (your
+ first-pass text, with the facts corrected). Draft:
+
+ > 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
+ > whose platform domain the instance's hostname is under
+ > (`<name>.<account>.<apps domain>`), wherever the instance runs, or to the
+ > owner its box recorded with the reading. An instance with neither, such as
+ > one on a custom domain, appears as `(unattributed)`. Its usage counts
+ > against no account, including the platform.
+
+- UA-6, new, docs/site/plans.md, a sentence after "The figures come from what
+ the console already records: its own app list, the monthly usage
+ statements, the daily storage sweep and the mail counts. A cap whose limit
+ is 0 is skipped." Readers: account owners and operators. Draft:
+ `Awake hours count the instances on the account's own platform domain, on
+ every server. An instance on a custom domain is not counted, because nothing
+ records whose it was in each hour.`
+
+## House rules (Paul's, all binding)
+
+- No em dashes, ever. Use a full stop and a new sentence; in CLI strings the
+ new sentence continues in lower case.
+- Plain words. No jargon a reader would not know. Short.
+- Neutral names only (shop, example.com). Never a tenant's name. (The `bdx`
+ above is an example sqid and must not appear in your output.)
+- Keep UA-2's parentheses and the literal `(unattributed)` and
+ `<name>.<account>.<apps domain>`.
+- Do not change the facts. If a fact looks wrong or two rows disagree, flag it.
+
+## Output
+
+1. A table of changes only: `id | current | new | 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-R2.md b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md
new file mode 100644
index 000000000..86fcba1ad
--- /dev/null
+++ b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md
@@ -0,0 +1,9 @@
+| id | current | new | why |
+|---|---|---|---|
+| UA-2 | `(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)` | `(unattributed: neither its box nor its hostname identifies its account, so its usage counts against no account)` | Matches the two valid attribution sources. |
+| UA-5 | Existing paragraph using the instance record and box report as attribution evidence. | 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 whose own platform domain the instance's hostname is under (`<name>.<account>.<apps domain>`), wherever the instance runs, or to the owner its box recorded with the reading. An instance with neither, such as one on a custom domain, appears as `(unattributed)`. Its usage counts against no account, including the platform. | Uses the corrected attribution rules. |
+| UA-6 | `Awake hours count the instances on the account's own platform domain, on every server. An instance on a custom domain is not counted, because nothing records whose it was in each hour.` | Awake hours count readings for instances on the account's own platform domain, on every server, or readings whose box recorded the owner. An instance with neither is not counted, because nothing shows whose it was during that hour. | Includes live box ownership and avoids excluding every custom-domain instance. |
+
+- UA-6 | The draft incorrectly says custom-domain instances are never counted. A box can record their owner with a live reading.
+
+changed: 3, flagged: 1, left alone: 1
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md
new file mode 100644
index 000000000..090095032
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md
@@ -0,0 +1,47 @@
+1. **P1 — §1: `created_at` does not establish which tenant ran the process.**
+ **Evidence:** [usageattrib.go:219](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:219) accepts an untagged reading solely because the current record predates it. [remotemetrics_test.go:219](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/remotemetrics_test.go:219) establishes that, without a lifetime judge, reconcile can retain the predecessor’s running row after the successor’s record exists.
+ **Failure scenario:** A deletes a hostname; B recreates it at 10:59. A’s process continues into 11:00. The 11:00 rollup is charged to B. An untagged live reading is likewise assigned to B immediately after creation. The new reuse test manually deletes the predecessor’s row before checking attribution.
+ **Fix:** Require evidence binding the sampled process to its tenant for the measured interval. With the available inputs, leave unproven untagged readings unattributed; a longer creation-time delay cannot prove ownership. Add the retained-predecessor case to the billing test.
+ **Fault family:** Tenant identity of usage—record creation is not process ownership.
+
+2. **P1 — §2: Current reports and routes assign historical usage without any time bound.**
+ **Evidence:** [usageattrib.go:236](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:236) uses both fallbacks without consulting `at`; [remoteinstances.go:344](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/remoteinstances.go:344) checks only box and reported tenant.
+ **Failure scenario:** A used a hostname earlier this month. Its record is gone, and B now has a hand route on the same box. Today’s report assigns A’s earlier hours to B during the monthly re-sweep. The console-route fallback produces the same result.
+ **Fix:** Disable these fallbacks for historical attribution unless evidence establishes the tenant throughout the sampled interval. A report-generation timestamp or freshness threshold supplies no ownership start/end bound, so the existing reports cannot justify this retrospective join.
+ **Fault family:** Tenant identity of usage—present ownership cannot establish historical ownership.
+
+3. **P1 — §§1,3: Stamped units bypass the sampling-box boundary.**
+ **Evidence:** [usageattrib.go:201](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:201) matches the console registry’s stamped unit before checking `box`, records, or the live tag.
+ **Failure scenario:** The console box stamps `carlos-bespoke.service` for account A. Another box runs that unit name for B or as platform overhead. Every reading from that second box is assigned to A.
+ **Fix:** Apply stamped-route attribution only when the sampling box equals a known console-box label. An unknown label must not authorize every box; remove that permissive case from the local-route fallback too. Test identical stamped names on two boxes.
+ **Fault family:** Tenant identity of usage—a box-local unit name is not a fleet-wide identity.
+
+4. **P2 — §4: The create-only census discards malformed-record information.**
+ **Evidence:** [economicspass.go:123](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:123) discards `unreadable`. The strict reader explicitly returns malformed records through that map with no error ([reconcile.go:2711](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/reconcile.go:2711)). The census is then persisted at line 160.
+ **Failure scenario:** A remote app’s only instance record cannot decode. Its app and route disappear from the day’s census permanently, even after the record is repaired.
+ **Fix:** Refuse census creation when `unreadable` is nonempty. Test that no day object is written and that a subsequent clean read succeeds.
+ **Fault family:** Billing snapshot completeness—a permanent census must not treat an unreadable record as absent.
+
+5. **P2 — §4: Sidecar read failures still permit statement replacement.**
+ **Evidence:** [usageattrib.go:257](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:257) retains sidecar GET errors, but [usageattrib.go:215](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:215) converts them into ordinary unknown ownership. Statements subsequently reach [economicspass.go:864](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:864).
+ **Failure scenario:** One sidecar GET fails transiently. All its monthly hours are omitted, and the pass overwrites an otherwise correct statement with the reduced total. The economics page receives no corresponding records warning.
+ **Fix:** Propagate attribution read failures separately from genuinely unknown ownership. Abort statement writes on those failures; expose a warning on the read path. Add a failing-sidecar-GET test that preserves the existing statement.
+ **Fault family:** Billing snapshot completeness—failed reads must not become zero usage.
+
+6. **P2 — §5: Route fallback reintroduces excluded records.**
+ **Evidence:** [economicspass.go:150](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:150) skips trashed and customer-fleet records before marking their hosts covered; lines 156–157 then count every remaining local route.
+ **Failure scenario:** A trashed app still has a local route while withdrawal is pending. Its record is excluded, but its route restores the app to the permanent census. A placement change to a customer fleet has the same gap while the old local route remains.
+ **Fix:** Track all record-covered hosts separately from counted hosts. Apply exclusions before counting, and allow route fallback only for hosts no record covers.
+ **Fault family:** Census membership—route fallback must not override record exclusions.
+
+7. **P2 — §5: Remote sidecar-only apps remain absent from the census.**
+ **Evidence:** The reader used at [economicspass.go:123](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/economicspass.go:123) enumerates only `instances/` ([reconcile.go:2681](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/reconcile.go:2681)); the remaining census source is the console’s local routes.
+ **Failure scenario:** An app with only a sidecar on another platform box contributes zero apps and routes. The same app counts when its sidecar runs on the console box. This undercounts `app_months`.
+ **Fix:** Include eligible sidecar records in the census, using the same exclusions and host deduplication. Test a remote sidecar-only app.
+ **Fault family:** Census membership—an app’s count must not depend on its platform box.
+
+**Census verdict for envelope `.`: APPROVE.** Read [status_instances.go:36](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:36), lines 102–159, and the formatting helpers at [color.go:137](/home/paulca/amadan.net/carlos/platform-usage-attrib/color.go:137), lines 210–237. The changes add a decoded boolean, select display text, and print a conditional note. They introduce no new root open, execution, query, path traversal, or weakened validation.
+
+Validation: `git diff --check` passed. Targeted tests could not start because the read-only sandbox prevented Go from creating its work directory. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/console/apistatusinstances.go b/internal/console/apistatusinstances.go
index e5d71607b..fa7ff5144 100644
--- a/internal/console/apistatusinstances.go
+++ b/internal/console/apistatusinstances.go
@@ -35,10 +35,11 @@
// 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
+// otherwise an instance's unit goes to the account its hostname names by
+// construction (the account's platform namespace, or a sidecar's synthetic
+// host), wherever the box is. An instance's unit neither can place (a custom
+// domain with no tag) 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.
@@ -55,6 +56,7 @@ import (
"net/http"
"sort"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -93,11 +95,6 @@ type apiStatusInstance struct {
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 {
@@ -130,12 +127,17 @@ 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)
+ attrib, err := s.newUsageAttribution(routes)
+ if err != nil {
+ log.Printf("console: api status instances: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the route registry — try again")
return
}
+ apps := s.appNames(r.Context())
+ localApps := map[string]registry.Route{}
+ for _, rt := range routes {
+ localApps[rt.Host] = rt
+ }
boxes, _, err := s.LoadMetrics(r.Context())
if err != nil {
log.Printf("console: api status instances: metrics: %v", err)
@@ -149,14 +151,25 @@ 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)
- who := attrib.attribute(r.Context(), b.Box, u.Unit, b.At, b.latestOwner(u))
+ who := attrib.attribute(u.Unit, b.latestOwner(u))
switch who.class {
case unitTenant:
row.Host, row.Account, row.App = who.host, who.owner.Account, who.owner.App
+ // The app, for display only: the host's record, else the
+ // console box's route, when it names the same account.
+ if rec, ok := apps[who.host]; ok && row.App == "" && rec.Account == row.Account {
+ row.App = rec.App
+ }
+ if rt, ok := localApps[who.host]; ok && row.App == "" && release.RouteAccount(rt) == row.Account {
+ row.App = rt.App
+ }
case unitPlatform:
row.Platform, row.Account = true, release.OpsAccount
default:
row.Unattributed, row.Host = true, who.host
+ if row.Host == "" {
+ row.Host = u.Unit
+ }
}
if want != "" && row.Account != want {
continue
diff --git a/internal/console/apistatusinstances_test.go b/internal/console/apistatusinstances_test.go
index 489bf37c8..745b42528 100644
--- a/internal/console/apistatusinstances_test.go
+++ b/internal/console/apistatusinstances_test.go
@@ -100,10 +100,16 @@ func tenancyFixture(t *testing.T, fx *consoleFixture) {
t.Helper()
// fx.sqid is the built-in ops account; "cdef" is somebody else. Two
// tenants on one box is the whole point: a filter can only be shown to
- // narrow if there is something for it to leave behind.
- fx.addRoute(t, registry.Route{Host: "ours.example.com", Kind: "instance", Status: "ready",
+ // narrow if there is something for it to leave behind. Each host is in
+ // its account's platform namespace, which is what establishes the
+ // account (#390); the routes name the apps.
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := fx.st.CreateAccount(7777, "cdef", "Widgets", "w@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ fx.addRoute(t, registry.Route{Host: "ours." + fx.sqid + ".oncarlos.test", Kind: "instance", Status: "ready",
App: "kass", Account: fx.sqid, Channel: "stable"})
- fx.addRoute(t, registry.Route{Host: "theirs.example.com", Kind: "instance", Status: "ready",
+ fx.addRoute(t, registry.Route{Host: "theirs.cdef.oncarlos.test", Kind: "instance", Status: "ready",
App: "widgets", Account: "cdef", Channel: "stable"})
at := time.Now().UTC().Add(-time.Minute)
cpu, mem := 0.25, int64(1<<20)
@@ -113,9 +119,9 @@ func tenancyFixture(t *testing.T, fx *consoleFixture) {
// A full reading, a partial one (CPU but no memory — the reason
// those fields are pointers), and a unit matching no route at
// all: the console's own, which is platform overhead.
- activator.UnitName("ours.example.com"): {CPUFrac: &cpu, MemBytes: &mem},
- activator.UnitName("theirs.example.com"): {CPUFrac: &cpu},
- "console.service": {},
+ activator.UnitName("ours." + fx.sqid + ".oncarlos.test"): {CPUFrac: &cpu, MemBytes: &mem},
+ activator.UnitName("theirs.cdef.oncarlos.test"): {CPUFrac: &cpu},
+ "console.service": {},
}}},
}); err != nil {
t.Fatal(err)
@@ -162,16 +168,16 @@ func TestAPIStatusInstancesAttributesUnitsToAccounts(t *testing.T) {
t.Fatalf("unfiltered = %d rows %+v, want one per sampled unit", len(rows), rows)
}
- ours := byUnit[activator.UnitName("ours.example.com")]
- if ours.Account != fx.sqid || ours.App != "kass" || ours.Host != "ours.example.com" || ours.Platform {
+ ours := byUnit[activator.UnitName("ours."+fx.sqid+".oncarlos.test")]
+ if ours.Account != fx.sqid || ours.App != "kass" || ours.Host != "ours."+fx.sqid+".oncarlos.test" || ours.Platform {
t.Errorf("ours = %+v, want the ops account's kass route rather than platform", ours)
}
if ours.Box != "box-tenancy" || ours.CPU == nil || *ours.CPU != 0.25 || ours.Mem == nil || *ours.Mem != 1<<20 {
t.Errorf("ours = %+v, want box-tenancy carrying its own readings", ours)
}
- theirs := byUnit[activator.UnitName("theirs.example.com")]
- if theirs.Account != "cdef" || theirs.App != "widgets" || theirs.Host != "theirs.example.com" || theirs.Platform {
+ theirs := byUnit[activator.UnitName("theirs.cdef.oncarlos.test")]
+ if theirs.Account != "cdef" || theirs.App != "widgets" || theirs.Host != "theirs.cdef.oncarlos.test" || theirs.Platform {
t.Errorf("theirs = %+v, want cdef's widgets route", theirs)
}
// A sampled unit with no memory reading must arrive as nil rather than 0:
@@ -213,7 +219,7 @@ func TestAPIStatusInstancesAccountFilterNarrows(t *testing.T) {
if len(only) != 1 {
t.Fatalf("?account=cdef = %d rows %+v, want just the one", len(only), only)
}
- if got, want := only[0].Unit, activator.UnitName("theirs.example.com"); got != want {
+ if got, want := only[0].Unit, activator.UnitName("theirs.cdef.oncarlos.test"); got != want {
t.Errorf("?account=cdef returned %q, want %q", got, want)
}
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index c7a79dcd5..1beca1d30 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -97,15 +97,17 @@ func (s *Server) openPassRegistry() (consoleRegistry, error) {
// 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.
+// What it counts (#390): every instance and sidecar record, wherever its box
+// is, plus every console-box route no record covers (a hand route, an apex
+// mint), 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, though their hosts still count as covered so their
+// console-box routes are not counted either: 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). Every read must
+// succeed, a record that does not decode included: 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 {
@@ -119,23 +121,14 @@ 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()
+ held, err := s.censusRecords(ctx)
if err != nil {
return fmt.Errorf("console: census pass: %w", err)
}
accounts := map[string]usage.CensusAccount{}
apps := map[string]map[string]bool{}
- counted := map[string]bool{}
- count := func(host, acct, app string) {
- if counted[host] {
- return
- }
- counted[host] = true
+ covered := map[string]bool{}
+ count := func(acct, app string) {
c := accounts[acct]
c.Routes++
if apps[acct] == nil {
@@ -147,35 +140,85 @@ func (s *Server) censusPass(ctx context.Context, date string) error {
}
accounts[acct] = c
}
- for _, rec := range recs {
- if _, fleet := registry.FleetPlacement(rec.Region); fleet || trashed[rec.Account+"/"+rec.App] {
+ for _, h := range held {
+ if covered[h.host] {
continue
}
- count(rec.Host, rec.Account, rec.App)
+ covered[h.host] = true
+ if h.counts {
+ count(h.acct, h.app)
+ }
}
for _, rt := range routes {
- count(rt.Host, release.RouteAccount(rt), rt.App)
+ if covered[rt.Host] {
+ continue
+ }
+ covered[rt.Host] = true
+ count(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) {
+// censusTenancy is one record's host and tenant for the census; counts is
+// false for a record the census covers but does not count (an app in the
+// Trash, a customer-fleet placement).
+type censusTenancy struct {
+ host, acct, app string
+ counts bool
+}
+
+// censusRecords is every instance and sidecar record for the census, read
+// through the record view when it is armed. Any read that fails, and any
+// record that does not decode, is an error: the census day is create-only.
+func (s *Server) censusRecords(ctx context.Context) ([]censusTenancy, error) {
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ recs, unreadable, err := provision.ListAllRecordsStrictJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ return nil, fmt.Errorf("instance records: %w", err)
+ }
+ if len(unreadable) > 0 {
+ return nil, fmt.Errorf("instance records: %d could not be decoded", len(unreadable))
+ }
accts, err := s.store.Accounts()
if err != nil {
return nil, err
}
- out := map[string]bool{}
+ trashed := map[string]bool{}
+ var out []censusTenancy
for _, a := range accts {
- apps, err := s.store.TrashedAppsIn(a.ID)
+ live, err := s.store.AppsIn(a.ID)
+ if err != nil {
+ return nil, err
+ }
+ gone, err := s.store.TrashedAppsIn(a.ID)
if err != nil {
return nil, err
}
- for _, t := range apps {
- out[a.Sqid+"/"+t.App] = true
+ // Trashed apps' sidecars are listed too, so their hosts are covered
+ // and a console-box route of theirs is not counted in their place.
+ inTrash := map[string]bool{}
+ names := append([]string(nil), live...)
+ for _, t := range gone {
+ trashed[a.Sqid+"/"+t.App] = true
+ inTrash[t.App] = true
+ names = append(names, t.App)
}
+ for _, app := range names {
+ scs, err := provision.ListSidecarRecordsStrict(ctx, src, a.Sqid, app)
+ if err != nil {
+ return nil, fmt.Errorf("sidecar records %s/%s: %w", a.Sqid, app, err)
+ }
+ for _, sc := range scs {
+ _, fleet := registry.FleetPlacement(sc.Region)
+ out = append(out, censusTenancy{host: sc.Host, acct: sc.Account, app: sc.App, counts: !fleet && !inTrash[app]})
+ }
+ }
+ }
+ for _, rec := range recs {
+ _, fleet := registry.FleetPlacement(rec.Region)
+ out = append(out, censusTenancy{host: rec.Host, acct: rec.Account, app: rec.App, counts: !fleet && !trashed[rec.Account+"/"+rec.App]})
}
return out, nil
}
@@ -297,15 +340,16 @@ type usageSweep struct {
// Task 11's LoadEconomics (arbitrary period, priced live under a scenario).
//
// 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).
+// instance's hour goes to the account its hostname names by construction
+// (its account's platform namespace, or a sidecar's synthetic host),
+// wherever the box was; a platform unit's to release.OpsAccount; and a
+// tenant's hour whose account 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 is missing (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
@@ -380,11 +424,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
sweep.BoxDays[box]++
bl := boxLoad(box)
bl.Hours += float64(len(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 _, hour := range roll.Hours {
for unit, um := range hour.Units {
var instN int
var cpuCoreHours, memGBHours float64
@@ -400,7 +440,7 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usa
instN = mem.N
}
}
- who := attrib.attribute(ctx, box, unit, at, nil)
+ who := attrib.attribute(unit, nil)
var acct string
switch who.class {
case unitTenant:
@@ -757,8 +797,8 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin
// usage.UpsertStatement — safe to run repeatedly as new days' objects
// 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),
+// openPassRegistry — 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.
@@ -769,13 +809,12 @@ 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.
+// Every run re-attributes the whole month (#390), by evidence that does not
+// change with time: the account a hostname names by construction, not
+// whoever routes the host today. So a move, a delete or a recreate never
+// moves an hour between accounts. An instance on a hostname outside every
+// account's namespace (a custom domain) carries no such evidence, and its
+// hours are counted against no account and logged.
//
// fleetMeters failing (a bad registry read, a bucket hiccup under a fleet
// prefix) makes this WHOLE pass return an error rather than upsert
@@ -789,7 +828,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 {
- attrib, err := s.passAttribution(ctx)
+ attrib, err := s.passAttribution()
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 3502b0b66..7d768eacf 100644
--- a/internal/console/economicspass_test.go
+++ b/internal/console/economicspass_test.go
@@ -334,18 +334,21 @@ func TestStatementsPassGolden(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance",
+ // The host is in the ops account's platform namespace, which is what
+ // attributes its unit (#390).
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if err := reg.Upsert(registry.Route{Host: "a.bab.oncarlos.test", Kind: "instance",
Status: "ready", App: fixtureApp, Version: "v1"}); err != nil {
t.Fatal(err)
}
- // One box, one day of metrics: unit carlos-app@a.example.com with
+ // One box, one day of metrics: unit carlos-app@a.bab.oncarlos.test with
// cpu avg 0.5 for 60 samples in hour 09 (= 0.5 core-hours), mem avg
// 1e9 bytes (= 1 GB-hour, 1 instance-hour).
cpu, mem := 0.5, 1e9
roll := metrics.DayRollup{V: 1, Box: "box1", Date: "2026-08-10", Hours: map[string]metrics.HourAgg{
"09": {Units: map[string]map[string]metrics.Agg{
- "carlos-app@a.example.com.service": {
+ "carlos-app@a.bab.oncarlos.test.service": {
"cpu": {Avg: cpu, N: 60},
"mem_bytes": {Avg: mem, N: 60},
},
@@ -425,25 +428,32 @@ func TestStatementsPassZeroUsageAccountListed(t *testing.T) {
}
// 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".
+// brief's literal text: a unit that is not a tenant'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{}) {
+ if who := a.attribute("console.service", nil); who.class != unitPlatform || who.owner != (metrics.Owner{}) {
t.Fatalf("console.service = %+v, want platform overhead", who)
}
}
-// 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)
+// TestAttributionStampedUnits: a unit stamped on a tenant's console-box route
+// is that tenant's workload, but a stamped name is no identity on another
+// box or over time, so it is counted against no account (#390, Astra round
+// 1). A unit stamped on the platform's own route stays platform overhead.
+func TestAttributionStampedUnits(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.addRoute(t, registry.Route{Host: "bespoke.example.com", App: "bespoke", Account: "cdef", Unit: "carlos-bespoke.service"})
+ fx.addRoute(t, registry.Route{Host: "console.example.com", App: "console", Unit: "console.service"})
+ a, err := fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if who := a.attribute("carlos-bespoke.service", nil); who.class != unitUnknown {
+ t.Fatalf("tenant-stamped unit = %+v, want counted against no account", who)
+ }
+ if who := a.attribute("console.service", nil); who.class != unitPlatform {
+ t.Fatalf("platform-stamped unit = %+v, want platform overhead", who)
}
}
diff --git a/internal/console/economicsview.go b/internal/console/economicsview.go
index 2dbeec26f..24ff37471 100644
--- a/internal/console/economicsview.go
+++ b/internal/console/economicsview.go
@@ -47,9 +47,8 @@ type EconomicsView struct {
// absent (a fresh deployment, not a fault; see loadActiveScenario).
ScenarioWarning string
// 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
+ // configured/reachable (a unit stamped on a tenant's console-box route
+ // reads as platform overhead), 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
@@ -410,7 +409,10 @@ 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()
- attrib, warning, recordsWarning := s.loadAttributionForEconomics(sweepCtx)
+ attrib, warning, err := s.loadAttributionForEconomics()
+ if err != nil {
+ return nil, fmt.Errorf("console: load economics: %w", err)
+ }
sweep, err := s.sweepUsage(sweepCtx, from, to, attrib)
if err != nil {
@@ -462,16 +464,6 @@ 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)
@@ -727,31 +719,27 @@ func poolTopupAccrual(from, to time.Time, topupUSD float64) float64 {
// 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) {
+// registry is missing or unreadable — the opposite of passAttribution's
+// refusal, and deliberately so: that refusal protects a WRITE pass from
+// reading registry.Open's freshly-created empty sqlite and writing numbers
+// it should not. This is a READ path — there is nothing to protect by
+// refusing. With no registry, a unit stamped on a tenant's console-box route
+// is not recognised, so it reads as platform overhead, 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. err is the console's own account list
+// failing, which no page can do without.
+func (s *Server) loadAttributionForEconomics() (attrib *usageAttribution, warning string, err error) {
var routes []registry.Route
- reg, err := s.openPassRegistry()
- if err != nil {
- 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 {
+ reg, rerr := s.openPassRegistry()
+ if rerr != nil {
+ warning = fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", rerr)
+ } else if routes, rerr = reg.List(); rerr != nil {
routes = nil
- registryWarning = 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)
+ warning = fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", rerr)
}
- return attrib, registryWarning, recordsWarning
+ attrib, err = s.newUsageAttribution(routes)
+ return attrib, warning, err
}
// loadActiveScenario resolves economics.ActiveKey -> named scenario ->
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index f992c3679..2b3a4c77b 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -337,19 +337,6 @@ 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 916122237..974f061ce 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, "tenantOn": true},
+ "byHost": {"foldFleetReports": true, "host": true, "seen": true, "unrecorded": true},
}
files, err := filepath.Glob("*.go")
if err != nil {
diff --git a/internal/console/usageattrib.go b/internal/console/usageattrib.go
index 33f9f86ae..22f58951b 100644
--- a/internal/console/usageattrib.go
+++ b/internal/console/usageattrib.go
@@ -6,42 +6,44 @@ package console
// 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.
+// statements pass, which re-sweeps the whole month, 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:
+// The rule now: a reading is an account's only on evidence that holds for
+// the whole time the reading covers. Two things qualify.
//
-// 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.
+// 1. The box's own tag on the reading (metrics.UnitSample.Owner,
+// docs/superpowers/notes/remote-instance-metrics.md): the box vouches
+// that everything the reading measured was that tenant's. Day rollups
+// carry no tag, so this applies to live readings only.
+// 2. A hostname that names its account by construction: <...>.<sqid>.<apps
+// domain>, the account's own platform namespace (the console pins a
+// self-serve app's domain to it, handleAPIInstanceEnable), or a
+// sidecar's synthetic <name>.<app>.<sqid>.sidecar.internal
+// (provision.SidecarHost). No other account can ever hold such a host,
+// before, during or after any move, delete or recreate, and account
+// sqids are never reused. The sqid must be a live console account.
//
-// 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.
+// What does not qualify, and why (Astra, round 1): a record's created_at says
+// when the record was written, not whose process the box was running (a box
+// can keep a predecessor's row and process after a successor's record
+// exists); a box's report and the console box's routes say who holds a host
+// now, not who held it during an earlier hour of the month; and a unit name
+// stamped on a console-box route is not an identity on any other box. So an
+// instance unit (carlos-exec@<host>, carlos-app@<host>.service) on a host
+// outside every account's namespace, with no tag, and a unit stamped on a
+// tenant's console-box route, are counted against no account, not even the
+// platform's, and the sweep logs them. Any other unit is the platform's own
+// overhead, charged to release.OpsAccount as before.
+//
+// Nothing here reads the bucket: the namespace needs only the console's
+// account list and apps domain. Records are read only for display, to name
+// an instance's app (appNames).
import (
"context"
- "errors"
"fmt"
"log"
- "os"
"sort"
"strings"
"time"
@@ -57,112 +59,66 @@ import (
type unitClass int
const (
- // unitPlatform is not an instance's unit: the platform's own overhead,
- // charged to release.OpsAccount.
+ // unitPlatform is not a tenant's workload: the platform's own
+ // overhead, charged to release.OpsAccount.
unitPlatform unitClass = iota
- // unitTenant is an instance whose tenant is established.
+ // unitTenant is a reading whose account is established.
unitTenant
- // unitUnknown is an instance's unit whose tenant cannot be established.
- // It is counted against no account.
+ // unitUnknown is a tenant's workload whose account cannot be
+ // established. It is counted against no account.
unitUnknown
)
-// unitOwnership is one reading's owner.
+// unitOwnership is one reading's owner. owner.App is set only when the
+// evidence names it (a tag, a sidecar's host); the account is what
+// attribution establishes.
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.
+// built once per pass (newUsageAttribution) and reads nothing after that.
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
+ // appsDomain is the console's platform apps domain; "" switches the
+ // namespace rule off, and then only tags attribute instances.
+ appsDomain string
+ // accounts is every live console account's sqid.
+ accounts map[string]bool
+ // tenantStamped is every unit stamped on a console-box route of a
+ // tenant (an account other than the platform's own).
+ tenantStamped map[string]bool
}
-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 {
+// newUsageAttribution builds the attribution: the console's accounts and
+// apps domain, and the units stamped on the console box's routes (routes
+// may be nil when it has no registry).
+func (s *Server) newUsageAttribution(routes []registry.Route) (*usageAttribution, error) {
+ accts, err := s.store.Accounts()
+ if err != nil {
+ return nil, fmt.Errorf("accounts: %w", err)
+ }
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, "", "") },
+ appsDomain: strings.ToLower(strings.TrimSuffix(s.cfg.AppsDomain, ".")),
+ accounts: map[string]bool{},
+ tenantStamped: map[string]bool{},
+ }
+ for _, acct := range accts {
+ a.accounts[acct.Sqid] = true
}
for _, rt := range routes {
- if rt.Unit != "" {
- a.stamped[rt.Unit] = rt
- }
- if rt.Host != "" {
- a.local[rt.Host] = rt
+ if rt.Unit != "" && release.RouteAccount(rt) != release.OpsAccount {
+ a.tenantStamped[rt.Unit] = true
}
}
- 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
+ return a, nil
}
// 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) {
+// its place), or the pass writes nothing.
+func (s *Server) passAttribution() (*usageAttribution, error) {
reg, err := s.openPassRegistry()
if err != nil {
return nil, err
@@ -171,11 +127,7 @@ func (s *Server) passAttribution(ctx context.Context) (*usageAttribution, error)
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
+ return s.newUsageAttribution(routes)
}
// instanceHost is the host of an instance's unit: carlos-exec@<host> (an
@@ -194,87 +146,55 @@ func instanceHost(unit string) (string, bool) {
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}}
- }
+// attribute is the owner of a reading of unit. tag is the tenant the box
+// tagged the reading with, nil for none (and always nil for a rollup).
+func (a *usageAttribution) attribute(unit string, tag *metrics.Owner) unitOwnership {
host, ok := instanceHost(unit)
if !ok {
+ if a.tenantStamped[unit] {
+ return unitOwnership{class: unitUnknown}
+ }
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 {
+ if o, ok := a.namespaceOwner(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
+ return unitOwnership{class: unitUnknown, host: host}
}
-// 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
+// namespaceOwner is the account a host names by construction: a sidecar's
+// <name>.<app>.<sqid>.sidecar.internal (with its app), or a host under
+// <sqid>.<apps domain> with at least one label before the sqid (a bare
+// <x>.<apps domain> may be a pre-accounts app's host whose name happens to
+// be a sqid). The sqid must be a live console account.
+func (a *usageAttribution) namespaceOwner(host string) (metrics.Owner, bool) {
+ host = strings.ToLower(host)
+ if rest, ok := strings.CutSuffix(host, provision.SidecarSuffix); ok {
+ parts := strings.Split(rest, ".")
+ if len(parts) == 3 && provision.ValidSidecarName(parts[0]) && release.ValidApp(parts[1]) && a.accounts[parts[2]] {
+ return metrics.Owner{Account: parts[2], App: parts[1]}, true
+ }
+ return metrics.Owner{}, false
}
- if l, ok := a.sidecars[host]; ok {
- return l.tenants, l.err
+ if a.appsDomain == "" {
+ return metrics.Owner{}, false
}
- 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}}
- }
+ rest, ok := strings.CutSuffix(host, "."+a.appsDomain)
+ if !ok {
+ return metrics.Owner{}, false
}
- 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
+ i := strings.LastIndexByte(rest, '.')
+ if i <= 0 {
+ return metrics.Owner{}, false
+ }
+ sqid := rest[i+1:]
+ if !a.accounts[sqid] {
+ return metrics.Owner{}, false
}
- return a.fleetFacts.tenantOn(box, host)
+ return metrics.Owner{Account: sqid}, true
}
// unattributedUsage tallies the instance-hours a sweep counted against no
@@ -283,7 +203,7 @@ 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
+// log writes the sweep's one line about readings it attributed to no
// account, naming the ten largest.
func (u unattributedUsage) log(from, to time.Time) {
if len(u) == 0 {
@@ -312,8 +232,28 @@ func (u unattributedUsage) log(from, to time.Time) {
}
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",
+ log.Printf("console: usage attribution %s..%s: %.2f instance-hours on %d units counted against no account (no box tag, and the host is in no account's namespace): %s",
usageDay(from), usageDay(to), total, len(keys), b.String())
}
func usageDay(t time.Time) string { return t.UTC().Format("2006-01-02") }
+
+// appNames is the app of every instance record by host, for display only
+// (the live view's APP column): read tolerantly, so a record that will not
+// read leaves its row's app blank and nothing else. ctx bounds the walk.
+func (s *Server) appNames(ctx context.Context) map[string]metrics.Owner {
+ out := map[string]metrics.Owner{}
+ if s.cfg.Releases == nil {
+ return out
+ }
+ src, _ := s.recordWalkStore(ctx, s.cfg.Releases)
+ recs, _, err := provision.ListAllRecordsTolerantJudged(ctx, src, provision.JudgeFrom(ctx))
+ if err != nil {
+ log.Printf("console: instance records for app names: %v", err)
+ return out
+ }
+ for _, rec := range recs {
+ out[rec.Host] = metrics.Owner{Account: rec.Account, App: rec.App}
+ }
+ return out
+}
diff --git a/internal/console/usageattrib_test.go b/internal/console/usageattrib_test.go
index a2f9f77e2..7838ffe91 100644
--- a/internal/console/usageattrib_test.go
+++ b/internal/console/usageattrib_test.go
@@ -3,10 +3,12 @@ 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.
+// pass, reported by each box's real status snapshot. The app's domain is the
+// account's own platform namespace (<sqid>.<apps domain>), as the console's
+// enable door pins it. 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"
@@ -121,32 +123,73 @@ func recordOf(t *testing.T, fx *consoleFixture, acct, app, host string) provisio
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.
+// nsAppsDomain is the fixture console's platform apps domain.
+const nsAppsDomain = "oncarlos.test"
+
+// nsHost is a host in account sqid's platform namespace.
+func nsHost(label, sqid string) string { return label + "." + sqid + "." + nsAppsDomain }
+
+// inNamespace points the fixture's shop app at the account's own platform
+// namespace, the domain the console's enable door pins a self-serve app to.
+func (tb *twoBoxes) inNamespace(t *testing.T) {
+ t.Helper()
+ tb.fx.srv.cfg.AppsDomain = nsAppsDomain
+ tb.fx.srv.cfg.BoxLabel = status.Label("box-a")
+ if err := provision.PutManifest(context.Background(), tb.fx.rel, tb.sqid, "shop", shopManifest("shop", tb.sqid+"."+nsAppsDomain)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// reportBoth writes both boxes' status snapshots from their registries.
+func (tb *twoBoxes) reportBoth(t *testing.T) {
+ t.Helper()
+ regA, err := registry.Open(tb.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ report(t, tb.fx.rel, regA, "box-a", "ie", time.Now(), nil, 1024)
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ tb.fresh()
+}
+
+// TestUsageTwoBoxTenant: one account with an instance on the console's box,
+// one on box B and a sidecar on B. All their 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 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)
+ tb.inNamespace(t)
+ remote, local := nsHost("eu", tb.sqid), nsHost("ie", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", remote, "uk", "")
+ tb.create(t, tb.token, tb.sqid, "shop", local, "ie", "")
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remote); rt == nil {
+ t.Fatal("fixture: box B did not mint the uk instance")
+ }
+ tb.reportBoth(t)
+ // A sidecar of a second app, which has no instance anywhere.
+ if _, err := fx.st.CreateAppIn(5151, "worker", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ side := provision.SidecarHost("bot", "worker", tb.sqid)
+ if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot",
+ Host: side, App: "worker", Account: tb.sqid, Region: "uk", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
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)
+ hours := hoursAfter(time.Now(), 3)
+ rollHour(t, fx.rel, boxA, hours[0], map[string]metrics.UnitSample{execUnit(local): busy()}, 60)
+ rollHour(t, fx.rel, boxB, hours[0], map[string]metrics.UnitSample{execUnit(remote): busy(), "carlos-edge.service": busy()}, 60)
+ // A unit-backed instance is never tagged by its box; its host still
+ // names its account. And the sidecar.
+ rollHour(t, fx.rel, boxB, hours[1], map[string]metrics.UnitSample{activator.UnitName(remote): busy(), execUnit(side): 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)
+ near(t, "instance_hours", ours[usage.MeterInstanceHours], 4)
+ near(t, "cpu_core_hours", ours[usage.MeterCPUCoreHours], 2)
+ near(t, "mem_gb_hours", ours[usage.MeterMemGBHours], 4)
ops := statement(t, fx, hours[2], release.OpsAccount)
near(t, "ops instance_hours (the edge on B)", ops[usage.MeterInstanceHours], 1)
@@ -162,36 +205,41 @@ func TestUsageTwoBoxTenant(t *testing.T) {
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)
+ if got, want := day.Accounts[tb.sqid], (usage.CensusAccount{Apps: 2, Routes: 3}); got != want {
+ t.Fatalf("census %s = %+v, want %+v (an instance on each box and the sidecar-only app)", tb.sqid, got, want)
}
- // The live view: B's unit is the account's, not the platform's.
+ // The live view: B's unit is the account's shop, not the platform's.
if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
t.Fatal(err)
}
+ writeSamples(t, fx.rel, boxB, metrics.Sample{At: time.Now().UTC(), Units: map[string]metrics.UnitSample{execUnit(remote): {CPUFrac: p(0.2)}}})
tb.fresh()
- rows := statusInstanceRows(t, fx, tb.token, "?account="+tb.sqid)
- got := map[string]apiStatusInstance{}
- for _, r := range rows {
- got[r.Unit] = r
+ var found bool
+ for _, r := range statusInstanceRows(t, fx, tb.token, "?account="+tb.sqid) {
+ if r.Unit == execUnit(remote) {
+ found = true
+ if r.Box != boxB || r.Host != remote || r.App != "shop" || r.Platform || r.Unattributed {
+ t.Fatalf("status --instances row = %+v, want B's unit as the account's shop instance", 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)
+ if !found {
+ t.Fatal("status --instances --account left out B's instance")
}
}
-// 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.
+// TestUsageReusedHostname: a hostname reused across accounts. Outside every
+// account's namespace (a custom domain, here shop.example.com) nothing says
+// whose process a box ran in which hour: the record, B's row and B's report
+// all name the successor now, and B kept the predecessor's row after the
+// successor's record existed. So neither account is charged for any of it,
+// and the hours are logged. Inside a namespace the reuse cannot happen: the
+// rival cannot create a host in this account's namespace.
func TestUsageReusedHostname(t *testing.T) {
tb := newTwoBoxes(t)
fx := tb.fx
+ fx.srv.cfg.AppsDomain = nsAppsDomain
fx.srv.cfg.BoxLabel = status.Label("box-a")
ctx := context.Background()
now := time.Now()
@@ -219,82 +267,104 @@ func TestUsageReusedHostname(t *testing.T) {
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)
- }
+ // B keeps the rival's row (and process) after this account's record
+ // exists: reconcile with no lifetime judge leaves another tenant's row.
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)
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != tb.sqid && rt.Account != rival {
+ t.Fatalf("fixture: B's row = %+v", rt)
}
- report(t, fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
- tb.fresh()
+ tb.reportBoth(t)
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...) {
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt.UTC().Truncate(time.Hour)
+ era := []time.Time{created.Add(-time.Hour), created, created.Add(time.Hour), created.Add(2 * time.Hour)}
+ for _, h := range era {
rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(remoteHost): busy()}, 60)
}
logs := captureLog(t)
- attrib, err := fx.srv.passAttribution(ctx)
+ attrib, err := fx.srv.passAttribution()
if err != nil {
t.Fatal(err)
}
- sweep, err := fx.srv.sweepUsage(ctx, rivalEra[0], oursEra[1], attrib)
+ sweep, err := fx.srv.sweepUsage(ctx, era[0], era[3], attrib)
if err != nil {
t.Fatal(err)
}
- near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 2)
+ near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 0)
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())
}
+
+ // The rival cannot take a host in this account's namespace.
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, rival, "shop"), bob, `{"host":"`+nsHost("eu", tb.sqid)+`","region":"uk"}`); code == http.StatusCreated {
+ t.Fatalf("the rival created a host in this account's namespace: %s", out)
+ }
+}
+
+// TestUsageSameAccountRecreate: inside its namespace an account's hostname
+// deleted and created again, on another box, is its own throughout, so the
+// re-run statement keeps every hour.
+func TestUsageSameAccountRecreate(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ host := nsHost("eu", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", host, "ie", "")
+ tb.reconcile(t, "v3")
+ hours := hoursAfter(time.Now(), 3)
+ rollHour(t, fx.rel, status.Label("box-a"), hours[0], map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ if code, _, out := rawReq(t, http.MethodDelete, instancesURL(fx, tb.sqid, "shop")+"/"+host, tb.token, ""); code/100 != 2 {
+ t.Fatalf("delete = %d %s", code, out)
+ }
+ tb.reconcile(t, "v3")
+ tb.create(t, tb.token, tb.sqid, "shop", host, "uk", "")
+ tb.reconcile(t, "v3")
+ rollHour(t, fx.rel, status.Label("box-b"), hours[1], map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
+ near(t, "instance_hours", statement(t, fx, hours[2], tb.sqid)[usage.MeterInstanceHours], 2)
}
// 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.
+// move, and keeps the hours from before it. 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")
+ tb.inNamespace(t)
ctx := context.Background()
- tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "")
+ host := nsHost("ie", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", host, "ie", "")
tb.reconcile(t, "v3")
regA, err := registry.Open(fx.regPath)
if err != nil {
t.Fatal(err)
}
- if rt, _ := regA.Get(localHost); rt == nil {
+ if rt, _ := regA.Get(host); 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)
+ hours := hoursAfter(time.Now(), 6)
for _, h := range hours[:3] {
- rollHour(t, fx.rel, boxA, h, map[string]metrics.UnitSample{execUnit(localHost): busy()}, 60)
+ rollHour(t, fx.rel, boxA, h, map[string]metrics.UnitSample{execUnit(host): 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 {
+ if err := provision.SetRecordRegion(ctx, fx.rel, tb.sqid, "shop", host, "uk"); err != nil {
t.Fatal(err)
}
tb.reconcile(t, "v3")
- if rt, _ := regA.Get(localHost); rt != nil {
+ if rt, _ := regA.Get(host); rt != nil {
t.Fatalf("fixture: the console's box still routes the moved instance: %+v", rt)
}
- if rt, _ := tb.regB.Get(localHost); rt == nil {
+ if rt, _ := tb.regB.Get(host); 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)
+ rollHour(t, fx.rel, boxB, h, map[string]metrics.UnitSample{execUnit(host): busy()}, 60)
}
ours := statement(t, fx, hours[5], tb.sqid)
near(t, "after the move, re-run", ours[usage.MeterInstanceHours], 5)
@@ -302,37 +372,49 @@ func TestStatementRerunAcrossAMove(t *testing.T) {
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.
+// TestUsageUnknownInstanceCountsNowhere: a tenant's unit whose account
+// nothing establishes for the whole hour is nobody's: an untagged instance on
+// a custom domain (even one B's report and B's registry name now), a host
+// under the namespace of no live account, and a unit stamped on a tenant's
+// console-box route, on either box. It is not platform overhead, so ops is
+// not charged either; it is logged. A unit stamped on the platform's own
+// route stays the platform'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.
+ tb.inNamespace(t)
+ boxA, boxB := status.Label("box-a"), status.Label("box-b")
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})
+ fx.addRoute(t, registry.Route{Host: "bespoke.example.com", Kind: "instance", Status: "ready", App: "bespoke", Account: "cdef", Unit: "carlos-bespoke.service"})
+ fx.addRoute(t, registry.Route{Host: "console.example.com", Kind: "instance", Status: "ready", App: "console", Unit: "console.service"})
+ tb.reportBoth(t)
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(),
+ execUnit("stray.example.com"): busy(),
+ execUnit("hand.example.com"): busy(),
+ execUnit(nsHost("x", "zzzq")): busy(),
+ // The bare <sqid>.<apps domain>: a pre-accounts <app>.<apps domain>
+ // host could share its name with a sqid, so it names no account.
+ execUnit(tb.sqid + "." + nsAppsDomain): busy(),
+ "carlos-bespoke.service": busy(),
+ activator.UnitName("a.b.c.de"): busy(),
}, 60)
+ rollHour(t, fx.rel, boxA, hours[0], map[string]metrics.UnitSample{"carlos-bespoke.service": busy(), "console.service": 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")} {
+ near(t, "ops instance_hours (console.service only)", statement(t, fx, hours[1], release.OpsAccount)[usage.MeterInstanceHours], 1)
+ near(t, "the account whose bare domain was sampled", statement(t, fx, hours[1], tb.sqid)[usage.MeterInstanceHours], 0)
+ if raw, _, err := fx.rel.Get(context.Background(), usage.StatementKey("cdef", usage.MonthOf(hours[1]))); err == nil {
+ var st usage.Statement
+ if err := json.Unmarshal(raw, &st); err != nil {
+ t.Fatal(err)
+ }
+ near(t, "cdef instance_hours", st.Meters[usage.MeterInstanceHours], 0)
+ }
+ for _, u := range []string{execUnit("stray.example.com"), execUnit("hand.example.com"), execUnit(nsHost("x", "zzzq")), "carlos-bespoke.service on box " + boxA, "carlos-bespoke.service on box " + boxB} {
if !strings.Contains(logs.String(), u) {
t.Fatalf("%s was not logged as unattributed:\n%s", u, logs.String())
}
@@ -340,21 +422,23 @@ func TestUsageUnknownInstanceCountsNowhere(t *testing.T) {
}
// 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
+// owner by the box's tag or the host's namespace. A sample its box tagged
+// names its tenant; an instance unit nothing establishes 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)
+ tb.inNamespace(t)
+ remote := nsHost("eu", tb.sqid)
+ tb.create(t, tb.token, tb.sqid, "shop", remote, "uk", "")
+ tb.reconcile(t, "v3")
+ tb.reportBoth(t)
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)},
+ writeSamples(t, fx.rel, boxB, metrics.Sample{At: time.Now().UTC(), Units: map[string]metrics.UnitSample{
+ execUnit(remote): {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)},
@@ -364,7 +448,7 @@ func TestStatusInstancesAcrossBoxes(t *testing.T) {
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 {
+ if r := got[execUnit(remote)]; r.Account != tb.sqid || r.App != "shop" || r.Host != remote || 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 {
@@ -377,3 +461,53 @@ func TestStatusInstancesAcrossBoxes(t *testing.T) {
t.Errorf("edge = %+v, want platform overhead", r)
}
}
+
+// TestCensusRecordsAcrossBoxes: the census counts records wherever they run,
+// does not count an app in the Trash even while its console-box route is
+// still there, and refuses the day when a record will not decode (the day is
+// create-only).
+func TestCensusRecordsAcrossBoxes(t *testing.T) {
+ tb := newTwoBoxes(t)
+ fx := tb.fx
+ tb.inNamespace(t)
+ ctx := context.Background()
+ tb.create(t, tb.token, tb.sqid, "shop", nsHost("eu", tb.sqid), "uk", "")
+ tb.create(t, tb.token, tb.sqid, "shop", nsHost("ie", tb.sqid), "ie", "")
+ tb.reconcile(t, "v3")
+ // Trash the app; the console box's route is still there until its
+ // domains pass withdraws it.
+ if err := fx.st.TrashAppRow(5151, "shop", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ regA, _ := registry.Open(fx.regPath)
+ if rt, _ := regA.Get(nsHost("ie", tb.sqid)); rt == nil {
+ t.Fatal("fixture: the console box's route is gone")
+ }
+ date := usage.DayOf(time.Now())
+ if err := fx.srv.censusPass(ctx, date); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := fx.rel.Get(ctx, 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, ok := day.Accounts[tb.sqid]; ok {
+ t.Fatalf("census counts the trashed app: %+v", got)
+ }
+
+ // A record that does not decode: no day is written.
+ next := usage.DayOf(time.Now().Add(24 * time.Hour))
+ if _, err := fx.rel.Put(ctx, provision.RecordKey(tb.sqid, "shop", "bad."+tb.sqid+"."+nsAppsDomain), []byte(`{"schema":1,`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.srv.censusPass(ctx, next); err == nil {
+ t.Fatal("census with an undecodable record succeeded")
+ }
+ if _, _, err := fx.rel.Get(ctx, usage.CensusDayKey(next)); err == nil {
+ t.Fatal("census with an undecodable record wrote its day")
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index ded47da0c..8c4be30fd 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := retireAppLock407WriteCensusInventory()
+ inventory := usageAttribution390WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
index 42478266b..cdc079343 100644
--- a/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
+++ b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv
@@ -1,3 +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
+@coverage . ab0281815fc5e3d7f3470905dc8208d4f399b2a918a8ca2661db127e7a462939
diff --git a/internal/provision/usage_attribution_390_census_test.go b/internal/provision/usage_attribution_390_census_test.go
new file mode 100644
index 000000000..ed376179c
--- /dev/null
+++ b/internal/provision/usage_attribution_390_census_test.go
@@ -0,0 +1,31 @@
+package provision
+
+// Record-write census entry for usage-attribution-390 (#390: console usage
+// and billing attribute every box's readings by the box's tag or the
+// hostname's account namespace, not the console box's registry), layered on
+// retireAppLock407WriteCensusInventory (main's newest at 78c23655). Reviewed
+// by the branch author and the cross-model reviewer (Astra) with the branch.
+// No record write is added, moved or reclassified:
+// - Server.handleAPIStatusInstances keeps its one key site, the
+// "instances" JSON literal of its answer. Its body now attributes each
+// reading through usageAttribution, reads the instance records (read
+// only, for the APP column) and marks an unattributed row. It writes
+// nothing.
+func usageAttribution390WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), retireAppLock407WriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/apistatusinstances.go", "Server.handleAPIStatusInstances", "key-site", "lit:instances", "f6f97ed6ce5d68f2dd8a7254409b9d26c64cda6dde78460812ea7f7603bd386d"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("usage-attribution-390 replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/status_instances.go b/status_instances.go
index cef383b0d..d61760fcc 100644
--- a/status_instances.go
+++ b/status_instances.go
@@ -150,12 +150,12 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string)
}
// statusInstancesCopy is `carlos status --instances`' new copy (#390; Luna
-// pass 2026-10-26, docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md).
+// passes 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)",
+ UnattributedNote: "(unattributed: neither its box nor its hostname identifies its account, so its usage counts against no account)",
}
// statusLayoutRow is one host's layout, as the console answers it