carlos / platform Public

spec: instance memory alert rev 2 (Astra round 1 dispositions)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ab036d9610926a18a346a14d10f27a2c51d32ba7 parent a0b984c
1 file changed, +194 −148
  • docs/superpowers/specs/2026-11-13-instance-memory-alert-design.md +194 −148

Intent

Human

<task-notification> <task-id>a0cb75f46636465fa</task-id> <tool-use-id>toolu_01M3m5TYRbJ5412DdAq89C5d</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/96a09f74-e398-48ed-a97f-140bd1f7e255/tasks/a0cb75f46636465fa.output</output-file> <status>completed</status> <summary>Agent "Draft #996 memory alert design" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The design is revised to rev 2 in the same file, with a "Round 1 dispositions" section at the end. I accepted all nine findings and declined none. Nothing was committed. **What changed structurally:** - **Kills are no longer sampled.** They are recorded when the process ends. - Nested: the activator adds `Result` to the `systemctl show` call it already makes on exit, invocation-matched. - Flat: the exec wait goroutine reads `memory.events` once before it removes the cgroup. - Both count a stop only if the cgroup's own `oom` counter grew. `oom_kill` is not used, because a box-wide OOM moves it too. - The advisory exit record is not trusted, because it is written inside the instance's namespace. - **Every entry carries tenant identity:** account, app and the record's incarnation, which the box already computes. The console drops any entry that doesn't match the record it is showing, the same rule `metricsview.go:873-885` uses. - **The box reports only current state.** The states are pressure, ok, asleep, swapping and unavailable; the last three pause the timers. The alerts engine owns episodes, keyed by incarnation, so restarts and kill loops don't open new ones. - **One monitored cgroup per layout:** the one whose `memory.max` is the instance's size. While a deploy swaps two generations, nothing fires or clears. - **Without per-cgroup pressure data there is no verdict.** It clears once pressure drops below 1 percent for 15 minutes, even if `high` keeps rising. - Also added: - The scope is narrowed: `carlos-app@` and stamped units are now non-goals. - A root-run agent reads nothing. - The census applies. - Both facts are fixed, and alerts can take up to about 25 minutes from onset. Two things are still unverified. I don't know whether systemd 257 still reports `oom-kill` with PrivatePIDs, or whether systemd says `oom-kill` for a box-wide OOM too. The spec says how to check each. The file is about 1,500 words counting citations, slightly over the 1,400 asked. The sandbox failed with the worktree as the working directory, so I ran two word counts with the sandbox off.</result> <usage><subagent_tokens>165217</subagent_tokens><tool_uses>27</tool_uses><duration_ms>286214</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/specs/2026-11-13-instance-memory-alert-design.md b/docs/superpowers/specs/2026-11-13-instance-memory-alert-design.md
index 536ea7933..b99b67626 100644
--- a/docs/superpowers/specs/2026-11-13-instance-memory-alert-design.md
+++ b/docs/superpowers/specs/2026-11-13-instance-memory-alert-design.md
@@ -1,158 +1,204 @@
# Instance memory alert (#996): design
-Status: draft for Paul. Grounded in origin/main 4c641678. Owner-facing strings
-are drafts for a later copy review.
+Status: rev 2, after Astra round 1. Grounded in origin/main 4c641678.
+Owner-facing strings are drafts for a later copy review.
## 1. Why
Nothing tells an owner that one instance is running out of room. The cap is
-real: `memory.max` from the instance's size, `memory.high` at 90 percent
-(`internal/cgroup/cgroup.go:158-161`, written at `cgroup.go:771-783`), and
-`memory.oom.group=1`, so a kill takes the whole family
-(`cgroup.go:764-766`, `:800`). Throttling and kills are silent from the
-owner's side. Box memory is watched (`internal/host/memwatch.go:21-33`);
-instances are not.
-
-Two triggers. #992: in an app with one instance per customer, the owner needs
-to see which customer outgrew shared hosting before moving it. And the nesting
-plan's W2 conversion batches (`docs/superpowers/plans/2026-11-13-tito-nesting-and-self-serve-moves.md`
-W5) need a per-instance view while instances land under their caps.
+real: `memory.max` from the size, `memory.high` at 90 percent
+(`internal/cgroup/cgroup.go:158-161`, `:771-783`), `memory.oom.group=1`
+(`cgroup.go:764-766`). Box memory is watched (`internal/host/memwatch.go:21-33`);
+instances are not. Triggers: #992 (which customer outgrew shared hosting) and
+the nesting plan's W2 batches (`docs/superpowers/plans/2026-11-13-tito-nesting-and-self-serve-moves.md` W5).
## 2. Goals, non-goals, anti-goals
-- **Goals.** An owner sees, per instance, "near its limit" and "ran out and
- restarted", with the next step. Operators see the same during batches.
-- **Non-goals.** Changing sizes or caps; forecasting memory creep (left for
- later by the alerts spec §7.1); the move itself (#992).
-- **Anti-goals.** Noise: fire only when sustained, one alert per instance per
- episode (alerts spec §6 rules 1, 3, 6). Any new per-box S3 polling or new
- object. Any new root read of tenant-writable files: none is needed (§4).
-
-## 3. The signal
-
-Read per instance, at the cgroup that holds the cap, once a minute:
-
-| File | Use |
+- **Goals.** Owner and operator see, per instance, "under memory pressure"
+ and "stopped for using all its memory", with the next step.
+- **Scope.** Vouched instance kinds only: exec cgroups (flat) and nested
+ units, both keyed `carlos-exec@<host>` (`internal/metrics/owner.go:35-57`,
+ `internal/host/metrics_nested.go:71-73`).
+- **Non-goals.** `carlos-app@` units and stamped or platform units: nothing
+ vouches them (`owner.go:39-41`). Changing sizes; forecasts; the move (#992).
+- **Anti-goals.** Noise; any new S3 object or per-box polling; any root read.
+
+## 3. Two signals, two mechanisms
+
+### 3.1 Stops for memory: lifecycle, not sampling
+
+Kills are not sampled; a cgroup can die between ticks. They are recorded
+where the platform already handles a process ending:
+
+- **Nested units.** On exit the activator already runs `systemctl show -p
+ InvocationID,ExecMainCode,ExecMainStatus,...` and matches the invocation
+ (`internal/activator/control.go:151-167`, `unitproc.go:581-597`). Add
+ `Result` to that one call: `oom-kill` is systemd's own word, set under the
+ templates' `OOMPolicy=kill` (`internal/instancectl/gen.go:44`). It counts
+ only when the host slice's `oom` counter also grew since the spawn, as
+ systemd may say `oom-kill` for a box-wide OOM too (unknown: check
+ systemd's `unit_check_oom`). Not the exit
+ record: it is advisory and written inside the instance's namespace
+ (`instancectl/names.go:604-606`, `instanceexec/exit.go:26-32`). Unknown:
+ whether `Result` still reads `oom-kill` on systemd 257 with PrivatePIDs,
+ given `unitproc.go:576-579`; check by forcing an OOM in a nested unit on dev.
+- **Flat exec.** The wait goroutine (`internal/activator/backend_exec.go:2737-2754`)
+ reads the boundary's `memory.events` once at spawn and once after
+ `cmd.Wait()`, before `RemoveChild`. A SIGKILL exit with the `oom` counter
+ grown (this cgroup's own limit was hit) is a stop for memory. `oom_kill`
+ and `oom_group_kill` are not used: a box-wide OOM moves them too.
+
+The activator counts these per instance incarnation (§4) since the agent
+started, with the time of the last one. One stop is one count, however many
+processes the group kill took.
+
+### 3.2 Pressure: the 60 s sampler
+
+The metrics sampler (`internal/host/metrics_loop.go:1-8`, `:1024`) already
+reads every vouched instance cgroup (`metrics_probes.go:223-241`,
+`metrics_nested.go:80-111`). It adds `memory.events` `high`, `memory.pressure`
+`some avg60`, `memory.current` and `memory.max` at the boundary (§3.3). No
+production code reads `memory.events` per cgroup today; tests do
+(`internal/host/size_rootrunner_linux_test.go:213-221`). Losing a minute here
+is harmless.
+
+`memory.current` near `memory.max` is never a trigger: the charge includes
+page cache (`cgroup.go:758-762`). The box reports one current state per
+instance, never history:
+
+| State | Rule (proposal, calibrate first) |
+|---|---|
+| `pressure` | `high` grew in at least 8 of the last 10 read minutes and `some avg60` at or above 5 percent |
+| `ok` | from `pressure`: `some avg60` below 1 percent for 15 read minutes, whatever `high` does (cheap reclaim cannot hold it open) |
+| `asleep` | no process |
+| `swapping` | a generation swap is under way (`sizestatus.go:106-108`) |
+| `unavailable` | a read failed, no PSI, an unvouched reading, or a root-run agent |
+
+`asleep`, `swapping` and `unavailable` pause the windows: they neither fire
+nor clear. Without PSI there is no verdict: `high` alone cannot tell a full
+page cache from pain. memwatch reads PSI on every armed box (`memwatch.go:28`);
+unknown whether every box has per-cgroup `memory.pressure`: check with
+`cat` on a nested slice on dev and on a Pi. An agent restart starts the
+windows empty (`metrics_loop.go:982`); the console owns episodes, so that
+only delays a fire.
+
+### 3.3 The boundary per layout
+
+The monitored cgroup is the one whose `memory.max` is the instance's size,
+resolved as `readSizeInForce` does (`internal/host/sizestatus.go:64-100`).
+Usage, limit and events all come from that one cgroup, read hierarchically
+there and never summed, so nothing is counted twice.
+
+| Layout | Boundary |
|---|---|
-| `memory.events` `high` | delta per minute: throttled at `memory.high` |
-| `memory.events` `oom_kill` | delta: kills since last tick |
-| `memory.current`, `memory.max` | the figure shown ("470 of 512 MB"), never a trigger alone |
-| `memory.pressure` `some avg60` (proposal) | stall time, to tell real pain from a full page cache |
-
-Why not `memory.current` near `memory.max` (the alerts spec's "too busy",
-§7.3 line 415): the charge includes page cache (`cgroup.go:758-762`), so a
-healthy file-reading app sits near `memory.high` all day. Swap is allowed up
-to the cap (`cgroup.go:785-791`), so `current` can also look fine while the
-app is swapping. Nothing reads `memory.events` or `memory.pressure` today
-(git grep finds no reader).
-
-**Proposed thresholds** (calibrate before switch-on, §6):
-
-- *Near its limit*: `high` grew in at least 8 of the last 10 minutes, and,
- where `memory.pressure` reads, `some avg60` at or above 5 percent. Clears
- after 30 minutes with no `high` growth. Ten minutes matches the box `mem`
- rule's sustain (`internal/metrics/alert.go:16-17`, `:42-43`); the gentler
- clear is §6 rule 4.
-- *Ran out*: any `oom_kill` delta. A one-off event: it closes after 24 hours
- quiet (§6 rule 8), and further kills in that window update its count, not
- a new message.
-
-Counters reset when the cgroup is remade. A new cgroup id
-(`internal/host/metrics_nested_linux.go:13`) or a smaller value is a new
-baseline, never a negative delta.
-
-## 4. Where it lives
-
-**Computed on the box**, in the metrics sampler: 60-second ticks
-(`internal/host/metrics_loop.go:1-8`, `:1024`). It already walks every
-instance cgroup and reads `memory.current` and `memory.peak`
-(`internal/host/metrics_probes.go:223-241`): flat units in
-`system-carlos\x2dapp.slice` (`metrics_probes.go:82-90`, `:97`), exec children
-under the edge's delegated subtree (`metrics_probes.go:261`), and nested units
-(`internal/host/metrics_nested.go:80-111`). It keeps per-unit state between
-ticks already (`metrics_loop.go:71-80`). Readings are vouched to a tenant
-(`metrics_loop.go:130-139`); an episode should only count vouched readings.
-
-The cap's cgroup differs by layout. Nested: the host's slice, or the
-generation cgroup when one exists (`internal/host/sizestatus.go:64-81`), while
-the sampler reads the units below it (`metrics_nested.go:74-76`).
-`memory.events` is hierarchical, so reading it at the slice covers every
-generation. gVisor caps at the physical limit (`sizestatus.go:90-93`).
-
-**No root read.** The agent runs as `User=carlos`
-(`internal/host/units/carlos-edge.service:41`) and already reads
-`memory.max` and `memory.current` in these same directories
-(`sizestatus.go:82`, `metrics_probes.go:231`). cgroupfs files are written by
-the kernel; a tenant cannot write them. Unknown: check how, by running
-`stat -c '%a %U' memory.events memory.pressure` on a nested slice and an exec
-cgroup on dev.
-
-**Carried** in the 5-minute status heartbeat's private `Metrics` block
-(`status.SnapshotPeriod`, `internal/status/fleet.go:120`), as a host-keyed map
-beside `RouteDBBytes` (`internal/status/snapshot.go:720-726`), private for
-the same reason (`snapshot.go:579-583`). Only instances in an episode, or with
-one closed in the last 24 hours, get an entry: verdict, since, current, max,
-kill count. That adds bytes to a PUT that already happens, no new request.
-
-**Judged** by the alerts engine, which reads heartbeats every fifth pass with
-conditional GETs (`internal/console/alertengine_pass.go:46-51`,
-`alertsignals.go:3-7`). Grouping, flapping and snooze are its noise rules.
-Today it has only fleet scope (`alertsignals.go:444-450`); account and app
-scope is the alerts spec's Plan 3 (§11), not built.
-
-**Shown** in `carlos instances list` REASON (`instances_cli.go:713-727`), joined
-from heartbeats as DB is (`internal/console/apiinstances.go:948`, `:1096`);
-on the console instance page (`internal/console/instancepage.go`, which
-already shows box-reported words); and in alerts.
-
-## 5. Words an owner sees (drafts)
-
-- REASON: `memory: near its limit, 470 of 512 MB since 14:02`
-- REASON: `memory: ran out and restarted 3 times today`
-- Instance page, state line: "Near its memory limit" / "Ran out of memory and
- restarted" / "Memory OK".
-- Instance page, body: "This instance has used most of its 512 MB for 25
- minutes, so it’s slowing down. If it keeps growing it will run out and
- restart. A bigger size or a box of its own will fix it."
-- Alert, fire: "shop-42.example.com is near its memory limit. It has used most
- of its 512 MB for 10 minutes and is slowing down. Next step: a bigger size,
- or its own box."
-- Alert, kill: "shop-42.example.com ran out of memory and restarted at 14:07."
-- Alert, clear: "shop-42.example.com is back under its memory limit."
-
-## 6. Approaches
-
-1. **Box judges, heartbeat carries, engine and listings read it.**
- Recommended. One carrier, so REASON and Slack never disagree (alerts spec
- §3, line 103). No new object or read. Minute-level judging on the box,
- up to 10 minutes' delivery delay, which suits a warning.
-2. **Per-host box rules in `alerts/boxes/<box>.json`.** The shape exists
- (`restarts@<unit>`, `verify_failed@<host>`, `alert.go:188`), written on
- change and read every minute. Faster, but the engine maps box rules to
- fleet scope, and the listings would need a second read to show REASON.
-3. **Console judges from raw chunks** (`metrics/boxes/<box>/raw/`,
- `metrics_loop.go:175-180`) or Plan 3's per-app window object (§7.2). Raw
- chunks change on every flush, so each read is a full GET per box every 5
- minutes; the window object is per app, not per instance. Rejected.
-
-Calibration first: ship the box half reporting only, read a week of dev and
-production heartbeats, and count would-be fires (§6 rule 6), as edge
-protection was calibrated.
-
-## 7. Left to the builder
-
-The heartbeat field's names and cap; reading `memory.pressure` only where
-present; the generation-or-slice choice per tick; the cgroup-id baseline;
-tests with fixture cgroup trees as `metrics_probes_test.go` does.
-
-## 8. Open questions for Paul
-
-1. Until Plan 3, who hears? (a) REASON and the instance page now, plus an
- operator fleet rule grouped per box; owners get alerts with Plan 3. Or
- (b) build a minimal app scope now.
-2. Next step wording: `carlos instances set --size` is operator-only
- (`docs/site/cli.md:1348`) and the move does not exist (#992). Say "contact
- us", or name the commands?
-3. Is a kill an incident (pages through quiet hours) or a warning?
-4. Should this replace "too busy"'s memory half (§7.3), so there is one
- memory signal?
+| Flat exec | `carlos-exec@<host>` (`cgroup.go:449`), or the serving `g<n>` under the generation layout (`cgroup/gen.go:17-24`) |
+| Nested, native | the serving generation unit's cgroup, else the host slice (`sizestatus.go:69-81`) |
+| gVisor | the retained unit, at the physical limit (`sizestatus.go:90-93`) |
+
+During a swap the parent holds the two tiers summed (`cgroup/gen.go:54-58`),
+so it is never the boundary, and the state is `swapping`. A successor that
+overruns dies alone and is reported as a release refusal
+(`internal/status/snapshot.go:751-754`), not here. Role children (seed,
+sidecar) have no limit of their own (`gen.go:21-22`) and are outside the
+signal.
+
+## 4. Identity, carrier, judge, display
+
+**Identity.** Every entry carries account, app and the record's incarnation,
+`provision.Incarnation(account, app, host, created)`
+(`internal/provision/incarnation.go:17-23`), which the box already computes
+(`internal/activator/wakeidentity.go:255`). A reused hostname gets a new
+incarnation.
+
+**Carrier.** The 5-minute heartbeat's private `Metrics` block
+(`internal/status/fleet.go:120`, `snapshot.go:579-583`), one map keyed by
+host: state, minutes in state, current, max, stop count, last stop time.
+Only instances not `ok`, or with a stop since agent start, get an entry. That
+adds bytes to an existing PUT, no request.
+
+**Judge.** The alerts engine owns episodes, dedup and suppression. It reads
+heartbeats every fifth pass (`internal/console/alertengine_pass.go:46-51`).
+- Subject: incarnation, so restarts and wakes never open a new episode, and
+ the flapping and 24-hour quiet rules (alerts spec §6 rules 7, 8) hold
+ against deliberate kill loops.
+- Stops dedupe on (incarnation, box, last stop time); count deltas add up.
+- After a move, pressure comes from the box serving the host now. Stops from
+ any box count.
+- Account and app scope is the alerts spec's Plan 3, not built; today the
+ engine has fleet scope only (`alertsignals.go:444-450`).
+
+**Display and routing.** Before showing or routing an entry, the console
+checks account, app and incarnation against the authorized record and drops
+any mismatch. This is the rule `metricsview.go:873-885` and
+`apiinstances.go:552-558` apply to resource readings. Shown in REASON
+(`instances_cli.go:713-727`, joined at `apiinstances.go:1096`), on the
+instance page and in alerts.
+
+**Latency.** Ten minutes to `pressure`, then up to 5 each for the heartbeat,
+the engine's read and its grouping hold (`alertengine.go:77`): about 25
+minutes at most. Fine for a warning.
+
+## 5. Privilege and census
+
+The agent runs as `carlos` (`internal/host/units/carlos-edge.service:41`).
+cgroupfs files are kernel-written, and the activator's `systemctl show` call
+needs no privilege (`control.go:151-155`). The new readers take the same
+effective-UID gate as the engine beat and the verify watch
+(`metrics_loop.go:971-1003`): a root-run agent reads nothing and reports
+`unavailable`. The changes touch `internal/host` and `internal/activator`, so
+they are in the census scope (`AGENTS.md:337-370`). The plan needs a census
+proposal and an independent reviewer's approval.
+
+## 6. Words (drafts)
+
+- REASON: `memory: under pressure for 25 min, 470 of 512 MB`
+- REASON: `memory: stopped 3 times today for using all its memory`
+- Page: "Under memory pressure" / "Stopped for using all its memory" /
+ "Memory OK" / "Asleep".
+- Alert: "shop-42.example.com has been short of memory for 10 minutes and is
+ slowing down. Next step: a bigger size, or its own box."
+- Alert: "shop-42.example.com was stopped at 14:07 for using all its memory."
+- Clear: "shop-42.example.com is no longer short of memory."
+
+## 7. Approaches
+
+1. **Recommended:** this design. One carrier, so REASON and Slack agree.
+2. Per-host rules in `alerts/boxes/<box>.json` (`metrics/alert.go:188`):
+ faster, but fleet-scoped, and listings need a second read.
+3. Console judging raw chunks (`metrics_loop.go:175-180`): a full GET per box
+ every 5 minutes. Rejected.
+
+Calibrate first: a week reporting only, counting would-be fires.
+
+## 8. Left to the builder
+
+Field names and the map's cap; tests: an OOM and a wake entirely between two
+ticks, before the first tick, a cache-heavy fixture, no PSI, and recovery
+with `high` still rising.
+
+## 9. Open questions for Paul
+
+1. Before Plan 3: REASON and the page now, plus an operator rule; or a
+ minimal app scope now?
+2. The next step: `carlos instances set --size` is operator-only
+ (`docs/site/cli.md:1348`) and #992 does not exist yet. "Contact us"?
+3. Is a stop for memory an incident or a warning?
+4. Replace "too busy"'s memory half (alerts spec §7.3) with this?
+
+## Round 1 dispositions
+
+1. P1 OOM lost between samples: accepted. Kills come from lifecycle at exit
+ (§3.1); nothing samples them.
+2. P1 tenant identity: accepted. Account, app and incarnation travel with
+ every entry; the console drops mismatches (§4).
+3. P2 episode continuity: accepted. The box reports current state only;
+ the engine owns episodes keyed by incarnation; asleep, swapping and
+ unavailable pause windows (§3.2, §4).
+4. P2 wording beyond evidence: accepted. "Stopped for using all its memory"
+ from the cgroup's `oom` counter (with systemd's Result when nested); no
+ restart claim (§6).
+5. P2 boundary: accepted. One cgroup per layout, swaps paused (§3.3).
+6. P2 PSI and recovery: accepted. No PSI, no verdict; clear on low PSI (§3.2).
+7. P2 vouch scope: accepted. `carlos-app@` and stamped units are non-goals (§2).
+8. P2 privilege and census: accepted. Effective-UID gate; census applies (§5).
+9. P3 facts: accepted. The test reader and the 5-minute hold are in §3.2, §4.