diff --git a/docs/sandbox.md b/docs/sandbox.md new file mode 100644 index 0000000..0a68762 --- /dev/null +++ b/docs/sandbox.md @@ -0,0 +1,530 @@ +# 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` 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` 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. + +```rust +/// 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; + + /// File operations, with paths inside the environment. + fn read_file(&self, path: &Path) -> io::Result; + fn write_file(&self, path: &Path, content: &str) -> io::Result<()>; + fn exists(&self, path: &Path) -> io::Result; + fn is_dir(&self, path: &Path) -> io::Result; + fn list_files(&self, path: &Path) -> io::Result>; + + /// Copy a host file or tree to `dest` inside the environment. + fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) + -> io::Result; + + /// 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; + + /// 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) -> 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: + +```rust +pub struct CommandSpec { + pub program: OsString, + pub args: Vec, + pub env: Vec<(OsString, OsString)>, + pub cwd: Option, +} + +pub enum Capture { + Inherit, + Lines(Arc), + Output, +} + +pub struct Execution { + pub status: ExitStatus, + pub stdout: Vec, + pub stderr: Vec, +} +``` + +`Execution` fills `stdout` and `stderr` only for `Capture::Output`. The shared +`BuildCommand` builder collects arguments and calls `run`: + +```rust +pub struct BuildCommand<'a> { + sandbox: &'a dyn Sandbox, + spec: CommandSpec, + capture: Capture, +} + +pub trait SandboxExt: Sandbox { + fn command(&self, program: &str) -> BuildCommand<'_> { /* ... */ } +} + +impl SandboxExt for T {} +``` + +The extension trait keeps `sandbox.command("apt-get")` working on +`Arc` without putting a generic or `Self: Sized` method on the +trait. `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: + +```rust +pub struct PutOptions { + /// Backend state to reuse for a resumable tree copy. + pub reuse: Option, + /// Directory names to skip at any depth. + pub skip_dirs: Vec, +} + +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: + +```rust +pub struct StageOptions { + /// Backend state to reuse for a resumable tree copy. + pub reuse: Option, + /// 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 { + 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` names backend state to reuse. `Unshare` treats it as the directory + that holds a persistent upper and work layer. 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` 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: + +```rust +pub struct UnshareSpec { + pub root: PathBuf, + pub series: String, + pub arch: Option, + pub mirror: Option, + pub ccache: Option, + 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`. + +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>`. 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. + `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` so it works through + `Arc`. `deb` calls `cleanup(Some(Success))` after a good build + and `cleanup(Some(Failure))` before returning an error; `Drop` and the + interrupt hook call `cleanup(None)`. `Unshare` stores the outcome in an + `AtomicBool` and 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 `/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>` 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. + +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}` and `Host`. +- `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 + `pkh::apt::keyring::download_trust_ppa_key` take `&dyn Sandbox`. +- `pkh::apt::keyring::download_cache_keyrings` becomes 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 + +```text +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. + +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`. 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::create` + and `Drop`. +5. `deb: drop the ctx and mode options` removes + `DebBuildOptions.ctx`, `DebBuildOptions.mode` and `BuildMode`, and passes the + `Arc` explicitly through `deb/local`. +6. `test: make local mode use Host` replaces `Bed::Local(Arc)` with + `Bed::Host` and the trait methods. +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`. +- 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 11 methods, and every backend must implement all + of them. One trait keeps `Arc` 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 `/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` 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 `/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 host `PathBuf` 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 + +- Add a conformance suite that 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. Run it against `Host` always and against `Unshare` when root and + `unshare` are available. +- A future `Ecrou` runs the same suite. That is the main reason to keep the trait + small and behavior explicit. +- Use `Arc` in a test to catch object-safety regressions. +- Port the existing `context` unit tests: staging strips VCS metadata, copies + dangling symlinks, maps unshare paths, prunes nested VCS directories, and + stages over an overlay upperdir. +- Delete the `ContextManager` tests with the manager. +- Add lifecycle tests: create an `Unshare` over a pre-populated fake root, drop + it, and check the root is kept or removed per `Teardown`. These do not need + privileges if they stop before `unshare`. +- Keep the `Host` implementation, so `build/binary.rs`, `deb/local.rs` and + `apt/sources.rs` unit tests stay fast and unprivileged. +- Run `pkh test --mode local` and `--mode chroot` in the e2e harness. +- Run the full suite and `cargo fmt --all` plus + `cargo clippy --all-targets --all-features` before each commit, as + `AGENTS.md` requires.