Build code needs an interface it can receive explicitly instead of a global context. Add the 11-method Sandbox trait, the command description and builder, the transfer options, and the shared stage_tree helper that owns VCS pruning. Host implements the trait with std::process and std::fs. A conformance test runs against it and pins the command contract through an Arc<dyn Sandbox>.
24 KiB
Replacing Context with the Sandbox trait
Status: design proposal, not implemented.
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 exists today
| 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>;
/// 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:
putcopies a host file or tree to a path inside the sandbox.getcopies a file or tree from the sandbox to the host.removedeletes a file or directory tree inside the sandbox.
put takes the copy policies the backend needs to apply:
pub struct PutOptions {
/// Backend state to reuse for a resumable tree copy.
pub reuse: Option<PathBuf>,
/// 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<PathBuf>,
/// 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:
reusenames backend state to reuse.Unsharetreats it as the directory that holds a persistent upper and work layer. A backend without resume ignores it and returnsFresh.skip_dirslists directory names the backend may omit during a copy.stage_treefills it with the VCS names.PutOutcome::Resumedtells 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 are today:
an ephemeral unshare chroot with the same tarball cache, device nodes, /proc,
apt cache and ccache mounts. Its spec holds what the current guard takes:
pub struct UnshareSpec {
pub root: PathBuf,
pub series: String,
pub arch: Option<String>,
pub mirror: Option<String>,
pub ccache: Option<PathBuf>,
pub share_apt_cache: bool,
pub teardown: Teardown,
}
pub enum Teardown {
/// Remove the root on success and on failure.
Always,
/// Remove the root on success, keep it after a failure for inspection.
KeepOnFailure,
/// The owner removes the root; the sandbox only unmounts.
Owner,
}
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 that currently build a Context::new(ContextConfig::Local). 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::create is async because it downloads and extracts a tarball.
Host::new is trivial. Ecrou::create will be async.
pkh deb calls Unshare::create 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.
Unshare::create stays crate-private while it takes a &mut BuildProfiler.
Publishing a constructor for downstream callers means making the profiler
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.
Unshareunmounts and removes its root.Ecrouwill power off the guest and remove its disk overlay.pkh debkeeps its own hook for the build record's interrupted state; the sandbox hook only releases backend resources. - Each implementation implements
Dropand callscleanup(None), which applies the conservative teardown policy.Unsharekeeps a failed anonymous chroot for inspection and removes it on success, as today. cleanuptakesOption<BuildOutcome>so it works throughArc<dyn Sandbox>.debcallscleanup(Some(Success))after a good build andcleanup(Some(Failure))before returning an error;Dropand the interrupt hook callcleanup(None).Unsharestores the outcome in anAtomicBooland the first call applies the teardown.- 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 bycleanup. - Methods are safe to call concurrently on one sandbox.
Unsharekeeps its mount list behind a mutex. Sandboxes are notClone; owners share them withArc.
What disappears
src/context/manager.rsandcontexts.json. The settings directory remains forconfig.yml.ContextConfig, theLocal/Ssh/Schroot/Unshareenum, and parent resolution.ContextDriverand driver boxing, includingtest_support::wrap_driver.SshDriverandSchrootDriver.context::current()andmanager(), and with them theprevious_contextsave and restore.DebBuildOptions.ctx,DebBuildOptions.modeandBuildMode, which has one variant.ensure_available,ensure_available_with_overlay,retrieve_path,copy_path,OverlayStaging,StageModeandStagedTree. The trait'sputandget,PutOptions,PutOutcomeand thestage_treehelper replace them. The onecopy_pathcaller writes its backup withwrite_file.- The
Option<Arc<Context>>parameter onapt::sources::{load, save}and theOptionon the keyring helpers. Every caller passes a value today; thecontext::current()default goes away.
After the migration the word does not appear in the code. This document mentions it only to describe what is 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::{Unshare, UnshareSpec, Teardown}andHost.pkh::exec::{LineSink, Stream}.report::BuildView::sinkreturns the movedLineSink.pkh::deb::DebBuildOptionslosesctxandmode. A laterBackendvalue is additive.pkh::apt::sources::{load, save}andpkh::apt::keyring::download_trust_ppa_keytake&dyn Sandbox.pkh::apt::keyring::download_cache_keyringsbecomes host-only. The bootstrap always runs on the host now.
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, UnshareSpec, Teardown, Drop
bootstrap.rs tarball cache, download, extraction
finalize.rs device nodes, /proc, apt cache, ccache shim
overlay.rs overlay mounting, resume state
namespace.rs namespace and pivot scripts, MAPPED_BUILD_ID
ecrou.rs future Ecrou
build_profile.rs Phase, BuildProfiler, moved out of deb
Phase and BuildProfiler move out of deb because Unshare::create needs
them and sandbox must not depend on deb. pkh::deb::Phase can be
re-exported for compatibility.
Migration plan
Each step compiles and passes its tests. The work is additive first, subtractive last.
exec: move line capture out of contextaddssrc/exec.rswithStream,LineSink,pumpand the host runner, and switches imports. No behavior change.sandbox: add the Sandbox traitadds the trait,CommandSpec,Capture,Execution,BuildCommand,PutOptions,PutOutcome,StageOptions, thestage_treehelper and theHostimplementation. Add a conformance test that runs againstHost.sandbox: implement the trait for Unsharemovesapi,unshareandshellintosandbox/unshare/, foldsLocalDriverintoHostandUnshareDriverintoUnshare, and switchesdebandtesttoArc<dyn Sandbox>. The SSH and schroot drivers are not moved.sandbox: move the chroot bootstrap out of debmoves the tarball, extraction, finalize, ccache, apt cache and teardown helpers fromdeb/ephemeral.rs, and foldsEphemeralContextGuardintoUnshare::createandDrop.deb: drop the ctx and mode optionsremovesDebBuildOptions.ctx,DebBuildOptions.modeandBuildMode, and passes theArc<dyn Sandbox>explicitly throughdeb/local.test: make local mode use HostreplacesBed::Local(Arc<Context>)withBed::Hostand the trait methods.apt,build: take the sandbox explicitlyremoves theOptionparameters and thecontext::current()defaults, and passesHostin the unit tests.context: remove the manager and the unused driversdeletessrc/context/, thecontexts.jsonloader,test_support::wrap_driverand the public module.docs: describe the sandboxupdatesREADME.md,lib.rs,AGENTS.mdand the doc comments inconfig.rs,prune.rsandinterrupt.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 putstill uploads over SSH through its own transport; only remote builds disappear. contexts.jsonis ignored. The code should not delete it. A release note can tell users they may remove it.pkh test --mode localmeans the host. It no longer means "whatever context is configured".pkh debalways builds in a local ephemeral unshare chroot until a second backend is wired in. TheLocalbuild mode and the local-versus-other branch inbuild_binary_package_impldisappear.- 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
- Sync versus async. A microVM command channel may be easier to write with
async I/O. The plan keeps the trait synchronous and lets
Ecrouown a blocking channel. Confirm this before writingEcrou, because switching later touches every caller. - Staging and
--incremental. Host-side overlayfs is specific to the unshare backend. Theputandstage_treeAPI must be settled beforeEcrou, or the Ecrou backend will not support incremental builds. - Trait size. The trait has 11 methods, and every backend must implement all
of them. One trait keeps
Arc<dyn Sandbox>simple. If it grows, split it intoCommandRunnerandFileSystemsupertraits rather than adding optional methods. - 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,getandlist_filesfor bulk work, not loops ofexistsandread_file. Add bulk methods later if the Ecrou backend needs them. - Path model. The trait has no
root(), and callers must not reconstruct host paths.deb/session.rsstill chooses<record>/chrootfor the unshare backend, but removal moves intoUnshare::cleanup; the Ecrou backend picks its own state path under the record. - Public commitment. A public trait with a
0.3.0bump is a semver commitment. Adding a required method later breaks implementors. Default methods and new supertraits are the safe route. - Naming.
TestMode::Vmalready means autopkgtest's qemu runner. Pick a different name for the Ecrou backend, for exampleecrou. - 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
Sandboximplementation selected by an explicit flag, without restoringcontexts.jsonor the global current. - Selection surface. The CLI needs a closed
Backendenum. The library may need an injectedArc<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. - Build record metadata.
deb/session.rsrecords the chroot tarball SHA and the<record>/chrootpath. An Ecrou run needs a backend tag and its own state fields. Pruning and the--incrementalbase 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. - Resume state shape.
PutOptions.reuseis a hostPathBufbecauseUnsharekeeps its upper and work layers on the host. An Ecrou overlay may live inside the guest. Decide whetherreusebecomes an opaque token before Ecrou, or whether Ecrou also keeps its resume state on the host.
Testing
- Add a conformance suite that takes
&dyn Sandboxand 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. Run it againstHostalways and againstUnsharewhen root andunshareare available. - A future
Ecrouruns the same suite. That is the main reason to keep the trait small and behavior explicit. - Use
Arc<dyn Sandbox>in a test to catch object-safety regressions. - Port the existing
contextunit tests: staging strips VCS metadata, copies dangling symlinks, maps unshare paths, prunes nested VCS directories, and stages over an overlay upperdir. - Delete the
ContextManagertests with the manager. - Add lifecycle tests: create an
Unshareover a pre-populated fake root, drop it, and check the root is kept or removed perTeardown. These do not need privileges if they stop beforeunshare. - Keep the
Hostimplementation, sobuild/binary.rs,deb/local.rsandapt/sources.rsunit tests stay fast and unprivileged. - Run
pkh test --mode localand--mode chrootin the e2e harness. - Run the full suite and
cargo fmt --allpluscargo clippy --all-targets --all-featuresbefore each commit, asAGENTS.mdrequires.