# Performance checks [`perf/run.py`](../perf/run.py) runs daemon scenarios against recorded provider responses and produces measurements and comparison results. The runner measures memory, HTTP traffic, and disk writes. These checks describe the test workload, not production performance. ## Commands A full replay requires Linux `/proc` and derives gates. The default is five repetitions per scenario. Repetitions are concurrent unless `--jobs` limits them, except the kernel cell-growth scenario, which runs one repetition at a time to avoid contention causing a model wait to release its measured kernel. ```sh nix develop -c python3 perf/run.py --mode replay --runs 5 --out /tmp/perf/results.json nix develop -c python3 perf/compare.py /tmp/perf/results.json --baseline /tmp/perf/baseline.json ``` Use `--scenario NAME` to reproduce the gates for one workload. Repeat the flag to combine workloads. The two peak gates require `chat`, `coding`, and `long` together. `agents` supplies diagnostic observations. Pass the same baseline JSON to reproduce historical comparisons. Record mode requires `--runs 1` and `--url`. It records responses instead of measuring. [`run.py`](../perf/run.py) defines the arguments and exit status. [`scenarios.py`](../perf/scenarios.py) defines the workloads. ## Measurements [`measurement.py`](../perf/measurement.py) discovers the daemon process tree, samples memory and write counters, and gathers BEAM checkpoints. Kernel and process measurements depend on Linux process information. [`transport.py`](../perf/transport.py) proxies daemon and provider traffic and tracks request and response bytes. The recordings replay response bytes, not upstream packet timing. Replay compares request digests with the recording and reports stale turns. A completed scenario also checks for unused recorded responses. A missing or surplus response fails replay. See `request_digests` and `Recordings` in [`transport.py`](../perf/transport.py). ## Metric definitions [`run.py`](../perf/run.py) derives the metric families below. [`budgets.toml`](../perf/budgets.toml) defines each gate, its unit, ceiling, and tolerance floor. Keep workload and calibration rationale with those entries. | Family | Meaning and interpretation | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Repeated samples | `summary` reports the median and median absolute deviation, or MAD. A single sample cannot estimate noise. | | BEAM retained memory | `beam_kept` subtracts unused process-heap space and binaries not referenced by a process from major-GC total memory. It is not process RSS or USS. | | Growth | `robust_slope` uses the median of pairwise slopes for retained BEAM growth. Process-memory and kernel-cell growth use least squares. Turn and kernel-cell metrics omit their configured warm-up region. Warm-up retention is reported separately. | | Linux process memory | `measurement.tree` reads PSS and private-memory counters from `smaps_rollup`. Anonymous PSS and the private estimate include `SwapPss`, so swapping does not make owned memory disappear. This is not plain resident USS. | | Kernel and pool memory | Kernel startup, retained cell growth, fork sharing, and pool observations have different scopes. Use the named gate's definition rather than summing tiles. Some pool comparisons are diagnostic rather than gated. | | Physical disk writes | `measurement.Writes` totals `write_bytes` minus `cancelled_write_bytes` over the tracked process tree. Reaped child counters and last observations account for exited processes. | | Per-file write activity | The preloaded write shim records bytes returned by intercepted write calls. It misses some writes and measures calls rather than physical page writeback. It identifies files, not an additive breakdown of physical disk totals. | | Disk windows | `write_window` applies workload-specific windows. Long-run disk gates exclude warm-up, and per-turn physical writes use a median because WAL checkpoints are lumpy. Other reports can exclude database backfill when measuring append growth. | | HTTP bytes | [`transport.py`](../perf/transport.py) counts request and response bytes through the local proxy. Replay preserves response bytes, not provider latency or upstream packet timing. | The [scenario definitions](../perf/scenarios.py) set warm-up and scaled idle periods. A scaled idle experiment represents its configured duration, not an equal amount of wall-clock production observation. Read the metric and window together before comparing runs. ## Large-context loop The `context` scenario warms one session's kernel, then runs 300 Python cells in one turn. Each cell prints 6144 characters. The final request is about 2 MB, spread across many medium tool results. The session window is set to one million tokens so compaction does not shorten the loop. Replay fails if the loop uses a different number of requests or the final body is outside 1.8 to 2.5 MB. [`scenarios.py`](../perf/scenarios.py) owns those checks. [`recordings/generate_context.py`](../perf/recordings/generate_context.py) generates the synthetic SSE recording without an upstream. Regenerate it with `python3 perf/recordings/generate_context.py`. Synthetic recordings have no original request digests. Their response count and workload size are checked instead. The other recordings retain their digest checks. [`run.py`](../perf/run.py) reports the loop's costs in `scenarios.context.context`: - `peak_beam_blocks_per_mb` and `peak_daemon_uss_per_mb` subtract the warmed pre-turn value from the peak over the whole turn. - `retained_beam_per_mb` and `retained_daemon_uss_per_mb` subtract the warmed checkpoint from the settled checkpoint after the turn. BEAM retention uses `beam_kept`, including its heap-slack and unowned-binary exclusions. - Each memory cost is divided by the final decompressed JSON request body's decimal megabytes, not cumulative traffic or compressed wire bytes. - `reductions_per_step_per_mb` divides the BEAM's reductions between those two checkpoints by the number of cells and by the same megabytes. The [probe](../perf/albedo_perf_probe.erl) reads `exact_reductions` in each snapshot. Reductions count work done, so host load does not move them: five concurrent repetitions agree within 0.1%. Work that grows with history, such as parsing every stored result again for each request, raises it. - `wall_ms_per_step` divides prompt-to-idle wall time by the number of cells. It excludes checkpoint settling, inspection, and client history reads, but includes local replay transport and tool execution. It is not provider latency. The reductions ratio has a blocking ceiling. The allocator-peak and retained-BEAM ratios have advisory ceilings until Linux CI records calibrate them: the allocator peak sums per-instance maxima and is noisy under concurrency. USS ratios and milliseconds per step are diagnostic only. Run `--scenario context --runs 5` to reproduce this workload alone. ## Kernel measurement boundaries The `kernel` scenario waits for its first resting namespace checkpoint before measuring memory. This includes serializer startup before the cell-growth warm-up. Every measured cell checkpoint must hold the same kernel PID as the first cell. A release or replacement voids the repetition instead of becoming a negative slope or an apparent improvement. A session releases its idle kernel when a model wait outlasts its 3 s rest delay, which a stalled runner can cause even for a replayed reply. The [session](sessions.md#loaded-sessions-and-unloading) logs each release to `daemon.log` as `kernel released: session pid `. When the replaced kernel has exited and that line names it, [`run.py`](../perf/run.py) reruns the repetition, up to three attempts in all, and prints the reason. A replaced kernel with no logged release crashed, and one that still runs is untracked. Both fail the run at once, with the old and new PIDs and the log since the last checkpoint. The `pool` scenario configures two spares and waits for that sharing cohort before its warm and adopted checkpoints. These workload boundaries live in [`scenarios.py`](../perf/scenarios.py). Every checkpoint measures each held kernel in the process tree. The daemon reports a kernel as held until the stop that releases it completes, so a checkpoint that sees a held kernel already exited reads the daemon and the tree again. A held kernel that is still running but missing from the tree fails the run, as does one that stays held after it exits. [`measurement.py`](../perf/measurement.py) owns this check. `kernel_rest_anon`, `kernel_first_anon`, and `kernel_cell_slope` carry the `rested-kernel-v2` measurement tag. Older measurements could include late initialization or a replacement process and cannot supply their comparison baseline. The first passing result under this contract seeds later regression checks. `kernel_forked_anon` uses a fixed absolute cost cap for the configured sharing cohort and the default serializer environment. ## Runtime admission measurements [`admission_measure_test.py`](../test/manual/admission_measure_test.py) uses the shared real-daemon harness to burst 24 sessions through concurrent opens, composition observations and stops. Its [probe](../apps/albedo/test/albedo/manual/albedo_admission_measure_probe.erl) uses public runtime entrypoints. Run the same fixture normally and under CPU/disk contention: ```sh ALBEDO_ADMISSION_REPORT=/tmp/admission.jsonl nix develop -c python3 e2e/run.py "$PWD/test/manual/admission_measure_test.py" ALBEDO_ADMISSION_REPORT=/tmp/admission-stress.jsonl nix develop -c python3 test/manual/stress.py python3 e2e/run.py "$PWD/test/manual/admission_measure_test.py" ``` [`runtime/measurement`](../apps/albedo/src/albedo/runtime/measurement.gleam) enables JSONL samples only when `ALBEDO_ADMISSION_MEASURE` names an output file. The fixture sets this on its private harness daemon. Samples include per-class queue wait and service duration, oldest queued age, active workers, runtime and reservation-owner mailbox counts, process/table bytes, serialized queued bytes, and reservation/refusal/cancellation counts. Started and finished events share a worker ticket. Finished events distinguish `confirmed_stop`, `failed_stop`, `success`, `error`, `uncertain`, and `worker_death`. For `confirmed_stop`, queue plus service duration measures worker confirmation latency. The burst summary records success, error, crash, and timeout counts per public operation, and the fixture fails when any operation does not succeed. Queue age starts when the runtime first samples a queued request; reservation age includes producer and deferred waiting. Keep reports under `/tmp`, with the revision, working diff, environment and command used. JSONL file writes add measurement overhead, and one burst does not establish production latency or justify scheduling changes. Producer byte budgets count captured heaps and backing binaries conservatively; serialized queued bytes measure a different representation. The [runtime contract](runtime.md#admission-and-worker-lifetime) defines the bounds these measurements observe. ## Record provider responses Direct record mode is part of the runner, not the CI report gate. It requires `--runs 1` and `--url`. Recording contacts the selected upstream and produces artifacts that need review before sharing. The intended container workflow is [`record_container.py`](../perf/record_container.py), recorded as running on valefar. It requires Linux, Docker, the selected local image, the bonsai bridge setup, and its build tools. It prefers `runsc` when available and otherwise uses `runc`. It serializes access through `/tmp/bonsai-gpu.lock` and runs the workload without a container network, with a dedicated bridge to the provider. ```sh nix develop -c python3 perf/record_container.py --out /tmp/new-perf-recordings ``` The output directory must not exist. `--scenario` can select recordings. The script's isolation probe checks selected network and host-file access before recording. Neither the host name nor a chosen container runtime alone proves isolation. Inspect the script's prerequisites before running it on another host. ## Comparison A full replay derives metrics in [`run.py`](../perf/run.py). [`compare.py`](../perf/compare.py) applies ceilings and, when a baseline is supplied, regression tolerances from [`budgets.toml`](../perf/budgets.toml). Each metric defaults to `comparison = "regression"`. A metric with `comparison = "absolute"` checks only its ceiling and retains the historical baseline for reference. Byte metrics use 1% of the baseline. Disk metrics use the larger of three times baseline noise and the configured floor. Other metrics also include 5% of the baseline in that maximum. The `[required]` table pairs each PR workload with its blocking ceilings. All other ceilings and historical increases are advisory. Main and manual runs also collect the remaining scenarios. To reproduce the PR workload, pass `--scenario fan-out --scenario pool --scenario kernel --scenario long --scenario context` with `--runs 5`. Candidate noise never widens its own tolerance. A metric's optional `measurement` tag identifies its workload contract. Missing tags mean `legacy`. Different tags skip the historical baseline comparison and print the reason, while the absolute ceiling still applies. Change a tag only when the measurement boundary changes, not to accept a production regression. A later result with the same tag uses the normal regression rules. `boot_tree_uss` reports an advisory absolute ceiling because allocator and process-memory variation can move its batch median without comparable retained BEAM growth. `boot_beam` compares retained BEAM at the same empty checkpoint using `beam_kept`. The process footprint remains visible alongside the retained BEAM measurement. Older records without `boot_beam` supply no baseline for that metric, so its first comparison uses only the ceiling. `retained_turn_tree_uss` also uses its fixed absolute ceiling. Unused allocator space and the SQLite writer cache can change its process-memory slope without matching retained BEAM growth. `retained_turn_beam` keeps its regression comparison and its ceiling as the precise retained-BEAM leak check. The idle session and transient peak comparisons retain their calibrated tolerances. `disk_written_boot` has an explicit fresh-home initialization allowance. Its schema and migration writes accumulate as the supported database grows. The baseline regression check still detects large increases. Steady-state turn, append, backfill, and idle writes have their own limits. Review an initialization increase against its schema changes and measured writes. Do not raise steady-state limits to accommodate it or let an initialization ceiling follow each passing measurement automatically. The comparison output records each regression limit and prints the verdict, values, and limits before CI's full result JSON. A ceiling failure requires review of the budget. An entry in `accepted.toml` changes baseline eligibility and cannot clear a ceiling failure. The allocator peak from [`albedo_perf_probe`](../perf/albedo_perf_probe.erl) sums each allocator instance's high-water mark. Those maxima need not occur together, so this is an upper bound on simultaneous allocated memory. Its comparison floor accounts for variation between repeated batches on unchanged production code. Keep the calibration runs and environment beside its entry in `budgets.toml`. ## Output safety [`safety.py`](../perf/safety.py) scans output for supplied environment secrets and recognizable credential patterns before writing JSON. This is a guard, not proof that a recording contains no sensitive data. Recording contacts the supplied upstream and can fail. Inspect the generated artifact before sharing it. See [performance reporting](../perf/report/README.md) for CI baseline selection, publication, external deployment observations, and report interpretation. The report comparison picker does not replace the gate's per-metric baseline. ## Related pages - [All topics](README.md) - [Change guidance](contributing.md) - [Test execution](testing.md) - [Provider requests](provider-requests.md)