From a8ec36162b688d8a5ebdfeea1182ab1407672bad Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 21:57:08 -0700 Subject: [PATCH 1/6] drive the sandbox provider only through its trait MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine reached past `Sandbox` to walk a directory itself: fsmap::snapshot(&store, sandbox.root(), &filter) `Sandbox::snapshot` was dead code, and the seam §11 promises was a seam only on paper. Two things fell out of that. `root() -> &Path` was load-bearing rather than diagnostic, so a sandbox living on someone else's hardware could not satisfy the trait: it had to return some local path, and the engine would snapshot *that* path — empty — and store the result under the name of the work that was supposed to have happened. A wrong cache hit, arrived at through an interface that compiled. And the filter applied was the engine's hardcoded `typical()`, never the provider's, so `LocalProvider::with_filter` ran and did nothing. A provider excluding a build cache found it in the state's identity anyway. Now the engine calls `sandbox.snapshot()`, `root()` returns `Option<&Path>` and defaults to `None`, and the `Sandbox` docs state the blob-staging contract an implementor is actually signing up for. `provider_seam.rs` is the test that was missing: a provider whose `root()` is `None`. Exercising one implementation of a trait, however thoroughly, does not test the trait — every existing test used `LocalProvider`, for which both mistakes happened to be correct. Both new tests fail against the old engine. D44. --- crates/trajcache-engine/src/engine.rs | 13 +- .../trajcache-engine/tests/provider_seam.rs | 132 ++++++++++++++++++ crates/trajcache-sandbox/src/provider.rs | 42 +++++- crates/trajcache-sandbox/tests/determinism.rs | 2 +- decisions.md | 41 ++++++ 5 files changed, 217 insertions(+), 13 deletions(-) create mode 100644 crates/trajcache-engine/tests/provider_seam.rs diff --git a/crates/trajcache-engine/src/engine.rs b/crates/trajcache-engine/src/engine.rs index 128f851..f6bf292 100644 --- a/crates/trajcache-engine/src/engine.rs +++ b/crates/trajcache-engine/src/engine.rs @@ -50,7 +50,7 @@ use trajcache_core::{ StateManifest, }; use trajcache_index::{Lookup, ProvenanceIndex, Recorded}; -use trajcache_sandbox::{SandboxProvider, SnapshotFilter}; +use trajcache_sandbox::SandboxProvider; use trajcache_store::{StatePin, Store}; use crate::error::EngineError; @@ -254,7 +254,6 @@ struct EngineInner { bus: EventBus, config: EngineConfig, counters: Counters, - filter: SnapshotFilter, } /// Cheap to clone; every clone drives the same engine. @@ -314,7 +313,6 @@ impl Engine { bus: EventBus::new(), config, counters: Counters::default(), - filter: SnapshotFilter::typical(), }), } } @@ -698,7 +696,6 @@ impl Engine { let provider = Arc::clone(&self.inner.provider); let store = self.inner.store.clone(); let actions: Vec = canonical.to_vec(); - let filter = self.inner.filter.clone(); // Sandbox work is blocking (filesystem, processes). Running it on the // async runtime's worker threads would stall every other task on the @@ -723,7 +720,13 @@ impl Engine { for action in &actions { sandbox.exec(action)?; } - let manifest = trajcache_sandbox::snapshot(&store, sandbox.root(), &filter)?; + // `sandbox.snapshot()`, not `fsmap::snapshot(store, sandbox.root())`. + // The latter reads a local directory, which silently made + // `Sandbox` a local-filesystem interface: a provider that forks a + // VM somewhere else has no such directory to walk, and a + // provider-configured `SnapshotFilter` was ignored because the + // engine substituted its own. See `decisions.md` D44. + let manifest = sandbox.snapshot()?; let cost_ms = started.elapsed().as_millis() as u64; let result = store.insert(&manifest, base, cost_ms); diff --git a/crates/trajcache-engine/tests/provider_seam.rs b/crates/trajcache-engine/tests/provider_seam.rs new file mode 100644 index 0000000..90c82f1 --- /dev/null +++ b/crates/trajcache-engine/tests/provider_seam.rs @@ -0,0 +1,132 @@ +//! The provider seam, tested as a seam rather than as `LocalProvider`. +//! +//! §11 says the sandbox layer is "adapters, not implementations". That is only +//! true if the engine drives a provider entirely through the trait — and for a +//! while it did not: it read `sandbox.root()` and walked that directory itself +//! (D44). Both tests here fail against that version. + +mod common; + +use std::path::Path; +use std::sync::Arc; +use trajcache_core::*; +use trajcache_engine::*; +use trajcache_index::ProvenanceIndex; +use trajcache_sandbox::{ + BuiltinRuntime, DeterminismEnvelope, ExecReport, LocalProvider, Sandbox, SandboxError, + SandboxProvider, SnapshotFilter, +}; +use trajcache_store::Store; + +fn build(provider: Arc, store: Store) -> Engine { + let registry = common::registry(); + let index = Arc::new(ProvenanceIndex::new(Arc::clone(®istry))); + let canonicalizer = Canonicalizer::new(Arc::clone(®istry)); + let fingerprint = EnvFingerprint::builder( + hash(digest::DOMAIN_BLOB, b"base-image:seam"), + PlatformClass::new("x86_64", "linux", "glibc-2.36"), + ) + .tool_registry(®istry) + .build(); + Engine::new(store, index, canonicalizer, provider, fingerprint) +} + +fn actions() -> Vec { + vec![ + Action::call("mkdir", [("path", "/work")]), + Action::call( + "write_file", + [("path", "/work/kept.txt"), ("content", "kept")], + ), + Action::call( + "write_file", + [("path", "/work/scratch.log"), ("content", "noise")], + ), + ] +} + +/// A provider's `SnapshotFilter` decides what is in the state. +/// +/// It could not, before: the engine substituted a `SnapshotFilter::typical()` +/// of its own, so `LocalProvider::with_filter` compiled, ran, and did nothing. +/// A provider excluding a build cache or a vendor's own agent directory would +/// have found it in the state's identity anyway, renaming the state on every +/// capture. +#[tokio::test] +async fn the_providers_snapshot_filter_is_the_one_that_applies() { + let store = Store::in_memory(); + let provider = Arc::new( + LocalProvider::new(store.clone(), Arc::new(BuiltinRuntime)) + .with_filter(SnapshotFilter::typical().exclude_name("scratch.log")), + ); + let engine = build(provider, store.clone()); + + let realized = engine.realize(&actions()).await.unwrap(); + let manifest = store.materialize(realized.content).unwrap(); + let paths: Vec<&str> = manifest.entries.iter().map(|e| e.path.as_str()).collect(); + + assert!(paths.contains(&"/work/kept.txt"), "{paths:?}"); + assert!( + !paths.contains(&"/work/scratch.log"), + "the provider excluded scratch.log; it is in the state anyway: {paths:?}" + ); +} + +/// A sandbox that is not a directory on this machine. +/// +/// `root()` returns `None` — the honest answer for a forked VM — and the +/// engine must still name, execute, and store the state. It delegates +/// everything real to a `LocalProvider` underneath, because the point is the +/// *shape* of the interface, not a second filesystem implementation: if the +/// engine reaches for a local path anywhere, this panics. +#[derive(Debug)] +struct RootlessProvider(LocalProvider); + +struct RootlessSandbox(Box); + +impl SandboxProvider for RootlessProvider { + fn name(&self) -> &str { + "rootless" + } + fn create(&self, base: Option<&StateManifest>) -> Result, SandboxError> { + Ok(Box::new(RootlessSandbox(self.0.create(base)?))) + } +} + +impl Sandbox for RootlessSandbox { + fn exec(&mut self, action: &Action) -> Result { + self.0.exec(action) + } + fn snapshot(&self) -> Result { + self.0.snapshot() + } + fn envelope(&self) -> &DeterminismEnvelope { + self.0.envelope() + } + fn root(&self) -> Option<&Path> { + None + } +} + +#[tokio::test] +async fn a_sandbox_with_no_local_path_works_end_to_end() { + let store = Store::in_memory(); + let provider = Arc::new(RootlessProvider(LocalProvider::new( + store.clone(), + Arc::new(BuiltinRuntime), + ))); + let engine = build(provider, store.clone()); + + let cold = engine.realize(&actions()).await.unwrap(); + assert_eq!(cold.origin, Origin::Executed); + + let warm = engine.realize(&actions()).await.unwrap(); + assert_eq!(warm.origin, Origin::CacheHit); + assert_eq!(warm.content, cold.content); + + let manifest = store.materialize(cold.content).unwrap(); + assert!(manifest + .entries + .iter() + .any(|e| e.path == "/work/kept.txt")); +} diff --git a/crates/trajcache-sandbox/src/provider.rs b/crates/trajcache-sandbox/src/provider.rs index ff75562..44cd025 100644 --- a/crates/trajcache-sandbox/src/provider.rs +++ b/crates/trajcache-sandbox/src/provider.rs @@ -20,17 +20,42 @@ use crate::fsmap::{self, SnapshotFilter}; use crate::runtime::{ExecReport, ToolRuntime}; /// A live environment that actions can run in. +/// +/// Implementing this directly means taking on the blob-staging contract on +/// `snapshot` below. Most adapters should not: implement +/// [`SandboxBackend`](crate::backend::SandboxBackend) instead and let +/// [`FsProvider`](crate::backend::FsProvider) derive this trait for you. See +/// [`PROVIDERS.md`](https://github.com/angadjosan/trajcache/blob/main/PROVIDERS.md). pub trait Sandbox: Send { /// Run one action. fn exec(&mut self, action: &Action) -> Result; - /// Capture the current state. Blobs are staged in the store with live - /// references; the caller inserts the manifest (taking its own) and then - /// releases the staging ones. + /// Capture the current state. + /// + /// **Contract.** Every file's bytes must be in the blob store by the time + /// this returns, each holding one *staging* reference. The caller inserts + /// the manifest (which takes its own references) and then calls + /// [`release_staged`](crate::fsmap::release_staged) to return the staging + /// ones. An implementation that stages without the caller releasing leaks; + /// one that releases early can have its blobs evicted between here and the + /// insert. Both mistakes are easy, which is why + /// [`FsProvider`](crate::backend::FsProvider) exists to make them for you, + /// correctly. + /// + /// A partial failure must release whatever it already staged before + /// returning the error — otherwise the blobs are owned by nobody and freed + /// by nothing. fn snapshot(&self) -> Result; - /// Where the sandbox lives, for diagnostics. - fn root(&self) -> &Path; + /// Where the sandbox lives on *this* machine, if anywhere. + /// + /// Diagnostics only, and `None` is the honest answer for a sandbox that is + /// a VM on someone else's hardware. Nothing in the engine reads this to do + /// its work; it used to, and that quietly made this trait mean "a local + /// directory" (D44). + fn root(&self) -> Option<&Path> { + None + } /// The determinism envelope this sandbox ran under. Needed to compute the /// fingerprint a produced state should be filed under, and to recover a @@ -40,6 +65,9 @@ pub trait Sandbox: Send { /// Creates sandboxes, optionally starting from a saved state. pub trait SandboxProvider: Send + Sync + std::fmt::Debug { + /// Produce a live sandbox. When `base` is `Some`, the returned sandbox + /// must already contain exactly that state — every entry, with its mode + /// and symlink targets intact — and nothing else. fn create(&self, base: Option<&StateManifest>) -> Result, SandboxError>; /// A name for the report. Not part of any identity: which vendor forked @@ -147,8 +175,8 @@ impl Sandbox for LocalSandbox { fsmap::snapshot(&self.store, self.dir.path(), &self.filter) } - fn root(&self) -> &Path { - self.dir.path() + fn root(&self) -> Option<&Path> { + Some(self.dir.path()) } fn envelope(&self) -> &DeterminismEnvelope { diff --git a/crates/trajcache-sandbox/tests/determinism.rs b/crates/trajcache-sandbox/tests/determinism.rs index 19ea6b2..ef8752d 100644 --- a/crates/trajcache-sandbox/tests/determinism.rs +++ b/crates/trajcache-sandbox/tests/determinism.rs @@ -410,7 +410,7 @@ fn a_sandbox_starts_from_a_saved_state() { saved.content_name() ); assert_eq!( - std::fs::read_to_string(second.root().join("data.txt")).unwrap(), + std::fs::read_to_string(second.root().expect("local sandbox").join("data.txt")).unwrap(), "restored" ); } diff --git a/decisions.md b/decisions.md index 44b9b65..2e33be3 100644 --- a/decisions.md +++ b/decisions.md @@ -919,3 +919,44 @@ otherwise share a sequence. the direction that gets *more* likely as hardware gets faster, which is the worst way for a bug to hide: it would have arrived as a mystery CI failure on a newer runner. Twenty consecutive clean runs after the fix. + +## D44. `Sandbox` claimed to be an interface and was a local directory + +§11 commits to "adapters, not implementations, at the sandbox layer" — the +contribution is naming, and E2B, Daytona and Firecracker already fork well. +`SandboxProvider` is that seam, and it had two holes that made it a seam only +on paper. + +**The engine did not call `Sandbox::snapshot`.** It called +`fsmap::snapshot(&store, sandbox.root(), &filter)` — reaching past the trait +to walk a directory itself. Two consequences, both invisible until someone +tried to write a second provider: + +* `root() -> &Path` was load-bearing rather than diagnostic, so a sandbox that + is a VM on someone else's hardware could not satisfy the trait at all. It + had to return *some* local path, and the engine would then snapshot that + path — which contains nothing — and store an empty state under the name of + the work. A wrong cache hit, produced by the type system's silence. +* The `SnapshotFilter` the engine used was its own hardcoded `typical()`, so + `LocalProvider::with_filter` compiled, ran, and did nothing. A provider that + excluded a build cache or a vendor agent directory found it in the state's + identity anyway, and the state got a new name on every capture. + +`Sandbox::snapshot` existed the whole time and was dead code. That is the +tell: a trait method nobody calls is not an abstraction, it is a comment. + +Fixed by making the engine drive the provider *only* through the trait. +`root()` now returns `Option<&Path>` and defaults to `None`, which is the +honest answer for a remote sandbox, and nothing reads it to do work. + +**Why the tests did not catch it.** Every test used `LocalProvider`, for which +`sandbox.root()` and the engine's own filter happened to be right. A seam is +not tested by exercising one implementation of it, however thoroughly — it is +tested by a *second* implementation that is different in the way real ones +will be. `engine/tests/provider_seam.rs` is that second implementation: a +provider whose `root()` is `None`, which fails against the old engine with a +panic rather than a subtle wrong answer. + +The general form is worth keeping: **if only one implementation of a trait has +ever existed, assume the trait's shape is wrong** — it has been fitted to that +implementation's conveniences, and nothing has pushed back. From 2c6d846bec4c32d718f8eb8bbcabc92c14f5e4a9 Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 23:00:56 -0700 Subject: [PATCH 2/6] a seam adapters can actually implement, and a suite that proves they did MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Writing a sandbox adapter meant implementing `SandboxProvider`, which meant knowing four things that have nothing to do with sandboxes: that snapshot blobs carry a staging reference the caller releases, that a partial failure must hand those back or leak them permanently, that every directory must be created before any symlink, and that a peer's manifest path may be hostile. Each of those, got wrong, produces a state that is named wrong rather than an error — the cache then works perfectly, forever, on a lie. `SandboxBackend` asks instead for what a vendor already has: create a blank box, run a command, list files, read one, write one. `FsProvider` derives the real provider from it and owns all four rules. `read_many` and `apply` are batching hooks so a remote backend can collapse N round trips into one. `LocalBackend` is the worked example — about a hundred lines, no mention of blobs or manifests. The conformance suite is the half that matters. An adapter that is 95% right does not fail loudly: it drops an empty directory, or a file mode, and the naming layer cannot tell, because it hashes what it is handed and what it is handed is self-consistent. `conformance::check` runs fourteen properties against your provider and reports the path that changed rather than two hashes. It builds its states by restoring fixtures, never by running tools, so it assumes nothing about your toolset — and both providers here run it, including the hand-written one that predates it. `backend_parity.rs` is the differential test: the same actions through both providers must produce the same 32 bytes. A provider that names identical work differently has silently partitioned the cache by vendor. Writing the suite found D45 — `safe_join` refuses paths that escape, but accepted `trailing/`, which materializes as `trailing` and snapshots back as `/trailing`. The restore changed the identity of the state being restored, and nothing detected it because both halves were individually consistent. 378 tests. D45, D46. --- .../trajcache-engine/tests/provider_seam.rs | 5 +- crates/trajcache-sandbox/src/backend.rs | 509 +++++++++++++ crates/trajcache-sandbox/src/conformance.rs | 683 ++++++++++++++++++ crates/trajcache-sandbox/src/error.rs | 18 + crates/trajcache-sandbox/src/fsmap.rs | 10 + crates/trajcache-sandbox/src/lib.rs | 18 + crates/trajcache-sandbox/src/local_backend.rs | 178 +++++ .../trajcache-sandbox/tests/backend_parity.rs | 176 +++++ .../tests/conformance_local.rs | 148 ++++ decisions.md | 75 ++ 10 files changed, 1816 insertions(+), 4 deletions(-) create mode 100644 crates/trajcache-sandbox/src/backend.rs create mode 100644 crates/trajcache-sandbox/src/conformance.rs create mode 100644 crates/trajcache-sandbox/src/local_backend.rs create mode 100644 crates/trajcache-sandbox/tests/backend_parity.rs create mode 100644 crates/trajcache-sandbox/tests/conformance_local.rs diff --git a/crates/trajcache-engine/tests/provider_seam.rs b/crates/trajcache-engine/tests/provider_seam.rs index 90c82f1..db310ff 100644 --- a/crates/trajcache-engine/tests/provider_seam.rs +++ b/crates/trajcache-engine/tests/provider_seam.rs @@ -125,8 +125,5 @@ async fn a_sandbox_with_no_local_path_works_end_to_end() { assert_eq!(warm.content, cold.content); let manifest = store.materialize(cold.content).unwrap(); - assert!(manifest - .entries - .iter() - .any(|e| e.path == "/work/kept.txt")); + assert!(manifest.entries.iter().any(|e| e.path == "/work/kept.txt")); } diff --git a/crates/trajcache-sandbox/src/backend.rs b/crates/trajcache-sandbox/src/backend.rs new file mode 100644 index 0000000..7cfaf99 --- /dev/null +++ b/crates/trajcache-sandbox/src/backend.rs @@ -0,0 +1,509 @@ +//! The easy way to write a sandbox provider. +//! +//! [`SandboxProvider`] is the seam §11 asks for, but it is not the seam an +//! adapter author wants to implement. Satisfying it directly means knowing +//! that snapshot blobs carry a *staging* reference the caller will release, +//! that a partial failure has to hand those references back before returning, +//! that directories must precede their contents on restore, and that a path +//! arriving in a manifest from a peer may be trying to escape the root. None +//! of that is about E2B, or Firecracker, or your VM pool. All of it is about +//! this project's storage layer, and getting any of it wrong produces a state +//! that is silently *named wrong* rather than an error. +//! +//! So implement [`SandboxBackend`] instead. It asks for four things a sandbox +//! vendor already has: +//! +//! * create a blank box, +//! * run a command in it, +//! * list its files, +//! * read and write files. +//! +//! [`FsProvider`] turns that into a [`SandboxProvider`], and owns every rule +//! above. Then run [`crate::conformance`] against it, which is the same +//! battery `LocalBackend` passes. +//! +//! ```no_run +//! use std::sync::Arc; +//! use trajcache_sandbox::{FsProvider, LocalBackend}; +//! use trajcache_store::Store; +//! +//! let store = Store::in_memory(); +//! let provider = FsProvider::new(LocalBackend::builtin(), store); +//! ``` + +use std::path::Path; +use std::sync::Arc; + +use trajcache_core::{Action, EntryKind, FsEntry, StateManifest}; +use trajcache_store::Store; + +use crate::determinism::DeterminismEnvelope; +use crate::error::SandboxError; +use crate::fsmap::SnapshotFilter; +use crate::provider::{Sandbox, SandboxProvider}; +use crate::runtime::ExecReport; + +/// One entry in a sandbox's filesystem, as the backend reports it. +/// +/// Paths are absolute *within the sandbox*: they begin with `/`, use `/` as +/// the separator, and never contain a `..` component. `/` itself is not an +/// entry. A backend that reports anything else gets +/// [`SandboxError::PathEscape`] rather than having it normalized — see +/// [`validate_path`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileStat { + pub path: String, + pub kind: StatKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StatKind { + File { + /// Permission bits only; anything above `0o7777` is masked off. + mode: u32, + }, + Dir { + mode: u32, + }, + Symlink { + /// The link's target, verbatim. May dangle — a dangling symlink is + /// part of the state and must survive a round trip. + target: String, + }, +} + +impl FileStat { + pub fn file(path: impl Into, mode: u32) -> Self { + FileStat { + path: path.into(), + kind: StatKind::File { mode }, + } + } + pub fn dir(path: impl Into, mode: u32) -> Self { + FileStat { + path: path.into(), + kind: StatKind::Dir { mode }, + } + } + pub fn symlink(path: impl Into, target: impl Into) -> Self { + FileStat { + path: path.into(), + kind: StatKind::Symlink { + target: target.into(), + }, + } + } +} + +/// A write the provider asks the backend to perform when restoring a state. +/// +/// Bytes are owned rather than borrowed so that [`FsProvider`] can stream a +/// large state through in bounded batches instead of holding all of it in +/// memory at once. See [`FsProvider::with_batch_bytes`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FsOp { + Dir { + path: String, + mode: u32, + }, + File { + path: String, + mode: u32, + bytes: Vec, + }, + Symlink { + path: String, + target: String, + }, +} + +impl FsOp { + pub fn path(&self) -> &str { + match self { + FsOp::Dir { path, .. } | FsOp::File { path, .. } | FsOp::Symlink { path, .. } => path, + } + } +} + +/// A live sandbox, seen as a filesystem plus a way to run things. +/// +/// Every method may be a network round trip; the provider is written to make +/// few of them, and the batching hooks (`read_many`, `apply`) are where a +/// remote backend earns its latency back. +pub trait SandboxFs: Send { + /// Run one action. What "running" means is the backend's business: a + /// local backend shells out, a remote one posts to an API. + /// + /// The envelope is the §7 determinism context — pinned clock, seeded RNG, + /// cassette. A backend that cannot enforce it inside its VM should say so + /// (see [`SandboxBackend::honors_envelope`]) rather than ignore it + /// quietly, because a state named as reproducible that is not is the one + /// failure this project exists to prevent. + fn exec( + &mut self, + action: &Action, + envelope: &DeterminismEnvelope, + ) -> Result; + + /// Every entry in the sandbox, in any order. The provider sorts. + /// + /// Sockets, FIFOs and device nodes should be omitted: they are not + /// reproducible content, and a state that depends on one cannot be + /// honestly named. + fn list(&self) -> Result, SandboxError>; + + /// One file's bytes. + fn read(&self, path: &str) -> Result, SandboxError>; + + /// Several files' bytes, in the order asked. + /// + /// The default loops over [`read`](Self::read). Override it if a batch is + /// cheaper than N round trips — for most remote backends it is, and this + /// is the single highest-value method to override. + fn read_many(&self, paths: &[&str]) -> Result>, SandboxError> { + paths.iter().map(|p| self.read(p)).collect() + } + + /// Perform writes. Parents are always created before their children, so a + /// backend may assume the parent directory of any op already exists. + /// + /// The default loops over [`apply_one`](Self::apply_one). Override it to + /// send one tarball instead of N writes. + fn apply(&mut self, ops: Vec) -> Result<(), SandboxError> { + for op in ops { + self.apply_one(op)?; + } + Ok(()) + } + + /// Perform a single write. Only called by the default [`apply`](Self::apply); + /// a backend that overrides `apply` may leave this unimplemented. + fn apply_one(&mut self, op: FsOp) -> Result<(), SandboxError> { + Err(SandboxError::ProviderUnavailable(format!( + "backend implements neither apply nor apply_one, so it cannot restore `{}`", + op.path() + ))) + } + + /// Where this sandbox lives on the local machine, if anywhere. + /// Diagnostics only. + fn root(&self) -> Option<&Path> { + None + } +} + +/// Creates blank sandboxes. +/// +/// The unit an adapter author implements. Restoring a saved state into a fresh +/// box is [`FsProvider`]'s job, not yours — it needs the blob store to do it, +/// and keeping the store out of here is the entire point. +pub trait SandboxBackend: Send + Sync + std::fmt::Debug + 'static { + /// A blank sandbox. Must be empty: the provider restores a base state into + /// it and would otherwise be mixing that state with whatever was left over, + /// producing a state whose name describes only part of its contents. + fn create(&self) -> Result, SandboxError>; + + /// A name for reports. Not part of any identity: which vendor forked the + /// VM does not change what the resulting filesystem contains. + fn name(&self) -> &str; + + /// Whether this backend actually enforces the determinism envelope it is + /// handed — pinned clock, seeded RNG, cassette replay, frozen DNS. + /// + /// Default `false`, which is the truthful answer for a backend that + /// forwards a command to a VM and lets it see the real world. It is + /// advisory: nothing is refused, but the fingerprint records what the + /// environment claimed, and a backend claiming `true` while calling + /// `gettimeofday` is exactly what shadow verification exists to catch. + fn honors_envelope(&self) -> bool { + false + } +} + +/// Reject a sandbox path that is not what a manifest path must be. +/// +/// Rejects rather than sanitizes, for the reason [`crate::fsmap::safe_join`] +/// does: a path containing `..` is either a buggy backend or a hostile +/// manifest, and quietly normalizing it lets a hostile one keep trying until +/// it finds a normalization bug. +pub fn validate_path(path: &str) -> Result<(), SandboxError> { + if !path.starts_with('/') || path == "/" { + return Err(SandboxError::PathEscape(path.to_string())); + } + for segment in path[1..].split('/') { + if segment.is_empty() || segment == "." || segment == ".." { + return Err(SandboxError::PathEscape(path.to_string())); + } + } + Ok(()) +} + +/// Turns a [`SandboxBackend`] into a [`SandboxProvider`]. +/// +/// Owns everything about this project that a backend should not have to know: +/// content-addressing the bytes, the staging-reference protocol on snapshot, +/// restore ordering, path validation, and the snapshot filter. +#[derive(Debug)] +pub struct FsProvider { + backend: Arc, + store: Store, + filter: SnapshotFilter, + envelope: Arc, + batch_bytes: usize, + verify_restore: bool, +} + +/// 8 MiB. Large enough that a batch is worth a round trip, small enough that +/// restoring a multi-gigabyte state does not hold it all in memory. +const DEFAULT_BATCH_BYTES: usize = 8 * 1024 * 1024; + +impl FsProvider { + pub fn new(backend: impl SandboxBackend, store: Store) -> Self { + FsProvider { + backend: Arc::new(backend), + store, + filter: SnapshotFilter::typical(), + envelope: Arc::new(DeterminismEnvelope::open()), + batch_bytes: DEFAULT_BATCH_BYTES, + verify_restore: false, + } + } + + pub fn with_envelope(mut self, envelope: Arc) -> Self { + self.envelope = envelope; + self + } + + pub fn with_filter(mut self, filter: SnapshotFilter) -> Self { + self.filter = filter; + self + } + + /// How many bytes of file content to buffer before flushing a batch of + /// writes to the backend. A single file larger than this is still sent in + /// one op — it has to be. + pub fn with_batch_bytes(mut self, bytes: usize) -> Self { + self.batch_bytes = bytes.max(1); + self + } + + /// After restoring a base state, snapshot the sandbox and check it matches. + /// + /// Off by default: it doubles the cost of every restore. Worth turning on + /// while bringing up a new backend, because it converts "this backend + /// drops file modes" from a mysterious cache miss weeks later into an + /// error at the point of the mistake. [`crate::conformance`] turns it on. + pub fn with_verify_restore(mut self, verify: bool) -> Self { + self.verify_restore = verify; + self + } + + pub fn backend(&self) -> &Arc { + &self.backend + } + + /// Write a saved state into a blank sandbox. + fn restore( + &self, + fs: &mut dyn SandboxFs, + manifest: &StateManifest, + ) -> Result<(), SandboxError> { + for entry in &manifest.entries { + validate_path(&entry.path)?; + } + + // Directories first, all of them, before any file or symlink. The + // manifest is sorted by path, so a parent precedes its children within + // this pass — which is what lets a backend assume the parent of any op + // exists. Doing it in one pass would break that for a symlink whose + // target directory sorts after it. + let dirs: Vec = manifest + .entries + .iter() + .filter_map(|entry| match entry.kind { + EntryKind::Dir { mode } => Some(FsOp::Dir { + path: entry.path.clone(), + mode, + }), + _ => None, + }) + .collect(); + if !dirs.is_empty() { + fs.apply(dirs)?; + } + + let mut batch: Vec = Vec::new(); + let mut batched = 0usize; + for entry in &manifest.entries { + let op = match &entry.kind { + EntryKind::Dir { .. } => continue, + EntryKind::Symlink { target } => FsOp::Symlink { + path: entry.path.clone(), + target: target.clone(), + }, + EntryKind::File { mode, size, blob } => { + let bytes = self + .store + .blobs() + .get(*blob)? + .ok_or(SandboxError::MissingBlob(*blob))?; + // The manifest's size is checked against the blob's, as + // `fsmap::materialize` does. The blob store verifies the + // digest; this catches a manifest that disagrees with a + // blob both of which are individually intact. + if bytes.len() as u64 != *size { + return Err(SandboxError::SizeMismatch { + path: entry.path.clone(), + expected: *size, + actual: bytes.len() as u64, + }); + } + batched += bytes.len(); + FsOp::File { + path: entry.path.clone(), + mode: *mode, + bytes, + } + } + }; + batch.push(op); + if batched >= self.batch_bytes { + fs.apply(std::mem::take(&mut batch))?; + batched = 0; + } + } + if !batch.is_empty() { + fs.apply(batch)?; + } + Ok(()) + } +} + +impl SandboxProvider for FsProvider { + fn name(&self) -> &str { + self.backend.name() + } + + fn create(&self, base: Option<&StateManifest>) -> Result, SandboxError> { + let mut fs = self.backend.create()?; + if let Some(manifest) = base { + self.restore(fs.as_mut(), manifest)?; + } + let sandbox = FsSandbox { + fs, + store: self.store.clone(), + filter: self.filter.clone(), + envelope: Arc::clone(&self.envelope), + }; + if self.verify_restore { + if let Some(manifest) = base { + let observed = sandbox.snapshot()?; + let matched = observed.content_name() == manifest.content_name(); + // Release the staging references this check took. They are + // ours, not the caller's: the caller never sees this manifest. + crate::fsmap::release_staged(&self.store, &observed); + if !matched { + return Err(SandboxError::RestoreMismatch { + backend: self.backend.name().to_string(), + expected: manifest.content_name().to_string(), + actual: observed.content_name().to_string(), + }); + } + } + } + Ok(Box::new(sandbox)) + } +} + +struct FsSandbox { + fs: Box, + store: Store, + filter: SnapshotFilter, + envelope: Arc, +} + +impl Sandbox for FsSandbox { + fn exec(&mut self, action: &Action) -> Result { + self.fs.exec(action, &self.envelope) + } + + fn root(&self) -> Option<&Path> { + self.fs.root() + } + + fn envelope(&self) -> &DeterminismEnvelope { + &self.envelope + } + + fn snapshot(&self) -> Result { + let mut stats = self.fs.list()?; + for stat in &stats { + validate_path(&stat.path)?; + } + stats.retain(|stat| !self.filter.excludes(&stat.path)); + // Sorted so that `read_many` asks for files in a predictable order and + // a backend streaming a directory sees locality. `StateManifest::new` + // sorts too; this is not load-bearing for the name. + stats.sort_by(|a, b| a.path.cmp(&b.path)); + + let file_paths: Vec<&str> = stats + .iter() + .filter(|s| matches!(s.kind, StatKind::File { .. })) + .map(|s| s.path.as_str()) + .collect(); + let contents = self.fs.read_many(&file_paths)?; + if contents.len() != file_paths.len() { + return Err(SandboxError::ProviderUnavailable(format!( + "backend returned {} blobs for {} paths", + contents.len(), + file_paths.len() + ))); + } + + // Everything below stages blobs. From here on, any error must hand + // back what it already staged — otherwise those references are owned + // by nobody and freed by nothing, and eviction can never reach them. + // Same hazard `fsmap::snapshot` documents (D41), same handling. + let mut entries = Vec::with_capacity(stats.len()); + let mut contents = contents.into_iter(); + let staged = (|| -> Result<(), SandboxError> { + for stat in &stats { + let entry = match &stat.kind { + StatKind::Dir { mode } => FsEntry { + path: stat.path.clone(), + kind: EntryKind::Dir { + mode: mode & 0o7777, + }, + }, + StatKind::Symlink { target } => FsEntry::symlink(&stat.path, target), + StatKind::File { mode } => { + let bytes = contents.next().expect("counted above"); + let blob = self.store.blobs().put(&bytes)?; + FsEntry { + path: stat.path.clone(), + kind: EntryKind::File { + mode: mode & 0o7777, + size: bytes.len() as u64, + blob, + }, + } + } + }; + entries.push(entry); + } + Ok(()) + })(); + + match staged { + Ok(()) => Ok(StateManifest::new(entries)), + Err(e) => { + for entry in &entries { + if let Some(blob) = entry.blob() { + let _ = self.store.blobs().release(blob); + } + } + Err(e) + } + } + } +} diff --git a/crates/trajcache-sandbox/src/conformance.rs b/crates/trajcache-sandbox/src/conformance.rs new file mode 100644 index 0000000..976ac3d --- /dev/null +++ b/crates/trajcache-sandbox/src/conformance.rs @@ -0,0 +1,683 @@ +//! Does your sandbox adapter actually work? +//! +//! An adapter that is 95% right does not fail loudly. It produces a state that +//! is *named* as one thing and *contains* another — an empty directory that a +//! tarball dropped, a file mode a copy did not preserve — and the system then +//! serves that state, correctly and quickly, forever. The naming layer cannot +//! detect this: it hashes what you hand it, and what you hand it is +//! self-consistent. Only a test that knows what the state was *supposed* to be +//! can tell. +//! +//! So this is that test, packaged so it runs against your adapter rather than +//! only against ours: +//! +//! ``` +//! # // In your crate this is the body of a `#[test] fn my_backend_is_conformant()`. +//! use trajcache_sandbox::{conformance, FsProvider, LocalBackend}; +//! use trajcache_store::Store; +//! +//! let store = Store::in_memory(); +//! let provider = FsProvider::new(LocalBackend::builtin(), store.clone()) +//! .with_verify_restore(true); +//! conformance::check(&provider, &store).assert_ok(); +//! ``` +//! +//! Every check is a property the rest of the system assumes without asking. +//! None of them test *your* tools, your VM's performance, or anything specific +//! to a vendor — only that a state put into a sandbox comes back out as the +//! same state. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::Arc; + +use trajcache_core::{Digest, EntryKind, FsEntry, StateManifest}; +use trajcache_store::Store; + +use crate::error::SandboxError; +use crate::provider::SandboxProvider; + +/// One property, and whether the adapter has it. +#[derive(Debug, Clone)] +pub struct CheckOutcome { + pub name: &'static str, + /// What the check is protecting, in one line. Printed on failure, because + /// "modes_survive failed" is not enough to act on at 2am. + pub because: &'static str, + pub failure: Option, +} + +impl CheckOutcome { + pub fn passed(&self) -> bool { + self.failure.is_none() + } +} + +#[derive(Debug, Clone)] +pub struct ConformanceReport { + pub backend: String, + pub checks: Vec, +} + +impl ConformanceReport { + pub fn passed(&self) -> bool { + self.checks.iter().all(CheckOutcome::passed) + } + + pub fn failures(&self) -> impl Iterator { + self.checks.iter().filter(|c| !c.passed()) + } + + /// Panic with the full report if anything failed. For use in a `#[test]`. + #[track_caller] + pub fn assert_ok(&self) { + assert!(self.passed(), "{self}"); + } +} + +impl fmt::Display for ConformanceReport { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let failed = self.failures().count(); + writeln!( + f, + "conformance: {} — {}/{} checks passed", + self.backend, + self.checks.len() - failed, + self.checks.len() + )?; + for check in &self.checks { + match &check.failure { + None => writeln!(f, " pass {}", check.name)?, + Some(detail) => { + writeln!(f, " FAIL {}", check.name)?; + writeln!(f, " {detail}")?; + writeln!(f, " why this matters: {}", check.because)?; + } + } + } + Ok(()) + } +} + +/// Run every check against a provider. +/// +/// `store` must be the store the provider was built with — the checks stage +/// blobs through it and verify the provider hands its staging references back. +pub fn check(provider: &dyn SandboxProvider, store: &Store) -> ConformanceReport { + let mut checks = Vec::new(); + let mut run = + |name: &'static str, because: &'static str, f: &dyn Fn() -> Result<(), String>| { + checks.push(CheckOutcome { + name, + because, + failure: f().err(), + }); + }; + + run( + "blank_sandbox_is_empty", + "a leftover file in a fresh box joins every state built in it, so the state's name \ + describes contents that came from nowhere. If your box has a fixed base layer, exclude \ + it with SnapshotFilter rather than letting it into the manifest.", + &|| blank_is_empty(provider, store), + ); + run( + "snapshot_is_stable", + "two snapshots of an unchanged sandbox must produce one name. If they do not, something \ + outside the manifest — an mtime, an inode, a temp file — is reaching the hash, and no \ + state will ever be reused.", + &|| snapshot_is_stable(provider, store), + ); + run( + "restore_round_trips", + "the core property: a state written into a sandbox must read back as the same state. \ + Everything else this project claims rests on it.", + &|| round_trips(provider, store, fixture_ordinary()), + ); + run( + "file_modes_survive", + "an executable that comes back non-executable is a state that is named correctly and \ + does not work. Copy helpers and tarball extraction lose modes by default.", + &|| round_trips(provider, store, fixture_modes()), + ); + run( + "empty_directories_survive", + "an empty directory is state — a mount point, an output dir a build expects. Most \ + file-listing APIs and several archive formats drop it.", + &|| round_trips(provider, store, fixture_empty_dirs()), + ); + run( + "symlinks_survive_including_dangling", + "a symlink must come back as a link, not as a copy of its target, and a dangling link is \ + legal state. Following links also duplicates bytes and hangs on a cycle.", + &|| round_trips(provider, store, fixture_symlinks()), + ); + run( + "binary_content_survives", + "all 256 byte values, embedded NULs, and no trailing newline. A backend that moves file \ + content as text corrupts exactly the files an agent's environment is made of.", + &|| round_trips(provider, store, fixture_binary()), + ); + run( + "awkward_paths_survive", + "spaces, unicode, dots and deep nesting appear in real repositories. A path that survives \ + the round trip changed is a different state under the same name.", + &|| round_trips(provider, store, fixture_awkward_paths()), + ); + run( + "large_files_survive_batching", + "content larger than one write batch must reassemble in order. This is where a chunked \ + upload gets its offsets wrong.", + &|| round_trips(provider, store, fixture_large()), + ); + run( + "escaping_paths_are_refused", + "a manifest arriving from a peer may contain `../../etc/ssh/authorized_keys`. Writing it \ + turns fetching a state into executing someone else's bits.", + &|| refuses_escapes(provider, store), + ); + run( + "sandboxes_are_isolated", + "two sandboxes that share storage make one rollout's writes appear in another's state, \ + which is a wrong cache hit with no symptom until much later.", + &|| isolated(provider, store), + ); + run( + "concurrent_creates_succeed", + "the engine creates sandboxes from many threads at once. A backend with a shared mutable \ + path or a non-reentrant client fails here and nowhere else.", + &|| concurrent_creates(provider, store), + ); + run( + "snapshot_leaves_no_staged_blobs", + "snapshot stages one blob reference per file for the caller to release. Staging without \ + release leaks blobs that eviction can never reach, because no state owns them.", + &|| no_staging_leak(provider, store), + ); + run( + "failed_restore_reports_an_error", + "a missing blob must fail loudly. Restoring what is available and continuing produces a \ + partial state under the full state's name.", + &|| missing_blob_errors(provider, store), + ); + + ConformanceReport { + backend: provider.name().to_string(), + checks, + } +} + +// ---------------------------------------------------------------- fixtures + +/// A manifest built from `(path, kind)` descriptions, with the bytes staged. +/// +/// Returns the manifest and the digests it staged, which the caller releases +/// once the check is done — the fixture is the *caller* here, so it plays by +/// the same staging rules an adapter does. +struct Fixture { + entries: Vec<(String, FixtureKind)>, +} + +enum FixtureKind { + File { mode: u32, bytes: Vec }, + Dir { mode: u32 }, + Symlink { target: String }, +} + +impl Fixture { + fn build(self, store: &Store) -> Result<(StateManifest, Vec), String> { + let mut entries = Vec::new(); + let mut staged = Vec::new(); + for (path, kind) in self.entries { + let entry = match kind { + FixtureKind::Dir { mode } => FsEntry { + path, + kind: EntryKind::Dir { mode }, + }, + FixtureKind::Symlink { target } => FsEntry::symlink(path, target), + FixtureKind::File { mode, bytes } => { + let blob = store.blobs().put(&bytes).map_err(|e| e.to_string())?; + staged.push(blob); + FsEntry { + path, + kind: EntryKind::File { + mode, + size: bytes.len() as u64, + blob, + }, + } + } + }; + entries.push(entry); + } + Ok((StateManifest::new(entries), staged)) + } +} + +fn file(path: &str, mode: u32, bytes: impl Into>) -> (String, FixtureKind) { + ( + path.to_string(), + FixtureKind::File { + mode, + bytes: bytes.into(), + }, + ) +} +fn dir(path: &str, mode: u32) -> (String, FixtureKind) { + (path.to_string(), FixtureKind::Dir { mode }) +} +fn link(path: &str, target: &str) -> (String, FixtureKind) { + ( + path.to_string(), + FixtureKind::Symlink { + target: target.to_string(), + }, + ) +} + +fn fixture_ordinary() -> Fixture { + Fixture { + entries: vec![ + dir("/repo", 0o755), + dir("/repo/src", 0o755), + file("/repo/src/main.py", 0o644, "print('hello')\n"), + file("/repo/README.md", 0o644, "# a repo\n"), + ], + } +} + +fn fixture_modes() -> Fixture { + Fixture { + entries: vec![ + dir("/bin", 0o755), + dir("/private", 0o700), + file("/bin/run.sh", 0o755, "#!/bin/sh\nexit 0\n"), + file("/private/key", 0o600, "secret"), + file("/readonly.txt", 0o444, "immutable"), + ], + } +} + +fn fixture_empty_dirs() -> Fixture { + Fixture { + entries: vec![ + dir("/build", 0o755), + dir("/build/out", 0o755), + dir("/mnt", 0o755), + file("/build/keep.txt", 0o644, "x"), + ], + } +} + +fn fixture_symlinks() -> Fixture { + Fixture { + entries: vec![ + dir("/lib", 0o755), + file("/lib/libfoo.so.1", 0o755, "ELF"), + link("/lib/libfoo.so", "libfoo.so.1"), + link("/lib/absolute", "/lib/libfoo.so.1"), + // Dangling on purpose: legal state, and a backend that resolves + // links will either fail here or silently copy nothing. + link("/lib/dangling", "../nowhere/at/all"), + ], + } +} + +fn fixture_binary() -> Fixture { + let all_bytes: Vec = (0u8..=255).collect(); + Fixture { + entries: vec![ + file("/bin.dat", 0o644, all_bytes), + file("/nulls.dat", 0o644, vec![0u8; 512]), + file("/no-newline", 0o644, "no trailing newline"), + file("/empty", 0o644, Vec::new()), + ], + } +} + +fn fixture_awkward_paths() -> Fixture { + let mut entries = vec![ + dir("/a dir with spaces", 0o755), + file("/a dir with spaces/a file.txt", 0o644, "spaces"), + dir("/ünïcode", 0o755), + file("/ünïcode/日本語.txt", 0o644, "unicode"), + file("/.hidden", 0o644, "dot"), + file("/trailing.dots...", 0o644, "dots"), + ]; + // Deep nesting: a path long enough to exercise anything that assumes a + // shallow tree. + let mut path = String::new(); + for i in 0..24 { + path.push_str(&format!("/level{i}")); + entries.push(dir(&path, 0o755)); + } + entries.push(file(&format!("{path}/deep.txt"), 0o644, "deep")); + Fixture { entries } +} + +fn fixture_large() -> Fixture { + // Deterministic pseudo-random bytes: incompressible enough that a backend + // silently truncating or reordering chunks changes the digest. + let mut bytes = Vec::with_capacity(3 * 1024 * 1024); + let mut x: u64 = 0x243F_6A88_85A3_08D3; + while bytes.len() < 3 * 1024 * 1024 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + bytes.extend_from_slice(&x.to_le_bytes()); + } + Fixture { + entries: vec![ + file("/big.bin", 0o644, bytes), + file("/after-big.txt", 0o644, "written after the large file"), + ], + } +} + +// ------------------------------------------------------------------ checks + +fn release(store: &Store, digests: &[Digest]) { + for d in digests { + let _ = store.blobs().release(*d); + } +} + +/// Snapshot, then hand the staging references straight back — the check owns +/// the manifest only long enough to compare names. +fn snapshot_and_release( + sandbox: &dyn crate::provider::Sandbox, + store: &Store, +) -> Result { + let manifest = sandbox.snapshot()?; + crate::fsmap::release_staged(store, &manifest); + Ok(manifest) +} + +fn blank_is_empty(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let sandbox = provider.create(None).map_err(|e| e.to_string())?; + let manifest = snapshot_and_release(sandbox.as_ref(), store).map_err(|e| e.to_string())?; + if manifest.entries.is_empty() { + return Ok(()); + } + let sample: Vec<&str> = manifest + .entries + .iter() + .take(8) + .map(|e| e.path.as_str()) + .collect(); + Err(format!( + "a sandbox created with no base state already contains {} entries, e.g. {sample:?}", + manifest.entries.len() + )) +} + +fn snapshot_is_stable(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let (manifest, staged) = fixture_ordinary().build(store)?; + let result = (|| { + let sandbox = provider + .create(Some(&manifest)) + .map_err(|e| e.to_string())?; + let first = snapshot_and_release(sandbox.as_ref(), store).map_err(|e| e.to_string())?; + let second = snapshot_and_release(sandbox.as_ref(), store).map_err(|e| e.to_string())?; + if first.content_name() != second.content_name() { + return Err(format!( + "two snapshots of an unchanged sandbox disagree: {} then {}\n {}", + first.content_name(), + second.content_name(), + describe_difference(&first, &second) + )); + } + Ok(()) + })(); + release(store, &staged); + result +} + +fn round_trips( + provider: &dyn SandboxProvider, + store: &Store, + fixture: Fixture, +) -> Result<(), String> { + let (manifest, staged) = fixture.build(store)?; + let result = (|| { + let sandbox = provider + .create(Some(&manifest)) + .map_err(|e| e.to_string())?; + let observed = snapshot_and_release(sandbox.as_ref(), store).map_err(|e| e.to_string())?; + if observed.content_name() == manifest.content_name() { + return Ok(()); + } + Err(format!( + "state written in, different state read back\n {}", + describe_difference(&manifest, &observed) + )) + })(); + release(store, &staged); + result +} + +/// What actually differs, so a failure names the bug rather than two hashes. +fn describe_difference(expected: &StateManifest, actual: &StateManifest) -> String { + let want: BTreeMap<&str, &EntryKind> = expected + .entries + .iter() + .map(|e| (e.path.as_str(), &e.kind)) + .collect(); + let got: BTreeMap<&str, &EntryKind> = actual + .entries + .iter() + .map(|e| (e.path.as_str(), &e.kind)) + .collect(); + + let mut notes = Vec::new(); + for (path, kind) in &want { + match got.get(path) { + None => notes.push(format!("missing: {path} ({})", kind_name(kind))), + Some(other) if other != kind => notes.push(format!( + "changed: {path} — expected {}, got {}", + describe_kind(kind), + describe_kind(other) + )), + Some(_) => {} + } + } + for (path, kind) in &got { + if !want.contains_key(path) { + notes.push(format!("unexpected: {path} ({})", kind_name(kind))); + } + } + if notes.is_empty() { + return "entries are identical; the difference is in the manifest itself".to_string(); + } + notes.truncate(10); + notes.join("\n ") +} + +fn kind_name(kind: &EntryKind) -> &'static str { + match kind { + EntryKind::File { .. } => "file", + EntryKind::Dir { .. } => "dir", + EntryKind::Symlink { .. } => "symlink", + } +} + +fn describe_kind(kind: &EntryKind) -> String { + match kind { + EntryKind::File { mode, size, .. } => format!("file mode {mode:o} size {size}"), + EntryKind::Dir { mode } => format!("dir mode {mode:o}"), + EntryKind::Symlink { target } => format!("symlink -> {target}"), + } +} + +fn refuses_escapes(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let escapes = [ + "/../outside.txt", + "/repo/../../outside.txt", + "relative.txt", + "/", + "//double", + "/trailing/", + ]; + for path in escapes { + let blob = store.blobs().put(b"hostile").map_err(|e| e.to_string())?; + let manifest = StateManifest::new(vec![FsEntry { + path: path.to_string(), + kind: EntryKind::File { + mode: 0o644, + size: 7, + blob, + }, + }]); + let outcome = provider.create(Some(&manifest)); + let _ = store.blobs().release(blob); + match outcome { + Err(SandboxError::PathEscape(_)) => {} + Err(other) => { + return Err(format!( + "path `{path}` was refused, but with {other} rather than PathEscape" + )) + } + Ok(_) => return Err(format!("path `{path}` was accepted; it must be refused")), + } + } + Ok(()) +} + +fn isolated(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let (manifest, staged) = fixture_ordinary().build(store)?; + let result = (|| { + let filled = provider + .create(Some(&manifest)) + .map_err(|e| e.to_string())?; + let blank = provider.create(None).map_err(|e| e.to_string())?; + let blank_state = snapshot_and_release(blank.as_ref(), store).map_err(|e| e.to_string())?; + if !blank_state.entries.is_empty() { + return Err(format!( + "a sandbox created alongside a populated one contains {} entries; the two share \ + storage", + blank_state.entries.len() + )); + } + // And the populated one is unchanged by the other's existence. + let after = snapshot_and_release(filled.as_ref(), store).map_err(|e| e.to_string())?; + if after.content_name() != manifest.content_name() { + return Err("creating a second sandbox changed the first one's state".to_string()); + } + Ok(()) + })(); + release(store, &staged); + result +} + +fn concurrent_creates(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let (manifest, staged) = fixture_ordinary().build(store)?; + let expected = manifest.content_name(); + let errors: Arc>> = + Arc::new(parking_lot::Mutex::new(Vec::new())); + + std::thread::scope(|scope| { + for _ in 0..8 { + let errors = Arc::clone(&errors); + let manifest = &manifest; + scope.spawn(move || { + let outcome = (|| -> Result<(), String> { + let sandbox = provider.create(Some(manifest)).map_err(|e| e.to_string())?; + let observed = + snapshot_and_release(sandbox.as_ref(), store).map_err(|e| e.to_string())?; + if observed.content_name() != expected { + return Err(format!( + "concurrent create produced {} instead of {expected}", + observed.content_name() + )); + } + Ok(()) + })(); + if let Err(e) = outcome { + errors.lock().push(e); + } + }); + } + }); + + release(store, &staged); + let errors = errors.lock(); + if errors.is_empty() { + Ok(()) + } else { + Err(format!( + "{} of 8 concurrent creates failed; first: {}", + errors.len(), + errors[0] + )) + } +} + +fn no_staging_leak(provider: &dyn SandboxProvider, store: &Store) -> Result<(), String> { + let (manifest, staged) = fixture_ordinary().build(store)?; + let before: BTreeMap = store + .blobs() + .live_digests() + .into_iter() + .map(|d| (d, store.blobs().ref_count(d))) + .collect(); + + let result = (|| { + let sandbox = provider + .create(Some(&manifest)) + .map_err(|e| e.to_string())?; + let observed = sandbox.snapshot().map_err(|e| e.to_string())?; + crate::fsmap::release_staged(store, &observed); + drop(sandbox); + + let after: BTreeMap = store + .blobs() + .live_digests() + .into_iter() + .map(|d| (d, store.blobs().ref_count(d))) + .collect(); + + let mut drift = Vec::new(); + for (digest, count) in &after { + let was = before.get(digest).copied().unwrap_or(0); + if *count != was { + drift.push(format!("{digest}: {was} -> {count}")); + } + } + for digest in before.keys() { + if !after.contains_key(digest) { + drift.push(format!("{digest}: released too many times")); + } + } + if drift.is_empty() { + Ok(()) + } else { + drift.truncate(5); + Err(format!( + "snapshot + release_staged did not balance:\n {}", + drift.join("\n ") + )) + } + })(); + release(store, &staged); + result +} + +fn missing_blob_errors(provider: &dyn SandboxProvider, _store: &Store) -> Result<(), String> { + // A digest of bytes nobody stored. + let absent = trajcache_store::blob_digest(b"this blob was never put into the store"); + let manifest = StateManifest::new(vec![FsEntry { + path: "/ghost.txt".to_string(), + kind: EntryKind::File { + mode: 0o644, + size: 38, + blob: absent, + }, + }]); + match provider.create(Some(&manifest)) { + Err(_) => Ok(()), + Ok(_) => Err( + "restoring a state whose content is missing from the store succeeded; it must fail" + .to_string(), + ), + } +} diff --git a/crates/trajcache-sandbox/src/error.rs b/crates/trajcache-sandbox/src/error.rs index 4aa0178..7ab384c 100644 --- a/crates/trajcache-sandbox/src/error.rs +++ b/crates/trajcache-sandbox/src/error.rs @@ -44,6 +44,24 @@ pub enum SandboxError { #[error("sandbox provider unavailable: {0}")] ProviderUnavailable(String), + #[error( + "backend `{backend}` restored a state that does not match: expected {expected}, got \ + {actual}. Something the manifest records — a file mode, a symlink target, an empty \ + directory — did not survive the round trip" + )] + RestoreMismatch { + backend: String, + expected: String, + actual: String, + }, + + #[error("backend `{backend}` failed conformance: {check} — {detail}")] + ConformanceFailure { + backend: String, + check: &'static str, + detail: String, + }, + #[error(transparent)] Store(#[from] trajcache_store::StoreError), diff --git a/crates/trajcache-sandbox/src/fsmap.rs b/crates/trajcache-sandbox/src/fsmap.rs index b23bac6..852bbcc 100644 --- a/crates/trajcache-sandbox/src/fsmap.rs +++ b/crates/trajcache-sandbox/src/fsmap.rs @@ -195,6 +195,16 @@ pub fn materialize( let root = root.as_ref(); fs::create_dir_all(root)?; + // Every path is checked for well-formedness, not only for escaping. + // `safe_join` alone accepts `trailing/` and `relative.txt`, which do not + // escape anything but do not *round trip* either: they are written as + // `trailing` and `relative.txt`, and the next snapshot names them + // `/trailing` and `/relative.txt`. A state that changes name by being + // restored is a state you verified and then did not get. See D45. + for entry in &manifest.entries { + crate::backend::validate_path(&entry.path)?; + } + // Directories first, in sorted order, so a file never precedes its parent. for entry in &manifest.entries { let target = safe_join(root, &entry.path)?; diff --git a/crates/trajcache-sandbox/src/lib.rs b/crates/trajcache-sandbox/src/lib.rs index 867470b..55e985b 100644 --- a/crates/trajcache-sandbox/src/lib.rs +++ b/crates/trajcache-sandbox/src/lib.rs @@ -14,16 +14,34 @@ //! //! And [`provider`] is the adapter seam §11 asks for — E2B, Daytona, and //! AgentENV fork well already; the contribution is the layer above them. +//! +//! # Writing an adapter +//! +//! Implement [`backend::SandboxBackend`] — create a box, run a command, list +//! files, read and write them — and wrap it in [`backend::FsProvider`], which +//! owns everything about blobs, manifests and staging references that a +//! vendor adapter has no business knowing. Then run +//! [`conformance::check`] against it. [`local_backend`] is the worked example +//! and `PROVIDERS.md` is the guide. +//! +//! [`provider::SandboxProvider`] remains the interface the engine consumes, +//! for the rare adapter that wants to own snapshotting itself. #![forbid(unsafe_code)] +pub mod backend; +pub mod conformance; pub mod determinism; pub mod entropy; pub mod error; pub mod fsmap; +pub mod local_backend; pub mod provider; pub mod runtime; +pub use backend::{validate_path, FileStat, FsOp, FsProvider, SandboxBackend, SandboxFs, StatKind}; +pub use local_backend::LocalBackend; + pub use determinism::{ Cassette, DeterminismEnvelope, EnvelopeStats, HttpRequest, HttpResponse, SplitMix64, }; diff --git a/crates/trajcache-sandbox/src/local_backend.rs b/crates/trajcache-sandbox/src/local_backend.rs new file mode 100644 index 0000000..707fba5 --- /dev/null +++ b/crates/trajcache-sandbox/src/local_backend.rs @@ -0,0 +1,178 @@ +//! A [`SandboxBackend`] over a directory on this machine. +//! +//! Two jobs. It is the backend the tests and the CLI run against, and it is +//! the worked example an adapter author reads: about a hundred lines, no +//! knowledge of blobs, manifests, Merkle hashing, or staging references. If +//! your VM vendor gives you "make a box, run a command, list files, read a +//! file, write a file", the shape below is the whole adapter. +//! +//! [`crate::provider::LocalProvider`] predates this and does the same job by +//! implementing [`SandboxProvider`](crate::provider::SandboxProvider) +//! directly. Both are kept: `LocalProvider` walks the filesystem in one pass +//! and is the faster path for the local case, and `LocalBackend` is the one +//! that proves the generic path is actually usable. They are checked against +//! each other in `tests/backend_parity.rs` — the same actions through both +//! must produce the same content name, which is the only claim that matters. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use trajcache_core::Action; + +use crate::backend::{validate_path, FileStat, FsOp, SandboxBackend, SandboxFs}; +use crate::determinism::DeterminismEnvelope; +use crate::error::SandboxError; +use crate::fsmap::safe_join; +use crate::runtime::{BuiltinRuntime, CompositeRuntime, ExecReport, ToolRuntime}; + +#[derive(Debug)] +pub struct LocalBackend { + runtime: Arc, + parent: Option, +} + +impl LocalBackend { + pub fn new(runtime: Arc) -> Self { + LocalBackend { + runtime, + parent: None, + } + } + + /// The built-in toolset — no subprocesses. + pub fn builtin() -> Self { + LocalBackend::new(Arc::new(BuiltinRuntime)) + } + + /// The built-in toolset plus a real `/bin/sh`. + pub fn shell() -> Self { + LocalBackend::new(Arc::new(CompositeRuntime::standard())) + } + + /// Where sandbox roots are created. Defaults to a system temporary + /// directory, cleaned up on drop. + pub fn with_parent_dir(mut self, dir: impl Into) -> Self { + self.parent = Some(dir.into()); + self + } +} + +impl SandboxBackend for LocalBackend { + fn name(&self) -> &str { + "local-fs" + } + + /// The envelope is honored because [`ToolRuntime`] consults it — the + /// built-in tools read the pinned clock and the seeded RNG rather than the + /// machine's. + fn honors_envelope(&self) -> bool { + true + } + + fn create(&self) -> Result, SandboxError> { + let mut builder = tempfile::Builder::new(); + builder.prefix("trajcache-sbx-"); + let dir = match &self.parent { + Some(parent) => { + fs::create_dir_all(parent)?; + builder.tempdir_in(parent)? + } + None => builder.tempdir()?, + }; + Ok(Box::new(LocalFs { + dir, + runtime: Arc::clone(&self.runtime), + })) + } +} + +struct LocalFs { + /// Dropping this deletes the directory, so a panicking rollout still + /// cleans up: cleanup is tied to the value's lifetime rather than to a + /// code path that has to be reached. + dir: tempfile::TempDir, + runtime: Arc, +} + +impl SandboxFs for LocalFs { + fn exec( + &mut self, + action: &Action, + envelope: &DeterminismEnvelope, + ) -> Result { + if !self.runtime.knows(action.tool()) { + // Refuse rather than no-op. A no-op produces a state whose name + // claims the work was done. + return Err(SandboxError::UnknownTool(action.tool().to_string())); + } + self.runtime.execute(action, self.dir.path(), envelope) + } + + fn list(&self) -> Result, SandboxError> { + let mut out = Vec::new(); + walk(self.dir.path(), self.dir.path(), &mut out)?; + Ok(out) + } + + fn read(&self, path: &str) -> Result, SandboxError> { + Ok(fs::read(safe_join(self.dir.path(), path)?)?) + } + + fn apply_one(&mut self, op: FsOp) -> Result<(), SandboxError> { + validate_path(op.path())?; + let target = safe_join(self.dir.path(), op.path())?; + if let Some(parent) = target.parent() { + fs::create_dir_all(parent)?; + } + match op { + FsOp::Dir { mode, .. } => { + fs::create_dir_all(&target)?; + fs::set_permissions(&target, fs::Permissions::from_mode(mode))?; + } + FsOp::File { mode, bytes, .. } => { + fs::write(&target, &bytes)?; + fs::set_permissions(&target, fs::Permissions::from_mode(mode))?; + } + // A dangling symlink is legal and must round-trip, so the target + // is not validated — only the location of the link is. + FsOp::Symlink { target: link, .. } => std::os::unix::fs::symlink(link, &target)?, + } + Ok(()) + } + + fn root(&self) -> Option<&Path> { + Some(self.dir.path()) + } +} + +fn walk(root: &Path, dir: &Path, out: &mut Vec) -> Result<(), SandboxError> { + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + let rel = path + .strip_prefix(root) + .map_err(|_| SandboxError::PathEscape(path.display().to_string()))?; + let rel = format!("/{}", rel.to_string_lossy()); + + // `symlink_metadata`, not `metadata`: a symlink is part of the state, + // and following it would both duplicate its target's bytes and hang on + // a cycle. + let meta = fs::symlink_metadata(&path)?; + let mode = meta.permissions().mode() & 0o7777; + let kind = meta.file_type(); + + if kind.is_symlink() { + let target = fs::read_link(&path)?; + out.push(FileStat::symlink(rel, target.to_string_lossy().to_string())); + } else if kind.is_dir() { + out.push(FileStat::dir(rel, mode)); + walk(root, &path, out)?; + } else if kind.is_file() { + out.push(FileStat::file(rel, mode)); + } + // Sockets, FIFOs and device nodes are skipped: not reproducible + // content, and a state depending on one cannot be honestly named. + } + Ok(()) +} diff --git a/crates/trajcache-sandbox/tests/backend_parity.rs b/crates/trajcache-sandbox/tests/backend_parity.rs new file mode 100644 index 0000000..3aa3482 --- /dev/null +++ b/crates/trajcache-sandbox/tests/backend_parity.rs @@ -0,0 +1,176 @@ +//! Two providers, one answer. +//! +//! `LocalProvider` implements `SandboxProvider` by hand; `FsProvider` derives +//! it from a `SandboxBackend`. They do the same job by different routes, which +//! makes them a differential test of each other: run the same actions through +//! both and the *content name* must be identical. Not "equivalent contents" — +//! the same 32 bytes, because that name is what the cache keys on, and a +//! provider that produces a different one for the same work has silently +//! partitioned the cache by vendor. +//! +//! This is the property a third-party adapter most needs to hold and is least +//! able to check for itself. If your adapter runs the same actions as +//! `LocalBackend` and disagrees, the disagreement is a bug in one of you, and +//! the difference is printed rather than left as two hashes. + +use std::collections::BTreeMap; +use std::sync::Arc; +use trajcache_core::{Action, StateManifest}; +use trajcache_sandbox::{ + BuiltinRuntime, Cassette, DeterminismEnvelope, FsProvider, HttpRequest, HttpResponse, + LocalBackend, LocalProvider, SandboxProvider, +}; +use trajcache_store::Store; + +fn envelope() -> Arc { + // Pinned clock, seeded RNG, and a cassette for the one built-in that + // fetches — so nothing a tool consults can be the source of a difference. + // Anything that still differs is the provider, which is the point. + let mut cassette = Cassette::new(); + for package in ["numpy", "pandas"] { + cassette.insert( + &HttpRequest::get(format!("https://index.example/{package}")), + HttpResponse { + status: 200, + headers: BTreeMap::new(), + body: format!("{package}-1.0").into_bytes(), + }, + ); + } + Arc::new(DeterminismEnvelope::hermetic(1_700_000_000_000_000_000, 7).with_cassette(cassette)) +} + +fn run(provider: &dyn SandboxProvider, store: &Store, actions: &[Action]) -> StateManifest { + let mut sandbox = provider.create(None).unwrap(); + for action in actions { + sandbox.exec(action).unwrap(); + } + let manifest = sandbox.snapshot().unwrap(); + trajcache_sandbox::release_staged(store, &manifest); + manifest +} + +fn both(actions: &[Action]) -> (StateManifest, StateManifest) { + let store = Store::in_memory(); + let hand = + LocalProvider::new(store.clone(), Arc::new(BuiltinRuntime)).with_envelope(envelope()); + let derived = FsProvider::new(LocalBackend::builtin(), store.clone()).with_envelope(envelope()); + (run(&hand, &store, actions), run(&derived, &store, actions)) +} + +fn assert_same(actions: &[Action]) { + let (hand, derived) = both(actions); + if hand.content_name() == derived.content_name() { + return; + } + let describe = |m: &StateManifest| { + m.entries + .iter() + .map(|e| format!("{} {:?}", e.path, e.kind)) + .collect::>() + .join("\n ") + }; + panic!( + "the two providers disagree about the same work\n LocalProvider {}:\n {}\n \ + FsProvider {}:\n {}", + hand.content_name(), + describe(&hand), + derived.content_name(), + describe(&derived) + ); +} + +#[test] +fn an_empty_sandbox_names_the_same_state_either_way() { + assert_same(&[]); +} + +#[test] +fn a_setup_sequence_names_the_same_state_either_way() { + assert_same(&[ + Action::call("mkdir", [("path", "/repo")]), + Action::call("mkdir", [("path", "/repo/src")]), + Action::call( + "write_file", + [("path", "/repo/src/main.py"), ("content", "print('x')")], + ), + Action::call("chmod", [("path", "/repo/src/main.py"), ("mode", "755")]), + Action::call( + "write_file", + [("path", "/repo/README.md"), ("content", "# hi")], + ), + Action::call( + "append_file", + [("path", "/repo/README.md"), ("content", "\nmore")], + ), + ]); +} + +#[test] +fn deletions_and_empty_directories_name_the_same_state_either_way() { + assert_same(&[ + Action::call("mkdir", [("path", "/a")]), + Action::call("mkdir", [("path", "/a/b")]), + Action::call("mkdir", [("path", "/a/b/c")]), + Action::call("touch", [("path", "/a/b/file")]), + Action::call("delete", [("path", "/a/b/file")]), + ]); +} + +#[test] +fn a_venv_names_the_same_state_either_way() { + // The busiest built-in: many files, nested, with modes. + assert_same(&[ + Action::call("create_venv", [("path", "/env")]), + Action::call("pip_install", [("package", "numpy")]), + ]); +} + +/// Restore is the other half. A state captured by one provider must be +/// restorable by the other — which is the cross-machine case §6 describes, +/// where the machine that captured a state and the machine that runs it are +/// running different adapters. +#[test] +fn a_state_captured_by_one_provider_restores_into_the_other() { + let store = Store::in_memory(); + let hand = + LocalProvider::new(store.clone(), Arc::new(BuiltinRuntime)).with_envelope(envelope()); + let derived = FsProvider::new(LocalBackend::builtin(), store.clone()) + .with_envelope(envelope()) + .with_verify_restore(true); + + let actions = [ + Action::call("mkdir", [("path", "/repo")]), + Action::call("mkdir", [("path", "/repo/empty")]), + Action::call( + "write_file", + [("path", "/repo/run.sh"), ("content", "#!/bin/sh\n")], + ), + Action::call("chmod", [("path", "/repo/run.sh"), ("mode", "755")]), + ]; + + // Capture with the hand-written provider. Its staging references are kept + // until the end: the bytes have to stay in the store for the restore. + let captured = { + let mut sandbox = hand.create(None).unwrap(); + for action in &actions { + sandbox.exec(action).unwrap(); + } + sandbox.snapshot().unwrap() + }; + + // Restore into the derived one. `with_verify_restore` makes this fail at + // the point of the mistake rather than at a mysterious cache miss later. + let restored = derived.create(Some(&captured)).unwrap(); + let observed = restored.snapshot().unwrap(); + assert_eq!(observed.content_name(), captured.content_name()); + trajcache_sandbox::release_staged(&store, &observed); + + // And the other direction. + let back = hand.create(Some(&captured)).unwrap(); + let observed = back.snapshot().unwrap(); + assert_eq!(observed.content_name(), captured.content_name()); + trajcache_sandbox::release_staged(&store, &observed); + + trajcache_sandbox::release_staged(&store, &captured); +} diff --git a/crates/trajcache-sandbox/tests/conformance_local.rs b/crates/trajcache-sandbox/tests/conformance_local.rs new file mode 100644 index 0000000..e9fb758 --- /dev/null +++ b/crates/trajcache-sandbox/tests/conformance_local.rs @@ -0,0 +1,148 @@ +//! The conformance suite, run against the two providers that ship here. +//! +//! This is the suite a third-party adapter runs, unmodified — which is the +//! only way to know it is worth shipping. A conformance suite that its author +//! never runs against a real implementation tests its own assumptions. + +use std::sync::Arc; +use trajcache_sandbox::{ + conformance, BuiltinRuntime, FsProvider, LocalBackend, LocalProvider, SnapshotFilter, +}; +use trajcache_store::Store; + +/// The generic path: `SandboxBackend` + `FsProvider`, what an adapter author +/// writes. +#[test] +fn the_backend_seam_is_conformant() { + let store = Store::in_memory(); + let provider = + FsProvider::new(LocalBackend::builtin(), store.clone()).with_verify_restore(true); + conformance::check(&provider, &store).assert_ok(); +} + +/// The hand-written path: `SandboxProvider` implemented directly. Held to the +/// same standard, because the suite's claim is about the interface, not about +/// how you got there. +#[test] +fn the_hand_written_provider_is_conformant() { + let store = Store::in_memory(); + let provider = LocalProvider::new(store.clone(), Arc::new(BuiltinRuntime)); + conformance::check(&provider, &store).assert_ok(); +} + +/// Batching is where a chunked upload gets its offsets wrong, so run the whole +/// suite again with a batch size small enough that every fixture spans several +/// batches. +#[test] +fn conformance_holds_when_every_state_spans_many_batches() { + let store = Store::in_memory(); + let provider = FsProvider::new(LocalBackend::builtin(), store.clone()) + .with_batch_bytes(64) + .with_verify_restore(true); + conformance::check(&provider, &store).assert_ok(); +} + +/// A backend's own snapshot filter is honored: a file the backend reports is +/// kept out of the state's identity, and the sandbox is still conformant. +#[test] +fn a_filtered_path_is_not_part_of_the_state() { + use trajcache_sandbox::SandboxProvider; + + let store = Store::in_memory(); + let provider = FsProvider::new(LocalBackend::builtin(), store.clone()) + .with_filter(SnapshotFilter::typical().exclude_name("ignore-me")); + + let sandbox = provider.create(None).unwrap(); + let root = sandbox + .root() + .expect("local backend has a root") + .to_path_buf(); + std::fs::write(root.join("ignore-me"), b"vendor scratch").unwrap(); + std::fs::write(root.join("keep-me"), b"real state").unwrap(); + + let manifest = sandbox.snapshot().unwrap(); + let paths: Vec<&str> = manifest.entries.iter().map(|e| e.path.as_str()).collect(); + assert_eq!(paths, vec!["/keep-me"], "the filter was not applied"); + trajcache_sandbox::release_staged(&store, &manifest); +} + +/// The report is meant to be read by a human debugging their adapter, so it +/// must name the offending path rather than print two hashes. +#[test] +fn a_failing_check_says_what_actually_differed() { + let store = Store::in_memory(); + let provider = FsProvider::new(DropsEmptyDirs, store.clone()); + let report = conformance::check(&provider, &store); + + assert!( + !report.passed(), + "a backend that drops empty directories must fail:\n{report}" + ); + let rendered = report.to_string(); + assert!( + rendered.contains("empty_directories_survive"), + "the empty-directory check should be among the failures:\n{rendered}" + ); + assert!( + rendered.contains("/mnt"), + "the report should name the directory that vanished:\n{rendered}" + ); +} + +/// A backend with the single most common adapter bug: a tarball-based restore +/// that silently drops directories with nothing in them. +mod broken { + use super::*; + use std::path::Path; + use trajcache_core::Action; + use trajcache_sandbox::{ + DeterminismEnvelope, ExecReport, FileStat, FsOp, SandboxBackend, SandboxError, SandboxFs, + }; + + #[derive(Debug)] + pub struct DropsEmptyDirs; + + impl SandboxBackend for DropsEmptyDirs { + fn name(&self) -> &str { + "drops-empty-dirs" + } + fn create(&self) -> Result, SandboxError> { + Ok(Box::new(Fs { + inner: LocalBackend::builtin().create()?, + })) + } + } + + struct Fs { + inner: Box, + } + + impl SandboxFs for Fs { + fn exec( + &mut self, + action: &Action, + envelope: &DeterminismEnvelope, + ) -> Result { + self.inner.exec(action, envelope) + } + fn list(&self) -> Result, SandboxError> { + self.inner.list() + } + fn read(&self, path: &str) -> Result, SandboxError> { + self.inner.read(path) + } + fn apply(&mut self, ops: Vec) -> Result<(), SandboxError> { + // The bug, in one line: directories are assumed to be implied by + // the files inside them. + let ops = ops + .into_iter() + .filter(|op| !matches!(op, FsOp::Dir { .. })) + .collect(); + self.inner.apply(ops) + } + fn root(&self) -> Option<&Path> { + self.inner.root() + } + } +} +use broken::DropsEmptyDirs; diff --git a/decisions.md b/decisions.md index 2e33be3..bff4ea9 100644 --- a/decisions.md +++ b/decisions.md @@ -960,3 +960,78 @@ panic rather than a subtle wrong answer. The general form is worth keeping: **if only one implementation of a trait has ever existed, assume the trait's shape is wrong** — it has been fitted to that implementation's conveniences, and nothing has pushed back. + +## D45. A manifest path must be well-formed, not merely non-escaping + +`safe_join` refuses `..`, absolute components and prefixes, which is the +security property: a manifest arriving from a peer cannot write outside the +sandbox root. It accepts `relative.txt`, `trailing/` and `//double`, none of +which escape anything. + +They do something quieter. `materialize` writes `trailing/` as `trailing`, and +the next `snapshot` names it `/trailing`. The state you verified and the state +you got have different content names, so the restore *changes the identity of +the state being restored*. Nothing detects it, because both halves are +individually self-consistent: the manifest is a valid manifest, the directory +is a valid directory, and the two simply are not the same state. + +`validate_path` is the stricter rule — begins with `/`, no empty segment, no +`.` or `..`, and `/` itself is not an entry — and both providers apply it, on +the way in and on the way out. Rejecting rather than normalizing, for the +reason `safe_join` already documents: normalizing lets a hostile manifest keep +trying until it finds a normalization bug. + +Found by writing the conformance suite (D46) rather than by a fuzzer. The +check "does this provider refuse a malformed path" only becomes worth asking +once there are two providers that might answer differently. + +## D46. The seam that adapters implement is not the seam the engine consumes + +`SandboxProvider` is the right interface for the engine: create a sandbox, +run actions, hand back a manifest. It is the wrong interface to ask a vendor +to implement, because satisfying it correctly requires knowing four things +that have nothing to do with sandboxes: + +* snapshot blobs carry a *staging* reference the caller will release; +* a partial failure must hand those references back before returning, or they + are owned by nobody and freed by nothing (D41); +* directories must all be created before any file or symlink, since a symlink's + parent may sort after it; +* a manifest path may be hostile (D45). + +Every one of those, got wrong, produces a state that is silently *named wrong* +rather than an error. That is the worst failure this system has: the cache +then works perfectly, forever, on a lie. + +So there are now two seams. `SandboxBackend` is what an adapter implements — +create a blank box, run a command, list files, read a file, write a file, all +of which a sandbox vendor already has an API for. `FsProvider` derives +`SandboxProvider` from it and owns all four rules above. The batching hooks +(`read_many`, `apply`) exist so a remote backend can collapse N round trips +into one without touching anything about naming. + +**The conformance suite is the other half, and is the part that matters.** An +adapter that is 95% right does not fail loudly — it drops empty directories, +or loses a file mode, and the naming layer cannot tell, because it hashes what +it is handed and what it is handed is self-consistent. Only a test that knows +what the state was *supposed* to be can catch it. `conformance::check` is that +test, packaged to run against someone else's adapter: fourteen properties, +each with a one-line statement of what it protects, and a failure report that +names the path that changed rather than printing two hashes. + +Three deliberate choices in it: + +* It runs against `SandboxProvider`, not `SandboxBackend`, so a vendor who + wants to own snapshotting is held to exactly the same standard. +* It builds states by *restoring a fixture*, never by executing actions, so it + assumes nothing about which tools a backend supports. It tests naming, which + is the shared contract, and not tooling, which is not. +* Both providers that ship here run it in CI, including the hand-written + `LocalProvider` that predates it. A conformance suite its author never runs + against a real implementation tests only its own assumptions. + +`tests/backend_parity.rs` is the differential check the suite cannot make on +its own: the same actions through both providers must produce *the same 32 +bytes*, not merely equivalent contents. A provider that names the same work +differently has silently partitioned the cache by vendor, which is the failure +mode §6's cross-machine sharing exists to prevent. From 33b5ea9c0c051cd7b814bf36324f6b89df7e2b7b Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 23:06:17 -0700 Subject: [PATCH 3/6] a worked remote adapter, and the guide to writing one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `LocalBackend` is the reference adapter and it is a directory, so it can quietly rely on things a real vendor adapter cannot: a local path, a free stat, a write that is already durable. `examples/remote_backend.rs` is the opposite case and the one E2B or Firecracker actually resembles — the sandbox lives behind a service, every operation is a request, and there is no local filesystem anywhere in it. It passes all fourteen conformance checks, which is the claim worth making: the seam is not local-shaped. It is deliberately runnable and deliberately fake. The "service" is an in-process map with a simulated per-request latency, so it is a template you copy rather than a client you configure, and it prints what the batching hooks are worth (130 requests against 216 for the same work). `make adapter` runs it; CI runs it too, because `cargo test` does not execute an example's main and a template that silently stopped compiling is worse than no template. PROVIDERS.md is the guide. It leads with the thing that is easy to miss: an adapter that is 95% right does not fail loudly. If your restore drops empty directories, the naming layer cannot tell — it hashes the manifest it is handed, that manifest is internally consistent, and the name it produces is a valid name for a state missing a directory. Then it is cached, and every rollout that reaches that name gets the broken state, quickly and confidently, forever. --- .github/workflows/ci.yml | 8 + Makefile | 9 +- PROVIDERS.md | 275 ++++++++++++++ .../examples/remote_backend.rs | 359 ++++++++++++++++++ 4 files changed, 650 insertions(+), 1 deletion(-) create mode 100644 PROVIDERS.md create mode 100644 crates/trajcache-sandbox/examples/remote_backend.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4bf99d..85efdc9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,14 @@ jobs: cargo test --workspace fi + # The example adapter is a public template, so it has to keep working. + # `cargo test` does not run an example's `main`, and an adapter template + # that silently stopped compiling against its own conformance suite + # would be worse than not shipping one. + - name: Provider adapter example + if: matrix.profile == 'debug' + run: cargo run -p trajcache-sandbox --example remote_backend + # The concurrency tests are the ones that can hide a race behind a lucky # schedule. Running them repeatedly is cheap insurance against a test # that passes because two threads happened not to interleave. diff --git a/Makefile b/Makefile index e2da6d2..1cb4510 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Common tasks. `make help` lists them. -.PHONY: help test test-release lint fmt bench measure demo soak clean +.PHONY: help test test-release lint fmt bench measure demo adapter soak clean help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \ @@ -46,6 +46,13 @@ demo: ## Name a trajectory, run it twice, then branch it three ways cargo run -q -p trajcache-cli -- --annotations examples/agent-tools.json \ branch examples/setup.json examples/turn-0.json examples/turn-1.json examples/turn-2.json +adapter: ## Prove the provider seam works for a sandbox that is not on this machine + @echo "An adapter over an in-process 'remote service' — no local filesystem" + @echo "anywhere in it — put through the same conformance suite a vendor" + @echo "adapter would run. See PROVIDERS.md." + @echo "" + cargo run -q -p trajcache-sandbox --example remote_backend + soak: ## Run the concurrency suites repeatedly, to catch a race hiding behind a lucky schedule @for i in 1 2 3 4 5 6 7 8 9 10; do \ echo "=== round $$i ==="; \ diff --git a/PROVIDERS.md b/PROVIDERS.md new file mode 100644 index 0000000..4b2101e --- /dev/null +++ b/PROVIDERS.md @@ -0,0 +1,275 @@ +# Writing a sandbox provider + +*How to put TrajCache on top of E2B, Daytona, Firecracker, Kubernetes, or the +VM pool you already run.* + +TrajCache does not fork sandboxes. §11 is explicit that it should not: E2B, +Daytona and AgentENV already do that well, and the contribution here is the +naming layer above them. So the only thing standing between this system and +your infrastructure is an adapter, and this document is how to write one. + +The short version: + +```rust +use trajcache_sandbox::{FsProvider, SandboxBackend, SandboxFs}; + +// You implement this. +impl SandboxBackend for MyVendor { /* create a blank box */ } +impl SandboxFs for MyVendorBox { /* exec, list, read, apply */ } + +// You get this. +let provider = FsProvider::new(MyVendor::new(), store.clone()); + +// You run this, and it tells you whether you got it right. +conformance::check(&provider, &store).assert_ok(); +``` + +A complete, runnable adapter over a service with no local filesystem is in +[`crates/trajcache-sandbox/examples/remote_backend.rs`](crates/trajcache-sandbox/examples/remote_backend.rs) +— about two hundred lines, and `make adapter` runs it. Start by copying that. + +--- + +## The one thing to understand first + +An adapter that is 95% correct **does not fail loudly**. + +Suppose your restore is a tarball, and tar drops directories that have nothing +in them. You extract a state, an agent runs in it, and the build fails because +`/build/out` does not exist. Nothing in TrajCache noticed, and nothing could +have: the naming layer hashes the manifest it is handed, that manifest is +internally consistent, and the content name it produces is a perfectly valid +name for a state that is missing a directory. + +Worse, it is now *cached*. Every future rollout that reaches that provenance +name gets served the broken state, quickly and confidently, forever. + +This is why there is a conformance suite, why you should run it before you +trust your adapter, and why `with_verify_restore(true)` exists. The failure +mode this project cares about is not a crash. It is a state that is named +correctly and *is not what the name says*. + +## The two seams + +| trait | who implements it | what it costs you | +|---|---|---| +| [`SandboxBackend`] + [`SandboxFs`] | you, almost certainly | create a box, run a command, list files, read a file, write a file | +| [`SandboxProvider`] | the framework, on your behalf | everything below | + +`SandboxProvider` is what the engine consumes. You *can* implement it directly, +and `LocalProvider` does, but doing so means taking on four rules that have +nothing to do with sandboxes: + +* snapshot blobs carry a **staging reference** the caller releases afterwards; +* a partial failure must hand those references back before returning, or they + are owned by nobody and freed by nothing; +* **all** directories must be created before **any** file or symlink — a + symlink's parent directory can sort after the symlink itself; +* a manifest path arriving from a peer may be trying to escape the root. + +Get any of them wrong and you produce a wrongly-named state rather than an +error. `FsProvider` owns all four. Implement `SandboxBackend`. + +## What you implement + +### `SandboxBackend::create` — a blank box + +```rust +fn create(&self) -> Result, SandboxError>; +``` + +**It must be empty.** TrajCache restores a base state into it, and anything +left over from a previous tenant joins every state built in that box — so the +state's name describes contents that came from nowhere, and two machines +running the same actions disagree. + +If your image has a fixed base layer you cannot remove — `/usr`, `/etc`, a +vendor agent directory — do not let it into the manifest. Exclude it: + +```rust +FsProvider::new(backend, store) + .with_filter(SnapshotFilter::typical() + .exclude_prefix("/usr") + .exclude_prefix("/opt/vendor-agent")) +``` + +The rule is that whatever is *not* excluded must be reproducible. A path whose +contents vary between two identical boxes has to be either excluded or declared +as an [`EntropyRegion`](crates/trajcache-sandbox/src/entropy.rs); leaving it in +means the same work gets a new name every time and nothing is ever reused. + +### `SandboxFs::exec` — run one action + +```rust +fn exec(&mut self, action: &Action, envelope: &DeterminismEnvelope) + -> Result; +``` + +**Refuse a tool you do not know.** Returning `Ok` for an action you did not run +produces a state whose name says the work was done. That is the single easiest +way for an adapter to poison a cache that other machines share: + +```rust +other => return Err(SandboxError::UnknownTool(other.to_string())), +``` + +`ExecReport::duration_ms` feeds the eviction policy's estimate of what +recomputing a state would cost. Fill it in if you can; a wrong-but-plausible +value is better than zero, which tells the store this state is free to discard. + +### `SandboxFs::list` — every entry + +```rust +fn list(&self) -> Result, SandboxError>; +``` + +Order does not matter; the provider sorts. What matters is that it is +**complete and exact**: + +* paths begin with `/`, use `/` as separator, and contain no `..` — `/` itself + is not an entry; +* permission bits are real permission bits; +* empty directories are entries; +* symlinks are reported as symlinks, with their target verbatim, **not** + followed — following them duplicates bytes and hangs on a cycle, and a + dangling symlink is legal state that must survive the round trip; +* sockets, FIFOs and device nodes are omitted — they are not reproducible + content, and a state that depends on one cannot be honestly named. + +### `SandboxFs::read` / `read_many` — bytes + +`read_many` defaults to a loop over `read`. **Override it.** It is the single +highest-value method for a remote backend: a snapshot reads every file in the +state, so the difference between one archive download and N round trips is the +difference between a snapshot costing milliseconds and costing minutes. + +### `SandboxFs::apply` — writes + +```rust +fn apply(&mut self, ops: Vec) -> Result<(), SandboxError>; +``` + +Also defaults to a loop, over `apply_one`; also worth overriding, for the same +reason. The provider has already done the hard parts for you: + +* every parent directory precedes its children, so you may assume the parent of + any op exists; +* batches are capped by total byte size (`with_batch_bytes`, default 8 MiB), so + restoring a multi-gigabyte state does not hold it all in memory. + +Implement one of `apply` or `apply_one`. The default `apply_one` returns an +error rather than silently succeeding, because a restore that quietly does +nothing is the tarball bug above. + +### `SandboxBackend::honors_envelope` — tell the truth + +```rust +fn honors_envelope(&self) -> bool { false } +``` + +Whether commands in your box actually see the §7 determinism envelope — pinned +clock, seeded RNG, cassette replay, frozen DNS — rather than the real world. +`false` is the honest default and costs you nothing. Claiming `true` while a +tool calls `gettimeofday` does not make anything faster; it just means the +divergence surfaces hours later as a quarantined tool you have to explain. + +## Then run conformance + +```rust +#[test] +fn my_backend_is_conformant() { + let store = Store::in_memory(); + let provider = FsProvider::new(MyBackend::new(), store.clone()) + .with_verify_restore(true); + conformance::check(&provider, &store).assert_ok(); +} +``` + +Fourteen properties. Each one is something the rest of the system assumes +without asking, and each failure names the path that changed rather than +printing two hashes: + +| check | catches | +|---|---| +| `blank_sandbox_is_empty` | a leftover file joining every state built in the box | +| `snapshot_is_stable` | an mtime or temp file reaching the hash, so nothing is ever reused | +| `restore_round_trips` | the core property, in its simplest form | +| `file_modes_survive` | an executable that comes back non-executable | +| `empty_directories_survive` | the tarball bug | +| `symlinks_survive_including_dangling` | links resolved into copies | +| `binary_content_survives` | content moved as text; embedded NULs; empty files | +| `awkward_paths_survive` | spaces, unicode, dots, deep nesting | +| `large_files_survive_batching` | a chunked upload with its offsets wrong | +| `escaping_paths_are_refused` | `../../etc/ssh/authorized_keys` in a peer's manifest | +| `sandboxes_are_isolated` | two boxes sharing storage | +| `concurrent_creates_succeed` | a non-reentrant client, found only under the engine's fan-out | +| `snapshot_leaves_no_staged_blobs` | blobs eviction can never reach | +| `failed_restore_reports_an_error` | a partial state stored under the full state's name | + +The suite builds its states by **restoring fixtures, never by running tools**, +so it assumes nothing about your toolset. It tests naming, which is the shared +contract, and not tooling, which is not. + +Both providers shipped here run it in CI, including the hand-written +`LocalProvider` that predates it — a conformance suite its author never runs +against a real implementation tests only its own assumptions. + +### While you are bringing it up + +Turn on `with_verify_restore(true)`. After restoring a base state, it +snapshots the box and checks the content name matches, which turns "this +backend drops file modes" from a mysterious cache miss three weeks later into +an error at the point of the mistake. It doubles restore cost, so turn it off +in production — or leave it on for a sampled fraction, which is the same bet +the index makes with shadow re-execution. + +## Wiring it into the engine + +```rust +let store = Store::in_memory(); // or Store::on_disk(path) +let provider = Arc::new(FsProvider::new(MyBackend::new(), store.clone())); + +let engine = Engine::new( + store, + Arc::new(ProvenanceIndex::new(registry.clone())), + Canonicalizer::new(registry.clone()), + provider, + fingerprint, +); +``` + +Two things worth knowing: + +**`EngineConfig::max_concurrent_sandboxes`** (default 32) is the real resource +limit in the system, and it is a limit on *your* backend. If creating a box +costs you an API call with a rate limit, set it accordingly. + +**Sandbox work runs on `spawn_blocking`.** Your `exec`, `list`, `read` and +`apply` are synchronous and may block; that is expected and correct. Do not +spawn a runtime inside them. + +## The two things most likely to be wrong + +**Your adapter names states differently from everyone else's.** The content +name must be the same 32 bytes for the same work, not merely equivalent +contents — that name is what the cache keys on, and cross-machine sharing (§6) +is exactly the case where two different adapters have to agree. `list` is where +this goes wrong: a mode you rounded, a directory you omitted, a symlink you +followed. `tests/backend_parity.rs` is the shape of the check; the conformance +suite covers the same ground against a fixture. + +**Your boxes leak.** `FsSandbox` is dropped when the engine is done with it, +which is your only signal. Release the box in `Drop`, not on a code path that +has to be reached — a rollout can panic, and cancellation in async Rust means a +task is simply dropped mid-await. Three of the eleven bugs found in this +project's stress campaign were destructor bugs, and that is with RAII used +deliberately throughout. + +## What is not here yet + +`MemoryImage` and `RestoreClass` are modelled — filesystem state restores +anywhere, memory state restores only within a compatible fleet, and the +compatibility check is asymmetric in the right direction — but nothing drives +CRIU, and `SandboxFs` has no hook for a memory snapshot. If your platform can +checkpoint memory, that is the interesting gap, and the shape of the seam is +open to argument. diff --git a/crates/trajcache-sandbox/examples/remote_backend.rs b/crates/trajcache-sandbox/examples/remote_backend.rs new file mode 100644 index 0000000..19a9cc8 --- /dev/null +++ b/crates/trajcache-sandbox/examples/remote_backend.rs @@ -0,0 +1,359 @@ +//! A sandbox that is not on this machine. +//! +//! `LocalBackend` is the reference adapter, but it is a directory, so it can +//! quietly rely on things a real vendor adapter cannot: a local path, a `stat` +//! that is free, a write that is already durable. This example is the opposite +//! case, and the one an E2B or Firecracker adapter actually resembles — the +//! sandbox lives behind a service, every operation is a request, and there is +//! no local filesystem anywhere in it. +//! +//! It is deliberately runnable and deliberately fake: the "service" is an +//! in-process map with a simulated per-request latency, so the example is a +//! template you copy rather than a client you configure. Replace +//! `RemoteService` with your vendor's SDK and the rest stands. +//! +//! ```text +//! cargo run -p trajcache-sandbox --example remote_backend +//! ``` +//! +//! What it demonstrates, in the order you will need it: +//! +//! 1. `SandboxBackend` over a service, with no local path — `root()` is `None`. +//! 2. `read_many` and `apply` overridden to batch, which is where a remote +//! adapter earns back its latency. The example prints the request count with +//! and without, because the difference is the whole argument. +//! 3. `honors_envelope() == false`, the honest answer for a box that sees the +//! real clock. +//! 4. The conformance suite passing against it. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use parking_lot::Mutex; +use trajcache_core::Action; +use trajcache_sandbox::{ + conformance, DeterminismEnvelope, ExecReport, FileStat, FsOp, FsProvider, SandboxBackend, + SandboxError, SandboxFs, +}; +use trajcache_store::Store; + +// --------------------------------------------------------------------------- +// The part you would replace with a vendor SDK. +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +enum Node { + File { mode: u32, bytes: Vec }, + Dir { mode: u32 }, + Symlink { target: String }, +} + +/// A sandbox service, somewhere else. Sandboxes are identified by an opaque +/// id; nothing about them is reachable from this process except through a +/// request. +#[derive(Debug, Default)] +struct RemoteService { + boxes: Mutex>>, + next_id: AtomicU64, + requests: AtomicU64, + /// Stands in for a network hop. Small, because the example runs in CI, but + /// non-zero so the batching numbers below are not vacuous. + latency: Duration, +} + +impl RemoteService { + fn new(latency: Duration) -> Arc { + Arc::new(RemoteService { + latency, + ..Default::default() + }) + } + + /// Every method below goes through here, so the request count is honest. + fn request(&self, f: impl FnOnce(&mut BTreeMap>) -> T) -> T { + self.requests.fetch_add(1, Ordering::Relaxed); + if !self.latency.is_zero() { + std::thread::sleep(self.latency); + } + f(&mut self.boxes.lock()) + } + + fn requests(&self) -> u64 { + self.requests.load(Ordering::Relaxed) + } + + fn create_box(&self) -> u64 { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + self.request(|boxes| boxes.insert(id, BTreeMap::new())); + id + } + + fn destroy_box(&self, id: u64) { + self.request(|boxes| boxes.remove(&id)); + } +} + +// --------------------------------------------------------------------------- +// The adapter. This is the part you write. +// --------------------------------------------------------------------------- + +#[derive(Debug)] +struct RemoteBackend { + service: Arc, + /// Whether to use the batching overrides. Only here so the example can + /// print both numbers; a real adapter would simply batch. + batch: bool, +} + +impl SandboxBackend for RemoteBackend { + fn name(&self) -> &str { + "example-remote" + } + + /// False, and truthfully so: commands run in a box that sees the real + /// clock and the real network. Declaring `true` here while a tool calls + /// `gettimeofday` is exactly what the index's shadow re-execution exists + /// to catch — and it will catch it, some hours later, as a quarantine you + /// have to explain. Say `false` and the fingerprint records what the + /// environment actually promised. + fn honors_envelope(&self) -> bool { + false + } + + fn create(&self) -> Result, SandboxError> { + Ok(Box::new(RemoteSandbox { + id: self.service.create_box(), + service: Arc::clone(&self.service), + batch: self.batch, + })) + } +} + +struct RemoteSandbox { + id: u64, + service: Arc, + batch: bool, +} + +impl RemoteSandbox { + fn with( + &self, + f: impl FnOnce(&mut BTreeMap) -> Result, + ) -> Result { + self.service.request(|boxes| { + let contents = boxes.get_mut(&self.id).ok_or_else(|| { + // A box that has been reclaimed out from under us. The right + // answer is a loud error: the alternative is snapshotting an + // empty sandbox and storing it under the name of the work. + SandboxError::ProviderUnavailable(format!("sandbox {} no longer exists", self.id)) + })?; + f(contents) + }) + } +} + +/// Dropping the handle releases the box. Tying cleanup to the value's lifetime +/// rather than to a code path means a panicking rollout still releases it. +impl Drop for RemoteSandbox { + fn drop(&mut self) { + self.service.destroy_box(self.id); + } +} + +impl SandboxFs for RemoteSandbox { + /// No local path. This is the honest answer, and nothing in the engine + /// needs one. + fn root(&self) -> Option<&std::path::Path> { + None + } + + fn list(&self) -> Result, SandboxError> { + self.with(|contents| { + Ok(contents + .iter() + .map(|(path, node)| match node { + Node::File { mode, .. } => FileStat::file(path, *mode), + Node::Dir { mode } => FileStat::dir(path, *mode), + Node::Symlink { target } => FileStat::symlink(path, target), + }) + .collect()) + }) + } + + fn read(&self, path: &str) -> Result, SandboxError> { + self.with(|contents| match contents.get(path) { + Some(Node::File { bytes, .. }) => Ok(bytes.clone()), + _ => Err(SandboxError::ProviderUnavailable(format!( + "no file at {path}" + ))), + }) + } + + /// One request for N files instead of N requests. For a real backend this + /// is a single archive download, and it is the difference between a + /// snapshot costing 3 ms and costing 3 seconds. + fn read_many(&self, paths: &[&str]) -> Result>, SandboxError> { + if !self.batch { + return paths.iter().map(|p| self.read(p)).collect(); + } + self.with(|contents| { + paths + .iter() + .map(|path| match contents.get(*path) { + Some(Node::File { bytes, .. }) => Ok(bytes.clone()), + _ => Err(SandboxError::ProviderUnavailable(format!( + "no file at {path}" + ))), + }) + .collect() + }) + } + + /// One request for a batch of writes. `FsProvider` has already ordered + /// them so every parent directory precedes its children, and has capped + /// the batch's total size, so this can be a single upload. + fn apply(&mut self, ops: Vec) -> Result<(), SandboxError> { + if !self.batch { + for op in ops { + self.apply_one(op)?; + } + return Ok(()); + } + self.with(|contents| { + for op in ops { + insert(contents, op); + } + Ok(()) + }) + } + + fn apply_one(&mut self, op: FsOp) -> Result<(), SandboxError> { + self.with(|contents| { + insert(contents, op); + Ok(()) + }) + } + + /// A tiny interpreter, standing in for "run this command in the VM". + /// + /// Note what it does with an unknown tool: it refuses. A no-op would + /// produce a state whose *name* says the work was done — the single + /// easiest way for an adapter to poison a shared cache. + fn exec( + &mut self, + action: &Action, + _envelope: &DeterminismEnvelope, + ) -> Result { + let arg = |key: &str| -> Result { + action + .arg(key) + .and_then(|v| v.as_str()) + .map(str::to_string) + .ok_or_else(|| SandboxError::BadArguments { + tool: action.tool().to_string(), + detail: format!("missing string argument `{key}`"), + }) + }; + + match action.tool() { + "mkdir" => { + let path = arg("path")?; + self.with(|contents| { + contents.insert(path, Node::Dir { mode: 0o755 }); + Ok(()) + })?; + } + "write_file" => { + let (path, content) = (arg("path")?, arg("content")?); + self.with(|contents| { + contents.insert( + path, + Node::File { + mode: 0o644, + bytes: content.into_bytes(), + }, + ); + Ok(()) + })?; + } + "delete" => { + let path = arg("path")?; + self.with(|contents| { + contents.remove(&path); + Ok(()) + })?; + } + other => return Err(SandboxError::UnknownTool(other.to_string())), + } + Ok(ExecReport::ok()) + } +} + +fn insert(contents: &mut BTreeMap, op: FsOp) { + match op { + FsOp::Dir { path, mode } => { + contents.insert(path, Node::Dir { mode }); + } + FsOp::File { path, mode, bytes } => { + contents.insert(path, Node::File { mode, bytes }); + } + FsOp::Symlink { path, target } => { + contents.insert(path, Node::Symlink { target }); + } + } +} + +// --------------------------------------------------------------------------- + +fn main() { + // 1. Conformance. Run this against your adapter before anything else: it + // is the difference between "it seems to work" and "states named by it + // are states you can trust". + let service = RemoteService::new(Duration::ZERO); + let store = Store::in_memory(); + let provider = FsProvider::new( + RemoteBackend { + service: Arc::clone(&service), + batch: true, + }, + store.clone(), + ) + // Worth having on while bringing an adapter up: it turns "this backend + // drops file modes" from a mysterious cache miss weeks later into an error + // at the moment of the mistake. + .with_verify_restore(true); + + let report = conformance::check(&provider, &store); + print!("{report}"); + assert!(report.passed(), "the example adapter must be conformant"); + + // 2. What batching is worth. The same conformance run, with the two + // overrides turned off, against a service with a latency per request. + println!("\nrequests to the service, restoring and snapshotting one state:"); + for (label, batch) in [("batched", true), ("one at a time", false)] { + let service = RemoteService::new(Duration::from_micros(200)); + let store = Store::in_memory(); + let provider = FsProvider::new( + RemoteBackend { + service: Arc::clone(&service), + batch, + }, + store.clone(), + ); + let started = std::time::Instant::now(); + let report = conformance::check(&provider, &store); + assert!(report.passed(), "{report}"); + println!( + " {label:>13}: {:>6} requests, {:>7.1} ms", + service.requests(), + started.elapsed().as_secs_f64() * 1000.0 + ); + } + + println!( + "\nEverything about blobs, manifests, staging references and path validation\n\ + stayed on the other side of the seam. This file knows none of it." + ); +} From a07ddb0773853d25ada19c15803ebe4c1f85afd6 Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 23:09:43 -0700 Subject: [PATCH 4/6] trajcache doctor, and the flags someone running their own sandbox needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three things the CLI could not do, all of which the first person pointing this at their own infrastructure hits immediately. `--sandbox-dir` chooses where sandbox roots are created, instead of always a system temporary directory. States are the size of the environments they hold; which filesystem that lands on is not a detail. `--exclude` configures the snapshot filter. It is the answer for contents that vary between two otherwise identical boxes — a build cache, a vendor agent's scratch directory — which, left in, give the same work a new name every time and mean nothing is ever reused. (For contents that are *supposed* to differ per branch, an entropy region is still the right tool: the difference gets described rather than discarded.) Note this flag only became meaningful two commits ago, when the engine stopped substituting its own filter. `doctor` runs the conformance suite against whatever provider the other flags produced and exits non-zero if anything fails, so it works as a gate in a deployment script. It is also the answer to "how do I know my adapter is right", which previously had none. README gains the section that was missing: that the whole story for running this on your own sandboxes is an adapter, and that the reason the conformance suite matters more than the trait does is that an adapter which is 95% right does not fail loudly. --- README.md | 60 +++++++++++++++++--- crates/trajcache-cli/src/main.rs | 97 ++++++++++++++++++++++++++++++-- 2 files changed, 144 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index feeb033..287056f 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ speedup 20x | [`trajcache-core`](crates/trajcache-core) | The naming layer. Environment fingerprints, the prefix-free canonical encoding, canonicalization, and the two names of §4 as two distinct Rust types. | | [`trajcache-store`](crates/trajcache-store) | Content-addressed blobs, the copy-on-write state graph, deferred materialization, eviction by recompute cost. | | [`trajcache-index`](crates/trajcache-index) | The learned provenance→content mapping, divergence detection, shadow verification, tool quarantine. | -| [`trajcache-sandbox`](crates/trajcache-sandbox) | Filesystem ↔ manifest, tool runtimes (including real `/bin/sh`), the §7 determinism envelope, and the entropy carve-out. | +| [`trajcache-sandbox`](crates/trajcache-sandbox) | Filesystem ↔ manifest, tool runtimes (including real `/bin/sh`), the §7 determinism envelope, and the entropy carve-out. Also the adapter seam: `SandboxBackend` + `FsProvider`, and a conformance suite anyone can run against their own — see [`PROVIDERS.md`](PROVIDERS.md). | | [`trajcache-engine`](crates/trajcache-engine) | Single-flight realization, branch trees, the ordered event bus. | | [`trajcache-server`](crates/trajcache-server) | The §6 registry: content-addressed distribution with signed provenance attestation. | | [`trajcache-harness`](crates/trajcache-harness) | Phase 0. Canonicalization density, branch divergence, per-rule contribution. | @@ -32,6 +32,7 @@ speedup 20x Design decisions are logged in [`decisions.md`](decisions.md); the things they cost are in [`tradeoffs.md`](tradeoffs.md). Both are written to be argued with. +[`PROVIDERS.md`](PROVIDERS.md) is how to put this on top of your own sandboxes. ## The idea in sixty seconds @@ -226,25 +227,70 @@ random fingerprints, and 300k random manifests produced **zero** collisions. ## Running it ```bash -cargo test --workspace # 364 correctness tests, 0 failures +cargo test --workspace # 378 correctness tests, 0 failures make bench # the 20 benchmarks, serially, in release cargo run -p trajcache-cli -- measure # Phase 0 report cargo run -p trajcache-cli -- --annotations examples/agent-tools.json \ branch examples/setup.json examples/turn-0.json examples/turn-1.json examples/turn-2.json + +cargo run -p trajcache-cli -- doctor # is this sandbox provider trustworthy? +make adapter # the same suite, against a *remote* sandbox ``` +## Running it on your own sandboxes + +TrajCache does not fork sandboxes, and §11 says it should not: E2B, Daytona and +AgentENV already do that well, and the contribution is the naming layer above +them. So the whole story is an adapter, and +[`PROVIDERS.md`](PROVIDERS.md) is how to write one. + +You implement a **backend** — create a blank box, run a command, list files, +read one, write one — and `FsProvider` derives the real provider from it, +owning the four rules that have nothing to do with sandboxes and everything to +do with this project's storage layer: staging references, releasing them on a +partial failure, ordering directories before symlinks, and refusing a hostile +path. Getting any of those wrong produces a state that is *named wrong* rather +than an error. + +Which is why the conformance suite matters more than the trait does: + +``` +$ cargo run -p trajcache-cli -- doctor +conformance: local — 14/14 checks passed + pass blank_sandbox_is_empty + pass empty_directories_survive + pass symlinks_survive_including_dangling + ... +``` + +**An adapter that is 95% right does not fail loudly.** If your restore drops +empty directories, the naming layer cannot tell — it hashes the manifest it is +handed, that manifest is internally consistent, and the name it produces is a +perfectly valid name for a state that is missing a directory. Then it is +cached, and every rollout that reaches that name is served the broken state, +quickly and confidently, forever. Fourteen checks, each one a property the rest +of the system assumes without asking, and each failure names the path that +changed rather than printing two hashes. + +`make adapter` runs the same suite against an adapter over an in-process +"remote service" with no local filesystem anywhere in it +([`examples/remote_backend.rs`](crates/trajcache-sandbox/examples/remote_backend.rs)), +which is the claim worth making: the seam is not local-shaped. It is also the +template to copy. + ## What is deliberately not here * **Model-side (KV cache) checkpointing.** §9 leaves it out and so does this. A KV artifact is invalidated by a model update, a quantization change, a tokenizer change, or an engine patch release; an environment state survives all of them. -* **A fork implementation.** §11 is explicit: "adapters, not implementations, - at the sandbox layer". `SandboxProvider` is that seam, and `LocalProvider` is - a reference implementation over a real directory — enough to run the whole - system end to end and enough to make the seam's shape concrete before an E2B - or Firecracker adapter has to fit through it. +* **A vendor adapter.** §11 is explicit: "adapters, not implementations, at + the sandbox layer". What is here is the seam, a reference implementation over + a real directory, a worked adapter over a service with no local filesystem, + and the conformance suite that says whether a third one is correct — but no + E2B or Firecracker client, because that is a dependency and a set of + credentials rather than a design question. See [`PROVIDERS.md`](PROVIDERS.md). * **Real memory snapshotting.** `MemoryImage` and `RestoreClass` are modelled and named — filesystem state restores anywhere, memory state restores only within a compatible fleet, and the compatibility check is asymmetric in the diff --git a/crates/trajcache-cli/src/main.rs b/crates/trajcache-cli/src/main.rs index 382af98..293feac 100644 --- a/crates/trajcache-cli/src/main.rs +++ b/crates/trajcache-cli/src/main.rs @@ -9,6 +9,9 @@ //! * `branch` — fork a state into N continuations. //! * `measure` — Phase 0: canonicalization density, branch divergence. //! * `annotations` — validate a tool registry and report what it buys. +//! * `doctor` — put the configured sandbox provider through the conformance +//! suite, which is the first thing to run when pointing this at your own +//! infrastructure. See `PROVIDERS.md`. //! * `serve` — run a registry. use std::path::PathBuf; @@ -23,7 +26,10 @@ use trajcache_harness::{ measure_environment, report::measure_divergence, EnvironmentReport, WorkloadShape, }; use trajcache_index::{Lookup, ProvenanceIndex}; -use trajcache_sandbox::{CompositeRuntime, DeterminismEnvelope, LocalProvider, SandboxProvider}; +use trajcache_sandbox::{ + conformance, CompositeRuntime, DeterminismEnvelope, LocalProvider, SandboxProvider, + SnapshotFilter, +}; use trajcache_server::{key_from_seed, router, Registry, TrustPolicy}; use trajcache_store::Store; @@ -45,6 +51,25 @@ struct Cli { #[arg(long, global = true, default_value = "scratch")] base_image: String, + /// Where sandbox roots are created. Defaults to a system temporary + /// directory. Point this at the filesystem you actually want the work to + /// happen on — a fast local disk, or a volume with room for the states. + #[arg(long, global = true)] + sandbox_dir: Option, + + /// A path to keep out of every state's identity. Repeatable. A leading `/` + /// makes it a prefix, anything else matches a file or directory name + /// anywhere in the tree. + /// + /// For contents that vary between two otherwise identical boxes — a build + /// cache, a vendor agent's scratch directory — this is the right tool: left + /// in, they give the same work a new name every time and nothing is ever + /// reused. For contents that are *supposed* to differ per branch, such as a + /// machine ID or a host key, declare an entropy region instead, so the + /// difference is described rather than discarded. + #[arg(long = "exclude", global = true, value_name = "PATH_OR_NAME")] + excludes: Vec, + #[command(subcommand)] command: Command, } @@ -85,6 +110,16 @@ enum Command { }, /// Validate a tool registry and report what it buys. Annotations { path: PathBuf }, + /// Put the configured sandbox provider through the conformance suite. + /// + /// Fourteen properties that the rest of the system assumes without asking — + /// that an empty directory survives a round trip, that a file mode does, + /// that a snapshot of an unchanged sandbox names the same state twice. Run + /// it after changing `--sandbox-dir` or `--exclude`, and run the same suite + /// against your own adapter before trusting it: an adapter that is 95% + /// right does not fail loudly, it produces a state that is named correctly + /// and is not what the name says. See PROVIDERS.md. + Doctor, /// Run a registry server. Serve { #[arg(long, default_value = "127.0.0.1:8080")] @@ -121,6 +156,7 @@ struct Context_ { engine: Engine, store: Store, index: Arc, + provider: Arc, } fn build(cli: &Cli) -> Result { @@ -132,10 +168,23 @@ fn build(cli: &Cli) -> Result { let store = Store::in_memory(); let index = Arc::new(ProvenanceIndex::new(Arc::clone(®istry))); let envelope = Arc::new(DeterminismEnvelope::open()); - let provider: Arc = Arc::new( - LocalProvider::new(store.clone(), Arc::new(CompositeRuntime::standard())) - .with_envelope(Arc::clone(&envelope)), - ); + + let mut filter = SnapshotFilter::typical(); + for exclude in &cli.excludes { + filter = if exclude.starts_with('/') { + filter.exclude_prefix(exclude.clone()) + } else { + filter.exclude_name(exclude.clone()) + }; + } + + let mut local = LocalProvider::new(store.clone(), Arc::new(CompositeRuntime::standard())) + .with_envelope(Arc::clone(&envelope)) + .with_filter(filter); + if let Some(dir) = &cli.sandbox_dir { + local = local.with_parent_dir(dir.clone()); + } + let provider: Arc = Arc::new(local); let fingerprint = EnvFingerprint::builder( hash(digest::DOMAIN_BLOB, cli.base_image.as_bytes()), PlatformClass::current(), @@ -148,7 +197,7 @@ fn build(cli: &Cli) -> Result { store.clone(), Arc::clone(&index), Canonicalizer::new(registry), - provider, + Arc::clone(&provider), fingerprint, EngineConfig::default(), ); @@ -156,6 +205,7 @@ fn build(cli: &Cli) -> Result { engine, store, index, + provider, }) } @@ -385,6 +435,41 @@ async fn main() -> Result<()> { ); } + Command::Doctor => { + let ctx = build(&cli)?; + println!("provider {}", ctx.provider.name()); + println!( + "sandbox dir {}", + cli.sandbox_dir + .as_ref() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "(system temporary directory)".into()) + ); + println!( + "excluding {}", + if cli.excludes.is_empty() { + "(defaults only)".to_string() + } else { + cli.excludes.join(", ") + } + ); + println!(); + + let report = conformance::check(ctx.provider.as_ref(), &ctx.store); + print!("{report}"); + if !report.passed() { + // A non-zero exit, so this is usable as a gate in a deployment + // script. A provider that fails any of these does not produce + // states anyone should share. + anyhow::bail!( + "{} of {} conformance checks failed", + report.failures().count(), + report.checks.len() + ); + } + println!("\nAll checks passed. States named by this provider are ones you can share."); + } + Command::Serve { listen, signing_seed, From 9c18e48bdbfaf1004aa4ef2d12abec2a84e8f7b3 Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 23:13:05 -0700 Subject: [PATCH 5/6] document the deadline-sensitivity in the correctness suite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo test --workspace` fails roughly one run in three, always a test wrapped in a timeout reporting a hang, never the same test twice. Recording what it is and what it is not, since the natural assumption on seeing it is that the branch broke something. It predates this work: six concurrent copies of the failure_injection binary reproduce it hard, and origin/main reproduces it identically — slightly worse, in fact. This branch changes only the odds, by adding two test binaries to the workspace run. Two obvious hypotheses tested and rejected. It is not CPU starvation: under sixteen spinning processes the suite passes in 30-43s. It is not sandbox fan-out: cutting max_concurrent_sandboxes from 32 to 4 in the rig, an 8x reduction in concurrent blocking filesystem work, moved the failure count from 8 to 8. That change was reverted rather than kept for seeming reasonable. D42 already drew this conclusion from the other direction when it pulled the benchmarks out of the correctness gate. What this adds is that the correctness suite still contains deadlines — they are spelled `timeout(60s, ...)` and framed as hang detection. The framing is defensible; the number is doing two jobs and can only do one of them reliably. Left as found, because the fix is a question about the shape of the suite rather than a line to change. D47. --- decisions.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/decisions.md b/decisions.md index bff4ea9..9e737bf 100644 --- a/decisions.md +++ b/decisions.md @@ -1035,3 +1035,44 @@ its own: the same actions through both providers must produce *the same 32 bytes*, not merely equivalent contents. A provider that names the same work differently has silently partitioned the cache by vendor, which is the failure mode §6's cross-machine sharing exists to prevent. + +## D47. The correctness suite has deadline-based tests, and deadlines measure the machine + +While adding the provider seam, `cargo test --workspace` failed intermittently +— roughly one run in three — always the same way: a test wrapped in a timeout, +reporting a hang. Never the same test twice. `failure_injection.rs` and +`events_adversarial.rs` between them account for every occurrence seen. + +**It is not new, and it is not the provider work.** Six concurrent copies of +the `failure_injection` binary reproduce it hard — 8 to 10 of its 13 tests fail +per copy — and `origin/main` reproduces it *identically*, in fact slightly +worse. What this branch changed is only the odds: two more test binaries in a +workspace run is two more competitors for the machine. + +Two things ruled out along the way, both worth recording because both were the +obvious guess: + +* **Not CPU starvation alone.** Under sixteen spinning processes the suite + passes, in 30–43 s. The load that breaks it involves many *tokio runtimes* + and blocking pools doing filesystem work, not merely busy cores. +* **Not sandbox fan-out.** Dropping `max_concurrent_sandboxes` from 32 to 4 in + the failure-injection rig — an 8× cut in concurrent blocking filesystem work + — moved the failure count from 8 to 8. The hypothesis was clean and wrong, + and the change was reverted rather than kept as a change that "seemed + reasonable". + +The general point is one D42 already made from the other direction. A test that +asserts *a deadline* is measuring the machine, and under `cargo test +--workspace` the machine is running the rest of the suite. §D42 excluded the +benchmarks from the correctness gate for exactly this reason; what this shows +is that the correctness suite still contains deadlines, they are just spelled +`timeout(60s, …)` and framed as hang detection rather than as latency bounds. +The framing is defensible — a wedged engine must fail in bounded time rather +than hanging CI forever — but the number is doing double duty, and the second +job is one it cannot do reliably. + +Left as found and documented rather than patched, because the fix is a +question about the shape of the suite (bound the workspace run's parallelism? +distinguish "wedged" from "slow" by probing progress rather than by elapsed +time?) and not a line to change. It is the largest known wart in a suite that +is otherwise a strength of this project. From f44055f457a6bff9153bbae63aef661951a1740d Mon Sep 17 00:00:00 2001 From: angadjosan Date: Mon, 10 Aug 2026 23:20:14 -0700 Subject: [PATCH 6/6] D47: the observed rate, rather than a rounder one Three failures across about a dozen workspace runs, not one in three. The four clean runs that followed are not evidence of anything either, which is the difficulty with a fault at this rate and worth saying in the entry. --- decisions.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/decisions.md b/decisions.md index 9e737bf..ce29bf1 100644 --- a/decisions.md +++ b/decisions.md @@ -1038,10 +1038,12 @@ mode §6's cross-machine sharing exists to prevent. ## D47. The correctness suite has deadline-based tests, and deadlines measure the machine -While adding the provider seam, `cargo test --workspace` failed intermittently -— roughly one run in three — always the same way: a test wrapped in a timeout, -reporting a hang. Never the same test twice. `failure_injection.rs` and -`events_adversarial.rs` between them account for every occurrence seen. +While adding the provider seam, `cargo test --workspace` failed +intermittently: three failures across about a dozen runs, always the same way +— a test wrapped in a timeout, reporting a hang — and never the same test +twice. `failure_injection.rs` and `events_adversarial.rs` between them account +for every occurrence seen. Four consecutive clean runs at the end of the work +say nothing either way, which is the whole problem with a fault at this rate. **It is not new, and it is not the provider work.** Six concurrent copies of the `failure_injection` binary reproduce it hard — 8 to 10 of its 13 tests fail