Design & Security Review: Metrics and the Sink¶
- Target spec:
docs/superpowers/specs/2026-11-24-metrics-and-sink-design.md(wip/metrics-design@9f70082) - Date: 2026-11-24
- Cross-checked against:
wip/bootstrap-design(internal/trust/{signed,verify}.go,internal/sshsrv),wip/plan-2-macos-runner(internal/limavm,internal/warden), andmain(internal/cgroup,internal/runner).
Summary¶
The core architectural choices fit allmyram cleanly: RAM-first shipping with disk spill only when behind, constructing go.opentelemetry.io/proto/otlp messages directly without the OTel SDK, reading per-job resource use from the pod's cgroup, and calling libSystem via purego so Darwin builds stay CGO_ENABLED=0.
Before locking the spec for implementation, two High-impact issues (Linux hoardable-memory double-counting that would over-commit admission, and gaps in the sink's certificate/renewal/discovery/wire-auth lifecycle), one Medium-High storage/spill safety gap, and four smaller measurement & Darwin details should be resolved in the design.
1. High: Linux "Hoardable Memory" Double-Counts Reclaimable Job Page Cache (Can OOM Admission) + ZFS c_min¶
Where: Hoardable (lines 62–74) and Per job, on both platforms (line 154).
Issues:
1. Page-cache double-counting between MemAvailable and memory.current:
Line 62 defines Linux hoardable memory as:
hoardable - sum(running_job_limits)).
In Linux (mm/page_alloc.c: si_mem_available()), MemAvailable already includes reclaimable file page cache, including clean file pages charged to our job cgroups' memory.current (as line 154 notes, memory.current counts page cache).
- Concrete failure: On a 64 GiB Linux host (8 GiB reserve), idle MemAvailable is 56 GiB (hoardable = 48 GiB). Start a 32 GiB-limit job that uses 4 GiB anonymous memory and reads/writes 24 GiB of clean workspace/build files (memory.current = 28 GiB). MemAvailable only drops by ~4 GiB (to ~52 GiB) because the 24 GiB of clean file cache remains reclaimable. The formula computes 52 + 28 - 8 = 72 GiB (> physical RAM!), leaving 72 - 32 = 40 GiB for admission and admitting a second 40 GiB job that OOMs the host.
2. ZFS ARC floor (c_min):
OpenZFS refuses to shrink ARC below c_min in /proc/spl/kstat/zfs/arcstats. Only max(0, size - c_min) is evictable under memory pressure.
3. Mac VM overhead attribution (lines 94, 182–187):
ri_phys_footprint of com.apple.Virtualization.VirtualMachine includes the memory of active jobs inside the VM (plus dirty guest pages touched by earlier jobs until the VM idles out). Reporting raw ri_phys_footprint as "What does allmyram itself cost?" (Goal, line 24) makes a 6 GiB job look like 6.8 GiB of allmyram overhead.
Recommendations:
- Linux hoardable memory: Add only the non-reclaimable portion of job memory that MemAvailable already subtracted — e.g., anon + shmem + kernel + sock (+ file_dirty / unevictable) from memory.stat on the parent /sys/fs/cgroup/allmyram.slice/allmyram-warden.service/jobs cgroup (which the kernel already sums across all jobs in a single file read), use 0.5 * max(0, arc.size - arc.c_min) for ZFS, and clamp hoardable <= MemTotal - reserve.
- Mac VM cost: Report both raw vm_phys_footprint and vm_overhead = max(0, vm_phys_footprint - sum(active_jobs_memory_current)).
2. High: Sink Certificate Renewal, Runner Discovery, Role Separation, and Wire Auth¶
Where: Joining the hoard (lines 235–261) and Left open (line 286).
Cross-checking against wip/bootstrap-design's internal/trust/verify.go and internal/trust/signed.go exposes five lifecycle/security gaps:
- Sink's 30-day host certificate has no renewal path:
Host certificates in
internal/trust/verify.goexpire after 30 days (HostLifetime = 30 * 24 * time.Hour). Runners get renewed automatically when the laptop connects over SSH (< 10dleft) or viaallmyram renew <name>. If the sink does not accept SSH from the laptop for renewal (and sit in the laptop's config forrenew), every runner in the hoard will reject the sink's expired certificate on day 30. - How the sink learns newly joined (or removed) runners:
Line 254 says the sink learns runners' tailcat node keys and host keys "which the laptop already holds for every runner it joined". When a new runner joins after the sink is already running, the laptop needs a path to push the updated
(runnerName, nodeKey, hostKey)entry to the sink so the sink can callServer.AddAllowedClient(nodeKey)at runtime and admit that runner's host key. Also specify which tailcat key a runner dials the sink with (itsserverKeyFile.Privateintailcat-key.json, sincetransport.Dialcurrently expects aclientKeyFile). - Wire protocol vs. OpenSSH certificates (line 286):
Line 286 leaves "OTLP over HTTP or gRPC, on a tailcat connection" open, while lines 242 and 256 require mutual OpenSSH
HostCertverification against theowner.pub -> day-keychain. Plain HTTP or gRPC on a rawtailcatTCP connection never exchanges or checks OpenSSH certificates. - Cleanest fix — run
sshsrvon the sink overtailcat(same stack as runners):- SSH user
"client"(CheckClientCert): serves host-cert renewal, revocation sync, pushing allowed runners (allow-runners), and later the Tracker UI's read queries. - SSH user
"runner"(CheckHostCertinsideServerConfig.PublicKeyCallback, whichgolang.org/x/crypto/ssh's server userauth supports directly): serves onlyship(framed OTLP batches + per-batch confirmation ACKs over the SSH channel, with no HTTP/gRPC server needed).
- SSH user
- Mutual role exclusion in
CheckHostCert: Todaytrust.CheckHostCert(internal/trust/verify.go:135) checks onlyCertType == ssh.HostCertandValidPrincipalscontainingName. If "marked as a sink" (line 243) were implemented as an extension that only sink-dialers checked, a sink'sHostCertwould also passCheckHostCertas a valid runner! Make the role check mandatory and mutually exclusive on both sides (e.g., require an explicit extension"role@allmyram"equal to"runner"vs"sink", or role-prefixed principals"runner:<name>"vs"sink:<name>"). - Owner-signed "where the sink is" pointer needs a monotonic version + "disabled" state:
Unlike permanent client-key revocations, the sink's address/key can change (moving or retiring a sink). Give the owner-signed sink statement (
internal/trust/signed.go) a monotonicuint64version/timestamp: - Sign it once on the laptop when the sink joins or changes (1 Touch ID prompt), cache it locally, and sync it to runners on connect and at runner join (0 extra Touch ID prompts per runner).
- Support a signed "no sink" / disabled payload at version
N+1so runners can be told to stop shipping and clear any spill files when a sink is retired, without rejoining runners.
3. Medium-High: Unbounded Spill Disk Growth, Single-File Drain Starvation, and <runID>.json Contention¶
Where: Shipping (lines 205–227) and The sink (lines 230–233).
- Runner spill disk cap:
While the RAM buffer is capped at 1 MiB, the spill file on disk has no cap. If the optional sink is down or unreachable for days, unbounded spilling violates "The machine's owner comes first" and "losing the tracker loses visibility, never jobs". Cap total spill disk usage on runners (e.g., 64–128 MiB); past the cap, drop oldest/newest telemetry and increment a
dropped_recordscounter shipped on the next heartbeat. - Two-segment spill (
draining+active) instead of one append-only file: Lines 215–219 write all new records to one spill file and delete it only "when the file is fully confirmed". Over a slow recovery link, steady 30-second heartbeats appending to the tail can keep the reader from ever catching EOF and deleting the file. Rotating between two bounded segment files (spill.0,spill.1) lets the drained segment be unlinked cleanly while new records land in the active one. - Sink
--dirdisk bound and request size limit: Wrapping every CRI stdout/stderr line of chatty build/test jobs in OTLP JSON lines grows fast. Giveallmyram sinka bounded per-batch read limit and a configurable--max-bytes/ retention budget (or free-space floor) so an unattended sink cannot fillsmaug's disk. - Keep CRI log ship cursors out of
<StateDir>/runs/<runID>.json(line 207):Runner.updatewrites andfsyncs<runID>.jsonunderrunLock(runID)for run lifecycle transitions. Saving the shipper's byte position into<runID>.jsonon every confirmed batch creates heavyfsyncamplification and lock contention while a job streams output. Store shipper cursors in the shipper's own state (checkpointed periodically and on run end), and treatfs.ErrNotExiston a removed CRI log as "skip and clean cursor" so missing logs never wedge shipping.
4. Medium / Implementation Details: Warden Memory, Final Cgroup Read on Stop, and Darwin purego / Lima PID¶
Where: The heartbeat (lines 89–91), Per job (lines 141–153), The host and the VM, on a Mac (lines 181–198), Left open (line 280).
- Reading warden memory without idle RPCs, and choosing the right Go metric:
- On an idle Linux runner (zero active jobs),
Runnernever calls the warden — so polling Goruntime/metricsfrom the warden every 30s would require a new RPC (contradicting line 150, "no new operation"). Instead, on Linux read/sys/fs/cgroup/allmyram.slice/allmyram-warden.service/warden/memory.currentdirectly from the runner: zero RPCs, works when idle, and measures true kernel memory. - For the runner's own memory, avoid Go
runtime/metrics/memory/classes/total:bytes(which includes unbacked virtual arena address space, often 64–128 MiB on 64-bit Go for a <10 MiB RSS process). Use OS footprint/RSS (ri_phys_footprinton Darwin,/proc/self/statmVmRSS or/memory/classes/heap/objects:bytes+ stacks on Linux). - Final
memory.peakandusage_usecon cancelled/timed-out runs: Line 149 says the runner readsStatus"one last time before the cgroup is removed". Today, for cancelled or timed-out runs,warden.Stop(internal/warden/server.go:642–650) removes the pod and immediately callscgroup.RemoveinsidedoStopwithout returning stats. Return finalmemory.peakandcpu.statusage_usec(read betweenremovePodsandcgroup.Remove) inStopResponseso cancelled/timed-out runs don't lose their final peak/CPU numbers. - Darwin
mach_host_self()port leak underpurego(line 181): Unlikemach_task_self_, callingmach_host_self()allocates a new Mach port send right on every call. Cache the host port once (sync.OnceValue) or callmach_port_deallocateso a 30s heartbeat doesn't leak Mach port rights over weeks of uptime. - Answer for "Finding our VM's process" (lines 196–198, 280–282):
Lima writes its instance
hostagentPID to<LIMA_HOME>/<instance>/ha.pid(<StateDir>/lima/allmyram/ha.pid). WithvmType: vz,com.apple.Virtualization.VirtualMachineis either thathostagentprocess itself or its direct child (kp_eproc.e_ppid == haPIDviasysctlKERN_PROC_ALL/proc_listchildpids), giving exact ownership without name matching.