remote-instance-metrics: box tags exec cgroup readings with their tenant; note round 2
Round 1 (Astra) found the CPU delta spans the previous tick's counter. The rule is now about the cgroup's history: a host is vouched only if every activator entry this agent made for it named one tenant (putEntryLocked, Tenancies), the registry row agrees, the dir is not a previous agent's leftover, and the previous tick tagged the unit for the same tenant (CarryTags). The console side is not built yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
19 files changed,
+941
−69
docs/superpowers/notes/remote-instance-metrics.md+84 −40docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md+14 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md+38 −14internal/activator/activator.go+14 −4internal/activator/probewake.go+1 −1internal/activator/recoveryprobe.go+1 −1internal/activator/swaphold.go+1 −1internal/activator/tenancies.go+80 −0internal/activator/tenancies_test.go+184 −0internal/cgroup/cgroup.go+18 −0internal/cgroup/cgroup_test.go+31 −0internal/host/agent.go+9 −1internal/host/agentalerts_test.go+1 −1internal/host/metrics_loop.go+26 −6internal/host/metrics_owner.go+43 −0internal/host/metrics_owner_test.go+155 −0internal/metrics/owner.go+99 −0internal/metrics/owner_test.go+138 −0internal/metrics/sample.go+4 −0
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md| index 320f0034c..336afff76 100644 |
| --- a/docs/superpowers/notes/remote-instance-metrics.md |
| +++ b/docs/superpowers/notes/remote-instance-metrics.md |
| @@ -64,33 +64,45 @@ Owner *Owner `json:"owner,omitempty"` |
| ``` |
| **Invariant.** The box tags `carlos-exec@<host>` with tenant T only when |
| -every process that can be in that cgroup during the reading was started by |
| -the activator for a route of tenant T. The rule is enforced in one place, |
| -the sampler's tick (`internal/host/metrics_loop.go`), from one function that |
| -lists the vouched owners (`metricsOwners`). |
| - |
| -Where processes in a host's exec cgroup come from, and how each is covered: |
| - |
| -1. **The activator's live entry for the host.** Every spawn into |
| - `carlos-exec@<host>` goes through the activator (instance, legacy |
| - sidecar, seed, generations). A `carlos run` command runs in its own |
| - systemd unit, not in this cgroup. A wake re-reads the registry |
| - row before it spawns and refuses a row that now names another account |
| - or app (`wakeRouteChanged`). So an entry's processes belong to its |
| - route's tenant. A new method, `activator.Service.Tenancies()`, returns |
| - each live entry's tenant and a number that is new for every new entry. |
| -2. **Earlier entries of this agent.** A stop deletes the entry only after |
| - the process is gone; what the activator cannot prove stopped it records. |
| - `Tenancies` leaves out a host with an unproven failed wake, a stray |
| - sidecar, or a recorded stop that is not complete (`stopObservation.complete`, |
| - sticky for the agent's life). |
| -3. **A previous agent's processes.** In ordinary mode the agent's shutdown |
| - stops every child, and a restart kills the delegated subtree. The cgroup |
| - setup removes the per-host directories left behind; one it cannot remove |
| - still holds a process, so that host is recorded as a leftover and never |
| - tagged in this agent's life. |
| -4. **Claim mode** retains processes across restarts (`SetupRetaining`). |
| - `Tenancies` returns nothing in claim mode, so nothing is tagged there. |
| +everything that reading measured was T's: every process that can be in |
| +the cgroup during the reading, and everything the cgroup's counters and |
| +charged memory carry over from before it. The per-host cgroup outlives |
| +its processes for the agent's whole life (`Manager.hostDir`: only |
| +generation and seed children are removed, and a killed cgroup is |
| +remade before its next spawn), so its CPU counter and the |
| +page cache charged to it can carry an earlier occupant's use. The rule is |
| +therefore about the cgroup, not the current process: **in this agent's |
| +life, the host's cgroup has only ever held tenant T**. It is enforced in |
| +one place, `metricsOwners` and the sampler's tick |
| +(`internal/host/metrics_loop.go`), from `metrics.Vouched`, |
| +`metrics.TagUnits` and `metrics.CarryTags`. |
| + |
| +Where the cgroup's contents come from, and how each is covered: |
| + |
| +1. **This agent's activator.** Every spawn into `carlos-exec@<host>` is an |
| + activator entry's (instance, legacy sidecar, seed, generations). A |
| + `carlos run` command runs in its own systemd unit, not in this cgroup. |
| + Every entry enters `a.entries` through one helper, `putEntryLocked`, |
| + which records the tenant its route names (a guard test parses the |
| + package and fails on any other insertion). A host whose entries have |
| + named two tenants is **mixed** and never vouched again in this agent's |
| + life. A wake re-reads the row before it spawns and refuses one that now |
| + names another account or app (`wakeRouteChanged`), so an entry's |
| + processes are its route's tenant's; an entry inserted for a stale row |
| + whose wake is refused still marks the host, which errs toward vouching |
| + less. An entry whose route later names another tenant in place marks |
| + the host mixed too. A new method, `activator.Service.Tenancies()`, |
| + returns the tenant of each live entry on an unmixed host and a number |
| + that is new for every new entry. |
| +2. **A previous agent.** In ordinary mode the agent's shutdown stops every |
| + child, and a restart kills the delegated subtree. The cgroup setup |
| + removes the per-host directories left behind (with their charges); one |
| + it cannot remove may still hold a process or a child, so that host is |
| + recorded as a leftover (`Manager.Leftover`) and never tagged in this |
| + agent's life. |
| +3. **Claim mode** retains processes and cgroups across restarts |
| + (`SetupRetaining`). `Tenancies` returns nothing in claim mode, so |
| + nothing is tagged there. |
| The tick: |
| @@ -99,16 +111,24 @@ before := owners() // activator tenancies joined to registry rows |
| units := read cgroups // as today |
| after := owners() |
| tag unit u with T iff before[u] and after[u] both exist and are equal |
| - (same tenant, same entry number) |
| + (same tenant, same entry number) TagUnits |
| +untag u iff the previous tick read u and did not |
| + tag it T CarryTags |
| ``` |
| `owners()` maps `cgroup.ExecName(host)` to the tenant only when the |
| -activator's entry and the registry row name the same non-empty account and |
| -app, and the host is not a leftover. The two reads around the cgroup read |
| -mean a wake, a stop or a re-tenant during the reading leaves that sample |
| -untagged. The row check covers an entry whose host has since been given to |
| -another tenant: a predecessor still stopping while the successor's row |
| -exists. |
| +activator vouches for the host, the registry row names the same non-empty |
| +account and app, and the host is not a leftover. The read after the |
| +cgroup read catches a host that became mixed, or got a new entry, during |
| +the reading. The CPU fraction is a delta from the previous tick's counter |
| +of the same cgroup, so the previous tick must also have tagged the unit |
| +for T, or not read it at all (then there is no previous counter and no |
| +delta). The row check keeps a stopping entry from being vouched once its |
| +host's row names someone else. |
| + |
| +Consequence: a hostname that changes tenant on a box shows no remote |
| +readings for the new tenant until that box's agent restarts (a release |
| +roll restarts it). The console's local rows are unaffected. |
| Not tagged at all: `carlos-app@<host>.service` units (systemd runs them, |
| and they can outlive the agent), nested (isolated exec) instances and |
| @@ -167,13 +187,18 @@ per sample: about 2.4 KB per awake instance-hour in the raw chunk. |
| Production-wired where the code allows: |
| - **activator:** `Tenancies` over real wakes with the package's test |
| - backend: an awake entry is vouched; a new wake gets a new number; an |
| - unproven wake, a stray sidecar or an incomplete stop leaves the host |
| - out; claim mode returns nothing. |
| + backend: an awake entry is vouched; a new wake gets a new number; a host |
| + woken for one tenant and then another is never vouched again, nor is |
| + one whose wake for another tenant was refused; a route changed in place |
| + marks its host; claim mode returns nothing; every insertion into |
| + `a.entries` goes through `putEntryLocked` (a parse of the package). |
| +- **cgroup:** a per-host dir setup could not remove is a leftover. |
| - **host:** the sampler's tick and flush over a real registry and a |
| tenancy source: an agreeing row tags; a disagreeing or missing row does |
| not; an entry replaced between the two reads does not; a leftover host |
| - does not; the flushed chunk carries the tag. |
| + does not; a unit-backed tenant never is; the flushed chunk carries the |
| + tag; a delta whose previous counter was another tenant's is untagged |
| + (round 1's scenario, two ticks). |
| - **console, two boxes** (the `remoteinstances_test.go` fixture: real |
| create door, real reconcile on each box, real reports). Box B's chunk is |
| built by the box's own tagging code over B's real registry and written |
| @@ -193,7 +218,8 @@ Production-wired where the code allows: |
| - **Mutations** on the console filter (accept untagged, check only the |
| account, test any sample's tag instead of the latest, graph without the |
| per-sample check, drop the `created_at` bound) and on the box rule (one |
| - read instead of two, skip the row check, vouch a leftover). |
| + read instead of two, skip the row check, vouch a leftover, vouch a mixed |
| + host, skip `CarryTags`). |
| ## Not in this change |
| @@ -201,6 +227,24 @@ Production-wired where the code allows: |
| new record's `created_at` can show on the new record. Same account and |
| app, so not a tenant leak. |
| - Readings for unit-backed, stamped and never-sleeping instances on other |
| - boxes. |
| + boxes, and for a hostname that changed tenant on its box until that |
| + box's agent restarts. |
| - Local rows could adopt the tag once every box writes it; that would |
| close round 6's interleaving for the console's own box too. Follow-up. |
| + |
| +## Review rounds |
| + |
| +Round 1 (Astra, 98caa5f4): NOT READY, one P1 in the fault family. |
| + |
| +- P1: the CPU fraction is a delta from the previous tick's counter, read |
| + by unit name; a successor's fresh cgroup whose counter exceeded the |
| + predecessor's would be tagged with a delta that includes the |
| + predecessor's. Fixed by `CarryTags` (the previous tick must have tagged |
| + the unit for the same tenant). Looking at the same cause found a wider |
| + one: the per-host cgroup itself outlives its processes, so counters and |
| + charged memory can carry an earlier tenant's use without any two-tick |
| + race. Round 2's rule is therefore about the cgroup's whole history in |
| + this agent's life (a host is vouched only if it has only ever had one |
| + tenant), which also replaced round 1's per-process checks (unproven |
| + wakes, stray sidecars, incomplete stops): with one tenant ever, those |
| + leftovers are the same tenant's. |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md| new file mode 100644 |
| index 000000000..70190a751 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md |
| @@ -0,0 +1,14 @@ |
| +Round 1 of 3, reviewed at `98caa5f4ded08f0c5082311853275ae2633362e0`. |
| + |
| +1. **P1 — The box’s tag does not cover the previous CPU-counter reading.** |
| + **Fault family: tenant identity of samples.** |
| + |
| + The tick rule in [remote-instance-metrics.md:98](/home/paulca/amadan.net/carlos/platform-remote-metrics/docs/superpowers/notes/remote-instance-metrics.md:98) checks ownership only around the current cgroup read. However, [metrics_loop.go:94](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/host/metrics_loop.go:94) retrieves the previous counter by unit name alone and uses it to calculate `CPUFrac`. [parse.go:168](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/parse.go:168) rejects decreasing counters, but cannot detect a replacement cgroup whose counter already exceeds its predecessor’s. |
| + |
| + **Failure scenario:** tick N records tenant A’s counter as 5 million microseconds. A stops completely; tenant B acquires the hostname and starts in a fresh cgroup. At tick N+1, 60 seconds later, B’s counter is 20 million. Both ownership checks now agree on B and its new entry number, so the proposed rule tags the calculated CPU fraction `(20−5)/60 = 0.25` as B’s. That value incorporates A’s counter. Its timestamp is after B’s creation, so the console accepts it into B’s reading and graph. No surviving predecessor process or race within the current tick is necessary. |
| + |
| + **Fix:** retain the vouched tenant and entry number alongside each previous counter. Require matching proof for both counter observations before tagging a sample containing a CPU delta. Otherwise leave that sample untagged and establish a new baseline; this preserves local readings. Add a two-tick test with different tenants, stable ownership during each tick, and a replacement counter greater than its predecessor’s. Also cover an untagged previous observation. |
| + |
| +No additional P2 or P3 findings. No files edited or test suites run. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md| index 7a5a5d1fa..58d2f29db 100644 |
| --- a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-remote-instance-metrics-note.md |
| @@ -1,4 +1,4 @@ |
| -# Review brief: remote instance metrics design note, round 1 of 3 |
| +# Review brief: remote instance metrics design note, round 2 of 3 |
| Repo carlos/platform, branch `remote-instance-metrics`, commit named in the |
| reviewer's prompt. |
| @@ -35,19 +35,18 @@ wrong account). Name it beside every finding in that family. |
| `installRowLifetime` / `ownsRowLifetime`, and how a hostname changes |
| tenant on a box. Is there a path where a hostname changes tenant on a |
| box without the row's account or app changing? |
| -2. The box invariant: "`carlos-exec@<host>` is tagged with T only when |
| - every process that can be in that cgroup during the reading was started |
| - by the activator for a route of tenant T." Check the four sources the |
| - note lists against `internal/activator` (entries, `wakeRouteChanged`, |
| - `unprovenWakes`, `straySidecars`, `stopHistory`, `finishStop`, |
| - `Shutdown`), `internal/cgroup` (`Setup`, `sweepStale`, |
| - `SetupRetaining`) and `internal/host/metrics_loop.go`. Is there a |
| - spawner into a host's exec cgroup the note misses, or a way for an |
| - earlier tenant's process to remain in the cgroup while a later |
| - tenant's entry is vouched? |
| -3. The two reads around the cgroup read, and the entry number. Can a |
| - wake, stop or re-tenant during one tick still produce a tag naming the |
| - wrong tenant? |
| +2. The box invariant: "in this agent's life, the host's cgroup has only |
| + ever held tenant T". Check the sources the note lists against |
| + `internal/activator` (every insertion into `entries`, |
| + `wakeRouteChanged`, `Shutdown`), `internal/cgroup` (`Setup`, |
| + `sweepStale`, `freshen`, `SetupRetaining`) and |
| + `internal/host/metrics_loop.go`. Is there a spawner into a host's exec |
| + cgroup that is not an activator entry, a way for a second tenant's |
| + process or charge to reach the cgroup without the host being marked |
| + mixed, or a reading (CPU delta, memory) that still mixes tenants? |
| +3. The two reads around the cgroup read, the entry number and |
| + `CarryTags`. Can a wake, stop or re-tenant during or between ticks |
| + still produce a tag naming the wrong tenant? |
| 4. The console filter: latest sample's tag, per-sample graph filter, |
| `created_at` bound, freshest box. Can any remote row, page, |
| `carlos instances list` answer or Overview number show a sample not |
| @@ -57,6 +56,31 @@ wrong account). Name it beside every finding in that family. |
| everything that parses raw chunks or rollups. |
| 6. Request budget: is any new request added? |
| +## Round 2 |
| + |
| +Earlier rounds: round 1, `docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r1.md` |
| +(one P1, fault family tenant identity of samples). The round number |
| +counts every earlier review of this design or change, under any file |
| +name or reviewer. |
| + |
| +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. |
| + |
| +Round 2 changed the box rule from per-process checks to the cgroup's |
| +history: a host is vouched only if every activator entry this agent made |
| +for it named one tenant (`putEntryLocked`, `Tenancies`), plus |
| +`CarryTags` for the previous tick. The branch now carries the box-side |
| +code for this (`internal/metrics/owner.go`, `internal/activator/tenancies.go`, |
| +`internal/host/metrics_owner.go`, `internal/cgroup` `Leftover`) with its |
| +tests; check the note's claims against it. The console side is not built |
| +yet: review it as described in the note. |
| + |
| +AGENTS.md stopping rule 2 applies: a P1 in the same fault family this |
| +round stops the design and goes to Paul with options, so report one only |
| +with a concrete failure scenario and evidence. |
| + |
| ## Severity |
| - **P1**: unsafe, would not compile, a test fails, or it would not work. |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 196f8be8f..a6e24b244 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -492,6 +492,9 @@ type actEntry struct { |
| host string |
| route registry.Route |
| state actState |
| + // tenancyNo is this entry's number in Tenancies (tenancies.go), 0 until |
| + // it is first vouched. Under a.mu. |
| + tenancyNo uint64 |
| ready chan struct{} // waking: closed when the wake resolves; then check err |
| err error // waking: the wake's outcome |
| @@ -1210,6 +1213,13 @@ type Service struct { |
| mu sync.Mutex |
| entries map[string]*actEntry |
| + // tenancySeq numbers the entries Tenancies vouches for; hostTenants is |
| + // the first tenant each host's entries named in this agent's life, and |
| + // hostMixed the hosts whose entries have named two (putEntryLocked). |
| + // Under a.mu. |
| + tenancySeq uint64 |
| + hostTenants map[string]tenantKey |
| + hostMixed map[string]bool |
| // shuttingDown is set by Shutdown before it stops anything, and read by |
| // the supervised-respawn goroutines: the agent is going away, so nothing |
| // new may be spawned against a DB whose lease is about to be released. |
| @@ -1545,7 +1555,7 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| // and two restore attempts per request (#184, seen only as a |
| // loaded-suite test flake because the window is that narrow). |
| e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})} |
| - a.entries[rt.Host] = e |
| + a.putEntryLocked(rt.Host, e) |
| go a.wake(e) |
| edge.MarkWoke(req) |
| } |
| @@ -3281,7 +3291,7 @@ func (a *Service) WakeWorker(rt registry.Route) error { |
| // fails deletes its entry, so the initiator would find nothing and |
| // start a second one. |
| e = a.newWorkerEntry(rt) |
| - a.entries[rt.Host] = e |
| + a.putEntryLocked(rt.Host, e) |
| go a.wake(e) |
| } else if !e.worker { |
| // A live entry for this host that is NOT a worker means the route |
| @@ -5072,7 +5082,7 @@ func (a *Service) sweepOnce() { |
| } else { |
| e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})} |
| } |
| - a.entries[rt.Host] = e |
| + a.putEntryLocked(rt.Host, e) |
| go a.wake(e) |
| } |
| @@ -5105,7 +5115,7 @@ func (a *Service) sweepOnce() { |
| } |
| log.Printf("activator: always-on sidecar %s is not running — starting it", rt.Host) |
| e := a.newWorkerEntry(rt) |
| - a.entries[rt.Host] = e |
| + a.putEntryLocked(rt.Host, e) |
| go a.wake(e) |
| started++ |
| } |
diff --git a/internal/activator/probewake.go b/internal/activator/probewake.go| index c5965f00b..654908375 100644 |
| --- a/internal/activator/probewake.go |
| +++ b/internal/activator/probewake.go |
| @@ -213,7 +213,7 @@ func (a *Service) ProbeWake(ctx context.Context, cfg ProbeConfig) (ProbeResult, |
| a.mu.Unlock() |
| return ProbeResult{}, errors.Join(ErrProbeRefused, errProbeLive) |
| } |
| - a.entries[cfg.Host] = e |
| + a.putEntryLocked(cfg.Host, e) |
| a.mu.Unlock() |
| if probeWakePublished != nil { |
| probeWakePublished() |
diff --git a/internal/activator/recoveryprobe.go b/internal/activator/recoveryprobe.go| index 01ee80330..37d1f91d7 100644 |
| --- a/internal/activator/recoveryprobe.go |
| +++ b/internal/activator/recoveryprobe.go |
| @@ -87,7 +87,7 @@ func (a *Service) RecoveryProbe(ctx context.Context, rt registry.Route, p StartP |
| if a.entries == nil { |
| a.entries = make(map[string]*actEntry) |
| } |
| - a.entries[rt.Host] = e |
| + a.putEntryLocked(rt.Host, e) |
| fence := a.fences[rt.Host] |
| a.mu.Unlock() |
| if a.lifeCtx != nil { |
diff --git a/internal/activator/swaphold.go b/internal/activator/swaphold.go| index 279606566..443004da4 100644 |
| --- a/internal/activator/swaphold.go |
| +++ b/internal/activator/swaphold.go |
| @@ -327,7 +327,7 @@ func (a *Service) holdWakeLocked(e *actEntry, h *holdSpec) (*actEntry, error) { |
| // The same gate here, at the stop's end, and again at the pinned wake's |
| // exec (spec §6.3, §7.4): the lease and the restore come between. |
| next.pinCheck = func() error { return a.attemptCurrentLocked(next, h.at, h.newest, true) } |
| - a.entries[e.host] = next |
| + a.putEntryLocked(e.host, next) |
| if err := next.pinCheck(); err != nil { |
| delete(a.entries, e.host) |
| return nil, err |
diff --git a/internal/activator/tenancies.go b/internal/activator/tenancies.go| new file mode 100644 |
| index 000000000..7231d7405 |
| --- /dev/null |
| +++ b/internal/activator/tenancies.go |
| @@ -0,0 +1,80 @@ |
| +package activator |
| + |
| +// Tenancy is the tenant whose route a live entry's processes were started |
| +// for, and the entry's number: a new entry is a new number, so a reader |
| +// that sees the same number twice knows no wake or stop came between. |
| +type Tenancy struct { |
| + Account, App string |
| + Entry uint64 |
| +} |
| + |
| +// tenantKey is a route's tenant: its account and app as the row names them. |
| +type tenantKey struct{ acct, app string } |
| + |
| +// putEntryLocked is the one way an entry enters a.entries. Every process the |
| +// activator starts into a host's cgroup is an entry's, so recording each |
| +// entry's tenant here records every tenant whose processes the host's |
| +// cgroup has held in this agent's life: a host whose entries have named two |
| +// tenants is mixed for good (Tenancies). An entry whose wake is later |
| +// refused still counts; that errs toward vouching less. The caller holds |
| +// a.mu. TestEntriesEnterThroughPutEntryLocked keeps every insertion here. |
| +func (a *Service) putEntryLocked(host string, e *actEntry) { |
| + if a.entries == nil { |
| + a.entries = make(map[string]*actEntry) |
| + } |
| + a.entries[host] = e |
| + a.noteTenantLocked(host, e.route.Account, e.route.App) |
| +} |
| + |
| +// noteTenantLocked records that host's cgroup has held, or may hold, a |
| +// process of tenant (acct, app). A second tenant makes the host mixed. |
| +func (a *Service) noteTenantLocked(host, acct, app string) { |
| + k := tenantKey{acct, app} |
| + if a.hostTenants == nil { |
| + a.hostTenants = make(map[string]tenantKey) |
| + } |
| + first, ok := a.hostTenants[host] |
| + if !ok { |
| + a.hostTenants[host] = k |
| + return |
| + } |
| + if first != k { |
| + if a.hostMixed == nil { |
| + a.hostMixed = make(map[string]bool) |
| + } |
| + a.hostMixed[host] = true |
| + } |
| +} |
| + |
| +// Tenancies is the metrics sampler's word from the activator on whose |
| +// processes each host's exec cgroup holds (remote instance metrics note, |
| +// docs/superpowers/notes/remote-instance-metrics.md). A host is vouched |
| +// for tenant T only while it has a live entry and every entry this agent |
| +// has made for it named T: its cgroup persists between entries, so CPU |
| +// counters and charged memory can carry an earlier tenant's use, and a |
| +// host that ever had two tenants is never vouched again in this agent's |
| +// life. A route with no account or app vouches nothing, and an entry whose |
| +// route names another tenant than its host's first makes the host mixed |
| +// too. Claim mode retains processes across agent restarts, so it vouches |
| +// nothing. Entry numbers are given the first time an entry is vouched. |
| +func (a *Service) Tenancies() map[string]Tenancy { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if a.cfg.HostWrites.Enabled { |
| + return nil |
| + } |
| + out := make(map[string]Tenancy, len(a.entries)) |
| + for host, e := range a.entries { |
| + acct, app := e.route.Account, e.route.App |
| + a.noteTenantLocked(host, acct, app) // a route changed in place |
| + if a.hostMixed[host] || acct == "" || app == "" { |
| + continue |
| + } |
| + if e.tenancyNo == 0 { |
| + a.tenancySeq++ |
| + e.tenancyNo = a.tenancySeq |
| + } |
| + out[host] = Tenancy{Account: acct, App: app, Entry: e.tenancyNo} |
| + } |
| + return out |
| +} |
diff --git a/internal/activator/tenancies_test.go b/internal/activator/tenancies_test.go| new file mode 100644 |
| index 000000000..217edd0c6 |
| --- /dev/null |
| +++ b/internal/activator/tenancies_test.go |
| @@ -0,0 +1,184 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "io/fs" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestTenanciesVouchForLiveEntries drives real wakes and stops through the |
| +// fake backend: an awake entry is vouched with its route's tenant, a new |
| +// wake of the same host is a new entry number, and a host the activator |
| +// cannot vouch for is left out. |
| +func TestTenanciesVouchForLiveEntries(t *testing.T) { |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("eu.shop.example.com") |
| + rt.Account, rt.App = "bdn", "shop" |
| + if got := a.Tenancies(); len(got) != 0 { |
| + t.Fatalf("asleep host vouched: %+v", got) |
| + } |
| + arrangeAwake(t, a, rt) |
| + first := a.Tenancies()[rt.Host] |
| + if first.Account != "bdn" || first.App != "shop" || first.Entry == 0 { |
| + t.Fatalf("awake entry = %+v", first) |
| + } |
| + if again := a.Tenancies()[rt.Host]; again != first { |
| + t.Fatalf("the same entry changed number: %+v then %+v", first, again) |
| + } |
| + |
| + a.RetireExcept(map[string]bool{}) |
| + waitFor(t, "the stop", func() bool { return a.entryCount() == 0 }) |
| + if got := a.Tenancies(); len(got) != 0 { |
| + t.Fatalf("stopped host still vouched: %+v", got) |
| + } |
| + arrangeAwake(t, a, rt) |
| + second := a.Tenancies()[rt.Host] |
| + if second.Entry == 0 || second.Entry == first.Entry { |
| + t.Fatalf("a new wake kept the entry number: %+v then %+v", first, second) |
| + } |
| + |
| + // An unstamped route vouches nothing. |
| + bare := testRoute("bare.example.com") |
| + arrangeAwake(t, a, bare) |
| + if _, ok := a.Tenancies()[bare.Host]; ok { |
| + t.Fatal("a route with no account or app was vouched") |
| + } |
| +} |
| + |
| +// TestTenanciesHostThatHadTwoTenants: a host's exec cgroup outlives its |
| +// entries, so its counters and charged memory can carry an earlier |
| +// tenant's use. Once two tenants' entries have been made for one host, it |
| +// is never vouched again in this agent's life, whoever is live there now. |
| +func TestTenanciesHostThatHadTwoTenants(t *testing.T) { |
| + t.Run("woken for one tenant, then another", func(t *testing.T) { |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("eu.shop.example.com") |
| + rt.Account, rt.App = "rival", "shop" |
| + arrangeAwake(t, a, rt) |
| + a.RetireExcept(map[string]bool{}) |
| + waitFor(t, "the stop", func() bool { return a.entryCount() == 0 }) |
| + rt.Account = "bdn" |
| + arrangeAwake(t, a, rt) |
| + if got, ok := a.Tenancies()[rt.Host]; ok { |
| + t.Fatalf("the successor on a host that had another tenant was vouched: %+v", got) |
| + } |
| + other := testRoute("other.example.com") |
| + other.Account, other.App = "bdn", "shop" |
| + arrangeAwake(t, a, other) |
| + if _, ok := a.Tenancies()[other.Host]; !ok { |
| + t.Fatal("a host with one tenant lost its vouch") |
| + } |
| + }) |
| + t.Run("a refused wake for another tenant counts", func(t *testing.T) { |
| + a, _, _, reg := testActivator(t, time.Hour) |
| + a.Routes = reg |
| + rt := testRoute("eu.shop.example.com") |
| + rt.Account, rt.App, rt.Status = "bdn", "shop", "ready" |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The edge's cached row still names the predecessor: the wake |
| + // refreshes against the registry and refuses (wakeRouteChanged). |
| + stale := rt |
| + stale.Account = "rival" |
| + if _, err := a.beginRequest(context.Background(), stale); err == nil { |
| + t.Fatal("fixture: a wake for a re-tenanted row went ahead") |
| + } |
| + arrangeAwake(t, a, rt) |
| + if got, ok := a.Tenancies()[rt.Host]; ok { |
| + t.Fatalf("vouched %+v after another tenant's entry was made for the host", got) |
| + } |
| + }) |
| +} |
| + |
| +// TestTenanciesRouteChangedInPlace: an entry whose route names another |
| +// tenant than when it was first vouched is never vouched again. |
| +func TestTenanciesRouteChangedInPlace(t *testing.T) { |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("eu.shop.example.com") |
| + rt.Account, rt.App = "bdn", "shop" |
| + arrangeAwake(t, a, rt) |
| + if _, ok := a.Tenancies()[rt.Host]; !ok { |
| + t.Fatal("fixture: not vouched") |
| + } |
| + a.mu.Lock() |
| + a.entries[rt.Host].route.Account = "rival" |
| + a.mu.Unlock() |
| + if got, ok := a.Tenancies()[rt.Host]; ok { |
| + t.Fatalf("an entry re-tenanted in place was vouched: %+v", got) |
| + } |
| + a.mu.Lock() |
| + a.entries[rt.Host].route.Account = "bdn" |
| + a.mu.Unlock() |
| + if got, ok := a.Tenancies()[rt.Host]; ok { |
| + t.Fatalf("an entry that changed tenant once was vouched again: %+v", got) |
| + } |
| +} |
| + |
| +// TestEntriesEnterThroughPutEntryLocked: putEntryLocked is how the host's |
| +// tenants are recorded, so an entry inserted any other way would be a |
| +// tenant Tenancies never saw. Fails on any other assignment into |
| +// a.entries in the package's production code. |
| +func TestEntriesEnterThroughPutEntryLocked(t *testing.T) { |
| + fset := token.NewFileSet() |
| + pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool { |
| + return !strings.HasSuffix(fi.Name(), "_test.go") |
| + }, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := 0 |
| + for _, pkg := range pkgs { |
| + for _, f := range pkg.Files { |
| + for _, d := range f.Decls { |
| + fn, ok := d.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + as, ok := n.(*ast.AssignStmt) |
| + if !ok { |
| + return true |
| + } |
| + for _, lhs := range as.Lhs { |
| + ix, ok := lhs.(*ast.IndexExpr) |
| + if !ok { |
| + continue |
| + } |
| + sel, ok := ix.X.(*ast.SelectorExpr) |
| + if !ok || sel.Sel.Name != "entries" { |
| + continue |
| + } |
| + if fn.Name.Name == "putEntryLocked" { |
| + found++ |
| + continue |
| + } |
| + t.Errorf("%s: %s assigns into entries directly; use putEntryLocked", fset.Position(as.Pos()), fn.Name.Name) |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + } |
| + if found != 1 { |
| + t.Fatalf("putEntryLocked's own insertion found %d times, want 1", found) |
| + } |
| +} |
| + |
| +// TestTenanciesClaimModeVouchesNothing: claim mode retains processes across |
| +// agent restarts, so nothing is vouched there. |
| +func TestTenanciesClaimModeVouchesNothing(t *testing.T) { |
| + a, _, _, _ := testActivator(t, time.Hour) |
| + rt := testRoute("eu.shop.example.com") |
| + rt.Account, rt.App = "bdn", "shop" |
| + arrangeAwake(t, a, rt) |
| + a.cfg.HostWrites.Enabled = true |
| + if got := a.Tenancies(); len(got) != 0 { |
| + t.Fatalf("claim mode vouched %+v", got) |
| + } |
| +} |
diff --git a/internal/cgroup/cgroup.go b/internal/cgroup/cgroup.go| index fcea822d3..d4fe02e66 100644 |
| --- a/internal/cgroup/cgroup.go |
| +++ b/internal/cgroup/cgroup.go |
| @@ -223,6 +223,11 @@ type Manager struct { |
| // and in tests, where the window exposes no exempt leaf and the fallback |
| // keeps its Ruling 2 behaviour. |
| fencedSpawn bool |
| + // leftover is the hosts whose per-host dir sweepStale could not remove |
| + // at setup: something a previous agent started may still be alive in |
| + // it. Written once, during setup, before the manager is shared; read |
| + // only after (Leftover). |
| + leftover map[string]bool |
| // locks holds each host's start lock (hostLock), made on first use. |
| locksMu sync.Mutex |
| locks map[string]*sync.Mutex |
| @@ -382,10 +387,23 @@ func (m *Manager) sweepStale() { |
| } |
| if err := os.Remove(dir); err != nil { |
| m.logf("cgroup: stale %s not removed: %v", e.Name(), err) |
| + if m.leftover == nil { |
| + m.leftover = map[string]bool{} |
| + } |
| + m.leftover[strings.TrimPrefix(e.Name(), execPrefix)] = true |
| } |
| } |
| } |
| +// Leftover reports whether host's dir was left populated by a previous |
| +// agent: setup's sweep could not remove it, so a process that agent started |
| +// may still run in it. The metrics sampler never vouches for such a host's |
| +// tenant in this agent's life (docs/superpowers/notes/remote-instance-metrics.md). |
| +// Nil-safe: no manager, no leftovers. |
| +func (m *Manager) Leftover(host string) bool { |
| + return m != nil && m.leftover[host] |
| +} |
| + |
| // ErrKilledCgroupKept is a start refused because the cgroup it would spawn |
| // into took cgroup.kill and could not be removed and made fresh first |
| // (amadan #272). Spawning into it anyway would have the kernel SIGKILL the |
diff --git a/internal/cgroup/cgroup_test.go b/internal/cgroup/cgroup_test.go| index 6b815097f..bc70f698f 100644 |
| --- a/internal/cgroup/cgroup_test.go |
| +++ b/internal/cgroup/cgroup_test.go |
| @@ -567,3 +567,34 @@ func TestPlansTierMemoryAgrees(t *testing.T) { |
| t.Errorf("plans.TierMemoryMB[default] = %d, cgroup TierDefault = %d MB", got, want) |
| } |
| } |
| + |
| +// TestLeftoverNamesHostsTheSweepCouldNotRemove: a host whose dir a previous |
| +// agent left populated may still hold that agent's processes, so the |
| +// metrics sampler never vouches for it in this agent's life (remote |
| +// instance metrics note). Swept and never-seen hosts are not leftovers; a |
| +// nil manager and a retaining setup report none. |
| +func TestLeftoverNamesHostsTheSweepCouldNotRemove(t *testing.T) { |
| + root := newDelegatedRoot(t) |
| + if err := os.Mkdir(filepath.Join(root, "carlos-exec@old.example.com"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.MkdirAll(filepath.Join(root, "carlos-exec@busy.example.com", "child"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + m, err := SetupAt(root, t.Logf) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !m.Leftover("busy.example.com") { |
| + t.Error("a dir the sweep could not remove is not a leftover") |
| + } |
| + for _, h := range []string{"old.example.com", "new.example.com"} { |
| + if m.Leftover(h) { |
| + t.Errorf("%s reported as a leftover", h) |
| + } |
| + } |
| + var none *Manager |
| + if none.Leftover("busy.example.com") { |
| + t.Error("a nil manager reported a leftover") |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index e28bf3c75..14a7a47f5 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -193,6 +193,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancefs" |
| "github.com/carlosframework/platform/internal/layout" |
| "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -902,7 +903,14 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| go steeringLoop(boxJudge) |
| // The sweep reads the registry only through this closure — the stamped |
| // bespoke units to sample beside the carlos- ones, re-read each tick. |
| - go metricsLoop(cgm.Root(), func() []string { return stampedUnitNames(reg) }, alerts) |
| + // owners is the sweep's word on whose processes each exec cgroup |
| + // holds: the activator's live entries joined to the registry |
| + // (metricsOwners). With no activator it tags nothing. |
| + var owners func() map[string]metrics.Vouch |
| + if svc != nil { |
| + owners = func() map[string]metrics.Vouch { return metricsOwners(reg, svc, cgm.Leftover) } |
| + } |
| + go metricsLoop(cgm.Root(), func() []string { return stampedUnitNames(reg) }, owners, alerts) |
| go configSyncLoop(reg, svc, dd, claims.Writes) |
| go configGenLoop(reg, svc, dd, claims.Writes) |
| go socketAdvisoryLoop(reg, svc) |
diff --git a/internal/host/agentalerts_test.go b/internal/host/agentalerts_test.go| index 149f3a49b..fe006a6e1 100644 |
| --- a/internal/host/agentalerts_test.go |
| +++ b/internal/host/agentalerts_test.go |
| @@ -47,7 +47,7 @@ func TestStuckMarkBeforeMetricsReachesTheSink(t *testing.T) { |
| if _, _, err := openStatusStore(context.Background(), os.Getenv); err == nil { |
| t.Fatal("fixture: the metrics store opened") |
| } |
| - metricsLoop(t.TempDir(), nil, sinks) |
| + metricsLoop(t.TempDir(), nil, nil, sinks) |
| } |
| h := newRevertHarness(t) |
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go| index 845876a0c..b963933f8 100644 |
| --- a/internal/host/metrics_loop.go |
| +++ b/internal/host/metrics_loop.go |
| @@ -33,7 +33,11 @@ type sampleProbes struct { |
| memFrac func() *float64 |
| diskFrac func() *float64 |
| units func() map[string]unitRaw |
| - now func() time.Time |
| + // owners is the box's word on whose processes each exec cgroup holds |
| + // (metricsOwners), read before and after units so a reading is tagged |
| + // only when nothing changed during it. nil tags nothing. |
| + owners func() map[string]metrics.Vouch |
| + now func() time.Time |
| } |
| // samplerMaxBuf hard-caps sm.buf at ~2h of 60s ticks. metricsFlush only |
| @@ -57,7 +61,8 @@ const samplerMaxBuf = 120 |
| // process for the first time in the same call. |
| type sampler struct { |
| prevCPU *metrics.CPUCounters |
| - prevUnit map[string]*int64 // unit -> cpu usec at previous tick |
| + prevUnit map[string]*int64 // unit -> cpu usec at previous tick |
| + prevOwner map[string]*metrics.Owner // unit -> owner vouched at previous tick (nil: none) |
| prevAt time.Time |
| buf []metrics.Sample |
| writtenHours map[string]bool // hour -> this process has written/merged it at least once |
| @@ -74,7 +79,14 @@ func (sm *sampler) tick(p sampleProbes) { |
| l1, l5, l15 := p.loadavg() |
| mem := p.memFrac() |
| disk := p.diskFrac() |
| + var before, after map[string]metrics.Vouch |
| + if p.owners != nil { |
| + before = p.owners() |
| + } |
| units := p.units() |
| + if p.owners != nil { |
| + after = p.owners() |
| + } |
| var elapsed time.Duration |
| if !sm.prevAt.IsZero() { |
| @@ -102,7 +114,11 @@ func (sm *sampler) tick(p sampleProbes) { |
| } |
| newPrevUnit[name] = u.cpuUsec |
| } |
| + metrics.TagUnits(unitSamples, before, after) |
| } |
| + // The CPU fraction above is a delta from the previous tick's counter: |
| + // a reading keeps its tag only if that tick vouched the same tenant. |
| + sm.prevOwner = metrics.CarryTags(unitSamples, sm.prevOwner) |
| sm.buf = append(sm.buf, metrics.Sample{ |
| At: now, |
| @@ -603,7 +619,7 @@ func httpPostWebhook(url string, body []byte) error { return alerting.PostJSON(u |
| // start, and a route stamped this afternoon would go unsampled until the next |
| // restart. A nil func means "no stamped units" — the darwin/dev shape, and |
| // what every test double passes. |
| -func realSampleProbes(execRoot string, stampedUnits func() []string) sampleProbes { |
| +func realSampleProbes(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch) sampleProbes { |
| return sampleProbes{ |
| procStat: readProcStat, |
| loadavg: readLoadAvg, |
| @@ -616,7 +632,8 @@ func realSampleProbes(execRoot string, stampedUnits func() []string) sampleProbe |
| } |
| return realUnitReadings(execRoot, stamped) |
| }, |
| - now: time.Now, |
| + owners: owners, |
| + now: time.Now, |
| } |
| } |
| @@ -750,10 +767,13 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) } |
| // minute. It is a func, not the registry handle, so this loop keeps its "no |
| // state but a bucket and /proc" shape; nil = none. |
| // |
| +// owners tags each exec cgroup's reading with the tenant the box vouches |
| +// for (metricsOwners, agent.go's wiring); nil tags nothing. |
| +// |
| // sinks are the agent's alert sinks, built and armed for paging by runAgent |
| // at startup (armAgentAlerts); the loop delivers its alerts on them and |
| // never builds or arms its own. nil delivers nowhere. |
| -func metricsLoop(execRoot string, stampedUnits func() []string, sinks *alertSinks) { |
| +func metricsLoop(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch, sinks *alertSinks) { |
| // This loop is always on and shares a process with the agent that serves |
| // this box's traffic, so a panic in it — an unreadable cgroup shape, a |
| // nil no one expected — must not take the box down with it. Monitoring |
| @@ -801,7 +821,7 @@ func metricsLoop(execRoot string, stampedUnits func() []string, sinks *alertSink |
| log.Printf("agent: metrics loop armed (60s ticks, 5min flush), publishing to %s", target) |
| sm := &sampler{} |
| - probes := realSampleProbes(execRoot, stampedUnits) |
| + probes := realSampleProbes(execRoot, stampedUnits, owners) |
| tick := 0 |
| // One watch for the life of the loop: its memory of what it has already |
| // alerted is what keeps a standing refusal from paging every minute. |
diff --git a/internal/host/metrics_owner.go b/internal/host/metrics_owner.go| new file mode 100644 |
| index 000000000..0e8e2ae46 |
| --- /dev/null |
| +++ b/internal/host/metrics_owner.go |
| @@ -0,0 +1,43 @@ |
| +package host |
| + |
| +import ( |
| + "log" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// tenancySource is the activator's half of metricsOwners |
| +// (activator.Service.Tenancies). |
| +type tenancySource interface { |
| + Tenancies() map[string]activator.Tenancy |
| +} |
| + |
| +// metricsOwners is the sampler's one statement of whose processes the box's |
| +// exec cgroups hold (docs/superpowers/notes/remote-instance-metrics.md): |
| +// the activator's live entries joined to the registry's rows by |
| +// metrics.Vouched, leaving out hosts a previous agent left populated. The |
| +// sampler reads it before and after each cgroup read and tags a unit only |
| +// when both agree (metrics.TagUnits). The activator is read first, then the |
| +// registry; nil act (no activator on this box) or an unreadable registry |
| +// vouches nothing, which tags nothing. |
| +func metricsOwners(reg *registry.Registry, act tenancySource, leftover func(string) bool) map[string]metrics.Vouch { |
| + if act == nil || reg == nil { |
| + return nil |
| + } |
| + ten := act.Tenancies() |
| + if len(ten) == 0 { |
| + return nil |
| + } |
| + live := make(map[string]metrics.Live, len(ten)) |
| + for host, t := range ten { |
| + live[host] = metrics.Live{Account: t.Account, App: t.App, Entry: t.Entry} |
| + } |
| + routes, err := reg.List() |
| + if err != nil { |
| + log.Printf("agent: metrics: read route owners: %v", err) |
| + return nil |
| + } |
| + return metrics.Vouched(routes, live, leftover) |
| +} |
diff --git a/internal/host/metrics_owner_test.go b/internal/host/metrics_owner_test.go| new file mode 100644 |
| index 000000000..5354e62a1 |
| --- /dev/null |
| +++ b/internal/host/metrics_owner_test.go |
| @@ -0,0 +1,155 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type stubTenancies struct { |
| + next []map[string]activator.Tenancy |
| +} |
| + |
| +// Tenancies answers its queued views in turn, the last one forever. |
| +func (s *stubTenancies) Tenancies() map[string]activator.Tenancy { |
| + v := s.next[0] |
| + if len(s.next) > 1 { |
| + s.next = s.next[1:] |
| + } |
| + return v |
| +} |
| + |
| +// TestMetricsOwnersTagsWhatTheBoxVouches is the box half end to end: a |
| +// real registry, the activator's view, the sampler's tick and flush, and |
| +// the chunk the console reads. A unit is tagged only when the activator's |
| +// entry and the registry row name one tenant across the whole read. |
| +func TestMetricsOwnersTagsWhatTheBoxVouches(t *testing.T) { |
| + const own, prev, moved, gone = "own.example.com", "prev.example.com", "moved.example.com", "gone.example.com" |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + for _, rt := range []registry.Route{ |
| + {Host: own, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true}, |
| + // The successor's row, while the predecessor's entry still stops. |
| + {Host: prev, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true}, |
| + {Host: moved, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true}, |
| + {Host: gone, Kind: "instance", Account: "bdn", App: "shop", Provisioned: true}, |
| + } { |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + view := func(movedEntry uint64) map[string]activator.Tenancy { |
| + return map[string]activator.Tenancy{ |
| + own: {Account: "bdn", App: "shop", Entry: 1}, |
| + prev: {Account: "rival", App: "shop", Entry: 2}, |
| + moved: {Account: "bdn", App: "shop", Entry: movedEntry}, |
| + gone: {Account: "bdn", App: "shop", Entry: 4}, |
| + } |
| + } |
| + // moved gets a new entry between the two reads (a stop and a wake |
| + // during the cgroup read); gone is a leftover from a previous agent. |
| + src := &stubTenancies{next: []map[string]activator.Tenancy{view(3), view(5)}} |
| + owners := func() map[string]metrics.Vouch { |
| + return metricsOwners(reg, src, func(h string) bool { return h == gone }) |
| + } |
| + |
| + f := 0.4 |
| + at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + sm := &sampler{} |
| + sm.tick(sampleProbes{ |
| + procStat: func() *metrics.CPUCounters { return nil }, |
| + loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil }, |
| + memFrac: func() *float64 { return &f }, |
| + diskFrac: func() *float64 { return &f }, |
| + units: func() map[string]unitRaw { |
| + out := map[string]unitRaw{} |
| + for _, h := range []string{own, prev, moved, gone} { |
| + out["carlos-exec@"+h] = unitRaw{} |
| + } |
| + // A unit-backed tenant is never vouched, whatever the activator says. |
| + out["carlos-app@"+own+".service"] = unitRaw{} |
| + return out |
| + }, |
| + owners: owners, |
| + now: func() time.Time { return at }, |
| + }) |
| + store := release.NewDirStore(t.TempDir()) |
| + if err := metricsFlush(context.Background(), store, "box-b", sm, at); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, err := store.Get(context.Background(), metrics.RawKey("box-b", metrics.HourOf(at))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var chunk metrics.RawChunk |
| + if err := json.Unmarshal(body, &chunk); err != nil || len(chunk.Samples) != 1 { |
| + t.Fatalf("chunk = %s (%v)", body, err) |
| + } |
| + units := chunk.Samples[0].Units |
| + if o := units["carlos-exec@"+own].Owner; o == nil || *o != (metrics.Owner{Account: "bdn", App: "shop"}) { |
| + t.Fatalf("own unit owner = %+v", o) |
| + } |
| + for _, u := range []string{"carlos-exec@" + prev, "carlos-exec@" + moved, "carlos-exec@" + gone, "carlos-app@" + own + ".service"} { |
| + if o := units[u].Owner; o != nil { |
| + t.Errorf("%s tagged %+v, want untagged", u, o) |
| + } |
| + } |
| +} |
| + |
| +// TestMetricsOwnersWithoutAnActivator: a box with no activator vouches |
| +// nothing. |
| +func TestMetricsOwnersWithoutAnActivator(t *testing.T) { |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if got := metricsOwners(reg, nil, nil); len(got) != 0 { |
| + t.Fatalf("vouched %+v with no activator", got) |
| + } |
| +} |
| + |
| +// TestSamplerDeltaNeedsBothTicksVouched is Astra's round 1 finding on the |
| +// note: tick N reads tenant A's counter, A stops, B starts in the same |
| +// cgroup with a larger counter, and both reads at tick N+1 agree on B. The |
| +// CPU fraction at N+1 is a delta from A's counter, so it is not B's: the |
| +// reading stays untagged. The tick after that is B's on both ends. |
| +func TestSamplerDeltaNeedsBothTicksVouched(t *testing.T) { |
| + const unit = "carlos-exec@own.example.com" |
| + a := map[string]metrics.Vouch{unit: {Owner: metrics.Owner{Account: "rival", App: "shop"}, Entry: 1}} |
| + b := map[string]metrics.Vouch{unit: {Owner: metrics.Owner{Account: "bdn", App: "shop"}, Entry: 2}} |
| + f := 0.4 |
| + at := time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| + sm := &sampler{} |
| + tick := func(usec int64, owners map[string]metrics.Vouch, now time.Time) metrics.UnitSample { |
| + sm.tick(sampleProbes{ |
| + procStat: func() *metrics.CPUCounters { return nil }, |
| + loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil }, |
| + memFrac: func() *float64 { return &f }, |
| + diskFrac: func() *float64 { return &f }, |
| + units: func() map[string]unitRaw { return map[string]unitRaw{unit: {cpuUsec: &usec}} }, |
| + owners: func() map[string]metrics.Vouch { return owners }, |
| + now: func() time.Time { return now }, |
| + }) |
| + return sm.buf[len(sm.buf)-1].Units[unit] |
| + } |
| + if u := tick(5_000_000, a, at); u.Owner == nil || u.Owner.Account != "rival" { |
| + t.Fatalf("tick N = %+v, want A's", u.Owner) |
| + } |
| + if u := tick(20_000_000, b, at.Add(time.Minute)); u.Owner != nil || u.CPUFrac == nil { |
| + t.Fatalf("tick N+1 = owner %+v cpu %v: a delta from A's counter was tagged as B's", u.Owner, u.CPUFrac) |
| + } |
| + if u := tick(23_000_000, b, at.Add(2*time.Minute)); u.Owner == nil || u.Owner.Account != "bdn" { |
| + t.Fatalf("tick N+2 = %+v, want B's", u.Owner) |
| + } |
| +} |
diff --git a/internal/metrics/owner.go b/internal/metrics/owner.go| new file mode 100644 |
| index 000000000..04951d0be |
| --- /dev/null |
| +++ b/internal/metrics/owner.go |
| @@ -0,0 +1,99 @@ |
| +package metrics |
| + |
| +import ( |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Owner is the tenant whose process a unit's reading measured: the account |
| +// and app of the route the box's activator started it for. The console |
| +// shows a reading on an instance that lives on another box only when this |
| +// names the account and app of the record it is showing |
| +// (docs/superpowers/notes/remote-instance-metrics.md). A tenant, not a |
| +// lifetime: a hostname changes hands between tenants only through its |
| +// row's account or app changing. |
| +type Owner struct { |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| +} |
| + |
| +// Live is the activator's word on one host: the tenant of the route its |
| +// live entry was started for, and that entry's number, which is new for |
| +// every new entry (activator.Service.Tenancies). |
| +type Live struct { |
| + Account, App string |
| + Entry uint64 |
| +} |
| + |
| +// Vouch is one exec cgroup's tenant at one moment, with the entry that |
| +// started its processes. |
| +type Vouch struct { |
| + Owner Owner |
| + Entry uint64 |
| +} |
| + |
| +// Vouched is the box's one statement of whose processes its exec cgroups |
| +// hold: carlos-exec@<host> is vouched for tenant T only while the |
| +// activator's live entry for host was started for T, the registry row for |
| +// host names T too, and host is not a cgroup a previous agent left |
| +// populated. Nothing else is ever vouched: not carlos-app@ units (systemd |
| +// runs them, and they can outlive the agent), not stamped or platform |
| +// units. An empty account or app vouches nothing. |
| +func Vouched(rows []registry.Route, live map[string]Live, leftover func(host string) bool) map[string]Vouch { |
| + if len(live) == 0 { |
| + return nil |
| + } |
| + out := make(map[string]Vouch, len(live)) |
| + for _, rt := range rows { |
| + l, ok := live[rt.Host] |
| + if !ok || rt.Account == "" || rt.App == "" || rt.Account != l.Account || rt.App != l.App { |
| + continue |
| + } |
| + if leftover != nil && leftover(rt.Host) { |
| + continue |
| + } |
| + out[cgroup.ExecName(rt.Host)] = Vouch{Owner: Owner{Account: rt.Account, App: rt.App}, Entry: l.Entry} |
| + } |
| + return out |
| +} |
| + |
| +// TagUnits stamps each unit's reading with its owner when the box vouched |
| +// for that unit both before and after the cgroup read, for the same tenant |
| +// and the same activator entry. A wake, a stop or a change of tenant |
| +// during the read leaves the reading untagged, which no console shows on |
| +// an instance that lives on another box. |
| +func TagUnits(units map[string]UnitSample, before, after map[string]Vouch) { |
| + for name, u := range units { |
| + b, okB := before[name] |
| + a, okA := after[name] |
| + if !okB || !okA || a != b { |
| + continue |
| + } |
| + o := b.Owner |
| + u.Owner = &o |
| + units[name] = u |
| + } |
| +} |
| + |
| +// CarryTags applies the second half of the tag rule: a unit's CPU fraction |
| +// is the delta from the previous tick's counter of the same cgroup, so its |
| +// reading stays tagged only when the previous tick read that unit for the |
| +// same tenant, or did not read it at all (then there is no delta). prev is |
| +// the previous tick's vouched owner per unit read (nil for one it did not |
| +// vouch); the result is this tick's, made before anything is untagged |
| +// here, for the next call. |
| +func CarryTags(units map[string]UnitSample, prev map[string]*Owner) map[string]*Owner { |
| + next := make(map[string]*Owner, len(units)) |
| + for name, u := range units { |
| + next[name] = u.Owner |
| + if u.Owner == nil { |
| + continue |
| + } |
| + p, read := prev[name] |
| + if read && (p == nil || *p != *u.Owner) { |
| + u.Owner = nil |
| + units[name] = u |
| + } |
| + } |
| + return next |
| +} |
diff --git a/internal/metrics/owner_test.go b/internal/metrics/owner_test.go| new file mode 100644 |
| index 000000000..9bfbc1db0 |
| --- /dev/null |
| +++ b/internal/metrics/owner_test.go |
| @@ -0,0 +1,138 @@ |
| +package metrics |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const ownHost = "eu.shop.example.com" |
| + |
| +func execUnit(host string) string { return "carlos-exec@" + host } |
| + |
| +// TestVouchedJoinsLiveEntryToRow: a host is vouched only while the |
| +// activator's live entry and the registry row name the same tenant. |
| +func TestVouchedJoinsLiveEntryToRow(t *testing.T) { |
| + shop := Owner{Account: "bdn", App: "shop"} |
| + rows := []registry.Route{ |
| + {Host: ownHost, Account: "bdn", App: "shop"}, |
| + {Host: "b.example.com", Account: "bdn", App: "shop"}, |
| + {Host: "c.example.com", Account: "", App: "shop"}, |
| + {Host: "d.example.com", Account: "bdn", App: "shop"}, |
| + {Host: "e.example.com", Account: "bdn", App: "shop"}, |
| + } |
| + live := map[string]Live{ |
| + ownHost: {Account: "bdn", App: "shop", Entry: 7}, |
| + "b.example.com": {Account: "rival", App: "shop", Entry: 8}, // predecessor still stopping |
| + "c.example.com": {Account: "", App: "shop", Entry: 9}, // unstamped row |
| + "d.example.com": {Account: "bdn", App: "shop", Entry: 10}, // a leftover cgroup |
| + "x.example.com": {Account: "bdn", App: "shop", Entry: 11}, // no row |
| + } |
| + leftover := func(host string) bool { return host == "d.example.com" } |
| + got := Vouched(rows, live, leftover) |
| + want := map[string]Vouch{execUnit(ownHost): {Owner: shop, Entry: 7}} |
| + if len(got) != len(want) || got[execUnit(ownHost)] != want[execUnit(ownHost)] { |
| + t.Fatalf("Vouched = %+v, want %+v", got, want) |
| + } |
| + for unit := range got { |
| + if !strings.HasPrefix(unit, "carlos-exec@") { |
| + t.Fatalf("vouched a non-exec unit %q", unit) |
| + } |
| + } |
| + if Vouched(rows, nil, nil) != nil && len(Vouched(rows, nil, nil)) != 0 { |
| + t.Fatal("no live entries vouched something") |
| + } |
| +} |
| + |
| +// TestTagUnitsNeedsBothReads: a unit is tagged only when the reads before |
| +// and after the cgroup read agree on the tenant and the entry. |
| +func TestTagUnitsNeedsBothReads(t *testing.T) { |
| + shop := Owner{Account: "bdn", App: "shop"} |
| + rival := Owner{Account: "rival", App: "shop"} |
| + f := 0.5 |
| + units := func() map[string]UnitSample { |
| + return map[string]UnitSample{execUnit(ownHost): {CPUFrac: &f}, "carlos-edge.service": {CPUFrac: &f}} |
| + } |
| + cases := []struct { |
| + name string |
| + before, after map[string]Vouch |
| + want *Owner |
| + }{ |
| + {"agree", map[string]Vouch{execUnit(ownHost): {shop, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 1}}, &shop}, |
| + {"new entry during the read", map[string]Vouch{execUnit(ownHost): {shop, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 2}}, nil}, |
| + {"tenant changed during the read", map[string]Vouch{execUnit(ownHost): {rival, 1}}, map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil}, |
| + {"vouched only before", map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil, nil}, |
| + {"vouched only after", nil, map[string]Vouch{execUnit(ownHost): {shop, 1}}, nil}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + u := units() |
| + TagUnits(u, c.before, c.after) |
| + got := u[execUnit(ownHost)].Owner |
| + if (got == nil) != (c.want == nil) || (got != nil && *got != *c.want) { |
| + t.Fatalf("owner = %+v, want %+v", got, c.want) |
| + } |
| + if u["carlos-edge.service"].Owner != nil { |
| + t.Fatal("tagged a unit nothing vouched for") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestOwnerWireShape: the tag is additive and omitted when unset, so a |
| +// chunk without it reads as before and an old reader ignores it. |
| +func TestOwnerWireShape(t *testing.T) { |
| + f := 0.25 |
| + b, _ := json.Marshal(UnitSample{CPUFrac: &f}) |
| + if strings.Contains(string(b), "owner") { |
| + t.Fatalf("untagged sample carries an owner key: %s", b) |
| + } |
| + b, _ = json.Marshal(UnitSample{CPUFrac: &f, Owner: &Owner{Account: "bdn", App: "shop"}}) |
| + if !strings.Contains(string(b), `"owner":{"account":"bdn","app":"shop"}`) { |
| + t.Fatalf("tagged sample = %s", b) |
| + } |
| + var old struct { |
| + CPUFrac *float64 `json:"cpu"` |
| + } |
| + if err := json.Unmarshal(b, &old); err != nil || old.CPUFrac == nil { |
| + t.Fatalf("an old reader cannot read a tagged sample: %v", err) |
| + } |
| +} |
| + |
| +// TestCarryTagsAcrossTicks: a unit's CPU fraction is a delta from the |
| +// previous tick's counter, so a reading stays tagged only when the |
| +// previous tick read the unit for the same tenant, or did not read it at |
| +// all (no previous counter, no delta). Astra round 1 on the note. |
| +func TestCarryTagsAcrossTicks(t *testing.T) { |
| + shop := &Owner{Account: "bdn", App: "shop"} |
| + rival := &Owner{Account: "rival", App: "shop"} |
| + f := 0.25 |
| + tagged := func(o *Owner) UnitSample { return UnitSample{CPUFrac: &f, Owner: o} } |
| + cases := []struct { |
| + name string |
| + prev map[string]*Owner |
| + now *Owner |
| + want *Owner |
| + }{ |
| + {"first reading of the unit", map[string]*Owner{}, shop, shop}, |
| + {"same tenant before", map[string]*Owner{"u": {Account: "bdn", App: "shop"}}, shop, shop}, |
| + {"another tenant before", map[string]*Owner{"u": rival}, shop, nil}, |
| + {"untagged before", map[string]*Owner{"u": nil}, shop, nil}, |
| + {"untagged now", map[string]*Owner{"u": shop}, nil, nil}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + units := map[string]UnitSample{"u": tagged(c.now)} |
| + next := CarryTags(units, c.prev) |
| + got := units["u"].Owner |
| + if (got == nil) != (c.want == nil) || (got != nil && *got != *c.want) { |
| + t.Fatalf("owner = %+v, want %+v", got, c.want) |
| + } |
| + if o, ok := next["u"]; !ok || (o == nil) != (c.now == nil) { |
| + t.Fatalf("next tick's memory = %+v (present %v), want what the box vouched now (%+v)", o, ok, c.now) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/metrics/sample.go b/internal/metrics/sample.go| index da14784a0..1dc4b90eb 100644 |
| --- a/internal/metrics/sample.go |
| +++ b/internal/metrics/sample.go |
| @@ -24,6 +24,10 @@ type UnitSample struct { |
| MemPeakBytes *int64 `json:"mem_peak_bytes"` |
| ReadBytes *int64 `json:"read_bytes"` // cumulative |
| WriteBytes *int64 `json:"write_bytes"` // cumulative |
| + // Owner is the tenant the box vouches this reading measured (owner.go), |
| + // nil when it vouches none. Additive: omitted when unset, so a chunk |
| + // from a box built before it reads exactly as it did. |
| + Owner *Owner `json:"owner,omitempty"` |
| } |
| // Sample is one point-in-time reading of a box: the host as a whole plus |