carlos / platform Public

rollup-tenant-tags: hourly rollups carry each tenant's tagged usage, so statements count custom-domain instances for their owner

Squashed from rollup-tenant-tags into main.
claude agent, operated by paul@keymail.dev e92c22adbcfd5266edb6bcae589d31de6f12d736 parent 80343a5
11 files changed, +521 −35
  • docs/superpowers/notes/census-proposal-rollup-tenant-tags.md +11 −0
  • docs/superpowers/notes/remote-instance-metrics.md +41 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md +18 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md +82 −0
  • internal/console/economicspass.go +72 −31
  • internal/console/usageattrib.go +6 −3
  • internal/console/usageattrib_tags_test.go +167 −0
  • internal/metrics/rollup.go +75 −1
  • internal/metrics/rollup_test.go +45 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv +3 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
new file mode 100644
index 000000000..f50ea83f9
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rollup-tenant-tags.md
@@ -0,0 +1,11 @@
+# Census approval: rollup-tenant-tags
+
+Ruling `census-ruling-rollup-tenant-tags`. 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: `internal/metrics`.
+
+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: `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820` → `f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md
index 52859a9ec..cf8c43813 100644
--- a/docs/superpowers/notes/remote-instance-metrics.md
+++ b/docs/superpowers/notes/remote-instance-metrics.md
@@ -378,3 +378,44 @@ continuity family, so under stopping rule 2 the overlap summing was cut
rather than patched again: a host read in both layouts in one tick has no
reading that tick (`TestMergeNestedCutsAnOverlap`). Census: the changed
units and envelope approved. The branch review stops here.
+
+## Follow-up: tags in the hourly rollups (branch rollup-tenant-tags)
+
+Usage attribution (#390, 70930b64) counts a reading for an account by
+the box's tag (live readings) or by a host in that account's namespace.
+The statements read hourly rollups, which carried no tag, so instances
+on custom domains counted against no account.
+
+Each rolled-up hour now carries, per unit, `owned`: one entry per tenant
+the box tagged any of that unit's samples with, holding the same `cpu`
+and `mem_bytes` aggregates over exactly those samples
+(`metrics.HourAgg.Owned`, `rollupOwned`). Untagged samples join no
+owner and stay only in the whole-unit aggregate. The tag rule is the
+sample's, unchanged: the rollup only groups what the box already
+vouched, sample by sample. Additive and omitted when empty.
+
+The usage sweep (`sweepUsage`, so the statements) charges a unit whose
+hostname names its account, or a platform unit, as before. A unit no
+hostname attributes is charged to each owner for its owned aggregate
+only (through the same `attribute` rule as a live tagged reading), and
+the rest of its hour is counted against no account and logged.
+
+No new request: the same day objects, a little larger. Old boxes'
+rollups have no `owned`; their custom-domain hours count nowhere, as
+now. Rides the next box release.
+
+Tests (`internal/console/usageattrib_tags_test.go`, samples tagged by the
+box's rule over box B's real registry, rolled up and stored by the box's
+own functions, the real sweep and statements pass): a custom-domain
+instance on box B counted for its owner for exactly its tagged samples
+(whole, part and untagged hours); a reused custom hostname charged to
+the predecessor for the hours its tag is on and never to the new owner,
+and to no one while B's row and activator disagree. `TestRollupHourOwned`
+in `internal/metrics`. Mutations: 6, all killed.
+
+Review (Astra, billing, 5fe6b58b): READY AFTER FIXES. One P2: the
+uncounted remainder subtracted CPU-else-memory counts, so a tagged
+memory-only sample could cancel an untagged CPU one in the log. Fixed:
+`unchargedSamples` subtracts CPU and memory counts separately and then
+applies the CPU-else-memory rule. Census: `internal/metrics` envelope
+approved. The review stops here.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md
new file mode 100644
index 000000000..94ee4c5d9
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rollup-tenant-tags-r1.md
@@ -0,0 +1,18 @@
+Round 1 of 3: no P1 findings; one P2.
+
+1. **P2 — `sweepUsage`: subtract metric counts before selecting the unattributed remainder.**
+ At [economicspass.go:458](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/console/economicspass.go:458), the code subtracts independently selected instance counts. But [unitHourUsage:624](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/console/economicspass.go:624) selects CPU’s count when available, otherwise memory’s. Those counts can represent different samples.
+
+ **Failure scenario:** one tagged sample carries only memory; a later untagged sample carries CPU and memory. The whole aggregate selects CPU N=1; the owned aggregate selects memory N=1. Subtraction yields zero, so the untagged sample disappears from the log. A first reading without a CPU delta is supported by [parse.go:168](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/parse.go:168). Tenant charges remain isolated.
+
+ **Fix:** subtract accepted owners’ CPU and memory counts separately, then apply the CPU-else-memory rule to the residual counts. Add a regression test asserting the remaining `1/60` unattributed hour is logged.
+
+ **Fault family:** unattributed usage accounting — tagged samples must not cancel unrelated untagged samples in the remainder.
+
+Validation: reviewed both rollup production paths, replacement writes, statement reruns, live status, census and economics consumers, and fleet presence accounting. No new requests were introduced. `git diff --check` passed. Targeted Go tests could not start because the sandbox refused creation of Go’s build directory; the six reported mutation kills were not independently rerun.
+
+**Census verdict: APPROVE `internal/metrics` envelope re-pin.** The independently calculated fingerprint matches the overlay. [RollupHour:138](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/rollup.go:138) and [rollupOwned:145](/home/paulca/amadan.net/carlos/platform-rollup-tags/internal/metrics/rollup.go:145) add in-memory grouping over existing samples, calling the existing aggregator and sorting owners. They add no root reads, path resolution, execution, or weakened validation. No unit dispositions change.
+
+Fix the P2 without reopening the review, retaining the required checks on the resulting diff.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md
new file mode 100644
index 000000000..3a782cede
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rollup-tenant-tags.md
@@ -0,0 +1,82 @@
+# Review brief: branch rollup-tenant-tags (billing), round 1 of 3
+
+Repo carlos/platform, branch `rollup-tenant-tags`, commit named in the
+reviewer's prompt. Under review: the diff `origin/main..<commit>`.
+Authorities on main: `docs/superpowers/notes/remote-instance-metrics.md`
+(the box's per-sample tag rule, reviewed and merged in 4dc5902d and
+d7ae1d76) and `internal/console/usageattrib.go` (#390, 70930b64, its
+reviews in that branch's report). This branch adds the note's section
+"Follow-up: tags in the hourly rollups". Do not review against unmerged
+branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the new note section, then the
+diff, and check every claim against the code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings: a reading counts for an account only on evidence that
+ holds for the whole time it covers (#390); the box's per-sample tag is
+ such evidence (the merged tag rule); untagged usage of a custom-domain
+ instance counts against no account; local and namespace attribution
+ keep #390's behaviour.
+- The per-sample tag rule itself (merged). Raise it only with new
+ evidence that a rolled-up hour can carry a tag its samples did not.
+
+## What to check
+
+Fault family: **tenant identity of usage** (an hour, or part of one,
+charged to an account that did not run it, or a tenant's usage charged to
+the platform). Name it beside every finding in that family.
+
+1. `metrics.RollupHour`/`rollupOwned`: does each owner's aggregate cover
+ exactly the samples tagged with it, on every path the box rolls an
+ hour (metricsFlush's old-hour rollup over a merged chunk,
+ backfillPrevHourRollup)? Can a restart, a merged chunk or duplicate
+ timestamps make an owner's N or average include another tenant's or an
+ untagged sample?
+2. `sweepUsage` (`internal/console/economicspass.go`): namespace-owned and
+ platform units as before; an unknown unit charged to each owner only
+ for its owned aggregate, through `attribute`; the remainder counted for
+ no one. Double counting? Over-counting when an hour's rollup is
+ rewritten? Statements' re-runs over the month?
+3. Interaction with #390's other paths: status --instances (live), the
+ census, economics views. Anything still reading rollups as untagged?
+4. Wire shape: additive `owned`; every reader of day rollups (fleet
+ presence hours included).
+5. Tests: production-wired as described; a custom-domain instance on a
+ non-console box counted for its owner; a reused hostname not counted
+ for the wrong account; untagged hours counted nowhere. Mutations: 6,
+ all killed.
+6. Request budget: no new request.
+7. **Census (the reviewer decides every class).** Card
+ `docs/superpowers/notes/census-proposal-rollup-tenant-tags.md`: the
+ `internal/metrics` envelope re-pin. Approve or reject, citing lines.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index 1beca1d30..29668a523 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -424,45 +424,49 @@ 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))
+ // charge adds one unit's aggregates for an hour to acct.
+ charge := func(acct string, um map[string]metrics.Agg) {
+ cpuCoreHours, memGBHours, instN, hasCPU, hasMem := unitHourUsage(um)
+ 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
+ al.MemGBHours += memGBHours
+ bl.ByAccount[acct] = al
+ }
for _, hour := range roll.Hours {
for unit, um := range hour.Units {
- var instN int
- var cpuCoreHours, memGBHours float64
- cpu, hasCPU := um["cpu"]
- if hasCPU {
- cpuCoreHours = cpu.Avg * float64(cpu.N) / 60
- instN = cpu.N
- }
- mem, hasMem := um["mem_bytes"]
- if hasMem {
- memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9
- if instN == 0 {
- instN = mem.N
- }
- }
who := attrib.attribute(unit, nil)
- var acct string
switch who.class {
case unitTenant:
- acct = who.owner.Account
+ charge(who.owner.Account, um)
case unitPlatform:
- acct = release.OpsAccount
+ charge(release.OpsAccount, um)
default:
- unattributed.add(box, unit, float64(instN)/60)
- continue
- }
- mm := touch(acct)
- if hasCPU {
- mm[usage.MeterCPUCoreHours] += cpuCoreHours
- }
- if hasMem {
- mm[usage.MeterMemGBHours] += memGBHours
+ // No hostname names this unit's account. The part
+ // of the hour its box tagged with a tenant is that
+ // tenant's, as a live tagged reading is (the box's
+ // rollup aggregates each tenant's tagged samples
+ // alone, metrics.HourAgg.Owned); the rest counts
+ // against no account.
+ var charged []map[string]metrics.Agg
+ for _, oa := range hour.Owned[unit] {
+ tag := oa.Owner
+ if w := attrib.attribute(unit, &tag); w.class == unitTenant {
+ charge(w.owner.Account, oa.Metrics)
+ charged = append(charged, oa.Metrics)
+ }
+ }
+ if n := unchargedSamples(um, charged); n > 0 {
+ unattributed.add(box, unit, float64(n)/60)
+ }
}
- mm[usage.MeterInstanceHours] += float64(instN) / 60
- al := bl.ByAccount[acct]
- al.CPUCoreHours += cpuCoreHours
- al.MemGBHours += memGBHours
- bl.ByAccount[acct] = al
}
}
sweep.PerBox[box] = bl
@@ -613,6 +617,43 @@ func (s *Server) foldStorageAndCensus(ctx context.Context, from, to time.Time, d
return nil
}
+// unitHourUsage is one unit's hour of usage from its "cpu" and "mem_bytes"
+// aggregates: core-hours, GB-hours and the sample count that makes its
+// instance-minutes (the CPU count, else the memory count).
+func unitHourUsage(um map[string]metrics.Agg) (cpuCoreHours, memGBHours float64, instN int, hasCPU, hasMem bool) {
+ cpu, hasCPU := um["cpu"]
+ if hasCPU {
+ cpuCoreHours = cpu.Avg * float64(cpu.N) / 60
+ instN = cpu.N
+ }
+ mem, hasMem := um["mem_bytes"]
+ if hasMem {
+ memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9
+ if instN == 0 {
+ instN = mem.N
+ }
+ }
+ return cpuCoreHours, memGBHours, instN, hasCPU, hasMem
+}
+
+// unchargedSamples is the instance-minutes of a unit's hour left over once
+// the charged owners' parts are taken out: CPU and memory counts are
+// subtracted separately, then the hour's own rule (the CPU count, else the
+// memory count) applies to what remains, so a tagged sample that carried
+// only memory never cancels an untagged one that carried CPU (Astra,
+// rollup-tenant-tags round 1).
+func unchargedSamples(um map[string]metrics.Agg, charged []map[string]metrics.Agg) int {
+ cpuN, memN := um["cpu"].N, um["mem_bytes"].N
+ for _, m := range charged {
+ cpuN -= m["cpu"].N
+ memN -= m["mem_bytes"].N
+ }
+ if cpuN > 0 {
+ return cpuN
+ }
+ return max(memN, 0)
+}
+
// rollupPresenceHours converts one box's day rollup into billable box-hours
// under the fleet-hours presence rule (task-3 brief): fleet-box rollups may
// carry only the host-level aggregate (no per-unit CPU sampling — the box
diff --git a/internal/console/usageattrib.go b/internal/console/usageattrib.go
index 22f58951b..ea895756e 100644
--- a/internal/console/usageattrib.go
+++ b/internal/console/usageattrib.go
@@ -14,8 +14,10 @@ package console
//
// 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.
+// that everything the reading measured was that tenant's. A day
+// rollup's hour carries, per unit, each tenant's tagged samples
+// aggregated alone (metrics.HourAgg.Owned), so the statements count the
+// tagged part of an hour for its tenant and the untagged part for none.
// 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
@@ -147,7 +149,8 @@ func instanceHost(unit string) (string, bool) {
}
// 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).
+// tagged the reading with, nil for none (a rollup hour's whole-unit
+// aggregate; its tagged parts come with their owner, HourAgg.Owned).
func (a *usageAttribution) attribute(unit string, tag *metrics.Owner) unitOwnership {
host, ok := instanceHost(unit)
if !ok {
diff --git a/internal/console/usageattrib_tags_test.go b/internal/console/usageattrib_tags_test.go
new file mode 100644
index 000000000..d025d349c
--- /dev/null
+++ b/internal/console/usageattrib_tags_test.go
@@ -0,0 +1,167 @@
+package console
+
+// Usage of instances on custom domains (#390 follow-up): no hostname names
+// their account, so only the box's tenant tag can, and the statements read
+// hourly rollups. The box rolls each tenant's tagged samples up on their own
+// (metrics.HourAgg.Owned). Two boxes as in usageattrib_test.go; each box's
+// samples are tagged by the box's own rule over its real registry
+// (boxSample: metrics.Vouched, metrics.TagUnits), rolled up by
+// metrics.RollupHour and stored by metrics.UpsertRollup; the passes are the
+// real sweepUsage and statementsPass.
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// rollTaggedHour writes one hour of box's rollup from 60 one-minute
+// samples of host's unit: the first tagged of them read while live names
+// the activator's entry, the rest with no live entry (so untagged), each
+// tagged by the box's rule over reg.
+func rollTaggedHour(t *testing.T, tb *twoBoxes, box string, hour time.Time, host string, live map[string]metrics.Live, tagged int) {
+ t.Helper()
+ var samples []metrics.Sample
+ for i := 0; i < 60; i++ {
+ l := live
+ if i >= tagged {
+ l = nil
+ }
+ samples = append(samples, boxSample(t, tb.regB, l, hour.Add(time.Duration(i)*time.Minute),
+ map[string]metrics.UnitSample{execUnit(host): busy()}))
+ }
+ if err := metrics.UpsertRollup(context.Background(), tb.fx.rel, box, hour, metrics.RollupHour(samples)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestUsageTaggedCustomDomainCounted: an instance on a custom domain on
+// box B is counted for its owner for exactly the samples B tagged with it:
+// a whole tagged hour, two thirds of a part-tagged hour, nothing of an
+// untagged hour, and nothing charged to the platform.
+func TestUsageTaggedCustomDomainCounted(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.fx.srv.cfg.AppsDomain = nsAppsDomain
+ tb.fx.srv.cfg.BoxLabel = status.Label("box-a")
+ tb.setUp(t, false) // remoteHost (shop.example.com, a custom domain) on B
+ boxB := status.Label("box-b")
+ live := map[string]metrics.Live{remoteHost: {Account: tb.sqid, App: "shop", Entry: 1}}
+ hours := hoursAfter(time.Now(), 4)
+ rollTaggedHour(t, tb, boxB, hours[0], remoteHost, live, 60)
+ rollTaggedHour(t, tb, boxB, hours[1], remoteHost, live, 40)
+ rollTaggedHour(t, tb, boxB, hours[2], remoteHost, live, 0)
+
+ logs := captureLog(t)
+ attrib, err := tb.fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := tb.fx.srv.sweepUsage(context.Background(), hours[0], hours[3], attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "owner instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 1+40.0/60)
+ near(t, "owner cpu_core_hours", sweep.PerAccount[tb.sqid][usage.MeterCPUCoreHours], 0.5*(1+40.0/60))
+ near(t, "owner mem_gb_hours", sweep.PerAccount[tb.sqid][usage.MeterMemGBHours], 1+40.0/60)
+ 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 untagged part was not logged as counted against no account:\n%s", logs.String())
+ }
+ // The statement (the write pass) counts the same.
+ near(t, "statement instance_hours", statement(t, tb.fx, hours[3], tb.sqid)[usage.MeterInstanceHours], 1+40.0/60)
+}
+
+// TestUsageTaggedReusedHostname: the custom hostname was another
+// account's, which deleted it; this account created it again, and B (no
+// lifetime judge) kept the predecessor's row and process. B tags those
+// hours with the predecessor, and they are the predecessor's, never this
+// account's. When B's row names this account while the predecessor's
+// entry still stops, B vouches nothing: those hours count for no one.
+func TestUsageTaggedReusedHostname(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()
+ const rivalID int64 = 6464
+ 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-tag-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", "")
+ tb.reconcile(t, "v3")
+ if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != rival {
+ t.Fatalf("fixture: B's row = %+v, want the rival's still", rt)
+ }
+ boxB := status.Label("box-b")
+ rivalLive := map[string]metrics.Live{remoteHost: {Account: rival, App: "shop", Entry: 1}}
+ created := recordOf(t, fx, tb.sqid, "shop", remoteHost).CreatedAt.UTC().Truncate(time.Hour)
+ era := []time.Time{created, created.Add(time.Hour)}
+ rollTaggedHour(t, tb, boxB, era[0], remoteHost, rivalLive, 60)
+
+ // B withdraws the predecessor's row and mints this account's (a box
+ // with a lifetime judge); the rival's entry is still stopping.
+ 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)
+ }
+ rollTaggedHour(t, tb, boxB, era[1], remoteHost, rivalLive, 60)
+
+ attrib, err := fx.srv.passAttribution()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sweep, err := fx.srv.sweepUsage(ctx, era[0], era[1].Add(time.Hour), attrib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ near(t, "this account's instance_hours", sweep.PerAccount[tb.sqid][usage.MeterInstanceHours], 0)
+ near(t, "the predecessor's instance_hours (its own process, tagged)", sweep.PerAccount[rival][usage.MeterInstanceHours], 1)
+ near(t, "ops instance_hours", sweep.PerAccount[release.OpsAccount][usage.MeterInstanceHours], 0)
+}
+
+// TestUnchargedSamples (Astra, round 1, P2): a tagged sample with only a
+// memory reading and an untagged one with CPU and memory leave one
+// untagged minute, not zero.
+func TestUnchargedSamples(t *testing.T) {
+ whole := map[string]metrics.Agg{"cpu": {N: 1}, "mem_bytes": {N: 2}}
+ owned := map[string]metrics.Agg{"mem_bytes": {N: 1}}
+ if n := unchargedSamples(whole, []map[string]metrics.Agg{owned}); n != 1 {
+ t.Fatalf("uncharged = %d, want 1", n)
+ }
+ if n := unchargedSamples(map[string]metrics.Agg{"cpu": {N: 60}, "mem_bytes": {N: 60}}, []map[string]metrics.Agg{{"cpu": {N: 60}, "mem_bytes": {N: 60}}}); n != 0 {
+ t.Fatalf("a fully tagged hour leaves %d", n)
+ }
+ if n := unchargedSamples(map[string]metrics.Agg{"mem_bytes": {N: 5}}, nil); n != 5 {
+ t.Fatalf("an untagged memory-only hour = %d, want 5", n)
+ }
+}
diff --git a/internal/metrics/rollup.go b/internal/metrics/rollup.go
index 032562492..c206213cb 100644
--- a/internal/metrics/rollup.go
+++ b/internal/metrics/rollup.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"os"
+ "sort"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -27,6 +28,21 @@ type Agg struct {
type HourAgg struct {
Host map[string]Agg `json:"host"` // "cpu","mem","disk","load1"
Units map[string]map[string]Agg `json:"units"` // unit -> "cpu","mem_bytes" -> Agg
+ // Owned is, per unit, the hour's readings the box tagged with a tenant
+ // (UnitSample.Owner, owner.go), aggregated per tenant over exactly the
+ // samples that carried that tag. Untagged samples are in Units only.
+ // Usage billing charges a reading no hostname attributes to these owners
+ // alone (docs/superpowers/notes/remote-instance-metrics.md). Additive:
+ // absent on every hour a box built before it rolled up.
+ Owned map[string][]OwnedAgg `json:"owned,omitempty"`
+}
+
+// OwnedAgg is the part of one unit's hour tagged with one tenant: the same
+// "cpu" and "mem_bytes" aggregates as HourAgg.Units, over only the samples
+// the box vouched were Owner's.
+type OwnedAgg struct {
+ Owner Owner `json:"owner"`
+ Metrics map[string]Agg `json:"metrics"`
}
// DayRollup is a box's rolled-up day, keyed by UTC hour ("00".."23") —
@@ -119,7 +135,65 @@ func RollupHour(samples []Sample) HourAgg {
}
}
- return HourAgg{Host: host, Units: units}
+ return HourAgg{Host: host, Units: units, Owned: rollupOwned(samples)}
+}
+
+// rollupOwned is RollupHour's Owned: per unit and per tenant, the
+// aggregates of the samples tagged with that tenant. A sample with no tag
+// joins none. Owners are listed in account then app order, so the same
+// samples always roll up to the same bytes; nil when no sample is tagged.
+func rollupOwned(samples []Sample) map[string][]OwnedAgg {
+ type key struct {
+ unit string
+ owner Owner
+ }
+ cpu := map[key][]float64{}
+ mem := map[key][]float64{}
+ seen := map[key]bool{}
+ for _, s := range samples {
+ for name, u := range s.Units {
+ if u.Owner == nil {
+ continue
+ }
+ k := key{name, *u.Owner}
+ seen[k] = true
+ if u.CPUFrac != nil {
+ cpu[k] = append(cpu[k], *u.CPUFrac)
+ }
+ if u.MemBytes != nil {
+ mem[k] = append(mem[k], float64(*u.MemBytes))
+ }
+ }
+ }
+ if len(seen) == 0 {
+ return nil
+ }
+ out := map[string][]OwnedAgg{}
+ for k := range seen {
+ m := map[string]Agg{}
+ if agg, ok := aggOf(cpu[k]); ok {
+ m["cpu"] = agg
+ }
+ if agg, ok := aggOf(mem[k]); ok {
+ m["mem_bytes"] = agg
+ }
+ if len(m) > 0 {
+ out[k.unit] = append(out[k.unit], OwnedAgg{Owner: k.owner, Metrics: m})
+ }
+ }
+ for unit := range out {
+ sort.Slice(out[unit], func(i, j int) bool {
+ a, b := out[unit][i].Owner, out[unit][j].Owner
+ if a.Account != b.Account {
+ return a.Account < b.Account
+ }
+ return a.App < b.App
+ })
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
}
// UpsertRollup reads box's day object for hour's UTC date (a missing
diff --git a/internal/metrics/rollup_test.go b/internal/metrics/rollup_test.go
index 9711ad3bf..660f3dd85 100644
--- a/internal/metrics/rollup_test.go
+++ b/internal/metrics/rollup_test.go
@@ -131,3 +131,48 @@ func TestUpsertRollupTwoHoursSameDay(t *testing.T) {
t.Fatalf("Hours[11] = %+v, want cpu avg 0.2", got.Hours["11"])
}
}
+
+// TestRollupHourOwned: an hour's tagged readings are aggregated per tenant
+// over exactly the samples carrying that tenant's tag; untagged samples
+// join no owner but stay in Units; a unit never tagged has no entry.
+func TestRollupHourOwned(t *testing.T) {
+ shop := &Owner{Account: "bdn", App: "shop"}
+ rival := &Owner{Account: "rvl", App: "shop"}
+ at := time.Date(2026, 10, 26, 10, 0, 0, 0, time.UTC)
+ f := func(v float64) *float64 { return &v }
+ i := func(v int64) *int64 { return &v }
+ var samples []Sample
+ add := func(o *Owner, cpu float64) {
+ samples = append(samples, Sample{At: at.Add(time.Duration(len(samples)) * time.Minute), Units: map[string]UnitSample{
+ "carlos-exec@a.example.com": {CPUFrac: f(cpu), MemBytes: i(100), Owner: o},
+ "carlos-exec@b.example.com": {CPUFrac: f(cpu)},
+ }})
+ }
+ add(shop, 0.2)
+ add(shop, 0.4)
+ add(nil, 0.9)
+ add(rival, 0.6)
+ agg := RollupHour(samples)
+ if n := agg.Units["carlos-exec@a.example.com"]["cpu"].N; n != 4 {
+ t.Fatalf("Units cpu N = %d, want every sample (4)", n)
+ }
+ owned := agg.Owned["carlos-exec@a.example.com"]
+ if len(owned) != 2 || owned[0].Owner != *shop || owned[1].Owner != *rival {
+ t.Fatalf("owned = %+v, want bdn/shop then rvl/shop", owned)
+ }
+ if c := owned[0].Metrics["cpu"]; c.N != 2 || c.Avg < 0.2999 || c.Avg > 0.3001 {
+ t.Fatalf("bdn/shop cpu = %+v, want N 2 avg 0.3", c)
+ }
+ if c := owned[1].Metrics["cpu"]; c.N != 1 || c.Avg != 0.6 {
+ t.Fatalf("rvl/shop cpu = %+v", c)
+ }
+ if m := owned[0].Metrics["mem_bytes"]; m.N != 2 {
+ t.Fatalf("bdn/shop mem = %+v", m)
+ }
+ if _, ok := agg.Owned["carlos-exec@b.example.com"]; ok {
+ t.Fatal("a unit never tagged has owned readings")
+ }
+ if RollupHour([]Sample{{At: at, Units: map[string]UnitSample{"u": {CPUFrac: f(1)}}}}).Owned != nil {
+ t.Fatal("an hour with no tag has an Owned map (it must stay absent on the wire)")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 39cd92eed..a7b879c4b 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -10,3 +10,4 @@ plan14-root-reads-nearest-region-b.tsv f4e36134015ec6d09bada7be500c8faad22450afd
plan14-root-reads-alias-socket-follow-338.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
plan14-root-reads-usage-attribution-390.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927
plan14-root-reads-ha-p1a-433.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
+plan14-root-reads-rollup-tenant-tags.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820
diff --git a/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv b/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv
new file mode 100644
index 000000000..360a9cdea
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rollup-tenant-tags.tsv
@@ -0,0 +1,3 @@
+# Census overlay rollup-tenant-tags, written by census-propose (#369). census-ruling-rollup-tenant-tags, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rollup-tenant-tags.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/metrics ccc6723430e0c436f01843706c3e11e42dadcf357f0848795983e20ed9c9a439