`Phase`, its classifier selection and `BuildProfiler` described the build flow from inside `deb`, so `sandbox` had to import them from `deb` to announce chroot work. Moving them to `src/build_profile.rs` leaves `sandbox` depending on `deb` only for the session record. `PhaseTiming` and `BuildProfile` move with the profiler, since they are the record shape it produces. `deb` re-exports `Phase` and `session` re-exports the record types, so their public paths stay the same.
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:
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 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:
reusecarries the backend's persistent overlay upper and work paths (ReuseState). 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 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.
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>.debmarks success on theUnsharebefore it drops;Dropand the interrupt hook callcleanup(None).Unsharestores the outcome in anAtomicBool.- 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.
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}. TheUnshareconstructors are crate-private until their profiler and session inputs become optional.pkh::exec::{LineSink, Stream}.report::BuildView::sinkreturns the movedLineSink.pkh::deb::DebBuildOptionslosesctxandmode. A laterBackendvalue is additive.pkh::apt::sources::{load, save}and the keyring helpers takeOption<Arc<dyn Sandbox>>;Nonemeans aHostsandbox.
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
build_profile.rs Phase, BuildProfiler, BuildProfile, PhaseTiming
Phase, BuildProfiler and the profile record types live in
src/build_profile.rs. deb re-exports Phase and session re-exports the
record types, so their public paths do not change.
Migration plan (implemented)
Each step compiled and passed 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::new_with_base/new_for_sessionandDrop.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::Local(Arc<dyn Sandbox>)backed byHost.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 10 required methods and two provided methods
(
is_host,cleanup); every backend implements the required ones. One trait keepsArc<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 aReuseStateholding host paths becauseUnsharekeeps 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
sandbox::tests::conformancetakes&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. It runs againstHost.sandbox::unshare::namespace::path_testsruns the path and staging half againstUnshareDriverover a temp root, without namespace privileges.- A bootstrapped
Unshareneeds root,unshareand a tarball download, so its full command conformance is left to thepkh debandpkh teste2e 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.
Hoststays fast and unprivileged, sobuild/binary.rs,deb/local.rsandapt/sources.rsunit tests run without a chroot.