Skip to content

fix: validate snapshot benchmark data preparation - #486

Open
nothiny wants to merge 2 commits into
kvcache-ai:mainfrom
nothiny:codex/fix-snapshot-benchmark-dd
Open

nothiny wants to merge 2 commits into
kvcache-ai:mainfrom
nothiny:codex/fix-snapshot-benchmark-dd

Conversation

@nothiny

@nothiny nothiny commented Nov 7, 2026

Copy link
Copy Markdown

What

Ensure snapshot benchmarks only measure successfully prepared workloads:

  • Check exit codes from dd, sync, and guest cache-clearing commands.
  • Resize guest /dev/shm to 1 GiB before preparing the memory workload.
  • Propagate bounded-runner errors instead of reporting failed scenarios as successful skips.
  • Add unit tests, an opt-in Firecracker regression test, and reproduction instructions.

Why

run_command(...).await? checks whether command execution returned a result, but does not reject a nonzero process exit code. The benchmark previously discarded ProcessOutput, allowing failed dd commands to leave partially prepared workloads without stopping measurement.

The memory fixture also allocates 1536 MiB of guest RAM while relying on the default tmpfs size limit, approximately half of guest RAM. This is insufficient for its intended 1 GiB write.

Related issue

None. This is a small benchmark correctness fix with a real-VM reproduction.

Scope and non-goals

Limited to snapshot benchmark preparation, failure reporting, tests, and documentation. No new performance metrics or sandbox runtime behavior are introduced.

Design and behavior changes

Preparation commands must exit successfully before measurement starts. Remount failure prevents the memory fixture from running dd; write failure aborts preparation.

The default bounded runner now propagates selected workload errors to a nonzero process exit.

The real-VM test runs the original command, records the failure and partial file size, removes the partial file, then calls the fixed production preparation function and verifies the resulting size.

Real-VM comparison

Executed through Docker using Firecracker 1.15.1-patch-v2, guest kernel 6.18.0-agentenv-nestedvirt, 1 vCPU, and 1536 MiB RAM.

Both phases ran in the same guest:

Measurement Original preparation Fixed preparation
/dev/shm capacity 779,722,752 bytes 1,073,741,824 bytes
dd exit code 1 0
Resulting file size 779,722,752 bytes 1,073,741,824 bytes
Result No space left on device Complete 1 GiB write

This is a workload correctness comparison; no snapshot latency or throughput improvement is claimed.

Compatibility and operations

  • Public API or generated protocol: unchanged.
  • Configuration or defaults: no new settings; the benchmark explicitly sets its guest tmpfs limit.
  • Snapshot manifest, artifact layout, or storage format: unchanged.
  • Upgrade and rollback: benchmark-only changes; no migration required.
  • Host requirements, permissions, ports, or dependencies: existing KVM/ublk requirements apply to the opt-in VM test. The guest benchmark user needs permission to remount tmpfs. async-trait is added as a benchmark development dependency.

Validation

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

Commands and results:

# Inside Docker:
make fmt clippy
# Passed.

cargo test -p agentenv-benchmarks --test snapshot_benchmark
# 9 passed; 1 ignored.

# Opt-in test explicitly executed through the capability runner:
snapshot_benchmark::real_vm_dd_before_after
# 1 passed; original write failed, fixed write completed exactly 1 GiB.

Skipped checks and reasons:

  • Full unit and performance suites were not run; validation focused on the changed benchmark paths and the real-VM reproduction.
  • Go tests and code generation are not applicable: no services or schemas changed.
  • The VM test is ignored by default because it requires KVM, ublk, runtime assets, capabilities, and isolated state.

Risks and reviewer notes

The bounded runner intentionally changes automation behavior: selected workload failures now return a nonzero exit status.

Increasing the tmpfs limit does not allocate memory immediately; the fixture's dd performs the intended 1 GiB allocation. Changes are confined to disposable benchmark guests.

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.

Check guest command exit codes and resize /dev/shm before writing 1 GiB. Propagate bounded-runner failures and add unit and opt-in Firecracker regression tests.
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 3 selected item(s).

Comment on lines +185 to +187
let samples = run().with_context(|| format!("run {name}"))?;
print_samples(name, &samples);
Ok(true)

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.

other · medium
This changes a single benchmark failure from a logged skip into an error that exits run_default_snapshot_benchmarks immediately. Consequently, a failure in an environment-dependent workload (for example the 1 GiB memory case or a throughput setup) prevents all later selected benchmarks from running and makes the default command fail. If these workloads are intended to be independently runnable, retain per-benchmark reporting/continuation (while perhaps aggregating failures), or explicitly make this fail-fast behavior part of the default runner contract.

Comment on lines +294 to +298
let options = format!("remount,size={HEAVY_DATA_SIZE_MIB}M");
let output = sandbox
.run_command("mount", &["-o", &options, "/dev/shm"])
.await?;
ensure_guest_command_success("resize guest /dev/shm", &output)?;

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.

other · medium
This assumes every benchmark guest has /dev/shm mounted as a remountable tmpfs and that the benchmark process has permission to change its limit. A different image/mount setup (or a guest where /dev/shm is absent or non-tmpfs) now makes the entire 1 GiB memory benchmark fail before sampling. Consider validating the mount configuration during setup and/or handling unsupported configurations explicitly rather than hard-coding this remount as a prerequisite.

Comment on lines +38 to +39
let reply = self.replies.lock().unwrap().pop_front().unwrap();
Ok(ProcessOutput {

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.

other · low
The scripted executor panics if the helper issues more commands than the currently scripted replies. That makes adding a valid preparation step fail with an unrelated unwrap() panic instead of identifying the unexpected command; return an error (ideally including the command and arguments) when the queue is exhausted.

Suggestion:

Suggested change
let reply = self.replies.lock().unwrap().pop_front().unwrap();
Ok(ProcessOutput {
let reply = self
.replies
.lock()
.unwrap()
.pop_front()
.ok_or_else(|| anyhow::anyhow!("unexpected guest command {cmd:?} {args:?}"))?;
Ok(ProcessOutput {

Comment on lines +105 to +106
fn dd_write_failure_prevents_snapshot_sampling() {
let output = run_dd("of=/dev/full");

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.

other · medium
This integration test is always built and run, but it assumes a Unix/Linux /dev/full device and an external dd with these operands. On supported non-Linux targets (and minimal environments without dd) the test either fails at runtime or cannot exercise the intended behavior. Gate this test target/tests consistently with the benchmark's platform support, or replace the host dd dependency with a portable fixture.

Comment on lines +267 to +271
let cleanup = sandbox.stop().await;
let daemon_cleanup = UblkDeviceManager::global().shutdown_daemon().await;
result?;
cleanup?;
daemon_cleanup

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.

other · medium
If any command in the body fails (the normal path this reproduction is meant to diagnose), result? returns before either cleanup future is awaited. Cancellation while the body is running has the same effect. Use a cleanup guard or an unconditional cleanup path that records the body error while still stopping the sandbox, removing the workload, and shutting down ublk; otherwise an ignored test can leave a VM/daemon running and contaminate later tests or the host.

Suggestion:

Suggested change
let cleanup = sandbox.stop().await;
let daemon_cleanup = UblkDeviceManager::global().shutdown_daemon().await;
result?;
cleanup?;
daemon_cleanup
let cleanup = sandbox.stop().await;
let daemon_cleanup = UblkDeviceManager::global().shutdown_daemon().await;
result?;
cleanup?;
daemon_cleanup

Comment on lines +267 to +271
let cleanup = sandbox.stop().await;
let daemon_cleanup = UblkDeviceManager::global().shutdown_daemon().await;
result?;
cleanup?;
daemon_cleanup

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.

other · low
Correction to the cleanup concern: because result is awaited before this block but only propagated after both cleanup futures are awaited, ordinary body errors do not skip cleanup. The remaining gap is cancellation while the body is running (or during cleanup), which would require a drop/guard-based cleanup strategy if cancellation safety is required.

Comment on lines +267 to +271
let cleanup = sandbox.stop().await;
let daemon_cleanup = UblkDeviceManager::global().shutdown_daemon().await;
result?;
cleanup?;
daemon_cleanup

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.

other · low
The previously raised early-return concern is not applicable to this code: result is an already-completed future here, so the body is fully awaited before result?, and both cleanup futures are started/awaited first. Only cancellation during the body could bypass this cleanup block.

@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown

Cross-referencing #487, where we posted restore-latency numbers from our own Firecracker fleet; on the preparation-correctness side that this PR fixes, two things we hit internally reinforce the strictness:

  • Nonzero exits must abort measurement, not degrade it. In our delta-snapshot runs, a 1 MB/s dd append workload made the pause/snapshot itself 5× slower (2.7–5.1 s vs the usual 0.5–1.3 s) purely from ext4 writeback contending with the dense memfile write on NVMe. A fixture that silently under-prepares (the dd ENOSPC case here) shifts measured distributions in ways that look like system noise rather than a broken setup. Propagating exit codes into a nonzero runner exit is the right contract, and the resulting-size verification in the real-VM test doubles as a workload descriptor — restore/delta costs scale with the uniquely-dirty footprint, so recording it per run makes later comparisons meaningful.
  • Guest-visible capacity ceilings are easy to miss. The tmpfs-defaults-to-half-of-RAM behavior is a good catch; our equivalent lesson was that in-guest memory workloads only produce stable measurements once the working set is pinned explicitly below the ceiling, with the capacity assumption visible in the preparation steps rather than implicit in defaults.

Related note on cache state (the unpinned scenario in #487 keeps host page caches ambient): warm vs evicted differed >20× on restore in our runs, so if preparation ever grows cache-eviction steps, having them exit-checked inside the validated preparation — as this PR does for sync — is the difference between a pinned scenario and an ambient one.

@nothiny

nothiny commented Nov 11, 2026

Copy link
Copy Markdown
Author

Cross-referencing #487, where we posted restore-latency numbers from our own Firecracker fleet; on the preparation-correctness side that this PR fixes, two things we hit internally reinforce the strictness:

  • Nonzero exits must abort measurement, not degrade it. In our delta-snapshot runs, a 1 MB/s dd append workload made the pause/snapshot itself 5× slower (2.7–5.1 s vs the usual 0.5–1.3 s) purely from ext4 writeback contending with the dense memfile write on NVMe. A fixture that silently under-prepares (the dd ENOSPC case here) shifts measured distributions in ways that look like system noise rather than a broken setup. Propagating exit codes into a nonzero runner exit is the right contract, and the resulting-size verification in the real-VM test doubles as a workload descriptor — restore/delta costs scale with the uniquely-dirty footprint, so recording it per run makes later comparisons meaningful.
  • Guest-visible capacity ceilings are easy to miss. The tmpfs-defaults-to-half-of-RAM behavior is a good catch; our equivalent lesson was that in-guest memory workloads only produce stable measurements once the working set is pinned explicitly below the ceiling, with the capacity assumption visible in the preparation steps rather than implicit in defaults.

Related note on cache state (the unpinned scenario in #487 keeps host page caches ambient): warm vs evicted differed >20× on restore in our runs, so if preparation ever grows cache-eviction steps, having them exit-checked inside the validated preparation — as this PR does for sync — is the difference between a pinned scenario and an ambient one.

Thanks for sharing your experience. I agree that preparation failures should abort measurement.
I also added explicit sandbox cleanup on preparation failure in d241336, covering both the bounded and Criterion runners. If cleanup also fails, the original preparation error is preserved with the cleanup diagnostic attached.
Formatting and workspace Clippy passed; the benchmark tests report 11 passed and 1 ignored.

@yjjnls

yjjnls commented Nov 11, 2026

Copy link
Copy Markdown

Thanks for the confirmation, and for the cleanup addition in d241336 — that closes a real gap the original report didn't cover: a failed preparation that leaks a sandbox would otherwise pollute the next run's environment on a shared host, and preserving the original preparation error with the cleanup diagnostic attached keeps the root cause primary in the report. Covering both the bounded and Criterion runners matters too, since either entry point leaving a stray sandbox behind would produce the same hard-to-diagnose downstream noise.

Worth linking the two halves explicitly: the contamination your cleanup fences off after a failed preparation is the same failure family as the one the exit-code contract fences off during preparation — the dd writeback example above shows an under-prepared fixture can inflate measurements of adjacent operations (the pause/snapshot itself) while every step still exits zero. Neither the samples nor the environment can be trusted unless preparation is both exit-checked and cleaned up on failure, and this PR now does both.

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