Skip to content

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), and main (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:

MemAvailable + 0.5 * zfs_arc_size + sum(job_cgroups.memory.current) - reserve
and line 70 uses that same number as the admission budget (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:

  1. Sink's 30-day host certificate has no renewal path: Host certificates in internal/trust/verify.go expire after 30 days (HostLifetime = 30 * 24 * time.Hour). Runners get renewed automatically when the laptop connects over SSH (< 10d left) or via allmyram renew <name>. If the sink does not accept SSH from the laptop for renewal (and sit in the laptop's config for renew), every runner in the hoard will reject the sink's expired certificate on day 30.
  2. 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 call Server.AddAllowedClient(nodeKey) at runtime and admit that runner's host key. Also specify which tailcat key a runner dials the sink with (its serverKeyFile.Private in tailcat-key.json, since transport.Dial currently expects a clientKeyFile).
  3. 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 HostCert verification against the owner.pub -> day-key chain. Plain HTTP or gRPC on a raw tailcat TCP connection never exchanges or checks OpenSSH certificates.
  4. Cleanest fix — run sshsrv on the sink over tailcat (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" (CheckHostCert inside ServerConfig.PublicKeyCallback, which golang.org/x/crypto/ssh's server userauth supports directly): serves only ship (framed OTLP batches + per-batch confirmation ACKs over the SSH channel, with no HTTP/gRPC server needed).
  5. Mutual role exclusion in CheckHostCert: Today trust.CheckHostCert (internal/trust/verify.go:135) checks only CertType == ssh.HostCert and ValidPrincipals containing Name. If "marked as a sink" (line 243) were implemented as an extension that only sink-dialers checked, a sink's HostCert would also pass CheckHostCert as 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>").
  6. 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 monotonic uint64 version/timestamp:
  7. 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).
  8. Support a signed "no sink" / disabled payload at version N+1 so 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).

  1. 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_records counter shipped on the next heartbeat.
  2. 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.
  3. Sink --dir disk bound and request size limit: Wrapping every CRI stdout/stderr line of chatty build/test jobs in OTLP JSON lines grows fast. Give allmyram sink a bounded per-batch read limit and a configurable --max-bytes / retention budget (or free-space floor) so an unattended sink cannot fill smaug's disk.
  4. Keep CRI log ship cursors out of <StateDir>/runs/<runID>.json (line 207): Runner.update writes and fsyncs <runID>.json under runLock(runID) for run lifecycle transitions. Saving the shipper's byte position into <runID>.json on every confirmed batch creates heavy fsync amplification and lock contention while a job streams output. Store shipper cursors in the shipper's own state (checkpointed periodically and on run end), and treat fs.ErrNotExist on 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).

  1. Reading warden memory without idle RPCs, and choosing the right Go metric:
  2. On an idle Linux runner (zero active jobs), Runner never calls the warden — so polling Go runtime/metrics from 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.current directly from the runner: zero RPCs, works when idle, and measures true kernel memory.
  3. 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_footprint on Darwin, /proc/self/statm VmRSS or /memory/classes/heap/objects:bytes + stacks on Linux).
  4. Final memory.peak and usage_usec on cancelled/timed-out runs: Line 149 says the runner reads Status "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 calls cgroup.Remove inside doStop without returning stats. Return final memory.peak and cpu.stat usage_usec (read between removePods and cgroup.Remove) in StopResponse so cancelled/timed-out runs don't lose their final peak/CPU numbers.
  5. Darwin mach_host_self() port leak under purego (line 181): Unlike mach_task_self_, calling mach_host_self() allocates a new Mach port send right on every call. Cache the host port once (sync.OnceValue) or call mach_port_deallocate so a 30s heartbeat doesn't leak Mach port rights over weeks of uptime.
  6. Answer for "Finding our VM's process" (lines 196–198, 280–282): Lima writes its instance hostagent PID to <LIMA_HOME>/<instance>/ha.pid (<StateDir>/lima/allmyram/ha.pid). With vmType: vz, com.apple.Virtualization.VirtualMachine is either that hostagent process itself or its direct child (kp_eproc.e_ppid == haPID via sysctl KERN_PROC_ALL / proc_listchildpids), giving exact ownership without name matching.