Metrics and the sink¶
Intent¶
Runners lend their idle memory and CPU to jobs. We want to know whether that hurts the machine's owner, whether it's worth it, and how much of the idle capacity we actually put to work. This design says what each runner measures, where the numbers come from on Linux and on a Mac, how they reach the tracker's sink, and how the sink joins the hoard.
It refines the tracker section of the design
and assumes the macOS runner of Plan 2 (wip/plan-2-macos-runner): the
runner runs natively on the Mac and owns one Lima VM in which containerd,
gVisor and the warden run.
Goals¶
- Answer, per runner and across the hoard:
- Is the runner alive?
- Is allmyram hurting the owner? (host memory pressure, CPU use)
- How many jobs ran in the last N hours, and how did they end?
- What did each job cost? (peak memory against its limit, GiB-minutes, core-minutes)
- What does allmyram itself cost? (runner, warden, shipper, the Mac's VM)
- How much of the hoardable memory and idle CPU did we use?
- Keep the shipper under about 10 MiB, as the design already requires.
- Build without cgo on both platforms.
- A sink that is one command to run and joins the hoard like any other member.
Non-goals¶
- Durable or guaranteed delivery. See the principle below.
- GPU metrics. They come with GPU jobs leaving beta.
- Tailcat path quality (direct or relayed). Tailscale's
clientmetriccounters are already in our binaries and could supply it later. - Admission refusals and preemption counts. They come with admission and preemption, which aren't built.
- The tracker UI.
Principle: anything can be interrupted¶
Gavin: "since any job can be interrupted anyway, nothing in our design has to care. If you need production workloads go find another system." Every job can be preempted, timed out or orphaned by a runner going away, so nothing in allmyram promises durability or delivery. We try hard to report every failure; when even that fails, the answer is "unknown" or "gone", never a false "passed". This design adds the principle to Principles.
Here it means a runner that crashes loses whatever telemetry it held in RAM and hadn't yet had confirmed. That is accepted, not defended against.
What a runner measures¶
Hoardable¶
Hoardable memory is the memory the owner isn't using: what is free now, plus what our jobs are using, minus the owner's reserve. Memory the owner's own programs and services use never counts.
- Linux:
MemAvailablefrom/proc/meminfo, plus 50% of the ZFS cache that can shrink, plus our jobs' memory thatMemAvailableleft out, minus the owner's reserve, and never more thanMemTotalminus the reserve. - The ZFS cache: ZFS never shrinks its cache below its floor, so only
size − c_min(both in/proc/spl/kstat/zfs/arcstats) can be given up. The 50% is runner config. Gavin: giving away the whole cache costs the owner disk speed; 50% is a starting point to adjust once smaug's numbers show how it behaves. - Our jobs:
MemAvailablealready counts reclaimable page cache, including the cache our jobs fill, so adding the jobs' wholememory.currentwould count that cache twice and let admission overcommit. Add only what can't be reclaimed:anon,shmem,kernelandsockfrommemory.stat, read once from the parent cgroup that holds every job cgroup (the kernel sums it). - Mac: to be defined together with admission on a Mac (see "Left open"). The memory parts are available as sysctls (below).
- Admission starts from the same number. A runner admits a job when hoardable memory, minus the limits of the jobs it is already running, covers the new job. This replaces the design's "On smaug, ZFS's cache counts as available": with two definitions, the headline would claim memory that admission would never lend, or the reverse.
Idle CPU is likewise the cores the owner isn't using: cores idle now plus the cores our jobs are using.
The heartbeat¶
The runner sends one heartbeat every 30 seconds (my call, runner config): one OTLP metrics message whose gauges share a timestamp, so the design's "heartbeats as just another metric" holds. Each carries:
- runner version, uptime and platform;
- host memory pressure, hoardable memory, and host CPU use;
- hoardable GiB-minutes and idle core-minutes since the last heartbeat: each sample times the time since the previous one, summed;
- the runner's own memory as the OS sees it (RSS on Linux,
ri_phys_footprinton a Mac), not Go'sruntime/metricstotal, which counts memory Go has mapped but already handed back. The shipper runs inside the runner process, so this includes it; - on Linux, the warden's memory:
memory.currentof its systemd service's cgroup, read by the runner directly, with no call to the warden. On a Mac the warden is inside the VM and the VM's footprint covers it; - the shipper's state: bytes buffered in RAM, bytes spilled to disk, the age of the oldest unconfirmed record, and records dropped at the spill cap;
- on a Mac: whether the VM is running, its host footprint, and its overhead: the footprint minus the memory of the jobs inside it. The raw footprint includes the jobs, so on its own it would make a 6 GiB job look like allmyram's own cost;
- the runs in progress: each run's current memory and CPU time, as gauges labeled with its run ID.
The heartbeat is also how the tracker knows the runner is alive. Only time the runner is up and awake counts toward hoardable GiB-minutes: a sleeping Mac mini lent nothing, and wasn't idle either.
The run-end record¶
When a run ends the runner sends one record:
- run ID, how it ended (exited, preempted, timed out, cancelled, runner restarted, gone) and the exit code;
- start and end times;
- peak memory and the job's memory limit;
- used GiB-minutes: the job's memory, sampled on every status poll, times the time since the previous poll, summed;
- reserved GiB-minutes: the memory limit times the run's wall-clock time;
- core-minutes: the job's total CPU time.
"How many jobs ran in N hours" is a count of these records over the window, broken down by runner or outcome as wanted. The gap between used and reserved GiB-minutes shows whether job limits are sized well.
The headline¶
Used GiB-hours ÷ hoardable GiB-hours, per runner and across the hoard: of the memory that sat idle, how much we put to work. Reserved ÷ hoardable says how full we kept the machine. Core-hours work the same way against idle core-hours. Expect the ratio to be low at first: a home server idles most of the day and jobs come in bursts, so the number mostly measures how much work there was to give it.
Where the numbers come from¶
Metrics are read at the outermost layer the owner pays for, and below it where that adds detail.
Per job, on both platforms¶
The job's cgroup is the boundary. The warden passes it as the pod's
cgroup_parent, so gVisor's Sentry and gofer run inside it, and its numbers
include the sandbox's own cost (#7 put the sandbox in the job's cgroup; #8
measured about 20 MiB per pod).
The runner already polls the warden's Status for each running job every
second, and Status already returns the cgroup's memory.peak, which the
runner currently ignores. Status gains two fields, read by
internal/cgroup:
memory.current, for used GiB-minutes;usage_usecfromcpu.stat, for core-minutes.
The runner keeps the latest values from each poll. A run that exits keeps
the values from its last poll. A cancelled or timed-out run ends through the
warden's Stop, which removes the cgroup straight after the pod
(internal/warden/server.go, doStop), so StopResponse gains the same
fields, read between removing the pod and removing the cgroup. The warden
gains a few file reads and no new operation. On a Mac the warden runs inside
the VM, and the runner already reaches it there, so per-job numbers work the
same way.
The cgroup counts page cache, so a job that writes many files peaks higher than its processes alone would.
The host, on Linux¶
Plain files, read by the runner with no new dependency:
- pressure:
/proc/pressure/memoryand/proc/pressure/cpu(PSI); - memory:
/proc/meminfo, and/proc/spl/kstat/zfs/arcstatson ZFS hosts; - CPU:
/proc/stat.
The host and the VM, on a Mac¶
The runner runs natively on the Mac, so it reads the Mac's own numbers. The
macOS build is CGO_ENABLED=0.
- Pressure: the sysctl
kern.memorystatus_vm_pressure_level, throughgolang.org/x/sys/unix. It reads 1, 2 or 4 for normal, warn and critical, the values ofDISPATCH_MEMORYPRESSURE_*in the SDK'sdispatch/source.h. The sysctl isn't in the public headers; we checked it by reading 2 while Activity Monitor's pressure graph was yellow. Preemption uses the same reader. - Memory: sysctls
hw.memsize,hw.pagesize,vm.page_free_count,vm.page_speculative_count,vm.page_pageable_internal_count,vm.page_pageable_external_count,vm.page_wired_count, andkern.memorystatus_level(percentage free; it matchedmemory_pressure -Qwithin two points). - CPU: the Mach call
host_statistics(HOST_CPU_LOAD_INFO). - The VM's host footprint:
ri_phys_footprintfromproc_pid_rusagefor the VM'scom.apple.Virtualization.VirtualMachineprocess: the number experiment #17 read with thefootprintcommand (791 MB idle, 2865 MB during a 2 GiB job and still 2865 MB 60 s after it). That the two report the same number is likely but untested; check it when building. It is what the Mac pays for the VM and everything in it; the heartbeat also reports it net of the jobs inside.
host_statistics and proc_pid_rusage are not in x/sys/unix. We call
them through github.com/ebitengine/purego, which loads libSystem functions
without cgo (Gavin approved it). gopsutil v4.26.10 makes both calls the same
way (internal/common/common_darwin.go) and is the reference; we don't
depend on gopsutil, which doesn't expose the footprint and is a large
cross-platform package for two calls. host_statistics takes the port from
mach_host_self(), and each call to that hands out a new port right, so the
runner gets it once and keeps it; calling it every heartbeat would leak a
right every 30 seconds.
The runner must find its own VM's process, never match by name, because
the owner may run other Virtualization.framework VMs. Its parent PID doesn't
help: launchd starts Virtualization's XPC services, so on this Mac both
running com.apple.Virtualization.VirtualMachine processes have parent PID
1 (see "Left open").
Shipping¶
The sink dials the runners; runners never dial it. Once the tailcat connection is up, the roles turn around: the runner speaks HTTP as the client on that connection and sends to the sink as an ordinary OTLP exporter would. Gavin chose the direction: there are fewer sinks than runners, and in tailcat the side that dials is a separate client node with its own WireGuard engine. With the sink dialing, only the few sinks run client engines, and runners stay tailcat servers with the one key and engine they already have. With runners dialing, every runner would run a second engine, and the sink would need every runner's key. One client key shared by all of a sink's connections is safe (Gavin), as the laptop already does with its one key.
The design's shipper reads the runner's log files in small batches. This changes it for telemetry: records go straight from RAM while the sink keeps up, and touch disk only when it falls behind. A runner with no sink (no sink record, see "Joining the hoard") keeps no telemetry at all.
- Job output is already on disk: containerd writes each job's CRI log file whether we ship it or not. The shipper keeps a read position in that file and sends the output in batches of up to 1000 records or 1 MiB, or as much as it has read when it reaches the end of the file, one batch at a time per run, so the output stays in order. The position moves past a batch once the sink confirms it, or rejects it for good. On a good network it stays just behind the newest line, which is still in the page cache. The shipper keeps the positions in its own state file, written every few seconds and when a run ends, not in the run's record, which the runner fsyncs on every change under the run's lock. A restarted runner resumes from the last saved position and resends a few lines at most. A log file that has gone means that run's output is skipped and its position dropped.
- Metrics and the runner's own logs share one bounded RAM buffer.
- RAM mode: records append to the buffer and go to the sink in batches; a record leaves the buffer when the sink confirms it.
- Spill: when the buffer passes a threshold (my call: 1 MiB, or a record still unconfirmed 30 seconds after it was added, which on a LAN means the sink is badly behind or not connected), the buffer is written to a spill file, and every new record goes to the spill too, so records stay in order.
- Two spill files: new records go to one while the shipper drains the other. When the draining file is fully confirmed it is deleted and the two swap. With one file, a steady trickle of heartbeats onto its end could keep the drain from ever reaching the end and deleting it.
- Drain: when both spill files are empty, the shipper returns to RAM mode.
- Cap: the spill files together hold at most 64 MiB (my call, runner config, at least 2 MiB). Past that the oldest records are dropped and counted, and the count goes in the next heartbeat. A sink that is gone for days costs the owner 64 MiB of disk, never more. Job output needs no cap: it is containerd's file, kept as long as the run's logs are. A buffer that can't be opened at start turns telemetry off, with an error in the log; the runner still takes jobs.
- The sink's confirmations drive the spill: a growing buffer is the signal that the sink can't keep up. They are not there to prevent loss; a crash loses what is in RAM (see the principle above).
- Records are OTLP, built from
go.opentelemetry.io/proto/otlp's generated types, not the OpenTelemetry SDK: a few gauges sampled every 30 seconds need no aggregation pipeline, and building the messages directly keeps memory flat.
On the wire¶
OTLP over HTTP, as the OTLP specification (1.11.1) defines it, on a tailcat connection the sink opened:
- The sink dials, the runner sends. The runner serves a telemetry port
(my call: 4318, OTLP/HTTP's port) on its existing tailcat server,
beside SSH.
transport.Listenserves onlySSHPorttoday; it gains the second port and returns the server, so the runner can allow the sink's key and read peer keys. When the sink's connection arrives, the runner makes it the one connection its HTTP client uses: anhttp.TransportwhoseDialContexthands back that connection. The sink, having dialed, serves HTTP on it:http.Server.Serveover a listener that yields that one connection. Both are the standard library;x/net/http2'sNewClientConn, its direct API for this, is deprecated. A newer connection from the sink replaces an older one. While no sink is connected, records wait in the buffer and then the spill, as above, and the shipper waits for the sink's connection rather than retrying on a timer. - h2c: HTTP/2 without TLS, since tailcat already encrypts. The OTLP
specification allows HTTP/2. Go's standard library has it
(
Protocols.SetUnencryptedHTTP2, Go 1.24 and later), and every Go binary usingnet/httpalready contains the HTTP/2 code, so it costs no binary size. One connection carries logs and metrics side by side, so a heartbeat never waits behind a large log batch, andSendPingTimeoutnotices a dead tailcat path, which is a reason to spill. The sink caps its per-connection buffers throughhttp.HTTP2Config(MaxReceiveBufferPerConnectionand friends). - Binary protobuf bodies (
application/x-protobuf). Job output makes logs most of the volume, and OTLP's JSON encoding wraps every line in repeated field names and escapes control characters (a terminal colour code becomes six bytes). Protobuf keeps the wire small whatever a job prints. - One endpoint per kind, as OTLP defines them:
POST /v1/logsandPOST /v1/metrics. An OTLP request carries one kind only. Job output is logs, with the run ID as an attribute. The shipper's buffer holds tagged records and each batch takes one kind; order between logs and metrics doesn't matter, since every record carries its own timestamp. - Confirmation is the
200. The sink replies only after it has appended the batch. 429, 502, 503 and 504 mean "later" (honouringRetry-After); any other error means the batch is malformed or too big, and the shipper drops it. It logs the first of a run of such rejections, not each one, so a sink rejecting everything doesn't flood the runner's journal. - Authentication is tailcat's, not SSH's. Shipping bounded telemetry is nowhere near running code, and tailcat (the pre-shared key in the runner's address, the runner's key, the sink's node key) is already mutual WireGuard authentication, so there is no TLS and no SSH certificate on this path. Each side knows who the other is from the dial itself:
- The sink dialed a runner's address from its runner list, so the runner's own server key proves which runner is on the other end. The sink labels everything arriving on that connection with that runner's name.
- The runner adds the sink's node key from its owner-signed sink record
to its tailcat server's allowed clients, and the telemetry port accepts
a connection only from a peer whose node key (
Server.PeerEnv'sTAILCAT_PEER_KEY) is that key. The check is in the runner's code, not only in tailcat, because tailcat can add an allowed key at run time but not remove one: a sink moved or retired would otherwise stay allowed until the runner restarts. Allowing the sink's key also lets the sink open the runner's SSH port, where it gets nowhere: SSH requires an owner-signed client certificate, and the sink has none.
The sink¶
allmyram sink --dir <path> is a mode of the same binary. It dials every
runner in its runner list, accepts what they send, converts each batch from
protobuf to OTLP's JSON encoding, and appends it as lines to time-rotated
files in that directory: logs and metrics in separate files
(logs-*.jsonl, metrics-*.jsonl), since they have different shapes and
DuckDB queries one shape more simply than a mix. Batches are small and
bounded, so the conversion costs the sink CPU, not memory. It does nothing
else. It is always on, on a machine such as smaug.
- One connection per runner. A runner that can't be reached is retried with backoff; its records wait on the runner, in RAM and then spill. So is a runner that closes the connection before any request, as one whose sink record names another sink does; the sink warns about that once per runner. A sink that has been removed keeps dialing until it is stopped.
- Bounded requests: the sink reads at most a fixed size per batch
(my call: 4 MiB) and answers larger ones with
413, as OTLP specifies. - Bounded disk: files older than the retention period (the design's
"30 days, say") are deleted, and so are the oldest files once the
directory passes a size budget (
--max-bytes), so an unattended sink can't fill its machine's disk. - OTLP's JSON differs from Go's standard protobuf JSON: enums are integers and trace and span IDs are hex, not base64. Tests check the sink's output against the OTLP specification's rules.
Joining the hoard¶
The sink is its own role (Gavin), joining through join by invite like a runner does. The session that built join by invite confirmed none of this conflicts with what's built. The sink needs:
- A sink kind in
inviteandjoin. It gets a host certificate with its name, as a runner does, and its role. Every host certificate has arole@allmyramextension, andCheckHostCertrefuses one whose role is missing or differs from the one it expects, so a sink's certificate never passes as a runner's or the reverse.RoleRunneris the only role so far; the sink addsRoleSinkininternal/trust/daykey.go. - Two tailcat keys on the sink: a server key, so the laptop can reach
the sink's
sshsrv, and a client key, for dialing runners. The sink creates both at join. This is the one place a member needs two, and there are only ever a few sinks. - The sink runs
sshsrvfor the laptop, like a runner, and nobody else uses it. Over it the laptop renews the sink's 30-day host certificate, syncs revocations, and pushes the runner list (below). The laptop connects to the sink when a runner joins or is removed, when it pushes revocations (allmyram revoke,allmyram rotate-client-key), and onallmyram sync-sink; each connection renews the certificate when it has under 10 days left, as for runners, andallmyram renewrenews one that has expired. Without renewal the sink's certificate would lapse on day 30. - An owner-signed sink record: the time it was signed (unix seconds)
and the sink's tailcat client node key, or no key to mean "no sink":
stop keeping telemetry and delete the spill files. The laptop learns the
key when the sink joins, signs the record once when the sink joins,
moves or is retired (one Touch ID prompt), keeps it, and hands it to
each runner every time it connects, with no further prompts. The join
exchange is unchanged for runners: once a runner has joined,
invitewaits for its service to answer (up to 2 minutes) and hands it the record, so the sink can collect from it at once; a runner that doesn't answer in time gets it on the laptop's next connection. A runner keeps only a record signed later than the one it has, in its state directory beside the host certificate and revocations. A runner that rejoins under another owner deletes its record and the telemetry it kept, which must never reach the new owner's sink. A record that doesn't verify is set aside with a warning: the runner starts without a sink rather than not at all. The signing time orders records, not a counter kept on the laptop: restoring~/.config/allmyramfrom a backup moves a counter backwards, after which the laptop either signs records runners refuse or reuses a number for a different key. The clock doesn't go back on a restore. (Join by invite hit the same problem with revocations.) Root-owned/etc/allmyram/trust.jsonis untouched. The trust sync ininternal/sshsrv/trust.gocarries only revocations today, so this needs a new signed statement with its own domain tag ininternal/trust/signed.go, a way to deliver it, and a file and loader for it on the runner. This record is the one thing besides a join that adds a key to a runner's inbound allow list, and it is owner-signed. - The runner list on the sink: each runner's name and tailcat address,
which the laptop already holds for every runner it joined. The laptop
pushes the whole list over the sink's
sshsrvwhenever it changes: a runner joins or is removed. Only the sink the laptop's sink record names gets it. The sink applies it at once, dialing new runners and closing its connections to removed ones. A newly joined sink's service starts after its join, soinvite --sinkwaits for it (up to 2 minutes) to push the list; if the sink doesn't answer in time, invite warns, saying to runallmyram sync-sink, and still exits 0, since the sink joined.
Changes to other documents¶
- Principles: add "Anything can be interrupted", and change the "Spend the memory on jobs" bullet about the shipper to describe the RAM buffer that spills to disk.
- Design, tracker section: the shipper holds a bounded RAM buffer and spills to files past it; metrics are the ones listed here; the sink is its own role. Memory admission: "ZFS's cache counts as available" becomes the hoardable rule above. These edits wait for Plan 2's changes to the same file to merge, to avoid a conflict.
- Plan 2's to fix: the design's admission overhead of "~300 MB per macOS VM" predates the Lima VM; #17 measured 791 MB idle.
Left open¶
- Hoardable memory on a Mac, decided together with Mac admission: which of the page counts (free, speculative, file-backed) count, and whether compressed or swapped memory changes the answer.
- Finding our VM's process among others on the Mac. Parent PID doesn't work (launchd is the parent). Something Lima records, or the process's open files or arguments naming our instance, may. Not yet checked. Plan 2 owns this.
- Per-job memory pressure (
memory.pressurein the job's cgroup): cheap to add toStatusif it turns out to be useful. - Splitting host CPU into the owner's share and ours.