Files
pkh/docs/sandbox.md
T
vhaudiquet 674b99b00b
CI / build (push) Successful in 1m40s
CI / test (push) Skipped
CI / publish (push) Skipped
CI / snap (push) Successful in 2m39s
CI / release (push) Skipped
docs: describe the implemented sandbox architecture
Update the design doc to the shipped shape: the public API, the module
layout, the crate-private Unshare constructors and what the conformance
tests actually cover. Refresh the AGENTS.md scope list and the test
mode wording in the README and CLI.

Rename the last context-named helpers (new_with_base,
unshare_test_sandbox, RunEnv) and the comments that still described the
old abstraction.
2026-11-24 18:35:17 +01:00

24 KiB

Replacing Context with the Sandbox trait

Status: implemented. The public build and test APIs take Arc<dyn Sandbox>; src/context/ is gone.

Why the old abstraction was wrong

pkh models the place where work happens as a Context: a filesystem plus a command runner, configured as Local, Ssh, Schroot or Unshare, stored in ~/.config/pkh/contexts.json, resolved through a process-global ContextManager, and swapped for an ephemeral handle while a build runs.

Having several implementations is not the problem. The problem is how an implementation was chosen and reached. A hidden configuration file selected it, context::current() returned it from a global, and every unqualified call site silently followed that global. An ephemeral build then swapped the global for its own handle and restored it later, which the code already documents as a race for concurrent builds.

The second problem is naming. A "context" can mean a user setting, a command builder, a driver, a parent chain, a persisted name, or the current process-global. New code has to say which one it means.

A small trait with explicit construction and explicit passing fixes both. The Ecrou microVM implementation can be added without touching build logic.

What the old design was

Piece Where Used by
Context, ContextConfig, ContextDriver, ContextCommand src/context/api.rs every build and test path
ContextManager, current(), manager(), contexts.json src/context/manager.rs deb, test, apt
LocalDriver src/context/local.rs host commands and file operations
UnshareDriver src/context/unshare.rs the build chroot
SshDriver, SchrootDriver src/context/{ssh,schroot}.rs unused in practice
Stream, LineSink, pump src/context/{api,capture}.rs every captured subprocess
EphemeralContextGuard src/deb/ephemeral.rs deb builds, test beds
BuildProfiler, Phase src/deb/mod.rs deb phase timings

deb/local.rs takes an Arc<Context> and calls command, read_file, write_file, exists, is_dir, ensure_available, retrieve_path and copy_path on it. The new trait names the two host crossings put and get, and drops copy_path; the one real caller writes its backup with write_file. For the unshare backend every one of those operations is either std::fs on chroot_root.join(path) or an unshare invocation. Ecrou would instead run commands through a guest agent and copy files over its channel.

Target design

Sandbox is a trait

Sandbox describes a place a build runs: a command runner plus a filesystem. It is public, object safe, and implemented by each backend. Build code takes Arc<dyn Sandbox> or &dyn Sandbox explicitly. No configuration file or global decides which one runs.

Paths passed to the trait are paths inside the environment. Only put and get cross the host boundary. The trait does not expose a host root path, because Ecrou does not have one.

/// A place a build runs: a command runner and a filesystem.
pub trait Sandbox: Send + Sync {
    /// Run a command inside the environment.
    fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result<Execution>;

    /// File operations, with paths inside the environment.
    fn read_file(&self, path: &Path) -> io::Result<String>;
    fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
    fn exists(&self, path: &Path) -> io::Result<bool>;
    fn is_dir(&self, path: &Path) -> io::Result<bool>;
    fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>>;

    /// Copy a host file or tree to `dest` inside the environment.
    fn put(&self, host: &Path, dest: &Path, opts: &PutOptions)
        -> io::Result<PutOutcome>;

    /// Copy a file or tree from the environment to `dest` on the host.
    fn get(&self, src: &Path, dest: &Path) -> io::Result<()>;

    /// Remove a file or directory tree inside the environment.
    fn remove(&self, path: &Path) -> io::Result<()>;

    /// A fresh temporary directory inside the environment.
    fn create_temp_dir(&self) -> io::Result<String>;

    /// Whether this sandbox is the host machine. Defaults to `false`.
    fn is_host(&self) -> bool {
        false
    }

    /// Release mounts, devices or guest state and apply the teardown
    /// policy. Idempotent. `outcome` is `None` when the owner did not
    /// report one. Defaults to a no-op.
    fn cleanup(&self, outcome: Option<BuildOutcome>) -> io::Result<()> {
        let _ = outcome;
        Ok(())
    }
}

pub enum BuildOutcome {
    Success,
    Failure,
}

The methods stay synchronous. The current build code is synchronous once it reaches the environment, and converting the whole trait to async would touch apt, build/binary and the test runner for no immediate gain. The Ecrou backend can own a blocking channel to its guest, or a small runtime for that channel, behind the synchronous methods. If that proves unworkable, an async trait is a separate, larger change.

Command execution

The trait's run takes a plain description, not a builder tied to one backend:

pub struct CommandSpec {
    pub program: OsString,
    pub args: Vec<OsString>,
    pub env: Vec<(OsString, OsString)>,
    pub cwd: Option<PathBuf>,
}

pub enum Capture {
    Inherit,
    Lines(Arc<dyn LineSink>),
    Output,
}

pub struct Execution {
    pub status: ExitStatus,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
}

Execution fills stdout and stderr only for Capture::Output. The shared BuildCommand builder collects arguments and calls run:

pub struct BuildCommand<'a> {
    sandbox: &'a dyn Sandbox,
    spec: CommandSpec,
    capture: Capture,
}

pub trait SandboxExt: Sandbox {
    fn command(&self, program: &str) -> BuildCommand<'_>;
    fn stage_tree(
        &self,
        host: &Path,
        dest: &Path,
        opts: &StageOptions,
    ) -> io::Result<PutOutcome>;
}

impl<T: Sandbox> SandboxExt for T { /* forward to free functions */ }
impl SandboxExt for dyn Sandbox + '_ { /* same */ }

The extension trait keeps sandbox.command("apt-get") working on Arc<dyn Sandbox> without putting a generic or Self: Sized method on the trait. Two impls are needed: a default method cannot coerce &Self to &dyn Sandbox when Self is unsized, so the blanket impl covers sized backends and a second impl covers dyn Sandbox. Both forward to the same free functions. status, output and capture keep their current behavior.

src/exec.rs holds the parts that are about processes, not environments: Stream, LineSink, pump, the sanitize_fds pre-exec hook, the LANG=C/LC_ALL=C default, the not-found error message, and the test sink check that replaces test_support::wrap_driver. Host and Unshare both call it, so test output capture keeps working without a driver wrapper.

File transfer and extraction

The trait has three transfer primitives:

  • put copies a host file or tree to a path inside the sandbox.
  • get copies a file or tree from the sandbox to the host.
  • remove deletes a file or directory tree inside the sandbox.

put takes the copy policies the backend needs to apply:

pub struct ReuseState {
    /// Overlay upper directory.
    pub upper: PathBuf,
    /// Overlay work directory.
    pub work: PathBuf,
}

pub struct PutOptions {
    /// Backend state to reuse for a resumable tree copy.
    pub reuse: Option<ReuseState>,
    /// Directory names to skip at any depth.
    pub skip_dirs: Vec<OsString>,
}

pub enum PutOutcome {
    /// The destination was copied from the host.
    Fresh,
    /// A previous copy's state was reused.
    Resumed,
}

put and get treat dest as the copied entry's full path, not as a parent directory. The caller builds the final name.

read_file and write_file handle small text files without a transfer.

stage_tree is a helper, not a trait method. It owns the source-tree policy:

pub struct StageOptions {
    /// Backend state to reuse for a resumable tree copy.
    pub reuse: Option<ReuseState>,
    /// Remove VCS metadata from the staged tree.
    pub prune_vcs: bool,
}

pub fn stage_tree(
    sandbox: &dyn Sandbox,
    host: &Path,
    dest: &Path,
    opts: &StageOptions,
) -> io::Result<PutOutcome> {
    let put = PutOptions {
        reuse: opts.reuse.clone(),
        skip_dirs: if opts.prune_vcs { vcs_dir_names() } else { Vec::new() },
    };
    let outcome = sandbox.put(host, dest, &put)?;
    if opts.prune_vcs {
        // An overlay mount exposes the lower tree, so skipping during
        // the copy is not enough.
        prune_vcs_dirs(sandbox, dest)?;
    }
    Ok(outcome)
}

vcs_dir_names and prune_vcs_dirs live in sandbox/staging.rs with the helper. stage_tree is exposed as a SandboxExt method. Every backend calls this one function. None of them knows which directory names are VCS metadata. Unshare::put applies skip_dirs while copying and mounts an overlay when reuse is set; stage_tree removes the directories an overlay still exposes.

Archive extraction is not a trait method. Unshare extracts its chroot tarball during bootstrap. A build step that needs to unpack an archive runs tar through run, or the caller copies files in with put. The trait does not commit to an archive format.

Staging and incremental builds

Overlayfs is specific to the unshare backend, so the mechanism stays in Unshare::put. The shared policy is PutOptions:

  • reuse carries the backend's persistent overlay upper and work paths (ReuseState). A backend without resume ignores it and returns Fresh.
  • skip_dirs lists directory names the backend may omit during a copy. stage_tree fills it with the VCS names.
  • PutOutcome::Resumed tells the caller that the previous attempt's build artifacts are visible.

Host ignores reuse, applies skip_dirs, and returns Fresh. A future Ecrou can keep overlay state inside the guest and return Resumed, or copy through its channel and return Fresh. This is still the part of the transfer API that needs the most care before Ecrou, because --incremental currently depends on host-side overlay upperdirs.

Implementations

Unshare is what EphemeralContextGuard and the old unshare Context were: an ephemeral unshare chroot with the same tarball cache, device nodes, /proc, apt cache and ccache mounts. The crate-private constructors take the values the old guard took:

impl Unshare {
    pub(crate) async fn new_with_base(
        series: &str,
        arch: Option<&str>,
        mirror: Option<&str>,
        base: Arc<dyn Sandbox>,
        view: &dyn BuildView,
        profiler: &mut BuildProfiler,
    ) -> Result<Self, Box<dyn Error>>;

    pub(crate) async fn new_for_session(
        session: Session,
        series: &str,
        arch: Option<&str>,
        mirror: Option<&str>,
        base: Arc<dyn Sandbox>,
        view: &dyn BuildView,
        keep_upper: bool,
        ccache: Option<&Path>,
        profiler: &mut BuildProfiler,
    ) -> Result<Self, Box<dyn Error>>;
}

The teardown policy is the old one: a successful build removes an anonymous chroot, a failed one leaves it for inspection, and a session record removes the per-run chroot in every case while retaining its staged tree exactly for --incremental.

An absolute environment path such as /etc/apt/sources.list maps to root/etc/apt/sources.list in the unshare backend. The implementation strips the leading slash before joining, because Path::join replaces the base on an absolute path.

Unshare::put is the only code that knows about overlayfs. It uses a fresh overlay for a tree when possible, or the upper and work layer under PutOptions.reuse for a resumable build. The VCS names stay out of it.

Host is the host machine. It runs commands with std::process::Command, uses std::fs, and has no teardown. It serves pkh test --mode local and the unit tests. It is not a user-selectable backend.

Ecrou is the future microVM backend. It runs commands through a guest agent and moves files over its channel. Its spec will name the kernel, initrd, root image, memory and channel. It implements the same trait and the same conformance tests. It does not need changes in deb/local, apt or build/binary.

Construction and selection

Each implementation owns its constructor, because each needs different inputs. Unshare::new_with_base and Unshare::new_for_session are async because they download and extract a tarball. Host::new is trivial. Ecrou::create will be async.

pkh deb calls Unshare::new_with_base today. Adding the Ecrou backend means adding a small Backend value to DebBuildOptions and a CLI flag, then choosing the constructor there. Everything downstream already takes Arc<dyn Sandbox>.

A closed Backend enum is enough for the CLI. Library callers that want to supply an implementation pkh does not know need an injection point, for example DebBuildOptions.sandbox: Option<Arc<dyn Sandbox>>. That is a new field with a new meaning, not the old config-resolved ctx.

The Unshare constructors stay crate-private while they take a &mut BuildProfiler and a Session. Publishing a constructor for downstream callers means making both optional in the signature first.

pkh test maps its modes to implementations: local to Host, chroot to Unshare, and a future microVM mode to Ecrou. The existing TestMode::Vm means "run autopkgtest with its qemu runner", so the Ecrou backend needs a different flag name.

Lifecycle

  • Each implementation registers the interrupt cleanup hook it needs. Unshare unmounts and removes its root. Ecrou will power off the guest and remove its disk overlay. pkh deb keeps its own hook for the build record's interrupted state; the sandbox hook only releases backend resources.
  • Each implementation implements Drop and calls cleanup(None), which applies the conservative teardown policy. Unshare keeps a failed anonymous chroot for inspection and removes it on success, as today.
  • cleanup takes Option<BuildOutcome> so it works through Arc<dyn Sandbox>. deb marks success on the Unshare before it drops; Drop and the interrupt hook call cleanup(None). Unshare stores the outcome in an AtomicBool.
  • A build record keeps its metadata and log outside the environment. Dropping a sandbox never touches them. Backend-owned state, such as <record>/chroot, belongs to the backend and is removed by cleanup.
  • Methods are safe to call concurrently on one sandbox. Unshare keeps its mount list behind a mutex. Sandboxes are not Clone; owners share them with Arc.

What disappears

  • src/context/manager.rs and contexts.json. The settings directory remains for config.yml.
  • ContextConfig, the Local/Ssh/Schroot/Unshare enum, and parent resolution.
  • ContextDriver and driver boxing, including test_support::wrap_driver.
  • SshDriver and SchrootDriver.
  • context::current() and manager(), and with them the previous_context save and restore.
  • DebBuildOptions.ctx, DebBuildOptions.mode and BuildMode, which has one variant.
  • ensure_available, ensure_available_with_overlay, retrieve_path, copy_path, OverlayStaging, StageMode and StagedTree. The trait's put and get, PutOptions, PutOutcome and the stage_tree helper replace them. The one copy_path caller writes its backup with write_file.
  • The Option<Arc<Context>> parameter on apt::sources::{load, save} and the Option on the keyring helpers. Every caller passes a value today; the context::current() default goes away.

The build and test APIs no longer expose the word. This document mentions it only to describe what was removed; no setting, global, driver or command builder keeps the name.

Public API changes

  • pkh::sandbox::{Sandbox, SandboxExt, BuildCommand, Capture, CommandSpec, Execution, PutOptions, PutOutcome, BuildOutcome, StageOptions, stage_tree}.
  • pkh::sandbox::{Host, Unshare, ReuseState}. The Unshare constructors are crate-private until their profiler and session inputs become optional.
  • pkh::exec::{LineSink, Stream}. report::BuildView::sink returns the moved LineSink.
  • pkh::deb::DebBuildOptions loses ctx and mode. A later Backend value is additive.
  • pkh::apt::sources::{load, save} and the keyring helpers take Option<Arc<dyn Sandbox>>; None means a Host sandbox.

pkh is a library and a binary at version 0.2.0. These are breaking changes, so the release that ships them should be 0.3.0.

Module layout

src/
  exec.rs                 Stream, LineSink, pump, host process helpers
  sandbox/
    mod.rs                Sandbox, BuildCommand, CommandSpec, Capture,
                          Execution, PutOptions, PutOutcome
    staging.rs            StageOptions, stage_tree, VCS pruning
    host.rs               Host
    unshare/
      mod.rs              Unshare, bootstrap, finalize, ccache, apt cache,
                          teardown
      namespace.rs        UnshareDriver, path mapping, overlay staging,
                          namespace and pivot scripts, MAPPED_BUILD_ID
    ecrou.rs              future Ecrou

Phase and BuildProfiler still live in deb; moving them to build_profile.rs is the remaining separation between sandbox and deb.

Migration plan (implemented)

Each step compiled and passed its tests. The work is additive first, subtractive last.

  1. exec: move line capture out of context adds src/exec.rs with Stream, LineSink, pump and the host runner, and switches imports. No behavior change.
  2. sandbox: add the Sandbox trait adds the trait, CommandSpec, Capture, Execution, BuildCommand, PutOptions, PutOutcome, StageOptions, the stage_tree helper and the Host implementation. Add a conformance test that runs against Host.
  3. sandbox: implement the trait for Unshare moves api, unshare and shell into sandbox/unshare/, folds LocalDriver into Host and UnshareDriver into Unshare, and switches deb and test to Arc<dyn Sandbox>. The SSH and schroot drivers are not moved.
  4. sandbox: move the chroot bootstrap out of deb moves the tarball, extraction, finalize, ccache, apt cache and teardown helpers from deb/ephemeral.rs, and folds EphemeralContextGuard into Unshare::new_with_base/new_for_session and Drop.
  5. deb: drop the ctx and mode options removes DebBuildOptions.ctx, DebBuildOptions.mode and BuildMode, and passes the Arc<dyn Sandbox> explicitly through deb/local.
  6. test: make local mode use Host replaces Bed::Local(Arc<Context>) with Bed::Local(Arc<dyn Sandbox>) backed by Host.
  7. apt,build: take the sandbox explicitly removes the Option parameters and the context::current() defaults, and passes Host in the unit tests.
  8. context: remove the manager and the unused drivers deletes src/context/, the contexts.json loader, test_support::wrap_driver and the public module.
  9. docs: describe the sandbox updates README.md, lib.rs, AGENTS.md and the doc comments in config.rs, prune.rs and interrupt.rs.

Steps 2 and 3 can be merged if the intermediate adapter is not worth keeping. The commit scopes follow AGENTS.md: add sandbox, build_profile and exec, and remove context.

Behavior changes

  • SSH and schroot build environments are gone. pkh put still uploads over SSH through its own transport; only remote builds disappear.
  • contexts.json is ignored. The code should not delete it. A release note can tell users they may remove it.
  • pkh test --mode local means the host. It no longer means "whatever context is configured".
  • pkh deb always builds in a local ephemeral unshare chroot until a second backend is wired in. The Local build mode and the local-versus-other branch in build_binary_package_impl disappear.
  • Concurrent builds in one process are safe by construction. Each owns its Arc<dyn Sandbox>.
  • The public Rust API changes as listed above.

Risks and open questions

  1. Sync versus async. A microVM command channel may be easier to write with async I/O. The plan keeps the trait synchronous and lets Ecrou own a blocking channel. Confirm this before writing Ecrou, because switching later touches every caller.
  2. Staging and --incremental. Host-side overlayfs is specific to the unshare backend. The put and stage_tree API must be settled before Ecrou, or the Ecrou backend will not support incremental builds.
  3. Trait size. The trait has 10 required methods and two provided methods (is_host, cleanup); every backend implements the required ones. One trait keeps Arc<dyn Sandbox> simple. If it grows, split it into CommandRunner and FileSystem supertraits rather than adding optional methods.
  4. Per-call cost over a microVM channel. A file read is cheap on the host and a round trip in a microVM. Callers should use stage_tree, get and list_files for bulk work, not loops of exists and read_file. Add bulk methods later if the Ecrou backend needs them.
  5. Path model. The trait has no root(), and callers must not reconstruct host paths. deb/session.rs still chooses <record>/chroot for the unshare backend, but removal moves into Unshare::cleanup; the Ecrou backend picks its own state path under the record.
  6. Public commitment. A public trait with a 0.3.0 bump is a semver commitment. Adding a required method later breaks implementors. Default methods and new supertraits are the safe route.
  7. Naming. TestMode::Vm already means autopkgtest's qemu runner. Pick a different name for the Ecrou backend, for example ecrou.
  8. Remote builds. Dropping SSH and schroot removes a feature some users may rely on, even though it is untested. Confirm this is intended. If remote builds must stay, they can become another Sandbox implementation selected by an explicit flag, without restoring contexts.json or the global current.
  9. Selection surface. The CLI needs a closed Backend enum. The library may need an injected Arc<dyn Sandbox> so callers can supply their own implementation. Decide whether both exist, and keep the enum in the CLI if the library takes an injected sandbox.
  10. Build record metadata. deb/session.rs records the chroot tarball SHA and the <record>/chroot path. An Ecrou run needs a backend tag and its own state fields. Pruning and the --incremental base check also assume a tarball; the microVM image identity has to replace or extend that check. Add the backend tag before the Ecrou work, not after.
  11. Resume state shape. PutOptions.reuse is a ReuseState holding host paths because Unshare keeps its upper and work layers on the host. An Ecrou overlay may live inside the guest. Decide whether reuse becomes an opaque token before Ecrou, or whether Ecrou also keeps its resume state on the host.

Testing

  • sandbox::tests::conformance takes &dyn Sandbox and checks the contract: run a command, capture its output, read and write a file, list a directory, stage a tree, copy a file out, create a temporary directory, and clean up. It runs against Host.
  • sandbox::unshare::namespace::path_tests runs the path and staging half against UnshareDriver over a temp root, without namespace privileges.
  • A bootstrapped Unshare needs root, unshare and a tarball download, so its full command conformance is left to the pkh deb and pkh test e2e runs.
  • The existing staging units moved with the code: VCS metadata is skipped, dangling symlinks round-trip, unshare paths map below the root, and overlay mounts prune the lower tree.
  • Host stays fast and unprivileged, so build/binary.rs, deb/local.rs and apt/sources.rs unit tests run without a chroot.