usage-attribution-390: usage and billing attribute every box's readings by the box's tenant tag or the host's account namespace, not the console box's registry (#390)
Statements, the census, the economics page and carlos status --instances charged instances on other boxes to the ops account, and the monthly re-sweep moved a moved instance's earlier hours to ops. A reading is now an account's only on evidence that holds for the whole reading: the box's tag on a live reading, or a host under <sqid>.<apps domain> (or a sidecar's synthetic host) for a live account. Other tenant workloads, such as custom-domain instances without a tag and units stamped on a tenant's console-box route, are counted against no account and logged. The census counts instance and sidecar records on every box. No backfill; the open month corrects at the next statements pass. Astra round 2 READY; census approved on #280. Squashed from usage-attribution-390 into main.
26 files changed,
+1,653
−210
docs/site/cli.md+7 −5docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION-R2.md+64 −0docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md+67 −0docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-R2.md+9 −0docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md+13 −0docs/superpowers/notes/census-proposal-usage-attribution-390.md+11 −0docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md+47 −0docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md+23 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md+103 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md+131 −0internal/console/apistatusinstances.go+52 −26internal/console/apistatusinstances_test.go+17 −11internal/console/economicspage_test.go+17 −8internal/console/economicspass.go+151 −83internal/console/economicspass_test.go+29 −24internal/console/economicsview.go+34 −30internal/console/economicsview_test.go+13 −7internal/console/metricsview.go+11 −0internal/console/usageattrib.go+259 −0internal/console/usageattrib_test.go+513 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv+3 −0internal/provision/usage_attribution_390_census_test.go+31 −0status_instances.go+27 −8status_instances_test.go+19 −7
CI passed — run details
landed from usage-attribution-390
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 42cf3ac0a..8d5ffd699 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2305,11 +2305,13 @@ not a secret — a wrong-method request gets a 405 from the router, like every |
| other route here — but the answer is, because it names other people's |
| accounts. |
| -Two things it cannot see, both printed under the table. A sleeping instance |
| -has no process and so no reading, so it does not appear. And the readings are |
| -fleet-wide while the account each one is attributed to comes from the |
| -console's own box's route registry, so on a multi-box deployment an instance |
| -running elsewhere can show up under `(platform)` rather than under its tenant. |
| +A sleeping instance has no process or reading, so it does not appear. A note |
| +under the table explains this. Each reading belongs to the account 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-BRIEF-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md| new file mode 100644 |
| index 000000000..281ba1596 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/LUNA-COPY-BRIEF-USAGE-ATTRIBUTION.md |
| @@ -0,0 +1,67 @@ |
| +# Copy review brief: usage attribution across boxes (#390) |
| + |
| +Paul delegates copy review for platform CLI, console and docs copy to you. You |
| +are the copy editor; your edits will be applied as approved copy. |
| + |
| +## What changed |
| + |
| +Until now `carlos status --instances` and the console's usage statements |
| +decided whose a box's CPU and memory readings were by looking only at the |
| +console's own box. An instance on any other box was filed under the |
| +platform. Now each reading belongs to the account and app its instance |
| +record names, on any box. A reading that nothing can be shown to belong to |
| +(no instance record, no box report naming its owner) is shown as |
| +unattributed and is counted against no account, the platform's included. |
| + |
| +## The strings (draft text is yours to change; ids are fixed) |
| + |
| +Readers: platform operators. `carlos status --instances` is operator-only |
| +and lists every awake instance on every box, one row per instance, columns |
| +BOX REGION HOST ACCOUNT APP CPU MEM. |
| + |
| +- UA-1, the APP cell of an instance whose owner cannot be established (the |
| + ACCOUNT cell prints `-`). It sits beside the existing `(platform)` cell, |
| + which marks the platform's own services. Draft: `(unattributed)` |
| +- UA-2, a note printed in muted text under the table, only when at least one |
| + UA-1 row is present. The existing note above it reads `(awake instances |
| + only — a hibernating instance has no process to measure)` (older copy, not |
| + in scope). Draft: `(unattributed: no record or box report says whose this |
| + instance is, so its usage counts against no account)` |
| +- UA-3, the console's refusal to `carlos status --instances` when it could not |
| + read the instance records (transient; retrying usually works). The CLI |
| + prints it after `status --instances: `. Draft: `could not read the instance |
| + records. Try again.` |
| +- UA-4, a warning banner on the operator-only economics page when the |
| + instance records could not be read; `%v` is a Go error string. Draft: |
| + `instance records: %v; no instance's usage is attributed to an account this |
| + sweep` |
| +- UA-5, a docs paragraph in docs/site/cli.md, `--instances` section, after a |
| + paragraph about who may call it. Draft: |
| + |
| + > A sleeping instance has no process and so no reading, so it does not |
| + > appear, and a note under the table says so. Each reading belongs to the |
| + > account and app its instance record names, on whichever box the instance |
| + > runs. An instance that no record or box report accounts for shows as |
| + > `(unattributed)`, and its usage counts against no account, the |
| + > platform's included. |
| + |
| +## House rules (Paul's, all binding) |
| + |
| +- No em dashes, ever. Use a full stop and a new sentence; in CLI and API |
| + error strings the new sentence continues in lower case (`could not provision |
| + the store. re-run ...`). |
| +- Plain words. No jargon a reader would not know. Short. |
| +- Human text only. If a string is not human text, flag it rather than edit it. |
| +- Neutral names only (shop, example.com). Never a tenant's name. |
| +- Keep every placeholder exactly (`%v`) and keep UA-1's parentheses (it sits |
| + beside `(platform)`). |
| +- Do not change the facts a string states. If a fact looks wrong or two rows |
| + disagree, flag it. |
| + |
| +## Output |
| + |
| +Markdown, in this shape: |
| + |
| +1. A table of changes only: `id | current | new | why` (a few words in why). |
| +2. A list of flagged rows: `id | problem`. |
| +3. One line of counts: changed, flagged, left alone. |
diff --git a/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION-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/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md| new file mode 100644 |
| index 000000000..d55f2c82f |
| --- /dev/null |
| +++ b/docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION.md |
| @@ -0,0 +1,13 @@ |
| +| id | current | new | why | |
| +|---|---|---|---| |
| +| UA-1 | `(platform)` | `(unattributed)` | Distinguishes unknown ownership from platform services. | |
| +| UA-2 | `(accounts are joined against the console's own box's route registry; an instance on another box in a fleet can land under (platform))` | `(unattributed: no instance record or box report identifies its owner, so its usage counts against no account)` | Explains the actual condition briefly. | |
| +| UA-3 | `could not read the route registry — try again` | `could not read the instance records. try again.` | Names the failed read and follows CLI sentence style. | |
| +| UA-4 | None | `instance records: %v. No instance's usage is attributed to an account this sweep.` | States the warning and its effect clearly. | |
| +| UA-5 | Existing paragraph about sleeping instances and the console box's route registry | A sleeping instance has no process or reading, so it does not appear. A note under the table explains this. Each reading belongs to the account and app named by its instance record, wherever the instance runs. An instance with no record or box report showing its owner appears as `(unattributed)`. Its usage counts against no account, including the platform. | Removes obsolete behavior and uses shorter, clearer sentences. | |
| + |
| +Flagged rows: |
| + |
| +None. |
| + |
| +changed: 5, flagged: 0, left alone: 0 |
| \ No newline at end of file |
diff --git a/docs/superpowers/notes/census-proposal-usage-attribution-390.md b/docs/superpowers/notes/census-proposal-usage-attribution-390.md| new file mode 100644 |
| index 000000000..d8a02fdb0 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-usage-attribution-390.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: usage-attribution-390 |
| + |
| +Ruling `census-ruling-usage-attribution-390`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `.`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Seal: `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927` → `5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md| new file mode 100644 |
| index 000000000..2cb1b45d0 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r2.md |
| @@ -0,0 +1,23 @@ |
| +R1 finding 1 (P1) — **resolved**: `created_at` no longer establishes ownership; untagged custom-domain readings remain unattributed. |
| +R1 finding 2 (P1) — **resolved**: historical attribution no longer uses current records, reports, or routes. |
| +R1 finding 3 (P1) — **resolved**: tenant-stamped bespoke units are unattributed on every box. |
| +R1 finding 4 (P2) — **resolved**: a nonempty `unreadable` set refuses census creation. |
| +R1 finding 5 (P2) — **resolved**: billing no longer reads sidecar records for attribution, removing the failed-read-to-zero path. |
| +R1 finding 6 (P2) — **resolved**: excluded records’ hosts are marked covered before route fallback. |
| +R1 finding 7 (P2) — **resolved**: the census includes sidecar records from live and trashed apps, with placement exclusions. |
| + |
| +No outstanding P1 or P2 findings. |
| + |
| +1. **P3 — §§2–3: Comments still describe the removed attribution algorithm.** |
| + **Problem and evidence:** [apistatusinstances.go:90](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/apistatusinstances.go:90) describes creation-time, report, and route fallbacks; [status_instances.go:141](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:141) says ownership comes from instance records. Neither matches [usageattrib.go:151](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/usageattrib.go:151). |
| + **Failure scenario:** A maintainer investigating attribution follows an ownership rule deliberately removed after round 1. No current runtime failure. |
| + **Fix:** Update these comments to describe live tags, account namespaces, and the stamped-unit exclusion. Keep this on the follow-up list. |
| + **Fault family:** Attribution documentation must match the implemented evidence requirements. |
| + |
| +Validation: targeted tests could not start because the read-only sandbox prevented Go from creating its work directory. Mutation results were not independently rerun. Formatting checks on the inspected Go files passed. `git diff --check` reported only Markdown hard-break whitespace in the committed R1 findings. No files were edited. |
| + |
| +**Root census, envelope `.` — APPROVE.** Reviewed [status_instances.go:36](/home/paulca/amadan.net/carlos/platform-usage-attrib/status_instances.go:36), the printer at line 102, copy values at line 154, and their formatting helpers. The changes decode a boolean and select printed text. They introduce no new root open, execution, query, path traversal, or weakened validation. |
| + |
| +**Record-write census, `Server.handleAPIStatusInstances` — APPROVE.** Reviewed [apistatusinstances.go:98](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/console/apistatusinstances.go:98) through its response, including attribution and app-name reads. No record write is added, moved, or reclassified; the `key-site` / `lit:instances` disposition retained at [usage_attribution_390_census_test.go:17](/home/paulca/amadan.net/carlos/platform-usage-attrib/internal/provision/usage_attribution_390_census_test.go:17) remains appropriate. |
| + |
| +**READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md| new file mode 100644 |
| index 000000000..1c0b8cbad |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390-R2.md |
| @@ -0,0 +1,103 @@ |
| +# Review brief: branch usage-attribution-390 (#390), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `usage-attribution-390`, commit b84f7d476e876b4ebcb777db7a11bd88ee7134f6 (the code; |
| +this brief is committed on top). |
| +Under review: the diff `origin/main...usage-attribution-390` (main merged in at |
| +d3c5601b). |
| +Authorities, all on main: discussion #390, and |
| +`docs/superpowers/notes/remote-instance-metrics.md`. Do not review against |
| +unmerged branches. |
| + |
| +You are an independent reviewer. Read the diff, then the code it names, and |
| +check every claim against that code. This is billing code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul, #390, 2026-10-26: "Build the fix; October self-corrects". No backfill. |
| +- A reading whose account cannot be established is counted against no |
| + account and logged, never charged to ops. |
| +- Day rollups carry no tag; rolling tags into hours is a box change, out of |
| + scope here (a follow-up). |
| +- Cap check done: plans are off on flagship (no CARLOS_PLAN_CATALOG, no |
| + control/plans.json), so no cap can trip. |
| +- The consequence of the round 2 rule below is accepted: an instance on a |
| + custom domain (5 of 202 instance records on flagship) is counted against no |
| + account in statements until boxes roll tags into hours. |
| + |
| +## The change since round 1 |
| + |
| +`internal/console/usageattrib.go` was rewritten. A reading is an account's |
| +only on evidence that holds for the whole time it covers: the box's tag on a |
| +live reading, or a host that names its account by construction |
| +(`<...>.<sqid>.<apps domain>` with at least one label before the sqid, or a |
| +sidecar's `<name>.<app>.<sqid>.sidecar.internal`), for a live console account. |
| +Billing reads no records, box reports or console-box routes for ownership any |
| +more. A unit stamped on a tenant's console-box route is counted nowhere on |
| +any box; one stamped on the platform's own route is platform overhead. The |
| +census (`censusPass`, `censusRecords` in `economicspass.go`) keeps records |
| +and adds sidecar records. |
| + |
| +## What to check |
| + |
| +1. **The namespace as identity (fault family: tenant identity of usage).** |
| + Can any account other than <sqid> ever hold a host under |
| + `<sqid>.<apps domain>`, through any door a tenant can reach (instance |
| + create, domain attach, apex mints, sidecars, seeds, imports, moves, |
| + adoption)? Operator store-mode writes are trusted. Is the sqid parse in |
| + `namespaceOwner` right (case, trailing dot, the bare-domain exclusion, |
| + an apps domain that is itself a suffix of another)? |
| +2. **Live tag** in `attribute`: used only on the live view. |
| +3. **Stamped units**: `tenantStamped` from the console box's registry. |
| +4. **Census**: unreadable records refuse; Trash and fleet hosts are covered |
| + before console-box routes count; sidecars of live and trashed apps. |
| +5. **Request budget**: billing reads nothing new; the census adds one sidecar |
| + listing per app per day through the record view when armed; the status |
| + door reads records tolerantly for the APP column. |
| +6. **Tests** (`usageattrib_test.go` and the updated fixtures) and mutations |
| + (12 run, 12 killed: live account not required, wrong sqid label, sidecar |
| + not recognised, unknown charged to ops, tag ignored, tenant-stamped as |
| + platform, unknown as platform, census ignores records, excluded host not |
| + covered, undecodable accepted, sidecars skipped, bare domain accepted). |
| +7. **Census**: `docs/superpowers/notes/census-proposal-usage-attribution-390.md`, |
| + root envelope `.` re-pinned (only `status_instances.go`, the CLI printer, |
| + changed). Record-write census: |
| + `internal/provision/usage_attribution_390_census_test.go` re-pins |
| + `Server.handleAPIStatusInstances` (no write added). Verdict on both. |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: `docs/superpowers/reviews/CODEX-FINDINGS-usage-attribution-390-r1.md`. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings. The verdict covers everything outstanding, |
| +earlier rounds included. |
| + |
| +## 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 verdicts. 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/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md| new file mode 100644 |
| index 000000000..42aca29b7 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-usage-attribution-390.md |
| @@ -0,0 +1,131 @@ |
| +# Review brief: branch usage-attribution-390 (#390), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `usage-attribution-390`, commit 902e12c9312e5cfbff3a5a0cf961defd6ce8ef11 (the code; this brief is committed on top). |
| +Under review: the diff `origin/main...usage-attribution-390` (merge base |
| +78c23655). |
| +Authorities, all on main: discussion #390 and its proposal reply |
| +(`AMADAN_HOME=~/.amadan-agent amadan discuss show carlos/platform 390` if you |
| +can reach it; otherwise this brief carries what matters), and |
| +`docs/superpowers/notes/remote-instance-metrics.md` (the box's tenant tag on |
| +live samples). Do not review against unmerged branches. |
| + |
| +You are an independent reviewer. Read the diff, then the code it names, and |
| +check every claim against that code. This is billing code: statements feed |
| +the economics page and the (dormant) plan caps. |
| + |
| +## The change in one paragraph |
| + |
| +Statements (`statementsPass`, hourly, create-or-replace for the month to |
| +date), the census (`censusPass`, daily, create-only), the economics page |
| +(`buildEconomicsView`) and `carlos status --instances` used to attribute |
| +every box's sampled units against the console box's own registry, so an |
| +instance on another box was charged to the ops account, and the month's |
| +re-sweep moved a moved instance's earlier hours to ops. Now |
| +`internal/console/usageattrib.go` attributes each reading: stamped |
| +console-box unit; non-instance unit = platform (ops); live reading tagged by |
| +its box = the tag; the host's instance or sidecar record if it existed when |
| +the hour began (a host some record names is decided by its records alone); |
| +for a host with no record, the sampling box's fresh report, then the console |
| +box's route (console's own box only); otherwise counted against no account |
| +and logged. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul, #390, 2026-10-26: "Build the fix; October self-corrects". No |
| + backfill of stored statements or census days. The first statements pass |
| + after release rewrites the open month. |
| +- Readings whose tenant cannot be established are counted nowhere and |
| + logged, never charged to ops (the brief that started this branch). |
| +- Day rollups carry no tenant tag (remote-instance-metrics note, "Mixed |
| + fleet"), and changing the box to roll tags into hours is out of scope (it |
| + would need a box release). The tag is used only on the live view. |
| +- Cap check done before the switch: on flagship the console has no |
| + `CARLOS_PLAN_CATALOG` or `CARLOS_BILLING` set and no `control/plans.json` |
| + marker exists, so plans are off and no awake-hours cap can trip. |
| + |
| +## What to check |
| + |
| +1. **Attribution key (fault family: tenant identity of usage).** In |
| + `usageAttribution.attribute` and `recordsFor`: can any reading reach an |
| + account that did not run it? Walk: a hostname reused across accounts in |
| + the month (predecessor's record deleted, successor's created); the hour |
| + containing the successor's creation; same-account recreation; a move |
| + (record keeps `created_at`, region changes, the source box drops the |
| + route); a deleted instance; a sidecar's synthetic host |
| + (`provision.SidecarHost`); a record with zero `created_at`; two records |
| + naming one host. |
| +2. **Fallbacks for hosts with no record**: `appFacts.tenantOn` |
| + (`remoteinstances.go`) and the console-box route. They carry no time |
| + bound. Is that an attribution of a sample whose tenant cannot be |
| + established? Say what a bound would need, if anything is possible. |
| +3. **Platform versus instance**: `instanceHost` treats only |
| + `carlos-exec@<host>` and `carlos-app@<host>.service` as instances. |
| + Anything else (including stamped units on other boxes) is platform |
| + overhead, as on main. Is any tenant unit that main attributed correctly |
| + now lost? |
| +4. **Write-pass failure behaviour**: `passAttribution` refuses on a missing |
| + registry or unreadable records; `censusPass` refuses too (create-only). |
| + Unreadable record hosts (`unreadable`) attribute nothing. Is there a |
| + path that writes a statement or census day from a partial read? |
| +5. **Census**: records (minus Trash and customer-fleet placements) plus |
| + console-box routes no record covers, one per host. Does this over- or |
| + under-count `apps` (feeds `app_months`) against what main intended? |
| +6. **Read path**: `loadAttributionForEconomics` warnings and the fleet |
| + meters' one-banner rule in `buildEconomicsView`. |
| +7. **Live view**: `handleAPIStatusInstances` with `latestOwner` |
| + (`metricsview.go`) and the new `Unattributed` row; the CLI printer in |
| + `status_instances.go`. |
| +8. **Request budget** (memory: S3 requests cost money; no new per-box |
| + polling): records come through `recordWalkStore` (the change-index view |
| + when armed); box reports only when a host has no record, through the |
| + 60 s cache; one sidecar record GET per sidecar host per pass. Unarmed |
| + deployments walk the records once per statements pass, census pass, |
| + economics build and status request. Is that acceptable or a P2? |
| +9. **Tests** (`usageattrib_test.go`): production-wired through the real |
| + create/delete doors, both boxes' real reconcile and reports, and the box's |
| + own `metrics.RollupHour`/`UpsertRollup`. The move test re-homes the record |
| + with `provision.SetRecordRegion` rather than the box-driven move protocol. |
| + Mutations run (all killed): no created_at bound; bound on hour end; |
| + records keyed wrong; box reports before records; console-box route for |
| + any box; unknown charged to ops; live tag ignored; census ignores records; |
| + unknown host treated as platform. Is a material behaviour untested? |
| +10. **Census**: `docs/superpowers/notes/census-proposal-usage-attribution-390.md`. |
| + No unit changed; the root package's envelope (`.`) is re-pinned because |
| + `status_instances.go` (the CLI printer) changed. Give a verdict on the |
| + envelope: does anything in the root package's change let root open, run, |
| + query or follow something it did not before, from a path or input a |
| + tenant, an app or a box agent can create, write or name? |
| + |
| +## 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 for envelope `.` (approve or reject, citing |
| +lines read). 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. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +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/apistatusinstances.go b/internal/console/apistatusinstances.go| index 5577e207c..0e2b845c8 100644 |
| --- a/internal/console/apistatusinstances.go |
| +++ b/internal/console/apistatusinstances.go |
| @@ -31,23 +31,18 @@ |
| // outright: this is an operator's view of the whole fleet, and no app-scoped |
| // machine token has any business holding it. |
| // |
| -// SCOPE: the two halves of the join do not reach equally far, and the answer |
| -// is only as fleet-wide as the shorter one. The READINGS are fleet-wide — |
| -// every box writes metrics/boxes/<box>/ and LoadMetrics sweeps all of it — |
| -// but the ROUTES they are attributed against come from openPassRegistry, |
| -// which opens this console's OWN box-local registry file. On a multi-box |
| -// deployment a unit sampled on any other box therefore matches no route |
| -// here, falls through routeForUnit's unmatched case, and lands in the answer |
| -// as platform overhead charged to the ops account: a whole box's tenants |
| -// read as the platform's own, which is the opposite of what an operator |
| -// asking "who is using what" would take from it. sweepUsage |
| -// (economicspass.go) carries this same trap and the same reasoning — both |
| -// production deployments are single-box today, so it is inert, and the |
| -// structural fix is routes-as-bucket-records (PR #137, unmerged), which |
| -// would give every pass a registry view spanning boxes instead of one box's |
| -// local file. Until that lands the CLI prints the limit beside the answer, |
| -// the way `carlos routes` does, rather than letting a short list read as the |
| -// whole fleet. |
| +// SCOPE: the readings are fleet-wide — every box writes metrics/boxes/<box>/ |
| +// and LoadMetrics sweeps all of it — and so is the join (#390). Each reading |
| +// is attributed the way the economics passes attribute it |
| +// (usageattrib.go): a reading its box tagged with a tenant is that tenant's; |
| +// otherwise an instance's unit goes to the 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. |
| // |
| // The other limit is by design rather than a defect: an instance that is |
| // ASLEEP has no cgroup and therefore no sample, so it is not here at all. |
| @@ -61,12 +56,13 @@ import ( |
| "net/http" |
| "sort" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// apiStatusInstance is one awake instance. Account and app are joined on from |
| -// the registry through routeForUnit — the same matching rule the economics |
| -// pass attributes cost with, deliberately shared rather than reimplemented. |
| +// apiStatusInstance is one awake instance. Account and app are joined on |
| +// through usageAttribution — the same rule the economics passes attribute |
| +// cost with, deliberately shared rather than reimplemented. |
| type apiStatusInstance struct { |
| Box string `json:"box"` |
| Unit string `json:"unit"` |
| @@ -91,6 +87,13 @@ type apiStatusInstance struct { |
| // operator asking what is on the box wants the box's own overhead in the |
| // picture, clearly labelled rather than silently dropped. |
| Platform bool `json:"platform,omitempty"` |
| + // Unattributed marks a tenant's unit whose account cannot be |
| + // established (usageattrib.go): no tag from its box, and a host in no |
| + // live account's namespace, or a unit stamped on a tenant's console-box |
| + // route. Account and App are empty; Host is the unit's host (the unit |
| + // itself for a stamped unit). The economics passes count such a reading |
| + // against no account. |
| + Unattributed bool `json:"unattributed,omitempty"` |
| } |
| func (s *Server) handleAPIStatusInstances(w http.ResponseWriter, r *http.Request) { |
| @@ -125,6 +128,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, 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) |
| @@ -138,13 +152,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) |
| - // unitOwner's two cases, taken off the match already in hand |
| - // rather than by walking the whole route list a second time — |
| - // same rule, same answers, one pass. |
| - if rt, ok := routeForUnit(routes, u.Unit); ok { |
| - row.Host, row.App, row.Account = rt.Host, rt.App, release.RouteAccount(rt) |
| - } else { |
| + who := attrib.attribute(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/economicspage_test.go b/internal/console/economicspage_test.go| index 520990836..a655e5ed2 100644 |
| --- a/internal/console/economicspage_test.go |
| +++ b/internal/console/economicspage_test.go |
| @@ -67,7 +67,10 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance", |
| + // In the ops account's platform namespace, which 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) |
| } |
| @@ -75,7 +78,7 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) { |
| date := usage.DayOf(time.Now()) |
| roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, 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: 0.5, N: 60}, |
| "mem_bytes": {Avg: 1e9, N: 60}, |
| }, |
| @@ -86,7 +89,7 @@ func seedEconomicsGolden(t *testing.T, fx *consoleFixture) { |
| putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{ |
| V: 1, Box: "box1", Date: date, |
| Hours: map[string]map[string]usage.EdgeRow{"09": { |
| - "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| + "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| }}, |
| }) |
| } |
| @@ -211,7 +214,10 @@ func TestEconomicsPageHonestUnmetered(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance", |
| + // In the ops account's platform namespace, which 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) |
| } |
| @@ -219,7 +225,7 @@ func TestEconomicsPageHonestUnmetered(t *testing.T) { |
| date := usage.DayOf(time.Now()) |
| roll := metrics.DayRollup{V: 1, Box: "darkbox", Date: date, 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: 0.5, N: 60}, |
| "mem_bytes": {Avg: 1e9, N: 60}, |
| }, |
| @@ -450,7 +456,10 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance", |
| + // In the ops account's platform namespace, which 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) |
| } |
| @@ -461,7 +470,7 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) { |
| date := usage.DayOf(lastMonth) |
| roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, 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: 0.5, N: 60}, |
| "mem_bytes": {Avg: 1e9, N: 60}, |
| }, |
| @@ -471,7 +480,7 @@ func TestEconomicsAccountsPageThreadsPeriod(t *testing.T) { |
| putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{ |
| V: 1, Box: "box1", Date: date, |
| Hours: map[string]map[string]usage.EdgeRow{"09": { |
| - "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| + "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| }}, |
| }) |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index db4dd18ca..1beca1d30 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -18,10 +18,10 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/aws" |
| awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| - "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/usage" |
| @@ -96,6 +96,18 @@ func (s *Server) openPassRegistry() (consoleRegistry, error) { |
| // a route with no account (Route.Account == "") to release.OpsAccount, the |
| // deployment operator's built-in account — so pre-accounts routes land in |
| // one place instead of scattering under "". |
| +// |
| +// What it counts (#390): every instance 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 { |
| @@ -109,26 +121,108 @@ func (s *Server) censusPass(ctx context.Context, date string) error { |
| if err != nil { |
| return err |
| } |
| + 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{} |
| - for _, rt := range routes { |
| - acct := release.RouteAccount(rt) |
| + covered := map[string]bool{} |
| + count := func(acct, app string) { |
| c := accounts[acct] |
| c.Routes++ |
| if apps[acct] == nil { |
| apps[acct] = map[string]bool{} |
| } |
| - if rt.App != "" && !apps[acct][rt.App] { |
| - apps[acct][rt.App] = true |
| + if app != "" && !apps[acct][app] { |
| + apps[acct][app] = true |
| c.Apps++ |
| } |
| accounts[acct] = c |
| } |
| + for _, h := range held { |
| + if covered[h.host] { |
| + continue |
| + } |
| + covered[h.host] = true |
| + if h.counts { |
| + count(h.acct, h.app) |
| + } |
| + } |
| + for _, rt := range routes { |
| + 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 |
| } |
| +// 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 |
| + } |
| + trashed := map[string]bool{} |
| + var out []censusTenancy |
| + for _, a := range accts { |
| + 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 |
| + } |
| + // 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 |
| +} |
| + |
| // storagePass sizes every app's deployment-bucket prefix, plus its tenant |
| // object store when one is provisioned, create-only per day. Requires the |
| // bucket to support sized listings (release.SizeLister); a store that |
| @@ -214,45 +308,6 @@ func (s *Server) storagePass(ctx context.Context, date string) error { |
| return err |
| } |
| -// unitOwner attributes a sampled systemd unit (or exec-child cgroup name) to |
| -// its route's account/app. Matching mirrors OwnerAppMetrics (metricsview.go |
| -// ~698-730): rather than parse a host back out of the unit string, it builds |
| -// each route's OWN expected unit names — activator.UnitName/ExecName for a |
| -// unit-backed or exec-backed instance route, plus the route's stamped Unit |
| -// column (#110's bespoke unit) — and compares those forward against the |
| -// sampled name. (Read first per the brief: neither UnitName nor ExecName |
| -// systemd-escapes the host — activator.UnitName is a bare string |
| -// concatenation and cgroup.ExecName likewise — so there is no unescaping |
| -// helper to reuse; building the expected name forward, the same direction |
| -// OwnerAppMetrics does it, is what keeps a hyphenated or dotted host correct |
| -// with no separate escaping step.) A unit matching no route — the console's |
| -// own unit, system units — attributes to release.OpsAccount, app "": platform |
| -// overhead. |
| -func unitOwner(routes []registry.Route, unit string) (acct, app string, ok bool) { |
| - rt, ok := routeForUnit(routes, unit) |
| - if !ok { |
| - return release.OpsAccount, "", false |
| - } |
| - return release.RouteAccount(rt), rt.App, true |
| -} |
| - |
| -// routeForUnit is the matching rule itself, split out of unitOwner so that a |
| -// second reader of the same sampled units — `carlos status --instances`, |
| -// which needs the route's HOST and not only its owner — cannot end up with a |
| -// private second notion of which route a cgroup belongs to. The comment above |
| -// unitOwner is the rationale for the rule; this is the rule. |
| -func routeForUnit(routes []registry.Route, unit string) (registry.Route, bool) { |
| - for _, rt := range routes { |
| - if rt.Unit != "" && rt.Unit == unit { |
| - return rt, true |
| - } |
| - if rt.Host != "" && (unit == activator.UnitName(rt.Host) || unit == activator.ExecName(rt.Host)) { |
| - return rt, true |
| - } |
| - } |
| - return registry.Route{}, false |
| -} |
| - |
| // usageSweep is sweepUsage's result: the box- and account-shaped meters |
| // accumulated by reading metrics and edge days over [from, to], plus enough |
| // coverage bookkeeping for callers to label a total honestly. It deliberately |
| @@ -284,16 +339,17 @@ type usageSweep struct { |
| // by statementsPass (whole month to date, create-or-replace statements) and |
| // Task 11's LoadEconomics (arbitrary period, priced live under a scenario). |
| // |
| -// routes is the registry snapshot unitOwner attributes sampled units |
| -// against — the CALLER resolves it, deliberately not sweepUsage itself, |
| -// because the two callers need opposite failure behaviour on a |
| -// missing/unmounted registry: statementsPass (a WRITE pass) must refuse |
| -// outright rather than write a permanent all-zero day off an empty |
| -// registry.Open (openPassRegistry's own doc comment), while LoadEconomics |
| -// (a READ path) degrades instead — see loadRoutesForEconomics |
| -// (economicsview.go). A nil/empty routes therefore isn't an error here: |
| -// every sampled unit simply falls through unitOwner's unmatched-unit case |
| -// to release.OpsAccount, same as any other unmatched unit. |
| +// attrib says whose each sampled unit's hour is (usageattrib.go, #390): an |
| +// instance's hour goes to the 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 |
| @@ -304,18 +360,7 @@ type usageSweep struct { |
| // sweep and nothing else is still a covered day, exactly as before this |
| // function existed, even though the bytes themselves are read again by |
| // foldStorageAndCensus. |
| -// |
| -// unitOwner attributes a sampled unit against routes, which — for both |
| -// current callers — is this CONSOLE's own box-local registry, while this |
| -// sweep iterates units published by every box under metrics/boxes/. On a |
| -// multi-box deployment a unit sampled on a box other than this console's own |
| -// can fail to match any route in this registry and silently fall to |
| -// release.OpsAccount, indistinguishable from the intended platform-overhead |
| -// fallback. Both production deployments are single-box today, so this is |
| -// currently inert; the structural fix is routes-as-bucket-records (PR #137, |
| -// unmerged), which would give every pass a registry view that spans boxes |
| -// instead of one box's local file. |
| -func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []registry.Route) (*usageSweep, error) { |
| +func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, attrib *usageAttribution) (*usageSweep, error) { |
| metricsBoxes, err := s.cfg.Releases.ListDirs(ctx, metricsBoxesPrefix) |
| if err != nil { |
| return nil, fmt.Errorf("console: sweep usage: %w", err) |
| @@ -355,6 +400,9 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re |
| return bl |
| } |
| + unattributed := unattributedUsage{} |
| + defer unattributed.log(from, to) |
| + |
| fromDay := from.UTC().Truncate(24 * time.Hour) |
| toDay := to.UTC().Truncate(24 * time.Hour) |
| for d := fromDay; !d.After(toDay); d = d.AddDate(0, 0, 1) { |
| @@ -378,22 +426,38 @@ func (s *Server) sweepUsage(ctx context.Context, from, to time.Time, routes []re |
| bl.Hours += float64(len(roll.Hours)) |
| for _, hour := range roll.Hours { |
| for unit, um := range hour.Units { |
| - acct, _, _ := unitOwner(routes, unit) |
| - mm := touch(acct) |
| var instN int |
| var cpuCoreHours, memGBHours float64 |
| - if cpu, ok := um["cpu"]; ok { |
| + cpu, hasCPU := um["cpu"] |
| + if hasCPU { |
| cpuCoreHours = cpu.Avg * float64(cpu.N) / 60 |
| - mm[usage.MeterCPUCoreHours] += cpuCoreHours |
| instN = cpu.N |
| } |
| - if mem, ok := um["mem_bytes"]; ok { |
| + mem, hasMem := um["mem_bytes"] |
| + if hasMem { |
| memGBHours = mem.Avg * float64(mem.N) / 60 / 1e9 |
| - mm[usage.MeterMemGBHours] += memGBHours |
| if instN == 0 { |
| instN = mem.N |
| } |
| } |
| + who := attrib.attribute(unit, nil) |
| + var acct string |
| + switch who.class { |
| + case unitTenant: |
| + acct = who.owner.Account |
| + case unitPlatform: |
| + acct = release.OpsAccount |
| + default: |
| + unattributed.add(box, unit, float64(instN)/60) |
| + continue |
| + } |
| + mm := touch(acct) |
| + if hasCPU { |
| + mm[usage.MeterCPUCoreHours] += cpuCoreHours |
| + } |
| + if hasMem { |
| + mm[usage.MeterMemGBHours] += memGBHours |
| + } |
| mm[usage.MeterInstanceHours] += float64(instN) / 60 |
| al := bl.ByAccount[acct] |
| al.CPUCoreHours += cpuCoreHours |
| @@ -614,7 +678,7 @@ func hasDeviceTag(tags string) bool { |
| // |
| // Deliberately a SECOND bounded read over metrics day objects, not an |
| // extension of sweepUsage's single pass: sweepUsage iterates every box under |
| -// metrics/boxes/ once and attributes by UNIT (unitOwner), which has no |
| +// metrics/boxes/ once and attributes by UNIT (usageAttribution), which has no |
| // concept of a fleet box at all — a fleet box's day rollup carries no units |
| // most of the time (see rollupPresenceHours's doc comment), only a host |
| // aggregate, so folding this in there would mean threading a |
| @@ -652,9 +716,9 @@ func hasDeviceTag(tags string) bool { |
| // bucket-backed box publishing straight to the platform root, or one an |
| // operator hand-configured with CARLOS_STATUS_PREFIX="" — is invisible to |
| // this meter: its rollups never appear under fleets/<fleet>/, so it |
| -// contributes zero fleet box-hours, and its sampled units (if any) fall |
| -// through unitOwner's unmatched case to release.OpsAccount like any other |
| -// unrecognized unit, same as a platform box's stray unit would. This |
| +// contributes zero fleet box-hours, and its sampled units (if any) are |
| +// attributed like any platform box's (usageAttribution): an instance's |
| +// to the tenant its record names, anything else to release.OpsAccount. This |
| // closes itself once the box (re)publishes under its fleet prefix — no |
| // separate migration is needed. |
| // - fleetMeters failing makes statementsPass itself fail (see |
| @@ -731,7 +795,8 @@ func (s *Server) fleetMeters(ctx context.Context, from, to time.Time) (map[strin |
| // census, for app_months, and fleet box-hours, for fleet_box_hours_server/ |
| // device) into one usage.Statement per account, create-or-replace via |
| // usage.UpsertStatement — safe to run repeatedly as new days' objects |
| -// appear. It is a thin caller: open the registry (refusing early — see |
| +// appear. It is a thin caller: build the attribution (passAttribution: |
| +// refusing early when the console box's registry is missing — see |
| // 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 |
| @@ -744,6 +809,13 @@ 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), 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 |
| // statements missing that account's fleet hours — deliberate (review, fix |
| @@ -756,11 +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 { |
| - reg, err := s.openPassRegistry() |
| - if err != nil { |
| - return fmt.Errorf("console: statements pass: %w", err) |
| - } |
| - routes, err := reg.List() |
| + attrib, err := s.passAttribution() |
| if err != nil { |
| return fmt.Errorf("console: statements pass: %w", err) |
| } |
| @@ -771,7 +839,7 @@ func (s *Server) statementsPass(ctx context.Context, now time.Time) error { |
| month := usage.MonthOf(nowUTC) |
| monthStart := time.Date(y, mo, 1, 0, 0, 0, 0, time.UTC) |
| - sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, routes) |
| + sweep, err := s.sweepUsage(ctx, monthStart, nowUTC, attrib) |
| if err != nil { |
| return fmt.Errorf("console: statements pass: %w", err) |
| } |
diff --git a/internal/console/economicspass_test.go b/internal/console/economicspass_test.go| index 4a6819b99..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}, |
| }, |
| @@ -424,31 +427,33 @@ func TestStatementsPassZeroUsageAccountListed(t *testing.T) { |
| } |
| } |
| -// TestUnitOwnerUnmatchedFallsToOpsAccount pins the correction over the |
| -// brief's literal text: the fallback is release.OpsAccount ("bab"), never |
| -// the bare string "ops". |
| -func TestUnitOwnerUnmatchedFallsToOpsAccount(t *testing.T) { |
| - acct, app, ok := unitOwner(nil, "console.service") |
| - if ok { |
| - t.Fatalf("unitOwner matched an empty route list: acct=%q app=%q", acct, app) |
| - } |
| - if acct != release.OpsAccount { |
| - t.Fatalf("unmatched unit acct = %q, want release.OpsAccount (%q)", acct, release.OpsAccount) |
| - } |
| - if app != "" { |
| - t.Fatalf("unmatched unit app = %q, want empty", app) |
| +// TestAttributionPlatformUnitFallsToOpsAccount pins the correction over the |
| +// brief's literal text: a unit that is not 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("console.service", nil); who.class != unitPlatform || who.owner != (metrics.Owner{}) { |
| + t.Fatalf("console.service = %+v, want platform overhead", who) |
| } |
| } |
| -// TestUnitOwnerMatchesStampedUnitColumn: a route with a non-empty Unit |
| -// column matches that exact unit name, independent of Host. |
| -func TestUnitOwnerMatchesStampedUnitColumn(t *testing.T) { |
| - routes := []registry.Route{ |
| - {Host: "bespoke.example.com", App: "bespoke", Unit: "carlos-bespoke.service"}, |
| +// 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) |
| } |
| - acct, app, ok := unitOwner(routes, "carlos-bespoke.service") |
| - if !ok || app != "bespoke" || acct != release.OpsAccount { |
| - t.Fatalf("unitOwner(stamped unit) = %q %q %v", acct, app, ok) |
| + 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 bb6c0ac25..24ff37471 100644 |
| --- a/internal/console/economicsview.go |
| +++ b/internal/console/economicsview.go |
| @@ -46,10 +46,10 @@ type EconomicsView struct { |
| // not be loaded/parsed/validated — never set when active.json is simply |
| // absent (a fresh deployment, not a fault; see loadActiveScenario). |
| ScenarioWarning string |
| - // Warning is set when the SWEEP itself degraded — currently only "no |
| - // registry configured/reachable", which makes every sampled unit |
| - // attribute to release.OpsAccount instead of its real account (see |
| - // loadRoutesForEconomics). Distinct from ScenarioWarning: the two can |
| + // Warning is set when the SWEEP itself degraded: no registry |
| + // configured/reachable (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 |
| Scenarios []string // names under economics/scenarios/ |
| @@ -409,9 +409,12 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| // comment for why this must be the full month, not PeriodDays. |
| daysInMonth := time.Date(now.Year(), now.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day() |
| - routes, warning := s.loadRoutesForEconomics(sweepCtx) |
| + attrib, warning, err := s.loadAttributionForEconomics() |
| + if err != nil { |
| + return nil, fmt.Errorf("console: load economics: %w", err) |
| + } |
| - sweep, err := s.sweepUsage(sweepCtx, from, to, routes) |
| + sweep, err := s.sweepUsage(sweepCtx, from, to, attrib) |
| if err != nil { |
| return nil, fmt.Errorf("console: load economics: %w", err) |
| } |
| @@ -429,18 +432,18 @@ func (s *Server) buildEconomicsView(ctx context.Context, period string) (*Econom |
| // fleetMeters error — see that function's doc comment), THIS is a READ |
| // path: a bad registry read or a bucket hiccup under a fleet prefix |
| // degrades to "no fleet meters this render" plus a visible Warning, |
| - // never a failed dashboard — the same asymmetry loadRoutesForEconomics |
| + // never a failed dashboard — the same asymmetry loadAttributionForEconomics |
| // already draws for the registry itself. Called once per |
| // buildEconomicsView call, which is already the unit the 60s |
| // stale-while-revalidate cache (economicsCacheTTL) bounds — no separate |
| // throttling needed here. A registry-less console would otherwise show |
| - // TWO banners for the SAME missing registry (loadRoutesForEconomics's |
| + // TWO banners for the SAME missing registry (loadAttributionForEconomics's |
| // and this one, since fleetMeters opens that identical registry) — see |
| // the warning=="" guard below, which keeps it to one banner, one cause. |
| if fleetMM, ferr := s.fleetMeters(sweepCtx, from, to); ferr != nil { |
| log.Printf("console: load economics: fleet meters unavailable: %v", ferr) |
| // Suppress a second banner when routes are ALREADY degraded |
| - // (warning != "" here can only mean loadRoutesForEconomics found no |
| + // (warning != "" here can only mean loadAttributionForEconomics found no |
| // usable registry, the one thing that precedes this call): fleetMeters |
| // opens that exact same registry, so its failure here is the same |
| // root cause restated, not a second independent fault. One banner, |
| @@ -714,28 +717,29 @@ func poolTopupAccrual(from, to time.Time, topupUSD float64) float64 { |
| return total |
| } |
| -// loadRoutesForEconomics resolves the routes sweepUsage needs to attribute |
| -// sampled units to accounts, DEGRADING rather than failing when the |
| -// registry is missing or unreadable — the opposite of openPassRegistry's |
| +// loadAttributionForEconomics builds the attribution sweepUsage needs |
| +// (usageattrib.go), DEGRADING rather than failing when the console box's |
| +// 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 as "zero routes" and |
| -// writing a permanent, uncorrectable all-zero day. This is a READ path — |
| -// there is nothing to protect by refusing. A nil routes list simply means |
| -// unitOwner falls every sampled unit through to release.OpsAccount |
| -// (indistinguishable from platform overhead, same as any other unmatched |
| -// unit), and the dashboard still renders with a visible warning rather than |
| -// a blank 500 — precedent: commit 0958fa3, instances health degrading on a |
| -// console with no registry rather than failing the page. |
| -func (s *Server) loadRoutesForEconomics(ctx context.Context) (routes []registry.Route, warning string) { |
| - reg, err := s.openPassRegistry() |
| - if err != nil { |
| - return nil, fmt.Sprintf("no registry available (%v); usage cannot be attributed to accounts by route this sweep", err) |
| - } |
| - routes, err = reg.List() |
| - if err != nil { |
| - return nil, fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", err) |
| - } |
| - return routes, "" |
| +// 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, 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 |
| + warning = fmt.Sprintf("registry: %v; usage cannot be attributed to accounts by route this sweep", rerr) |
| + } |
| + attrib, err = s.newUsageAttribution(routes) |
| + return attrib, warning, err |
| } |
| // loadActiveScenario resolves economics.ActiveKey -> named scenario -> |
diff --git a/internal/console/economicsview_test.go b/internal/console/economicsview_test.go| index cd3f63dd7..33ed91651 100644 |
| --- a/internal/console/economicsview_test.go |
| +++ b/internal/console/economicsview_test.go |
| @@ -34,7 +34,10 @@ func TestLoadEconomicsGolden(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance", |
| + // In the ops account's platform namespace, which 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) |
| } |
| @@ -43,7 +46,7 @@ func TestLoadEconomicsGolden(t *testing.T) { |
| cpu, mem := 0.5, 1e9 |
| roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, 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}, |
| }, |
| @@ -54,7 +57,7 @@ func TestLoadEconomicsGolden(t *testing.T) { |
| putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{ |
| V: 1, Box: "box1", Date: date, |
| Hours: map[string]map[string]usage.EdgeRow{"09": { |
| - "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| + "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| }}, |
| }) |
| @@ -217,7 +220,10 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err := reg.Upsert(registry.Route{Host: "a.example.com", Kind: "instance", |
| + // In the ops account's platform namespace, which 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) |
| } |
| @@ -226,7 +232,7 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) { |
| cpu, mem := 0.5, 1e9 |
| roll := metrics.DayRollup{V: 1, Box: "box1", Date: date, 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}, |
| }, |
| @@ -250,8 +256,8 @@ func TestLoadEconomicsTierRevenueAndPool(t *testing.T) { |
| putStoreJSON(t, fx.rel, usage.EdgeDayKey("box1", date), usage.EdgeDay{ |
| V: 1, Box: "box1", Date: date, |
| Hours: map[string]map[string]usage.EdgeRow{"09": { |
| - "a.example.com": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| - "b.example.com": {Account: poolAcct, App: "poolapp", Requests: 1000, BytesOut: 1e9}, |
| + "a.bab.oncarlos.test": {Account: fixtureAcct, App: fixtureApp, Requests: 4000, BytesOut: 2e9}, |
| + "b.example.com": {Account: poolAcct, App: "poolapp", Requests: 1000, BytesOut: 1e9}, |
| }}, |
| }) |
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go| index 5e6142844..e9b2ca80c 100644 |
| --- a/internal/console/metricsview.go |
| +++ b/internal/console/metricsview.go |
| @@ -85,6 +85,17 @@ func (v BoxMetricsView) ownerIndex(tenant metrics.Owner) int32 { |
| return -1 |
| } |
| +// latestOwner is the tenant the box tagged u's latest reading with (the |
| +// reading UnitRow carries), nil when it tagged none. |
| +func (v BoxMetricsView) latestOwner(u UnitRow) *metrics.Owner { |
| + n := len(u.owner) |
| + if n == 0 || n != len(v.times) || u.owner[n-1] < 0 || int(u.owner[n-1]) >= len(v.owners) { |
| + return nil |
| + } |
| + o := v.owners[u.owner[n-1]] |
| + return &o |
| +} |
| + |
| // AlertRow is one currently-firing rule on one box. LoadMetrics only ever |
| // returns firing rules — a quiet rule has nothing to show. |
| type AlertRow struct { |
diff --git a/internal/console/usageattrib.go b/internal/console/usageattrib.go| new file mode 100644 |
| index 000000000..22f58951b |
| --- /dev/null |
| +++ b/internal/console/usageattrib.go |
| @@ -0,0 +1,259 @@ |
| +package console |
| + |
| +// Usage attribution (#390): whose is a sampled unit's reading? |
| +// |
| +// The readings are fleet-wide: every box writes metrics/boxes/<box>/ and the |
| +// sweeps read all of it. Until #390 the owner of each reading came from the |
| +// console box's own registry, so an instance on any other box matched no |
| +// route and was charged to the ops account as platform overhead, and the |
| +// statements pass, which re-sweeps the whole month, moved an instance's |
| +// earlier hours to ops as soon as it left the console's box. |
| +// |
| +// 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. 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. |
| +// |
| +// 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" |
| + "fmt" |
| + "log" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// unitClass is what a sampled unit is, for usage. |
| +type unitClass int |
| + |
| +const ( |
| + // unitPlatform is not a tenant's workload: the platform's own |
| + // overhead, charged to release.OpsAccount. |
| + unitPlatform unitClass = iota |
| + // unitTenant is a reading whose account is established. |
| + unitTenant |
| + // unitUnknown is a tenant's workload whose account cannot be |
| + // established. It is counted against no account. |
| + unitUnknown |
| +) |
| + |
| +// 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 |
| +} |
| + |
| +// usageAttribution answers unitOwnership for every reading of one pass. It is |
| +// built once per pass (newUsageAttribution) and reads nothing after that. |
| +type usageAttribution struct { |
| + // 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 |
| +} |
| + |
| +// 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{ |
| + 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 != "" && release.RouteAccount(rt) != release.OpsAccount { |
| + a.tenantStamped[rt.Unit] = true |
| + } |
| + } |
| + 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), or the pass writes nothing. |
| +func (s *Server) passAttribution() (*usageAttribution, error) { |
| + reg, err := s.openPassRegistry() |
| + if err != nil { |
| + return nil, err |
| + } |
| + routes, err := reg.List() |
| + if err != nil { |
| + return nil, err |
| + } |
| + return s.newUsageAttribution(routes) |
| +} |
| + |
| +// instanceHost is the host of an instance's unit: carlos-exec@<host> (an |
| +// exec-backed or nested instance, or a sidecar) or carlos-app@<host>.service |
| +// (a unit-backed one). Anything else is not an instance's. |
| +func instanceHost(unit string) (string, bool) { |
| + const app = "carlos-app@" |
| + switch { |
| + case strings.HasPrefix(unit, "carlos-exec@"): |
| + host := strings.TrimPrefix(unit, "carlos-exec@") |
| + return host, host != "" && activator.ExecName(host) == unit |
| + case strings.HasPrefix(unit, app) && strings.HasSuffix(unit, ".service"): |
| + host := strings.TrimSuffix(strings.TrimPrefix(unit, app), ".service") |
| + return host, host != "" && activator.UnitName(host) == unit |
| + } |
| + return "", false |
| +} |
| + |
| +// attribute is the owner of 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} |
| + } |
| + if tag != nil && tag.Account != "" && tag.App != "" { |
| + return unitOwnership{class: unitTenant, host: host, owner: *tag} |
| + } |
| + if o, ok := a.namespaceOwner(host); ok { |
| + return unitOwnership{class: unitTenant, host: host, owner: o} |
| + } |
| + return unitOwnership{class: unitUnknown, host: host} |
| +} |
| + |
| +// 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 a.appsDomain == "" { |
| + return metrics.Owner{}, false |
| + } |
| + rest, ok := strings.CutSuffix(host, "."+a.appsDomain) |
| + if !ok { |
| + return metrics.Owner{}, false |
| + } |
| + i := strings.LastIndexByte(rest, '.') |
| + if i <= 0 { |
| + return metrics.Owner{}, false |
| + } |
| + sqid := rest[i+1:] |
| + if !a.accounts[sqid] { |
| + return metrics.Owner{}, false |
| + } |
| + return metrics.Owner{Account: sqid}, true |
| +} |
| + |
| +// unattributedUsage tallies the instance-hours a sweep counted against no |
| +// account, by box and unit, for one log line per sweep. |
| +type unattributedUsage map[[2]string]float64 |
| + |
| +func (u unattributedUsage) add(box, unit string, hours float64) { u[[2]string{box, unit}] += hours } |
| + |
| +// log writes the sweep's one line about readings it attributed to no |
| +// account, naming the ten largest. |
| +func (u unattributedUsage) log(from, to time.Time) { |
| + if len(u) == 0 { |
| + return |
| + } |
| + keys := make([][2]string, 0, len(u)) |
| + var total float64 |
| + for k, h := range u { |
| + keys = append(keys, k) |
| + total += h |
| + } |
| + sort.Slice(keys, func(i, j int) bool { |
| + if u[keys[i]] != u[keys[j]] { |
| + return u[keys[i]] > u[keys[j]] |
| + } |
| + return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1] |
| + }) |
| + var b strings.Builder |
| + for i, k := range keys { |
| + if i == 10 { |
| + fmt.Fprintf(&b, "; and %d more", len(keys)-10) |
| + break |
| + } |
| + if i > 0 { |
| + b.WriteString("; ") |
| + } |
| + fmt.Fprintf(&b, "%s on box %s %.2f h", k[1], k[0], u[k]) |
| + } |
| + log.Printf("console: usage attribution %s..%s: %.2f instance-hours on %d units counted against no account (no 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| new file mode 100644 |
| index 000000000..7838ffe91 |
| --- /dev/null |
| +++ b/internal/console/usageattrib_test.go |
| @@ -0,0 +1,513 @@ |
| +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. 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" |
| + "encoding/json" |
| + "math" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// rollHour writes one hour of a box's day rollup the way the box's metrics |
| +// loop does: n one-minute samples of unit, rolled up by metrics.RollupHour |
| +// and stored by metrics.UpsertRollup. Units already in the hour are kept. |
| +func rollHour(t *testing.T, rel release.Store, box string, hour time.Time, units map[string]metrics.UnitSample, n int) { |
| + t.Helper() |
| + ctx := context.Background() |
| + var samples []metrics.Sample |
| + for i := 0; i < n; i++ { |
| + us := map[string]metrics.UnitSample{} |
| + for name, u := range units { |
| + us[name] = u |
| + } |
| + samples = append(samples, metrics.Sample{At: hour.Add(time.Duration(i) * time.Minute), Units: us}) |
| + } |
| + agg := metrics.RollupHour(samples) |
| + raw, _, err := rel.Get(ctx, metrics.DayKey(box, hour.UTC().Format("2006-01-02"))) |
| + if err == nil { |
| + var day metrics.DayRollup |
| + if err := json.Unmarshal(raw, &day); err != nil { |
| + t.Fatal(err) |
| + } |
| + if prev, ok := day.Hours[hour.UTC().Format("15")]; ok { |
| + for name, u := range prev.Units { |
| + if _, mine := agg.Units[name]; !mine { |
| + agg.Units[name] = u |
| + } |
| + } |
| + } |
| + } |
| + if err := metrics.UpsertRollup(ctx, rel, box, hour, agg); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// busy is one full minute of an instance: half a core and 1 GB, so an hour of |
| +// 60 samples is 1 instance-hour, 0.5 core-hours and 1 GB-hour. |
| +func busy() metrics.UnitSample { |
| + return metrics.UnitSample{CPUFrac: p(0.5), MemBytes: pi64(1e9)} |
| +} |
| + |
| +// hoursAfter is n whole UTC hours, the first starting after t, all in one |
| +// calendar month: a statement covers one month, so a window that would |
| +// cross into the next starts at that month's first hour instead. |
| +func hoursAfter(t time.Time, n int) []time.Time { |
| + first := t.UTC().Truncate(time.Hour).Add(time.Hour) |
| + if last := first.Add(time.Duration(n) * time.Hour); last.Month() != first.Month() { |
| + y, m, _ := last.Date() |
| + first = time.Date(y, m, 1, 0, 0, 0, 0, time.UTC) |
| + } |
| + out := make([]time.Time, n) |
| + for i := range out { |
| + out[i] = first.Add(time.Duration(i) * time.Hour) |
| + } |
| + return out |
| +} |
| + |
| +// statement runs the real statements pass at now and reads acct's month. |
| +func statement(t *testing.T, fx *consoleFixture, now time.Time, acct string) map[string]float64 { |
| + t.Helper() |
| + if err := fx.srv.statementsPass(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _, err := fx.rel.Get(context.Background(), usage.StatementKey(acct, usage.MonthOf(now))) |
| + if err != nil { |
| + t.Fatalf("statement %s %s: %v", acct, usage.MonthOf(now), err) |
| + } |
| + var st usage.Statement |
| + if err := json.Unmarshal(raw, &st); err != nil { |
| + t.Fatal(err) |
| + } |
| + return st.Meters |
| +} |
| + |
| +func near(t *testing.T, what string, got, want float64) { |
| + t.Helper() |
| + if math.Abs(got-want) > 1e-9 { |
| + t.Fatalf("%s = %v, want %v", what, got, want) |
| + } |
| +} |
| + |
| +func recordOf(t *testing.T, fx *consoleFixture, acct, app, host string) provision.Record { |
| + t.Helper() |
| + recs, _, err := provision.ListRecords(context.Background(), fx.rel, acct, app, 50) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range recs { |
| + if r.Host == host { |
| + return r |
| + } |
| + } |
| + t.Fatalf("no record of %s in %s/%s", host, acct, app) |
| + return provision.Record{} |
| +} |
| + |
| +// 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 |
| + 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") |
| + |
| + 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], 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) |
| + |
| + date := usage.DayOf(hours[2]) |
| + if err := fx.srv.censusPass(context.Background(), date); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _, err := fx.rel.Get(context.Background(), usage.CensusDayKey(date)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var day usage.CensusDay |
| + if err := json.Unmarshal(raw, &day); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, want := day.Accounts[tb.sqid], (usage.CensusAccount{Apps: 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 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() |
| + 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) |
| + } |
| + } |
| + } |
| + if !found { |
| + t.Fatal("status --instances --account left out B's instance") |
| + } |
| +} |
| + |
| +// 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() |
| + const rivalID int64 = 6363 |
| + rival := accountSqid(rivalID) |
| + if err := fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, fx.rel, rivalID, rival, "Rival", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipAndPromote(t, fx, rival, "shop", "v3", "stable") |
| + bob := cliToken(t, fx, "bob@keymail.dev", "code-usage-reuse-bob") |
| + fx.setUser("paul@keymail.dev") |
| + |
| + tb.create(t, bob, rival, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + if code, _, out := rawReq(t, http.MethodDelete, instancesURL(fx, rival, "shop")+"/"+remoteHost, bob, ""); code/100 != 2 { |
| + t.Fatalf("rival delete = %d %s", code, out) |
| + } |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + // 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 && rt.Account != rival { |
| + t.Fatalf("fixture: B's row = %+v", rt) |
| + } |
| + tb.reportBoth(t) |
| + |
| + boxB := status.Label("box-b") |
| + 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() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + 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], 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. On main the re-run moved them to |
| +// ops. |
| +func TestStatementRerunAcrossAMove(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + fx := tb.fx |
| + tb.inNamespace(t) |
| + ctx := context.Background() |
| + 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(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(time.Now(), 6) |
| + for _, h := range hours[:3] { |
| + 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", host, "uk"); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.reconcile(t, "v3") |
| + 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(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(host): busy()}, 60) |
| + } |
| + ours := statement(t, fx, hours[5], tb.sqid) |
| + near(t, "after the move, re-run", ours[usage.MeterInstanceHours], 5) |
| + near(t, "cpu after the move", ours[usage.MeterCPUCoreHours], 2.5) |
| + near(t, "ops after the move", statement(t, fx, hours[5], release.OpsAccount)[usage.MeterInstanceHours], 0) |
| +} |
| + |
| +// TestUsageUnknownInstanceCountsNowhere: 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 |
| + 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) |
| + } |
| + 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("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) |
| + 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()) |
| + } |
| + } |
| +} |
| + |
| +// TestStatusInstancesAcrossBoxes: the live view joins each sample to its |
| +// 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 |
| + 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") |
| + 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)}, |
| + }}) |
| + tb.fresh() |
| + got := map[string]apiStatusInstance{} |
| + for _, r := range statusInstanceRows(t, fx, tb.token, "") { |
| + got[r.Unit] = r |
| + } |
| + 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 { |
| + t.Errorf("tagged sample = %+v, want the tenant its box vouched for", r) |
| + } |
| + if r := got[execUnit("nobodys.example.com")]; !r.Unattributed || r.Account != "" || r.Platform || r.Host != "nobodys.example.com" { |
| + t.Errorf("unknown instance = %+v, want it unattributed, not the platform's", r) |
| + } |
| + if r := got["carlos-edge.service"]; !r.Platform || r.Account != release.OpsAccount { |
| + t.Errorf("edge = %+v, want platform overhead", r) |
| + } |
| +} |
| + |
| +// 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 1efefd276..d95103afb 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 := nearestRegionBWriteCensusInventory() |
| + 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-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 6d87270ab..b72da92e6 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -8,3 +8,4 @@ plan14-root-reads-remote-metrics-nested.tsv e923841657499fc729713abdd750cbd2d601 |
| plan14-root-reads-region-ha-p1a.tsv 125c5c411cd0a04000d9652800b51bc7c066081c00753fb1c7b6ee0b6e717dbd |
| plan14-root-reads-nearest-region-b.tsv f4e36134015ec6d09bada7be500c8faad22450afda12d033a8e3e24b1e8bb361 |
| plan14-root-reads-alias-socket-follow-338.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927 |
| +plan14-root-reads-usage-attribution-390.tsv 5192052a23d2fdd6f5d48b5617fe28a9bb03458e1e931c060fbdc42c3d627927 |
diff --git a/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv| new file mode 100644 |
| index 000000000..088139390 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-usage-attribution-390.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay usage-attribution-390, written by census-propose (#369). census-ruling-usage-attribution-390, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-usage-attribution-390.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage . 9861a9ec86221ad5d3d3c541c01511488cbd169ddd105ecced9402d0490439b0 |
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..719c322c0 |
| --- /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 |
| +// nearestRegionBWriteCensusInventory (main's newest at d3c5601b). 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), nearestRegionBWriteCensusInventory()...) |
| + 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 b6b2b04d6..d61760fcc 100644 |
| --- a/status_instances.go |
| +++ b/status_instances.go |
| @@ -42,6 +42,9 @@ type statusInstanceRow struct { |
| CPU *float64 `json:"cpu"` |
| Mem *int64 `json:"mem_bytes"` |
| Platform bool `json:"platform"` |
| + // Unattributed is an instance whose owner the console cannot establish |
| + // (#390); Account and App are empty. Absent from an older console. |
| + Unattributed bool `json:"unattributed"` |
| // Region and RegionName are the box's placement code and label (region |
| // labels spec §4); "" from an older console or for a box it cannot name. |
| Region string `json:"region"` |
| @@ -117,6 +120,12 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string) |
| // overhead in the picture. |
| host, app = r.Unit, "(platform)" |
| } |
| + if r.Unattributed { |
| + // An instance whose owner the console cannot establish: named |
| + // by its host, with the reason under the table, rather than |
| + // filed under the platform. |
| + app = statusInstancesCopy.Unattributed |
| + } |
| fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", |
| r.Box, statusRegionCell(r.Region, r.RegionName), dashIfEmpty(host), dashIfEmpty(r.Account), dashIfEmpty(app), |
| cpuCell(r.CPU), memCell(r.Mem)) |
| @@ -129,14 +138,24 @@ func printStatusInstances(w io.Writer, rows []statusInstanceRow, account string) |
| // it does not exist. The question this verb answers is "right now", and |
| // that limit belongs next to the answer. |
| mutedf(w, "(awake instances only — a hibernating instance has no process to measure)") |
| - // The readings are fleet-wide, but the console joins them against its own |
| - // box's route registry, so a unit on any other box matches nothing and |
| - // lands under (platform) rather than under its tenant. Inert on a |
| - // single-box deployment and fixed structurally by PR #137; until then an |
| - // operator reading this for "who is using what" has to be told, the same |
| - // way `carlos routes` says whose routes it is showing. |
| - mutedf(w, "(accounts are joined against the console's own box's route registry; "+ |
| - "an instance on another box in a fleet can land under (platform))") |
| + // Said only when it applies: since #390 the console joins every box's |
| + // readings to the instance records, so an instance on another box is |
| + // its tenant's. What is left is an instance nothing can be shown to own. |
| + for _, r := range rows { |
| + if r.Unattributed { |
| + mutedf(w, "%s", statusInstancesCopy.UnattributedNote) |
| + break |
| + } |
| + } |
| +} |
| + |
| +// statusInstancesCopy is `carlos status --instances`' new copy (#390; Luna |
| +// passes 2026-10-26, docs/superpowers/notes/LUNA-COPY-REVIEW-USAGE-ATTRIBUTION*.md). |
| +var statusInstancesCopy = struct { |
| + Unattributed, UnattributedNote string |
| +}{ |
| + Unattributed: "(unattributed)", |
| + 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 |
diff --git a/status_instances_test.go b/status_instances_test.go| index d9dfea623..fa2a98c94 100644 |
| --- a/status_instances_test.go |
| +++ b/status_instances_test.go |
| @@ -19,12 +19,12 @@ import ( |
| // (platform) rather than as two blank cells a reader would take for missing |
| // data. |
| // |
| -// And the table is followed, every time, by the two ways it misleads: a |
| -// hibernating instance has no process and so no reading, and the readings are |
| -// fleet-wide while the account each is attributed to comes from the console's |
| -// own box's registry. Neither caveat is conditional, because both are ways a |
| -// SHORT list reads as a complete one, and short is exactly when nobody thinks |
| -// to ask. |
| +// And the table is followed, every time, by the way it misleads: a |
| +// hibernating instance has no process and so no reading. Not conditional, |
| +// because a SHORT list reads as a complete one, and short is exactly when |
| +// nobody thinks to ask. An instance whose owner cannot be established |
| +// (#390) prints by its host with (unattributed), and the note saying what |
| +// that means follows the table only when such a row is there. |
| func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) { |
| rows := []statusInstanceRow{ |
| {Box: "box-a", Host: "app.example.com", Account: "cdef", App: "widgets", |
| @@ -39,12 +39,24 @@ func TestPrintStatusInstancesLabelsPlatformAndStatesItsLimits(t *testing.T) { |
| "app.example.com", "cdef", "widgets", "0.250", "1MB", |
| "console.service", "(platform)", |
| "awake instances only", |
| - "console's own box's route registry", |
| } { |
| if !strings.Contains(out, want) { |
| t.Errorf("missing %q in:\n%s", want, out) |
| } |
| } |
| + if strings.Contains(out, statusInstancesCopy.UnattributedNote) { |
| + t.Errorf("the unattributed note printed with no unattributed row:\n%s", out) |
| + } |
| + |
| + rows = append(rows, statusInstanceRow{Box: "box-b", Unit: "carlos-exec@stray.example.com", Host: "stray.example.com", Unattributed: true}) |
| + buf.Reset() |
| + printStatusInstances(&buf, rows, "") |
| + out = buf.String() |
| + for _, want := range []string{"stray.example.com", statusInstancesCopy.Unattributed, statusInstancesCopy.UnattributedNote} { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("missing %q in:\n%s", want, out) |
| + } |
| + } |
| } |
| // TestPrintStatusLayoutRendersSortedAndMarksStale pins the CLI table for |