Skip to content

feat(sbx): a host resource sampler, one JSON line every 15 s (#857 R2) - #904

Merged
pdettori merged 6 commits into
rossoctl:mainfrom
webchang:pr/i857-sbx-sampler
Nov 19, 2026
Merged

pdettori merged 6 commits into
rossoctl:mainfrom
webchang:pr/i857-sbx-sampler

Conversation

@webchang

Copy link
Copy Markdown
Member

Part of #857 (R2): a host resource sampler for sandbox-service KVM hosts, one JSON line in the journal every 15 s, and the same fields in status.sh --host

What changed and why

R2 asks that an operator can answer "how loaded was the host?" for any time in the retention window with one query. Until now nothing sampled a KVM host's CPU, memory, pressure or disk I/O, and the worker's /stats (opt-in via SH_DIAG_STATS_ADDR) was read by nothing.

  • deploy/sbx/sampler.sh (installed as /usr/local/libexec/sbx-sampler.sh) prints one {"sampler":"sample",…} line per run, in the janitor summary's style:
    • host: load (1/5/15 min), mem_kb (MemTotal, MemAvailable, SwapTotal, SwapFree, swap used), psi (cpu, memory, io: some and full, avg10 and avg60), workspaces (bytes and inodes of the filesystem holding $SBX_SRV/workspaces);
    • slice: the sbx.slice cgroup's cpu.stat (usage_usec, nr_throttled, throttled_usec), memory.current, memory.peak (null before Linux 5.19) and io.stat summed over devices;
    • workers, one per installed worker: vms, the VM cgroups in its slice that hold a process (the names vmpool makes: pool-<n>, vm-<n>, vm-vm-<n>.scope; the unit's own cgroup never counts), the slice's memory_current, budget_mb and reserve_mb (SH_MAX_COMMITTED_MB, SH_MEMORY_RESERVE_MB), and stats: committedBytes, standbyCommittedBytes and refusals from the worker's /stats, or null without SH_DIAG_STATS_ADDR. Those settings come from the running worker's /proc/<pid>/environ (so a drop-in's SH_DIAG_STATS_ADDR counts, and an install rewrites the env file anyway), else from its env file.
    • It reads /proc and cgroup files with bash builtins. The only programs it starts are df twice (under timeout 5) and one curl --max-time 1 per worker with /stats. It needs no jq, so a worker host needs nothing new. Every value is checked as a number and is null when it cannot be read. It always exits 0.
    • No journal flood. Each failure kind (loadavg, meminfo, psi, workspaces, slice, workers, curl, worker:<id>, stats:<id>) gets at most one {"sampler":"error","kind","why"} line per run. With the unit's preserved RuntimeDirectory, it gets only one when it starts failing, and one {"sampler":"recovered","kind"} line when it reads again. Every sample's errors names the kinds failing in it, so a lasting failure, for example a kernel without PSI, is one line rather than one every 15 s.
  • sbx-sampler.service + sbx-sampler.timer. The service is a oneshot with TimeoutStartSec=10s, Nice=10, ProtectSystem=strict and read-only kernel tunables and cgroups. It sets SyslogLevel=notice with LogLevelMax=notice, so systemd's own info lines about each run (started, finished, CPU consumed) stay out of the journal. The timer uses OnUnitActiveSec=15s with AccuracySec=1s (the default accuracy is a minute).
  • install-host.sh installs the sampler with every worker install, not behind a flag of its own like --janitor. The sampler needs no bundle and no secret, and it measures the workers, so every host that has a worker samples from its first install on, with no extra step to forget. Its three files are their own manifest kind, sampler <path>, and are shared like the template unit: one of two uninstalls keeps them, --keep-shared keeps them (so a host agent's retire of a build never stops the sampling), and the last plain --uninstall disables the timer, cleans the runtime directory and removes them. SBX_SAMPLER_INTERVAL_S (default 15, 5-3600) sets the interval; 0 installs none and removes an installed one. A bad value is refused before anything is touched. As with the read-ahead, a problem installing the sampler is a warning, never a failed worker install.
  • status.sh --host adds unit sbx-sampler.timer: … and host sample: <the sampler's line>, with a host sample error: … line before it for each failing kind. It runs the installed sampler, or else sampler.sh beside the script in a checkout, without the state directory. The one-shot view and the journal series come from one code path, and the host side piped over ssh still needs no checkout. The existing lines are unchanged.
  • Docs. The deploy/sbx README covers the sampler beside the read-ahead, and the last uninstall now removes it. The runbook gets a new section, "The host sampler": the fields, how errors are reported, journalctl -u sbx-sampler -o cat … | jq queries (a point in time, and sbx.slice CPU in cores between samples), how to turn on SH_DIAG_STATS_ADDR for one worker with a drop-in, and how to measure its cost. The runbook also gets the sampler in §8's host output and in §12, its journal volume under "What is kept", and step 4 of "Reproducing a member's issue" now pulls the window's samples. docs/reference/configuration.md lists SBX_SAMPLER_INTERVAL_S.

Tests

  • New deploy/sbx/tests/sampler.test.sh runs on a fake /proc and cgroup tree (SBX_SYS_ROOT, the host agent's seam), with df, curl and timeout mocked and PATH holding only the mocks, so it also proves the sampler runs nothing else. It checks:
    • every field against the fixtures, exactly one line on a clean host, and no stderr;
    • the VM count, which skips emptied pools, the unit's own cgroup and stray directories, and reads a cgroup with no cgroup.events by its cgroup.procs;
    • wildcard /stats addresses read on loopback, and a running worker's environment winning over its env file;
    • one error line per kind (two missing PSI files make one psi line), named in the sample's errors;
    • garbage or missing files give nulls, every line is valid JSON, a quote in a path is escaped, and the exit is 0;
    • with a state directory, a lasting failure is one error line over four runs, a new kind beside it is one more, and the end of each is one recovered line; without a usable state directory, every run reports;
    • nothing is written outside the state directory;
    • the unit files' settings.
  • install-host.test.sh:
    • refuses bad SBX_SAMPLER_INTERVAL_S values before systemd or any file is touched;
    • a worker install writes the 0755 script and both units with this host's paths, records sampler lines (not unit lines), and enables and restarts the timer before the worker restart;
    • the installed sampler runs from its unit's environment;
    • a re-run with 60 re-arms the timer and records nothing twice;
    • one of two uninstalls and --keep-shared keep the sampler, and the plain last uninstall disables, cleans and removes it, leaving the manifest empty;
    • 0 removes an installed sampler and on a clean host never touches its units.
  • status.test.sh:
    • one host sample line with the fixture's fields and the timer's unit state;
    • an error line per failing kind, and never the timer's state directory;
    • "unavailable" when no sampler exists;
    • over ssh (bash -s), the installed sampler runs.
  • Mutation checks on the sampler test each failed it: reporting a lasting failure every run, counting every populated child as a VM, and dropping the one-line-per-kind guard.
  • Ran bash deploy/sbx/tests/*.test.sh (all pass), shellcheck -x -S warning over deploy/ and scripts/, prettier --check on the changed Markdown, python3 scripts/check-doc-links.py and scripts/check-docs-publish.sh.

Overhead

The epic's target is under 1% of one core. Local numbers, on a developer machine (macOS, where fork and exec cost more than on Linux) with a fake tree of 4 workers with 8 VM cgroups each, 200 runs, CPU time of the runs (user + sys):

  • without /stats: about 35 ms of CPU per run, so 0.23% of one core at the 15 s interval;
  • with /stats on all 4 workers (a local HTTP server standing in for each worker): about 66 ms per run, 0.44% of one core.

On a KVM host (one template worker installed, idle; the installed script under its own unit, systemd-run --wait -p CPUAccounting=yes five times and GNU time -v three times): 11.5-14 ms CPU per run, 0.08-0.09 % of one core at the 15 s interval, about 3.2 MB peak RSS, about 954 bytes per sample in the journal, and no error or per-run systemd lines over 600 s. Under load (one sandbox created, one command run, then deleted), every sample stayed valid, workers[].vms followed the run's standby pool (0 before the run's first Exec, 2 between Execs, 0 again about 107 s after the delete), and the command showed as about 1 s of sbx.slice CPU between two samples.

The cadence is every 15-16 s in practice (38 samples in 600 s), since AccuracySec=1s lets systemd defer each elapse up to 1 s; the docs say so (2c22a56).

Out of scope

  • Shipping and retention (R1): the lines go to the host journal, and the pipeline R1 chooses ships them.
  • A Prometheus exporter: the Decision allows one to replace this timer with the same fields, if R1 picks Prometheus.
  • Turning on SH_DIAG_STATS_ADDR by default: it stays the operator's opt-in; the runbook shows the drop-in.
  • Per-VM figures beyond the count: the per-worker slice's memory.current and the worker's /stats cover budget use. A per-VM breakdown would read every VM cgroup every 15 s.

Every commit is signed off (DCO).

Assisted-By: Claude Code

…l#857 R2)

Nothing sampled a sandbox-service KVM host's CPU, memory, pressure or
disk I/O, so "how loaded was the host?" had no answer after the fact.

deploy/sbx/sampler.sh, run by sbx-sampler.timer (OnUnitActiveSec=15s,
AccuracySec=1s), writes one JSON line per sample to the journal: load,
memory and swap, PSI (cpu/memory/io), workspace bytes and inodes, the
sbx.slice cgroup's cpu.stat, memory.current/peak and io.stat, and per
worker its VMs (populated vmpool cgroups), slice memory, budget and,
with SH_DIAG_STATS_ADDR, committedBytes/standbyCommittedBytes/refusals
from /stats. It reads /proc and cgroup files with builtins, starts only
df and curl, needs no jq, and always exits 0. A failure kind is one
error line when it starts and one recovered line when it ends (state in
the unit's preserved RuntimeDirectory); every sample names the kinds
failing in it. The unit logs at notice with LogLevelMax=notice, so
systemd's per-run lines stay out of the journal.

install-host.sh installs it with every worker install (no bundle or
secret, so no flag of its own) as the shared manifest kind `sampler`:
--keep-shared keeps it, the last plain --uninstall removes it, and
SBX_SAMPLER_INTERVAL_S (5-3600, 0 = none) sets the interval.
status.sh --host prints the same line once, from the same script.
Docs: README, the runbook's new "The host sampler" section and step 4
of "Reproducing a member's issue", configuration.md.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
Review follow-up: stats() curled whatever host SH_DIAG_STATS_ADDR named
and only mapped the wildcard addresses to loopback. It now reads a
wildcard on loopback and refuses any address that is neither loopback
(127.*, [::1], localhost) nor a wildcard, with one error line, so the
sampler only ever reads this host's own workers. Tested; the header and
the RUNBOOK say so.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
Review follow-up: `127.*` was a glob and the host may hold letters, so a
name like 127.example.com matched and would have been resolved through
DNS. 127.0.0.0/8 is now matched as four numeric octets; tests refuse
127.example.com and read 127.0.0.2.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
Measured on a KVM host: the timer's AccuracySec=1s lets systemd defer each
elapse up to 1 s, so the default 15 s series runs every 15-16 s (38
samples in 600 s). The RUNBOOK and the timer's comment say so; the
interval itself is unchanged.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 18, 2026

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A well-scoped sampler. It reads only /proc and cgroup files, validates every value as a number, escapes strings, and caps errors at one line per kind. The install and uninstall paths follow the read-ahead and janitor patterns (manifest kind, --keep-shared, interval validation, plain-path check before the unit sed), and the /stats fetch is loopback-only with --noproxy. No blocking issues; the three inline comments are non-blocking.

Author: webchang (MEMBER). Commits: 4, all signed off. CI: all checks passing. No .claude/.vscode changes.

Comment thread deploy/sbx/sampler.sh Outdated
df_line() {
local -a t=()
command -v timeout >/dev/null && t=(timeout 5)
printf -v "$1" '%s' "$("${t[@]}" df -P "$2" -- "$SBX_SRV/workspaces" 2>/dev/null | { read -r _; read -r l; printf '%s' "${l:-}"; })"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: the worst case of the two timeout 5 df calls is 10 s, which equals TimeoutStartSec=10s. On a hung workspace filesystem systemd kills the unit, so there is no sample, and it logs a failure at warning level every 15 s. That is the journal flood the header says this script avoids ("always exits 0"). Consider timeout 3 for each df, or skip the inode df when the byte df timed out, so a hang still ends in a sample with workspaces null plus an error line.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bf0cfc9: each df runs under timeout -k 1 3, and the inode call is skipped after a byte call that did not answer, so a hung filesystem costs one 3-4 s bound and still ends in a sample with workspaces null and one error line. sampler.test.sh covers it with a df that never answers under the real timeout (about 3 s, one call; the previous version took the full 10 s).

Comment thread deploy/sbx/install-host.sh Outdated
systemctl daemon-reload
# enable, then restart rather than enable --now: a re-install with another interval must re-arm
# a timer that is already running.
systemctl enable sbx-sampler.timer

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: the PR text and the install_sampler comment say a sampler problem is "never a failed worker install". Only the precondition checks warn and return. install -d, install -m, systemctl daemon-reload, systemctl enable and systemctl restart run under set -e, so a failure aborts before install_worker. install_read_ahead behaves the same way. Either guard these with || { echo WARNING...; return 0; } or soften the wording.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c324259: every step of the sampler's install is now checked, and the first one that fails is a WARNING naming it while the worker install goes on; the files are recorded in the manifest first, so an uninstall cleans up after a partial install. Tested with a failing enable, a failing restart and an unwritable unit file. install_read_ahead is unchanged here, and the comment no longer claims the sampler behaves the same way.

Comment thread deploy/sbx/sampler.sh Outdated
# (SH_DIAG_STATS_ADDR is set in one, as the env file is rewritten by every install). Its main
# process is the first in the unit's cgroup (Type=simple: microvm-worker itself).
pid=''
read1 pid "$CG/sbx.slice/sbx-$id.slice/sbx-worker@$id.service/cgroup.procs" || pid=''

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the kernel doesn't guarantee that the first line of cgroup.procs is the unit's main process (pid wraparound, for example). A child such as the jailer could then supply /proc/<pid>/environ, and budget_mb and stats would silently fall back to the env file. Children mostly inherit the worker's env, so the impact is small. A softer comment, or a check that /proc/<pid>/comm is microvm-worker, would be more honest.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bf0cfc9: the worker is now the pid in its unit's cgroup.procs whose /proc/<pid>/comm is microvm-worker (no fork per worker, unlike systemctl show -p MainPID), falling back to the env file alone. Tested with a jailer listed first and with no such process.

The comment and the PR said so, but only the precondition checks
warned: install -d, install -m, the unit file writes, daemon-reload,
enable and restart ran under set -e, so any of them aborted the
install before the worker started (review on rossoctl#904).

install_sampler_steps checks each step and returns at the first that
fails, naming it; install_sampler turns that into a WARNING and the
worker install goes on. The three files are recorded in the manifest
first, so an uninstall removes whatever a failed step left. Tested: a
failing enable or restart of the timer, and a unit file it cannot
write, warn with the step, the worker still starts and attaches, and
the uninstall leaves no sampler file or line.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
…m; the worker pid by comm

Two review points on rossoctl#904:

- Two `timeout 5 df` calls could take 10 s, the unit's whole
  TimeoutStartSec, so a hung workspace filesystem got the unit killed
  every 15 s with a warning-level failure and no sample. Each df now
  runs under `timeout -k 1 3`, and the inode call is skipped after a
  byte call that did not answer: a hang costs one 3-4 s bound and ends
  in a sample with workspaces null and one error line. Tested with a
  df that never answers under the real timeout (about 3 s, one call);
  the previous version took 10 s on it.
- The kernel does not order cgroup.procs, so its first line could be a
  helper whose environment would stand in for the worker's. The worker
  is now the pid there whose /proc/<pid>/comm is microvm-worker (no
  fork, unlike systemctl show -p MainPID), else the env file alone.
  Tested with a helper listed first, and with no such process.

Part of rossoctl#857

Assisted-By: Claude Code
Signed-off-by: Rong Chang <[email protected]>
@webchang

Copy link
Copy Markdown
Member Author

@pdettori, thanks: all three points are fixed in c324259 and bf0cfc9 (replies inline). Since they came after your approval, a quick look before merge would be welcome.

@pdettori
pdettori merged commit 93c6f43 into rossoctl:main Nov 19, 2026
17 checks passed
webchang added a commit to webchang/moca that referenced this pull request Nov 19, 2026
Brings 15 upstream merges since 2eb0219, among them the R2 host sampler
in its reviewed form (rossoctl#904), the workspace-reset marker (rossoctl#895), turn
budgets and cancel (rossoctl#856), the egress allow-all option (rossoctl#886), the sbx
installer token (rossoctl#888), and the docs site with the product-name prose
(rossoctl#884, rossoctl#885, rossoctl#899).

One conflict, deploy/sbx/template-onboarding/README.md: upstream's
product-name wording for the deploy/sbx table, keeping the fork's
mint-login.sh row.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@pdettori pdettori added this to the v0.11.0 milestone Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants