Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 8 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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) | \
Expand Down Expand Up @@ -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 ==="; \
Expand Down
275 changes: 275 additions & 0 deletions PROVIDERS.md
Original file line number Diff line number Diff line change
@@ -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<Box<dyn SandboxFs>, 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<ExecReport, SandboxError>;
```

**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<Vec<FileStat>, 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<FsOp>) -> 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.
Loading
Loading