From 75100cedb24a4d3dfb697f35a48fc64a9499fe2a Mon Sep 17 00:00:00 2001 From: nothiny Date: Sat, 7 Nov 2026 22:44:20 +0800 Subject: [PATCH] feat(benchmarks): measure snapshot resume-to-command latency --- Cargo.lock | 1 + crates/benchmarks/Cargo.toml | 3 +- .../benchmarks/benches/snapshot_benchmark.rs | 163 +++++++++- crates/benchmarks/tests/snapshot_benchmark.rs | 287 ++++++++++++++++++ docs/src/internals/sandbox-testing.md | 67 ++++ 5 files changed, 519 insertions(+), 2 deletions(-) create mode 100644 crates/benchmarks/tests/snapshot_benchmark.rs diff --git a/Cargo.lock b/Cargo.lock index 7405d010f..0e92c0b92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,6 +196,7 @@ version = "0.1.0" dependencies = [ "agentenv", "anyhow", + "async-trait", "criterion", "libc", "libublk-rs-sys", diff --git a/crates/benchmarks/Cargo.toml b/crates/benchmarks/Cargo.toml index 8f5b7170f..c8da8499f 100644 --- a/crates/benchmarks/Cargo.toml +++ b/crates/benchmarks/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dev-dependencies] agentenv = { path = "../.." } anyhow = "1.0.100" +async-trait = "0.1" criterion = { version = "0.8", features = ["async_tokio"] } libc = "0.2" overlaybd = { path = "../../storage/overlaybd" } @@ -15,7 +16,7 @@ serde_json = "1" sha2 = { version = "0.10", features = ["asm"] } storage-util = { path = "../../storage/util" } tempfile = "3.22.0" -tokio = { version = "1", features = ["full"] } +tokio = { version = "1", features = ["full", "test-util"] } ublk-sys = { package = "libublk-rs-sys", git = "https://github.com/ublk-org/libublk-rs.git", rev = "c6a3e06" } uuid = "1" uvm-ublk = { path = "../../storage/ublk" } diff --git a/crates/benchmarks/benches/snapshot_benchmark.rs b/crates/benchmarks/benches/snapshot_benchmark.rs index 85ab06b48..a98df437a 100644 --- a/crates/benchmarks/benches/snapshot_benchmark.rs +++ b/crates/benchmarks/benches/snapshot_benchmark.rs @@ -1,7 +1,8 @@ use agentenv::image::ImageResolver; use agentenv::sandbox::{ CapturedSandboxSnapshot, FirecrackerSandbox, FirecrackerSandboxConfig, - FirecrackerSnapshotConfig, OverlaybdConfig, SandboxBackend, SandboxExecutor, UblkDeviceManager, + FirecrackerSnapshotConfig, OverlaybdConfig, ProcessOpts, SandboxBackend, SandboxExecutor, + UblkDeviceManager, }; use anyhow::{Context, Result}; use criterion::{Criterion, SamplingMode, Throughput}; @@ -33,6 +34,13 @@ const FULL_THROUGHPUT_MEASUREMENT_TIME: Duration = Duration::from_secs(30); const HEAVY_DATA_SIZE_MIB: u32 = 1024; const HEAVY_MEM_SIZE_MIB: u32 = HEAVY_DATA_SIZE_MIB + 512; const BENCH_UPPER_MODE_ENV: &str = "AENV_BENCH_UPPER_MODE"; +const RESUME_COMMAND_ENV: &str = "AENV_BENCH_RESUME_COMMAND"; +const DEFAULT_RESUME_COMMAND: &str = "printf 'aenv-resume-command-ok\\n'"; +const RESUME_COMMAND_TIMEOUT: Duration = Duration::from_secs(60); +const RESUME_COMMAND_BENCHMARKS: [(&str, bool); 2] = [ + ("snapshot_resume_to_command", true), + ("snapshot_resume_to_command_unpinned", false), +]; fn bench_upper_mode() -> UpperMode { match std::env::var(BENCH_UPPER_MODE_ENV) { @@ -98,6 +106,9 @@ fn filtered_benchmark_names() -> Result>> { println!("snapshot_creation_1gmem"); println!("snapshot_resume_cold"); println!("snapshot_resume"); + for (name, _) in RESUME_COMMAND_BENCHMARKS { + println!("{name}"); + } println!("concurrent_resume"); println!("concurrent_resume_throughput"); println!("concurrent_snapshot_capture_throughput"); @@ -622,6 +633,139 @@ fn default_snapshot_resume(rt: &Runtime) -> Result> { Ok(samples) } +fn resume_command() -> Result { + let command = match std::env::var(RESUME_COMMAND_ENV) { + Ok(command) => command, + Err(std::env::VarError::NotPresent) => DEFAULT_RESUME_COMMAND.to_owned(), + Err(error) => return Err(error).context(format!("read {RESUME_COMMAND_ENV}")), + }; + anyhow::ensure!( + !command.trim().is_empty(), + "{RESUME_COMMAND_ENV} must not be empty" + ); + println!("Resume workload (sh -c): {command:?}"); + Ok(command) +} + +fn run_resume_command(rt: &Runtime, sandbox: &FirecrackerSandbox, command: &str) -> Result<()> { + rt.block_on(run_resume_command_inner(sandbox, command)) +} + +async fn run_resume_command_inner(sandbox: &impl SandboxExecutor, command: &str) -> Result<()> { + // ProcessOpts only times process completion after StartEvent. The outer + // deadline also bounds connection setup, the start RPC, and StartEvent. + // On timeout the caller still stops the sandbox, including any guest process. + let output = tokio::time::timeout( + RESUME_COMMAND_TIMEOUT, + sandbox.run_command_with_opts( + "sh", + &["-c", command], + &ProcessOpts::new().with_timeout(RESUME_COMMAND_TIMEOUT), + ), + ) + .await + .context("resume command timed out after 60s, including process startup")??; + anyhow::ensure!( + output.exit_code == 0, + "resume command exited with {}: stdout={:?}, stderr={:?}", + output.exit_code, + output.stdout, + output.stderr + ); + Ok(()) +} + +fn resume_to_command_samples( + rt: &Runtime, + snapshot: &FirecrackerSnapshotConfig, + command: &str, + keep_warm: bool, + iterations: u64, +) -> Result> { + collect_resume_command_samples( + keep_warm, + iterations, + || resume_warm_sandbox(rt, snapshot), + |sandbox| run_resume_command(rt, sandbox, command), + |sandboxes| stop_batch(rt, sandboxes), + ) +} + +fn collect_resume_command_samples( + keep_warm: bool, + iterations: u64, + mut resume: impl FnMut() -> Result, + mut run_command: impl FnMut(&S) -> Result<()>, + mut stop: impl FnMut(Vec) -> Result<()>, +) -> Result> { + let print_stages = std::env::var_os("AENV_BENCH_PRINT_SAMPLES").is_some(); + let warm_sandbox = if keep_warm { Some(resume()?) } else { None }; + let result: Result> = (|| { + if let Some(sandbox) = warm_sandbox.as_ref() { + // Warm the workload's host-side reads without changing the source snapshot. + run_command(sandbox).context("warm resume command")?; + } + let mut samples = Vec::new(); + for _ in 0..iterations { + // Match snapshot_resume's start boundary, then include envd readiness, + // initialization, command submission, and receipt of process completion. + let start = Instant::now(); + let sandbox = resume()?; + let resume_elapsed = print_stages.then(|| start.elapsed()); + let command_result = run_command(&sandbox); + let elapsed = start.elapsed(); + let cleanup = stop(vec![sandbox]); + // Always stop the VM, including on RPC errors, timeout, or nonzero exit. + if let Err(error) = &cleanup { + eprintln!("Resume command sandbox cleanup failed: {error:#}"); + } + command_result.context("execute first command after resume")?; + cleanup?; + samples.push(elapsed); + if let Some(resume_elapsed) = resume_elapsed { + println!( + "resume_to_command stage sample {} warm={keep_warm} restore={} command={}", + samples.len(), + format_duration(resume_elapsed), + format_duration(elapsed.saturating_sub(resume_elapsed)), + ); + } + } + Ok(samples) + })(); + let cleanup = stop(warm_sandbox.into_iter().collect()); + if let Err(error) = &cleanup { + eprintln!("Resume command warm sandbox cleanup failed: {error:#}"); + } + let samples = result?; + cleanup?; + Ok(samples) +} + +fn bench_snapshot_resume_to_command(c: &mut Criterion) { + let mut prepared = None; + for (name, keep_warm) in RESUME_COMMAND_BENCHMARKS { + c.bench_function(name, |b| { + // Criterion only invokes this closure for selected benchmarks. + // Reuse preparation across warmup and measurement invocations. + let (rt, snapshot, command) = prepared.get_or_insert_with(|| { + let command = resume_command().expect("valid resume command"); + let rt = Runtime::new().expect("create resume command runtime"); + let snapshot = rt + .block_on(prepare_snapshot()) + .expect("prepare resume command snapshot"); + (rt, snapshot, command) + }); + b.iter_custom(|iterations| { + resume_to_command_samples(rt, snapshot, command, keep_warm, iterations) + .expect("measure resume to command completion") + .into_iter() + .sum() + }); + }); + } +} + fn run_concurrent_resume_samples( rt: &Runtime, base_snapshot: &FirecrackerSnapshotConfig, @@ -1111,6 +1255,22 @@ fn run_default_snapshot_benchmarks() -> Result<()> { default_snapshot_resume_cold(&rt) }); ran |= run_default_benchmark("snapshot_resume", &filters, || default_snapshot_resume(&rt)); + for (name, keep_warm) in RESUME_COMMAND_BENCHMARKS { + if should_run(name, &filters) { + let command = resume_command()?; + let snapshot = rt.block_on(prepare_snapshot())?; + let samples = resume_to_command_samples( + &rt, + &snapshot, + &command, + keep_warm, + DEFAULT_SAMPLE_COUNT as u64, + ) + .with_context(|| format!("run {name}"))?; + print_samples(name, &samples); + ran = true; + } + } ran |= run_default_benchmark("concurrent_resume", &filters, || { default_concurrent_resume(&rt) }); @@ -1197,6 +1357,7 @@ fn run_full_snapshot_benchmarks() { bench_snapshot_creation_1gmem(&mut criterion); bench_snapshot_resume_cold(&mut criterion); bench_snapshot_resume(&mut criterion); + bench_snapshot_resume_to_command(&mut criterion); bench_snapshot_concurrent_resume(&mut criterion); bench_snapshot_throughput(&mut criterion); bench_fresh_start_throughput(&mut criterion); diff --git a/crates/benchmarks/tests/snapshot_benchmark.rs b/crates/benchmarks/tests/snapshot_benchmark.rs new file mode 100644 index 000000000..9f10cd462 --- /dev/null +++ b/crates/benchmarks/tests/snapshot_benchmark.rs @@ -0,0 +1,287 @@ +// The benchmark uses a custom main (harness = false). Include it under the +// standard test harness to exercise its hardware-independent runner. +#[allow(dead_code)] +mod snapshot_benchmark { + include!("../benches/snapshot_benchmark.rs"); + + use agentenv::sandbox::ProcessOutput; + use std::collections::VecDeque; + use std::sync::atomic::AtomicUsize; + use std::sync::Mutex; + + #[derive(Default)] + struct CommandReply { + start_delay: Duration, + execution_delay: Duration, + exit_code: i32, + } + + struct ScriptedGuest { + replies: Mutex>, + calls: Mutex)>>, + completed: AtomicUsize, + } + + impl ScriptedGuest { + fn new(replies: Vec) -> Self { + Self { + replies: Mutex::new(replies.into()), + calls: Mutex::new(Vec::new()), + completed: AtomicUsize::new(0), + } + } + } + + #[test] + fn criterion_only_validates_resume_command_for_selected_benchmarks() { + const CHILD_FILTER: &str = "AENV_TEST_RESUME_CRITERION_FILTER"; + if let Ok(filter) = std::env::var(CHILD_FILTER) { + let output = tempfile::tempdir().unwrap(); + let mut criterion = Criterion::default() + .with_filter(filter) + .output_directory(output.path()); + bench_snapshot_resume_to_command(&mut criterion); + return; + } + + // Isolate the invalid command from other tests without changing the + // parent process environment. A selected case must still reject it. + for (filter, succeeds) in [ + ("^unrelated_benchmark$", true), + ("^snapshot_resume_to_command$", false), + ] { + let state = tempfile::tempdir().unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "snapshot_benchmark::criterion_only_validates_resume_command_for_selected_benchmarks", + "--nocapture", + ]) + .env(CHILD_FILTER, filter) + .env(RESUME_COMMAND_ENV, "") + .env("AENV_CONFIG_PATH", state.path().join("missing.toml")) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.success(), succeeds, "{filter}: {stderr}"); + if !succeeds { + assert!(stderr.contains("AENV_BENCH_RESUME_COMMAND must not be empty")); + } + } + } + + #[test] + fn failed_sample_command_stops_sample_and_warm_sandbox() { + for keep_warm in [false, true] { + for timeout in [false, true] { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .start_paused(true) + .build() + .unwrap(); + let mut replies = Vec::new(); + if keep_warm { + replies.push(CommandReply::default()); + } + replies.push(CommandReply { + start_delay: if timeout { + Duration::from_secs(120) + } else { + Duration::ZERO + }, + exit_code: 7, + ..Default::default() + }); + let guest = ScriptedGuest::new(replies); + let mut resumed = 0; + let mut stopped = Vec::new(); + let error = collect_resume_command_samples( + keep_warm, + 3, + || { + resumed += 1; + Ok(resumed) + }, + |_| rt.block_on(run_resume_command_inner(&guest, "workload")), + |sandboxes| { + stopped.extend(sandboxes); + Ok(()) + }, + ) + .unwrap_err(); + assert!(format!("{error:#}").contains(if timeout { + "timed out after 60s" + } else { + "exited with 7" + })); + assert_eq!(resumed, if keep_warm { 2 } else { 1 }); + assert_eq!(stopped, if keep_warm { vec![2, 1] } else { vec![1] }); + assert_eq!(guest.calls.lock().unwrap().len(), resumed); + } + } + } + + #[test] + fn warmup_or_sample_resume_failure_stops_retained_sandbox() { + for fail_warmup in [false, true] { + let mut resumed = 0; + let mut commands = 0; + let mut stopped = Vec::new(); + let error = collect_resume_command_samples( + true, + 3, + || { + resumed += 1; + anyhow::ensure!(resumed == 1, "sample resume failed"); + Ok(resumed) + }, + |_| { + commands += 1; + anyhow::ensure!(!fail_warmup, "warmup command failed"); + Ok(()) + }, + |sandboxes| { + stopped.extend(sandboxes); + Ok(()) + }, + ) + .unwrap_err(); + assert!(format!("{error:#}").contains(if fail_warmup { + "warmup command failed" + } else { + "sample resume failed" + })); + assert_eq!(commands, 1); + assert_eq!(stopped, vec![1]); + } + } + + #[test] + fn sample_cleanup_failure_still_stops_warm_sandbox_and_preserves_primary_error() { + for fail_command in [false, true] { + let mut resumed = 0; + let mut stopped = Vec::new(); + let error = collect_resume_command_samples( + true, + 3, + || { + resumed += 1; + Ok(resumed) + }, + |sandbox| { + anyhow::ensure!(!fail_command || *sandbox == 1, "sample RPC failed"); + Ok(()) + }, + |sandboxes| { + let sample = sandboxes == vec![2]; + stopped.extend(sandboxes); + anyhow::ensure!(!sample, "sample cleanup failed"); + Ok(()) + }, + ) + .unwrap_err(); + assert!(format!("{error:#}").contains(if fail_command { + "sample RPC failed" + } else { + "sample cleanup failed" + })); + assert_eq!(stopped, vec![2, 1]); + assert_eq!(resumed, 2); + } + } + + #[async_trait::async_trait(?Send)] + impl SandboxExecutor for ScriptedGuest { + fn executor(&self) -> Result { + anyhow::bail!("scripted guest uses the command overrides") + } + + async fn run_command(&self, cmd: &str, args: &[&str]) -> Result { + self.run_command_with_opts(cmd, args, &ProcessOpts::default()) + .await + } + + async fn run_command_with_opts( + &self, + cmd: &str, + args: &[&str], + opts: &ProcessOpts, + ) -> Result { + self.calls.lock().unwrap().push(( + cmd.to_owned(), + args.iter().map(|arg| (*arg).to_owned()).collect(), + )); + let reply = self.replies.lock().unwrap().pop_front().unwrap(); + // Match Executor's boundary: ProcessOpts starts timing only after + // startup. The benchmark must separately bound this first await. + tokio::time::sleep(reply.start_delay).await; + let completion = async { + tokio::time::sleep(reply.execution_delay).await; + self.completed.fetch_add(1, Ordering::SeqCst); + Ok(ProcessOutput { + stdout: "fixture stdout".into(), + stderr: "fixture stderr".into(), + exit_code: reply.exit_code, + }) + }; + match opts.timeout { + Some(timeout) => tokio::time::timeout(timeout, completion) + .await + .context("scripted process completion timed out")?, + None => completion.await, + } + } + } + + #[tokio::test(start_paused = true)] + async fn resume_command_timeout_covers_waiting_for_start_event() { + let guest = ScriptedGuest::new(vec![CommandReply { + start_delay: Duration::from_secs(120), + ..Default::default() + }]); + let start = tokio::time::Instant::now(); + let error = run_resume_command_inner(&guest, "echo ready") + .await + .unwrap_err(); + assert_eq!(start.elapsed(), RESUME_COMMAND_TIMEOUT); + assert!(error.to_string().contains("including process startup")); + tokio::time::advance(Duration::from_secs(120)).await; + assert_eq!(guest.completed.load(Ordering::SeqCst), 0); + } + + #[tokio::test(start_paused = true)] + async fn resume_command_start_and_completion_share_one_timeout_budget() { + let guest = ScriptedGuest::new(vec![CommandReply { + start_delay: Duration::from_secs(40), + execution_delay: Duration::from_secs(40), + ..Default::default() + }]); + let start = tokio::time::Instant::now(); + let error = run_resume_command_inner(&guest, "echo ready") + .await + .unwrap_err(); + assert_eq!(start.elapsed(), RESUME_COMMAND_TIMEOUT); + assert!(error.to_string().contains("including process startup")); + assert_eq!(guest.completed.load(Ordering::SeqCst), 0); + } + + #[tokio::test(start_paused = true)] + async fn resume_command_completes_within_deadline_and_checks_exit_code() { + for exit_code in [0, 7] { + let guest = ScriptedGuest::new(vec![CommandReply { + start_delay: Duration::from_secs(5), + execution_delay: Duration::from_secs(10), + exit_code, + }]); + let start = tokio::time::Instant::now(); + let result = run_resume_command_inner(&guest, "echo ready").await; + assert_eq!(start.elapsed(), Duration::from_secs(15)); + assert_eq!(guest.completed.load(Ordering::SeqCst), 1); + if exit_code == 0 { + result.unwrap(); + } else { + assert!(result.unwrap_err().to_string().contains("exited with 7")); + } + } + } +} diff --git a/docs/src/internals/sandbox-testing.md b/docs/src/internals/sandbox-testing.md index 197e4d0fa..86cc322e7 100644 --- a/docs/src/internals/sandbox-testing.md +++ b/docs/src/internals/sandbox-testing.md @@ -739,3 +739,70 @@ set `AENV_BENCH_FULL=1` for Criterion. `AENV_BENCH_CONCURRENCY` defaults to twic the available CPU parallelism, up to 50. A failed operation fails the batch; the benchmark attempts to stop any remaining sandboxes and reports cleanup errors. + +## 7) Resume-to-Command Latency + +The `snapshot` benchmark also measures the time from starting a backend resume +to receiving completion of the first specified guest command: + +- `snapshot_resume_to_command`: retain a resumed sandbox and execute the workload + on it before sampling, keeping the shared memory device alive and warming + host-side workload reads. +- `snapshot_resume_to_command_unpinned`: retain no warm sandbox between samples. + +Both start the timer before constructing the resumed sandbox, matching the +existing `snapshot_resume` boundary. They include Firecracker restore, envd +readiness and initialization, command submission, and command completion over +envd. Snapshot preparation, warmup, and sandbox cleanup are outside timing. +This measures the local backend; HTTP API and scheduler latency are excluded. +Each measured command runs in a newly resumed sandbox. A nonzero exit, RPC +failure, or 60-second command timeout fails the benchmark, and cleanup is +attempted for both the sample sandbox and the retained warm sandbox. +The command's 60-second budget covers connection setup, the start RPC, waiting +for the process start event, and process completion together. On expiry, the +in-flight command call is cancelled and the runner proceeds to sandbox cleanup. + +Use the isolated state, dependencies, and capability runner described above: + +```bash +cargo bench -p agentenv-benchmarks --bench snapshot -- --list +AENV_BENCH_PRINT_SAMPLES=1 \ + CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="$PWD/scripts/run-with-capabilities.sh" \ + cargo bench -p agentenv-benchmarks --bench snapshot -- snapshot_resume_to_command +``` + +The default workload is `printf 'aenv-resume-command-ok\n'`, which requires only +`sh` in the guest. Set `AENV_BENCH_RESUME_COMMAND` to a shell command or script; +the runner prints its exact value for reproducibility. For example, select a +base image containing Python through `image.resolver.default_image` in your +benchmark config, then run a fixed workload: + +```bash +export AENV_BENCH_RESUME_COMMAND="python3 -c 'import hashlib, json; data = json.dumps(list(range(10000))).encode(); assert len(data) == 58890; print(hashlib.sha256(data).hexdigest())'" +AENV_BENCH_PRINT_SAMPLES=1 \ + CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="$PWD/scripts/run-with-capabilities.sh" \ + cargo bench -p agentenv-benchmarks --bench snapshot -- snapshot_resume_to_command +``` + +Default mode reports ten samples per scenario; `AENV_BENCH_FULL=1` selects +Criterion sampling. The filter above matches both scenarios. +In Criterion mode, command validation and snapshot preparation happen only +when a resume-to-command scenario is selected. Preparation is reused across +warmup and measurement calls and remains outside the reported sample times. +With `AENV_BENCH_PRINT_SAMPLES=1`, each sample also reports the restore/readiness +and first-command portions separately. The extra timestamp is inside the timed +region; formatting and printing happen after timing and sandbox cleanup. Use +the same setting for both sides of a performance comparison. +In default mode, errors from selected resume-to-command benchmarks propagate +to a nonzero process exit. The runner's hardware-independent regression tests run +with `cargo test -p agentenv-benchmarks --test snapshot_benchmark`. + +`unpinned` does **not** mean all caches are cold: it does not evict the host page +cache, OverlayBD caches, or remote data caches. The older `snapshot_resume_cold` +similarly omits the retained warm instance without explicitly clearing every +cache. No host-wide cache eviction is performed by these benchmarks. + +The locally prepared snapshot has no startup-pack descriptor. These scenarios +establish the resume-to-command baseline; toggling startup-pack consumption +alone does not provide a prefetch A/B experiment. That comparison requires a +snapshot carrying a startup manifest and a separately controlled cache setup.