Skip to content

feat(benchmarks): measure snapshot resume-to-command latency - #487

Open
nothiny wants to merge 1 commit into
kvcache-ai:mainfrom
nothiny:codex/bench-resume-to-command
Open

nothiny wants to merge 1 commit into
kvcache-ai:mainfrom
nothiny:codex/bench-resume-to-command

Conversation

@nothiny

@nothiny nothiny commented Nov 7, 2026

Copy link
Copy Markdown

What

Add snapshot_resume_to_command and snapshot_resume_to_command_unpinned to measure the time from backend snapshot resume through completion of the first specified guest command.

Why

Restore-to-ready latency can miss memory faults and disk reads deferred until the first workload runs. Measuring command completion provides a baseline for evaluating whether changes such as prefetching improve the time to useful work.

Related issue

Related to #125 and #215.

Related implementation: #219.

Scope and non-goals

This change adds benchmark scenarios, focused regression tests, and documentation. Runtime behavior, snapshot formats, and storage formats are unchanged.

PR #219 already includes total timings spanning snapshot restore and guest command execution, plus first-workload experiments for pre-fault evaluation. This PR overlaps that measurement goal.

The difference is scope: #219 integrates measurements with its pre-fault implementation and specialized experiments. This PR provides a standalone baseline through existing restore interfaces, with a configurable shell command, warm/unpinned scenarios, bounded and Criterion runners, and filtering/timeout/cleanup regression tests. It requires no new pre-fault API or matching Firecracker changes. Overlapping helpers may be consolidated when the changes are integrated.

This is a baseline measurement tool, not a controlled cold-cache or prefetch A/B experiment.

Design and behavior changes

  • Start timing before constructing the resumed sandbox. Include restore, envd readiness and initialization, command submission, and receipt of completion. Exclude snapshot preparation, workload warmup, and sandbox cleanup. HTTP API and scheduler latency are outside this local backend measurement.
  • For the warm scenario, retain a resumed instance and execute the workload once before sampling. The unpinned scenario retains no such instance. Every measured command runs in a newly resumed sandbox.
  • Default to printf 'aenv-resume-command-ok\n'. Accept a shell workload through AENV_BENCH_RESUME_COMMAND and print its exact value.
  • Apply a 60-second deadline to the complete command call, including startup. Reject RPC errors, timeout, and nonzero exit codes.
  • Attempt sample and retained-instance cleanup before propagating failures. Preserve the command error when cleanup also fails.
  • In Criterion mode, prepare the command, runtime, and snapshot lazily after filtering, then reuse them across warmup and measurement calls. Default mode takes ten samples per scenario.
  • With AENV_BENCH_PRINT_SAMPLES=1, report restore/readiness and command portions separately. Formatting and printing occur after sample timing.

Compatibility and operations

  • Public API or generated protocol: unchanged.
  • Configuration or defaults: benchmark-only workload environment variable and two additional default-runner scenarios; no server configuration changes.
  • Snapshot manifest, artifact layout, or storage format: unchanged.
  • Upgrade and rollback: no migration required.
  • Host requirements, permissions, ports, or dependencies: real measurements retain existing KVM, ublk, runtime asset, and capability requirements. Tests add the async-trait dev dependency and Tokio test-util feature. The seven focused tests need no VM.

Validation

  • make fmt
  • make clippy
  • make test-unit
  • Relevant Rust integration tests
  • make -C services test (required when services/ changes)
  • Generated clients/server regenerated with the documented make target
  • Documentation updated
  • Benchmarks or performance comparison completed

Run in Docker as the non-root developer user on this isolated branch:

make fmt
  passed

make clippy
  passed: workspace, all targets and features, -D warnings

cargo test -p agentenv-benchmarks --test snapshot_benchmark
  7 passed, 0 failed, 0 ignored

git diff --check also passed. The Criterion filtering regression failed before the fix and passed afterward during development.

Tests cover filtered versus selected command validation, startup timeout, a shared startup/completion deadline, nonzero exit status, cleanup after sample/warmup/resume failure, and error precedence when cleanup fails. Cleanup tests exercise the same sampling loop as the real runner through controlled callbacks.

Skipped checks and reasons:

  • Broader VM/storage suites and performance measurements were not rerun on this isolated branch. Real-VM measurements were performed earlier in development; this PR makes no performance improvement claim.
  • Go tests and code generation do not apply to these benchmark-only changes.

Risks and reviewer notes

unpinned does not evict host page caches or OverlayBD caches. The default shell workload measures basic resume-to-command overhead. Application and prefetch studies need a fixed representative workload and controlled cache conditions. The locally prepared snapshot has no startup-pack descriptor.

The 60-second deadline covers the command call, not the entire VM restore. Mock cleanup tests verify stop calls and ordering, not actual device release.

Review the sampling loop and lazy Criterion setup in crates/benchmarks/benches/snapshot_benchmark.rs.

Checklist

  • The PR contains one coherent change and no unrelated formatting or refactoring.
  • New behavior is covered by tests, or I explained why testing is impractical.
  • Logs and examples contain no credentials, tokens, or private registry information.
  • I did not manually edit generated code without updating its source and regenerating it.

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 3 issue(s) in this PR.

  • ✅ Successfully posted inline: 3 comment(s)

!command.trim().is_empty(),
"{RESUME_COMMAND_ENV} must not be empty"
);
println!("Resume workload (sh -c): {command:?}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

security · medium
This prints the complete user-supplied shell command to benchmark/CI output. Since AENV_BENCH_RESUME_COMMAND is explicitly configurable, it can contain credentials, tokens, or other sensitive values intended for the guest, which would then be exposed in logs. Avoid logging the raw command (or provide an explicit opt-in/redaction mechanism) while retaining the command for execution.

Suggestion:

Suggested change
println!("Resume workload (sh -c): {command:?}");
println!("Resume workload configured via {RESUME_COMMAND_ENV}");

// standard test harness to exercise its hardware-independent runner.
#[allow(dead_code)]
mod snapshot_benchmark {
include!("../benches/snapshot_benchmark.rs");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

maintainability · medium
This test target textually includes the entire benchmark binary in order to reach private helpers. That makes the test's compilation and namespace depend on every future top-level import/declaration in the benchmark (and can also pull benchmark-only setup into the test), so an unrelated benchmark refactor can break or alter this test rather than test a stable API. Consider extracting the hardware-independent resume/cleanup helpers into a library module and testing that module directly, leaving the benchmark as a thin caller.

Comment on lines +57 to +58
"snapshot_benchmark::criterion_only_validates_resume_command_for_selected_benchmarks",
"--nocapture",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

maintainability · low
The child invocation hard-codes this test's fully qualified harness name. Renaming the module/test or changing the test harness layout will make this test fail before exercising Criterion filtering, and the exact diagnostic assertion below has the same coupling to an implementation detail. Prefer isolating the filtering logic behind a callable helper (or otherwise avoid recursively invoking the test binary) and assert a stable error classification/message at the boundary.

@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown

We run a Firecracker-based sandbox fleet and have built similar restore-latency baselines internally; sharing measured data points that may help calibrate these scenarios (FC v1.17.0, guest kernel 6.1.190, 1 vCPU / 512 MiB guests, busybox-class templates, ext4/NVMe local tier unless noted):

Restore-to-ready vs restore-to-first-command. Our primary metric is restore → in-guest agent HTTP 200 (analogous to the restore/readiness boundary here): warm P50 ≈ 10.2–10.5 ms, P99 ≈ 13.5 ms; with the template's page cache explicitly evicted (per-target fadvise(DONTNEED) on the memfile/disks — not a global drop_caches, to avoid clobbering co-tenants on shared hosts), e2e rises to ~230 ms, ≈20×. The gap is almost entirely guest working-set page faults on first touch — exactly the effect resume_to_command is designed to capture. Two observations from our runs:

  • Preheating is a warm/cold trade, not a win. Content baked into the snapshot before pause (a 31 MB application payload in one of our templates) enlarged the cold-restore window (cold P50 82.6 ms vs 57.9 ms for a minimal template) while leaving warm restore unchanged. For future prefetch A/B work, recording what is resident in the snapshot vs. what gets faulted on first command makes results interpretable.
  • Cache state is the dominant variance source, and "unpinned" is ambient rather than neutral. A single warm-up pass moves e2e by >20×. Since unpinned retains no warmed instance but also evicts nothing, its samples will land somewhere on that 20× spectrum depending on host cache weather — worth documenting explicitly, or adding a third cache-evicted scenario so warm / unpinned / evicted are three pinned points rather than two pinned plus one ambient.

A spectrum that bounds the metric (same guest size across all tiers):

Path Measured
template-hit warm restore e2e P50 ~40 ms including a fresh FC process spawn per restore (restore body ~13 ms)
full-boot fallback boot→ready P50 ~0.46 s (rootfs size 4 MB–1.3 GB made no difference)
persisted snapshot restored on a different node pull 671 MB from NFS @ ~198 MB/s + restore 45 ms ≈ 3.4 s serial per 512 MiB guest; ~7 s at 1 GiB; ~17 s per-VM under 7-way concurrent pull (shared server write path, not restore itself)
delta snapshots under real workloads 5-minute dirty-window gains span 193.6× (light network service) down to ~1.7× (continuous writers); at 30 s checkpoint intervals the same workloads give ~190×/17×/3.5×

Practical takeaway: the same "resume" operation spans 10 ms → 3.4 s depending on locality tier, so encoding the tier in the scenario name (resume_warm / resume_unpinned / a future resume_persisted) would keep regressions from averaging across tiers.

Workload descriptors worth recording per sample: guest RAM size, the command's working set, and for prefetch studies the unique-page churn rate — in our measurements the dirty-page fraction over a window is strongly bimodal (~0.5% for idle-ish network services, ~58–59% for continuous writers) and both restore and delta costs scale with it. Also echoing the direction of #486: validated preparation (exit-checked, size-verified) is what makes the workload dimension trustworthy in the first place.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants