Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Eryx is a library for running Python code in a WebAssembly sandbox. It’s designed for AI agents and applications that need to execute untrusted Python safely, with fine-grained control over what the code can access.

eryx (noun): A genus of sand boas (Erycinae) — non-venomous snakes that live in sand. Perfect for “Python running inside a sandbox.”

Try It Now

uvx --with pyeryx eryx -c 'import sys; print(f"Python {sys.version} in a sandbox!")'

Or try it in the browser at demo.eryx.run.

Features

Secure by default

  • Secrets management — Secrets are never exposed to sandboxed code; placeholders are substituted transparently only in HTTP requests to authorized hosts, and scrubbed from all outputs
  • Hybrid filesystem — Isolated virtual filesystem by default, with opt-in host directory mounts (read-only or read-write) for controlled file access
  • Resource limits — Configurable execution timeouts, memory caps, and CPU fuel limits to prevent runaway code
  • Network policies — Networking is disabled by default; opt-in with host allowlists, blocklists, and connection limits

Fast startup

  • Pre-compiled Wasm — Sandbox creation in ~10–20ms with ahead-of-time compilation (vs ~650ms cold start)
  • Sandbox pooling — Managed pool of warm sandbox instances for high-throughput scenarios
  • Pre-initialized packages — Bake third-party packages into the Wasm runtime to eliminate per-sandbox install overhead

Host integration

  • Async callbacks — Expose host functions as async Python functions (e.g., await get_time()) with parallel execution via asyncio.gather()
  • Real-time output streaming — Stream stdout/stderr as it’s produced, instead of buffering until completion
  • Session state — Variables, functions, and classes persist between executions for REPL-style usage
  • State snapshots — Capture and restore Python state with dill-based serialization
  • Execution tracing — Line-level progress reporting via sys.settrace
  • Execution cancellation — Cancel long-running executions via ExecutionHandle

True CPython

  • Real CPython 3.14 — Not a reimplementation or subset; runs the full CPython interpreter compiled to WebAssembly using techniques from componentize-py
  • Install packages — Add .whl and .tar.gz packages including WASI-compiled native extensions
  • Full standard library — json, sqlite3, pathlib, re, asyncio, and the rest of the stdlib work out of the box

Multi-language support

  • Rust, Python, and JavaScript — First-class bindings for all three
  • CLI — Run sandboxed Python from the terminal with python -m eryx or uvx --with pyeryx eryx

Use Cases

Eryx is designed for scenarios where you need to:

  • Give AI agents a safe Python execution environment
  • Execute untrusted or user-provided code with controlled access to host resources
  • Provide a sandboxed scripting environment in your application
  • Build REPL-style interfaces with persistent state
  • Create plugin systems with Python as the extension language

How It Works

Eryx uses Wasmtime to run CPython compiled to WebAssembly. This provides strong isolation guarantees:

  • Memory isolation — Sandboxed code cannot access host memory
  • File system isolation — No access to host files by default; opt-in via VFS or volume mounts
  • Network isolation — Networking is opt-in with configurable policies
  • Resource limits — Configurable timeouts, memory limits, and callback restrictions

Host callbacks are implemented using the WebAssembly Component Model, allowing Rust, Python, or JavaScript host code to expose async functions that sandboxed Python can call.

Next Steps

Installation

Eryx provides language bindings for Rust, Python, and JavaScript. Choose your preferred language below.

Rust

Add Eryx to your Cargo.toml:

[dependencies]
eryx = { version = "0.3", features = ["embedded"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

Setting up the embedded feature

The embedded feature embeds a pre-compiled Wasm runtime into your binary for zero-config sandbox creation. Because the pre-compiled runtime is platform-specific (~55MB), it is not included in the crate and must be generated once for your machine:

cargo binstall eryx-precompile   # install the pre-compile tool
eryx-precompile setup            # download runtime + pre-compile for your platform

After this one-time setup, cargo build will find the cached runtime automatically. You can also set ERYX_RUNTIME_CWASM=/path/to/runtime-python.cwasm to use a specific file, which is embedded without the checksum and ownership checks applied to the cached runtime. See Pre-compiling Runtimes for advanced options like cross-compilation, CPU targeting, and bundling packages.

Feature Flags

FeatureDescriptionTrade-offs
embeddedEmbeds pre-compiled Wasm runtime + Python stdlib into your binary+55MB binary size; requires one-time setup (see above)
macrosEnables the #[callback] proc macro for simplified callback definitionsAdds proc-macro compile time
preinitPre-initialization support for ~25x faster sandbox creationAdds eryx-runtime dep; requires build step
native-extensionsNative Python extension support (e.g., numpy) via late-linkingImplies preinit; experimental

Recommended: Start with the embedded feature for the simplest setup.

Package support (with_package() for .whl and .tar.gz files) is always available — no feature flag required.


Python

Install from PyPI:

pip install pyeryx

Note: The package is installed as pyeryx but imported as eryx.

Verify Installation

import eryx

sandbox = eryx.Sandbox()
result = sandbox.execute("print('Hello from Eryx!')")
print(result.stdout_text)

JavaScript

Install from npm:

npm install @eryx-org/eryx

Note: JavaScript bindings require WebAssembly JSPI support. In Node.js 24–25, pass --experimental-wasm-jspi (on by default in Node.js 26+). In browsers, Chrome 133+ and Edge 133+ are supported.

Node.js

node --experimental-wasm-jspi your-script.js   # flag not needed on Node.js 26+
import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();
const result = await sandbox.execute('print("Hello from Eryx!")');
console.log(result.stdout);

Browser

import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();
const result = await sandbox.execute('print("Hello from the browser!")');
console.log(result.stdout);

See the JavaScript API reference for full documentation.


Next Steps

Quick Start

This guide will help you create your first Eryx sandbox and execute Python code.

Basic Execution

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Create a sandbox with embedded Python runtime
    let sandbox = Sandbox::embedded().build()?;

    // Execute Python code
    let result = sandbox.execute(r#"
print("Hello from Python!")
x = 2 + 2
print(f"2 + 2 = {x}")
    "#).await?;

    println!("{}", result.stdout_text());
    // Output:
    // Hello from Python!
    // 2 + 2 = 4

    println!("Execution took {:.2}ms", result.stats.duration.as_secs_f64() * 1000.0);

    Ok(())
}
import eryx

# Create a sandbox with embedded Python runtime
sandbox = eryx.Sandbox()

# Execute Python code in isolation
result = sandbox.execute('''
print("Hello from the sandbox!")
x = 2 + 2
print(f"2 + 2 = {x}")
''')

print(result.stdout_text)
# Output:
# Hello from the sandbox!
# 2 + 2 = 4

print(f"Execution took {result.duration_ms:.2f}ms")

With Callbacks

Callbacks allow sandboxed code to interact with the host in a controlled way.

extern crate eryx;
extern crate tokio;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError, Sandbox};
use serde_json::{json, Value};

/// Echoes back the message
#[callback]
async fn echo(message: String) -> Result<Value, CallbackError> {
    Ok(json!({ "echoed": message }))
}

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded()
        .with_callback(echo)
        .build()?;

    let result = sandbox.execute(r#"
response = await echo(message="Hello!")
print(f"Echo: {response}")
    "#).await?;

    println!("{}", result.stdout_text());
    Ok(())
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Returns current Unix timestamp")
def get_time():
    import time
    return {"timestamp": time.time()}

sandbox = eryx.Sandbox(callbacks=registry)

result = sandbox.execute("""
t = await get_time()
print(f"Time: {t['timestamp']}")
""")

print(result.stdout_text)

Note: The Rust #[callback] macro requires the macros feature flag. See Installation.

With Sessions

Sessions maintain state across multiple executions, useful for REPL-style usage.

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    // State persists across executions
    session.execute("x = 42").await?;
    let result = session.execute("print(x * 2)").await?;
    println!("{}", result.stdout_text()); // "84"

    Ok(())
}
import eryx

session = eryx.Session()

# State persists across executions
session.execute("x = 42")
session.execute("y = x * 2")
result = session.execute("print(f'{x} * 2 = {y}')")
print(result.stdout_text)  # "42 * 2 = 84"

Performance

Both Rust and Python bindings use pre-compiled WebAssembly for fast sandbox creation:

MetricNormal WasmPre-compiledSpeedup
Sandbox creation~650ms~16ms41x faster
Per-execution overhead~1.8ms~1.6ms14% faster
Session (5 executions)~70ms~3ms23x faster

Rust Note: The embedded feature flag enables pre-compilation but requires a one-time setup step. See Installation for details.

Next Steps

Core Concepts

This page explains the key concepts in Eryx and how they work together.

Sandbox

A Sandbox is the main entry point for executing Python code in isolation. Each sandbox:

  • Contains a WebAssembly instance of CPython 3.14
  • Has isolated memory and no access to host resources by default
  • Can be configured with callbacks, resource limits, and network access
  • Is designed for one-off executions where state doesn’t persist

Use sandboxes when each execution should start with a clean slate.

Sessions

A Session wraps a sandbox and maintains Python state across multiple executions:

  • Variables, functions, and classes persist between executions
  • Useful for REPL-style interfaces and incremental computation
  • Can optionally include a virtual filesystem for file persistence
  • More efficient than creating new sandboxes for each execution

Use sessions when you need stateful, interactive Python execution.

Callbacks

Callbacks are functions exposed from the host that sandboxed Python can call:

  • Provide controlled access to host capabilities (database, API calls, etc.)
  • Are async from both host and sandbox perspectives
  • Can be strongly typed (Rust) or dynamically defined (Python)
  • Allow sandboxed code to request information without direct access

Callbacks are the primary way sandboxed code interacts with the outside world.

MCP Integration

MCP (Model Context Protocol) tools can be bridged into the sandbox as callbacks:

  • Automatically discovers MCP servers from IDE configs (Claude Code, Cursor, VS Code, Zed, Windsurf, Codex, Gemini)
  • Exposes tools as async functions under mcp.<server>.<tool> namespaces
  • Only stdio-type servers are supported

MCP integration lets sandboxed code access external tool servers without any custom callback code.

Resource Limits

Resource Limits control what sandboxed code can do:

  • Execution timeout — Maximum time for code to run
  • Memory limits — Maximum memory usage
  • Callback limits — Maximum number of callback invocations
  • Callback timeout — Maximum time for a single callback

Resource limits prevent runaway code from consuming excessive resources.

Networking

Networking is disabled by default but can be enabled with policies:

  • Host filtering — Allow/block specific domains with wildcard patterns
  • Connection limits — Maximum concurrent connections
  • Timeouts — Connection and I/O timeouts
  • TLS support — Full HTTPS support with custom certificates

Network access is controlled by the host, not the sandboxed code.

Secrets

Secrets provide secure handling of sensitive values like API keys:

  • Python code sees opaque placeholders, never real values
  • Real values are only substituted when making HTTP requests to authorized hosts
  • Placeholders are automatically scrubbed from stdout, stderr, and file writes
  • Each secret can be restricted to specific hosts

Secrets prevent untrusted code from exfiltrating sensitive credentials.

WebAssembly & WASI

Eryx uses WebAssembly (Wasm) and WASI for sandboxing:

  • WebAssembly provides memory isolation and controlled execution
  • WASI (WebAssembly System Interface) provides limited system access
  • Wasmtime is the runtime that executes the Wasm code
  • Component Model enables the callback mechanism

You don’t need to understand these details to use Eryx, but they provide strong security guarantees.

Pre-compilation

The embedded feature includes pre-compiled Wasm for fast startup:

  • Python interpreter initialization (~450ms) is done at build time
  • Sandbox creation is reduced from ~650ms to ~16ms (41x faster)
  • The pre-compiled binary is embedded in your application
  • Trade-off: adds ~32MB to your binary size

Packages

Eryx supports loading Python packages at runtime:

  • .whl files (standard Python wheels)
  • .tar.gz / .tgz files (used by wasi-wheels project)
  • Native extensions compiled for WASI
  • Packages are loaded per-sandbox or via SandboxFactory for reuse

Volume Mounts

Volume Mounts allow controlled access to host filesystem directories:

  • Mount host directories at specific paths inside the sandbox
  • Optional read-only enforcement
  • Uses capability-based security (cap-std)
  • Sandboxed code cannot access paths outside the mounted directories

Volume mounts complement the VFS by providing access to real host files when needed.

Architecture Overview

┌─────────────────────────────────────────────┐
│          Your Application (Host)            │
│  ┌─────────────────────────────────────┐   │
│  │         Eryx Sandbox                │   │
│  │  ┌───────────────────────────────┐  │   │
│  │  │   WebAssembly Instance        │  │   │
│  │  │  ┌─────────────────────────┐  │  │   │
│  │  │  │   CPython 3.14          │  │  │   │
│  │  │  │   (Sandboxed Code)      │  │  │   │
│  │  │  └─────────────────────────┘  │  │   │
│  │  │            ↑                   │  │   │
│  │  │            │ Callbacks         │  │   │
│  │  │            ↓                   │  │   │
│  │  └───────────────────────────────┘  │   │
│  │         (Wasmtime Runtime)          │   │
│  └─────────────────────────────────────┘   │
└─────────────────────────────────────────────┘

Sandbox vs Session Comparison

FeatureSandboxSession
State persistenceNo — fresh each execute()Yes — variables persist
Virtual filesystemNoOptional
Use caseOne-off executionREPL, multi-step workflows
IsolationComplete per-callComplete from host
PerformanceModerate overheadLower overhead after warmup

Security Model

Eryx provides defense-in-depth security:

  1. Process-level isolation — Wasm provides memory isolation
  2. Capability-based security — Only explicitly granted capabilities are available
  3. Resource limits — Prevent resource exhaustion
  4. Network policies — Control which hosts can be accessed
  5. No filesystem access — Unless explicitly enabled with VFS or volume mounts
  6. Secrets isolation — Sensitive values are never directly accessible to sandboxed code

This makes Eryx suitable for running untrusted Python code.

Next Steps

Sandboxes

Sandboxes are the core primitive in Eryx. A sandbox provides an isolated Python execution environment powered by WebAssembly, ensuring complete isolation from the host system.

Creating a Sandbox

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Create a sandbox with embedded runtime (recommended)
    let sandbox = Sandbox::embedded().build()?;

    // Execute code
    let result = sandbox.execute("print('Hello!')").await?;
    println!("{}", result.stdout_text());

    Ok(())
}
import eryx

# Create a sandbox
sandbox = eryx.Sandbox()

# Execute code
result = sandbox.execute("print('Hello!')")
print(result.stdout_text)  # "Hello!"

Guest Languages

Python is the default guest language. Eryx can also run JavaScript (QuickJS) and a bash-compatible shell (brush), through the same API: callbacks, resource limits, sessions and snapshots work the same way. In Rust, enable the javascript and shell cargo features to embed their runtimes, then switch the builder’s language. In Python, the pyeryx wheel only includes the Python runtime: install the others with pip install pyeryx[javascript], pyeryx[shell] or pyeryx[all] (or pass runtime_path= to a precompiled .cwasm).

The shell runtime is a WASI 0.3 component (wasm32-wasip3), and the Python and JavaScript runtimes are WASI 0.2 ones; eryx links both versions of WASI, so each sees the same sandboxed filesystem, environment and clocks. The JavaScript package (@eryx-org/eryx) still runs a WASI 0.2 build of the shell.

import eryx

js = eryx.Sandbox(language="javascript")
result = js.execute("console.log(6 * 7)")

Python-only options, such as the stdlib, site-packages and packages, are only available on a Python builder, as are library preambles. JavaScript has fetch and reads secrets from process.env; the shell exports their placeholders to its commands (see Network below). A shell script fails with its exit status (ErrorKind::ScriptFailed { exit_code: Some(n), .. }; in Python, PythonExceptionError.exit_code; in eryx-server’s ExecuteResult, exit_code, which is also 0 for a shell script that succeeds). Besides bash’s builtins, the shell has grep built in. Patterns are GNU basic regular expressions, as in grep (a\|b, \(x\)), and -E and -F work as usual. Callbacks are commands (see Callbacks in the Shell).

sh and bash run a nested shell in the same guest: bash -c 'CMD' [NAME [ARG]...], sh FILE [ARG]..., or commands from stdin (echo 'echo hi' | bash, bash -s ARG), with -e, -u, -x, -o OPTION and their + forms. A nested shell behaves like an external command. It sees only exported variables, its own file descriptors and the working directory. Nothing it changes (variables, functions, options, cd) comes back. Its exit status is the command’s. It shares the sandbox’s filesystem, commands and callbacks. Shells nest at most 16 deep; past that sh/bash exits 126. Like bash’s, a nested shell doesn’t wait for its background jobs: they keep running after it, and the script’s implicit wait (below) covers them.

Any file is runnable (./script.sh, or a file in a $PATH directory). WASI has no execute bit. A file whose first line is #!/bin/sh, #!/bin/bash, #!/usr/bin/env bash (or dash) runs in a nested shell, with the line’s one argument if it has one (#!/bin/bash -e). Any other #! line runs the sandbox’s command of the interpreter’s file name, with the script’s path: #!/usr/bin/env python3 runs python3 ./script. A command that isn’t there exits 127. A file without #! runs as an sh script. A path always names a file, never a command: ./ls runs a file named ls, not the ls command. env -S in a #! line isn’t supported. chmod is a builtin that changes nothing (ls -l and stat show the same mode after it): it checks the mode (+x, u+x, 755, …) and that each file exists, so chmod +x script.sh && ./script.sh works. A missing file fails as in GNU chmod (exit 1, chmod: cannot access ...).

env is a builtin, because uutils’ env can’t run commands on WASI. env alone prints the exported environment. env [-i] [-u NAME]... [NAME=VALUE]... COMMAND [ARG]... runs COMMAND with those variables added (NAME=VALUE), removed (-u), or as the only ones (-i). The command is looked up like any other (builtins, commands, sh/bash, scripts) except functions. A command that isn’t there exits 127, and any other option exits 125.

xargs is a builtin too, for the same reason, so its command is looked up like env’s: ls *.py | xargs grep -l TODO runs the grep builtin, and xargs -I {} sh -c '...' a nested shell. It takes GNU’s options: -0/--null, -d DELIM, -a FILE, -n MAX, -L MAX, -I REPLACE (and -i), -r, -s MAX, -x, -t, -E EOF and -P MAX, with GNU’s quoting ('a b', "a b", a\ b) when items are split at blanks. The default command is echo. Command lines are also kept under the host’s limit on a command’s arguments and environment (2 MiB), so long input runs as several commands, never one that fails to start. -P runs commands at once, 32 at most, and -P 0 means 8. Commands running at once share the execution’s child memory pool (max_child_memory_bytes, 256 MiB by default), so a run that doesn’t fit fails (with memory-heavy commands such as python3, keep -P low). xargs exits 123 if a command failed (exit 1-125), 124 if one exited 255, 125 if one was killed (exit 129-254, as a job kill stops exits), 126 or 127 if the command can’t be run or isn’t there, and 1 for its own errors. It reads all its input before running the first command, so it doesn’t work on endless input (yes | xargs). The commands get its stdin, which it has read to the end (or, with -a, left alone). -p isn’t supported.

timeout is a builtin too (uutils’ needs processes and signals), so timeout 30 pytest runs pytest looked up like env’s command. It takes GNU’s arguments, timeout [OPTION] DURATION COMMAND [ARG]...: DURATION is a number of seconds with an optional s, m, h or d suffix, and 0 means no limit. When the time runs out, the command is stopped at once, as kill stops a job (with its builtins and child commands), and timeout exits 124. --preserve-status makes that 128 plus the signal’s number (-s SIGNAL, TERM by default). --foreground and -k/--kill-after are accepted, and change nothing. Otherwise it exits with the command’s status: 127 if it isn’t there, 126 if it can’t be run, and 125 if timeout itself fails. The shell’s builtins run in the guest, between waits on child commands and pipes, so a command that only loops on builtins without waiting (sh -c 'while :; do :; done') isn’t stopped by timeout; the execution’s timeout still ends it.

Background jobs work as in bash: cmd & runs cmd alongside the script, and $! is its ID. wait waits for every job, wait ID|%N... for those jobs (returning the last one’s status), and wait -n for the first to finish (127 if there are none). jobs (with -l or -p) lists them. kill [-SIGNAL] ID|%N... stops a job, its builtins and its child commands. WASI has no signals, so every signal ends the job, which then exits with 128 plus the signal’s number (143 for the default TERM). kill -0 checks that a job is still running. Job IDs are the shell’s own; no process has one. A script ends with an implicit wait: jobs still running then finish within the same execution, their output is its output, and its status is still the script’s own. If the execution would time out while only jobs are left (the script itself has finished), the jobs are killed just before the deadline, stderr gets one line saying how many (eryx: killed 2 background jobs still running when the execution timed out), and the execution returns the script’s result instead of a timeout. Jobs a nested shell left running count too. A script that is itself still running at the timeout times out as usual. A job that loops on builtins alone (while :; do :; done &, with no command, pipe or sleep in it) never lets the shell stop it in time, so it ends in a timeout too. In a session, jobs never outlive the execution that started them. Jobs count against the execution’s limits like any other command. fg, bg, stopped jobs, trap on signals, and %name job specs aren’t supported.

Timers in JavaScript

JavaScript has setTimeout, setInterval, setImmediate and their clear* functions, queueMicrotask, and node:timers and node:timers/promises (await setTimeout(ms, value, { signal }), and setInterval as an async iterator). Waiting burns no fuel, but it counts towards the execution timeout.

  • An execute waits for referenced timers, as a Node process does. So setTimeout(() => console.log("hi"), 100) prints hi without an await, and a setInterval that’s never cleared runs until the execution timeout fails the execute (ErrorKind::Timeout). A timed-out execute discards its instance, so a session’s next execute starts fresh (state_was_reset), as after running out of fuel.
  • It waits for every callback in flight, awaited or not, wherever it started: at top level, in a promise callback, after an await, or in a timer. So a forgotten await (tool(); console.log("done")) still runs the callback to the end, and if it fails, the execute fails as an unhandled rejection (below). The wait counts towards the execution timeout. Python differs: a coroutine that’s never awaited never runs, and tasks still pending when the script ends are dropped.
  • timer.unref() lets the execute finish without that timer, and an unref’d timer alone (like AbortSignal.timeout()’s) doesn’t keep a script that never settles waiting. Timers still pending when the execute finishes are dropped: none carries over to a session’s next execute.
  • Each turn of the event loop runs the timers due when it started, then lets finished callbacks in, so timers that are always due (a setImmediate loop) don’t starve callback results.
  • An exception thrown in a timer callback fails the execute.
  • An uncaught error (or rejection, below) ends stderr as well as being the failure’s message, as Python’s traceback does.
  • A promise rejection still unhandled when the event loop drains fails the execute as a script failure, with Uncaught (in promise) Error: ... and its stack as the message (the first one, with a count of any others). So does an async function called without await that throws. A rejection that gets a handler later, in a later microtask or timer, doesn’t: this is more lenient than Node, which fails at the end of the tick. A rejection left over from a failed execute never fails a session’s next one.
  • fetch is synchronous inside the guest: it blocks until the response has been read, so timers don’t fire during a fetch, only after it returns.

Shell Environment

A shell sandbox starts with what CLI tools expect of a Unix system:

  • / is a read-only directory holding the mounts, so tools that walk up to it (mkdir -p, canonicalizing realpath, git’s repository discovery) work. Paths under a mount go to the mount; anything else under / doesn’t exist (cat /etc/passwd fails with “No such file or directory”), and nothing can be created, written, renamed or removed there.
  • /tmp is writable in every shell sandbox. With unstable-vfs it’s served from the sandbox’s VFS storage; without it, from a private in-memory storage. Either way it counts against ResourceLimits::max_vfs_bytes (default 64 MiB), and in a session it lasts until the session ends, across resets.
  • /dev/null, /dev/zero and /dev/urandom: writes are discarded; reads are empty, zeros and random bytes. A single read returns at most 1 MiB, however much was asked for. A mount at /dev replaces them.
  • Environment: HOME=/tmp, PATH=/eryx/bin (where the shell lists its commands), TERM=dumb, LANG=C.UTF-8, LC_ALL=C.UTF-8, USER=eryx, PWD=/ and TMPDIR=/tmp.
  • Permissions: WASI has no file modes, owners or exec bit, so what tools report is made up by their libc. uutils ls -l shows every directory as dr-xr-xr-x and every file (devices included) as -r-xr-xr-x, owned by somebody/somegroup, whatever can actually be written. Tools that compare modes against what they wrote need telling, for example git’s core.fileMode=false.

Python and JavaScript sandboxes keep their filesystem as it was: no root, /dev or these variables. The shell feature pulls in eryx-vfs to provide this, but the VFS API stays behind unstable-vfs.

External Commands

A shell sandbox can run WASI command programs as external commands: WASI 0.2 and 0.3 command components (built for wasm32-wasip2 or wasm32-wasip3, such as uutils coreutils, ripgrep or curl), and WASI preview 1 command modules (wasm32-wasip1, or any wasi_snapshot_preview1 CLI), which eryx adapts into 0.2 components when it loads them, with the adapter of the wasmtime it links. A preview 1 command’s exit status reaches the shell only as success (0) or failure (1). Building Commands walks through building one. Register them by name on a shell builder:

use eryx::{Command, Sandbox};

let coreutils = Command::from_file("coreutils.wasm")?; // compiled once
let rg = Command::from_file("rg.wasm")?;
let sandbox = Sandbox::embedded()
    .shell()
    .with_commands(["cat", "head", "sort", "wc"], coreutils) // one multicall binary
    .with_command("rg", rg)
    .build()?;
let result = sandbox.execute("printf 'b\na\n' | sort | head -n 1").await?;
  • Defaults: with the shell feature, Sandbox::embedded().shell() already runs uutils coreutils (cat, head, tail, ls, wc, cp, mv, rm, mkdir, touch, sort, seq, cut, tr, uniq, basename, dirname, tee, sleep, paste, comm, date, base64, realpath, readlink, rmdir, md5sum, sha1sum, sha256sum, sha512sum, b2sum, printenv; eryx::embedded::COREUTILS_TOOLS). A registered command replaces the tool of the same name, and without_embedded_commands() leaves them out. It also registers itself as sh and bash for commands that run them (see Shell as a command).

  • Python: pass commands by name, e.g. eryx.Sandbox(language="shell", commands={"rg": eryx.Command.from_file("rg.wasm")}) (Command.from_bytes and Command.from_precompiled_file too). The pyeryx-runtime-shell package (pip install pyeryx[shell]) brings coreutils, which pyeryx registers by default.

  • eryx-server: --shell-command NAME[,NAME...]=PATH[@sha256:<hex>] (repeatable, or ERYX_SHELL_COMMANDS separated by ;) registers a .wasm command or one precompiled by eryx-precompile compile (.cwasm). A .wasm can be pinned to its digest (see Commands from a registry). --no-shell-embedded-commands leaves the embedded coreutils (and sh/bash for children) out, --shell-python adds python/python3 (see Python as a command), --shell-node adds node/js (see JavaScript as a command), and --shell-command-tunnels NAME (repeatable) lets a command open tunnels (see Network). An empty ERYX_SHELL_COMMANDS means no extra commands.

  • Python as a command: Command::guest(Language::Python) (Rust, with embedded; Command::guest_from_precompiled_file for your own runtime), eryx.Command.python() (pyeryx) and --shell-python (eryx-server) run Python as a command. It isn’t registered by default; register it as python and python3:

    let sandbox = Sandbox::embedded()
        .shell()
        .with_commands(["python", "python3"], Command::guest(Language::Python)?)
        .build()?;
    sandbox.execute("seq 3 | python3 -c 'import sys; print(sum(map(int, sys.stdin)))'").await?;

    It takes -c CODE, -m MODULE, a script, - or no argument (the program from stdin), -V, and ignores -u, -B, -I, -E, -s and -q; anything else exits 2. sys.exit(n) is its exit status, and an uncaught exception prints its traceback and exits 1. Each run is a fresh interpreter, with the embedded standard library, on the shell’s files (/tmp and volumes), environment, working directory and stdio. It burns the execution’s fuel, stops at its timeout, and its memory (about 17 MB per run, more as it allocates) counts against the children’s shared pool (max_child_memory_bytes, 256 MiB by default). It gets no callbacks and no network (yet), so a credential can’t be for it. A script’s top-level asyncio.run(main()) works as in execute.

  • Shell as a command: a command registered with allow_spawn that runs sh or bash (git does, for aliases, hooks, core.pager, GIT_SSH_COMMAND and credential helpers) gets the embedded shell, as Command::guest(Language::Shell): a fresh shell guest for each run, with -c CMD [NAME [ARG]...], a script file or commands from stdin, the options above, and the args, env, directory and stdio the command gave it. It runs the commands its caller may run (the execution’s allowed ones), one level deeper (it counts towards the depth limit of 4), within its caller’s network, and has no callbacks and no network of its own. It waits for its background jobs before it exits, stopping them just before the execution’s timeout. Each run costs about 0.1 ms and 5 MB of the children’s memory pool. The embedded shell registers it unless without_embedded_commands(); an execution’s allowed commands must name sh (or bash) for a child to run it, as for the shell’s own nested sh.

  • JavaScript as a command: Command::guest(Language::JavaScript) (Rust, with embedded and javascript), eryx.Command.node() (pyeryx, from the JavaScript runtime Sandbox(language="javascript") would use) and --shell-node (eryx-server) run QuickJS as a command. It isn’t registered by default; register it as node and js:

    let sandbox = Sandbox::embedded()
        .shell()
        .with_commands(["node", "js"], Command::guest(Language::JavaScript)?)
        .build()?;
    sandbox.execute("seq 3 | node -e 'console.log(require(\"fs\").readFileSync(0, \"utf8\"))'").await?;

    It takes -e CODE, -p CODE (prints the value), a script (also through a #!/usr/bin/env node line), - or no argument (the program from stdin), -v (which prints the QuickJS version: this isn’t Node) and -h; any other option exits 9, as in Node. The program runs as an execute’s code does (leading imports and top-level await work), with process.argv ([execPath, script, ...args]), process.env, process.cwd(), process.exit(n), process.exitCode and process.stdout.write, and the main module’s require, module, exports, __filename and __dirname. require("./x") loads a CommonJS module (or .json) from the shell’s files, and a script’s import ... from "./x.mjs" an ES module. node:fs reads and writes the shell’s files: whole-file readFileSync/writeFileSync/appendFileSync (readFileSync(0) is stdin), existsSync, statSync, readdirSync, mkdirSync, rmSync, renameSync, copyFileSync and friends, each also as a callback and in fs.promises. There’s no process.stdin stream, fs.createReadStream or file descriptor API. The command waits for its timers and un-awaited promises, and an uncaught error or unhandled rejection prints to stderr and exits 1. process.exit throws to unwind the script, so a catch around it sees that, but the command still exits with its status when that code returns. Limits, files and the missing callbacks and network are as for Python.

  • JavaScript (@eryx-org/eryx): a shell sandbox includes coreutils (as a download on first use; coreutils: false leaves it out), and commands adds others by the URL of their jco transpile --instantiation async output. They run in batch, not as a pipeline: each reads all its stdin, runs to completion, then passes on its output (see the package’s README).

  • Per execution: an execution can be narrowed to some of the registered commands: with_allowed_commands(["cat", "sort"]) on a session’s (or executor’s) execute builder or on the ExecuteOptions of Sandbox::execute_with, allowed_commands=[...] on pyeryx Sandbox.execute and Session.execute, or ExecuteRequest.allowed_commands on eryx-server. The guest sees only those, and the others exit 127 as if not installed. An empty list allows none, unset allows all, and unknown names are ignored. It lasts one execution: a session’s next call without it gets every command back. The shell’s grep builtin and its nested sh and bash count as commands here (allow grep, sh or bash to keep them): left out, they fail as not installed when run, though type grep and command -v grep still report a builtin. Other builtins and callbacks aren’t commands and keep working. In a session, a command an earlier call allowed still shows in the shell’s hash table, but running it is refused.

  • Per command, per execution: with_command_options(name, options) on the same builders (and ExecuteOptions) takes away from what one registered command gets in that execution, as a CommandOptions: with_network(ChildNetwork::None | Inherit | Narrow(config)) gives its children no network, the execution’s, or only what both config and the execution’s allow (its connections and bytes count against config’s limits and the execution’s); without_tunnels() and without_spawn() turn off what allow_tunnels() and allow_spawn() gave it at registration. Options never add: the execution fails to start if they name a command that isn’t registered, or give one network when the sandbox gives children none. A command it spawns gets its own options, not its caller’s, so pair None or Narrow with without_spawn() to stop it reaching a command with more network. Like with_allowed_commands, they last one execution.

  • Lookup: the shell looks for functions first, then builtins, then callbacks, then registered commands. An unregistered name exits 127.

  • Running: each command runs as a child process with argv[0] set to the name it was called by, which is how a multicall binary picks its tool. It gets the shell’s environment, with PWD set to the shell’s directory, which is also its WASI initial working directory. Children built with eryx-build start in that directory; other wasi-libc programs start in /, because wasi-libc ignores both (WebAssembly/wasi-libc#915).

  • What children get: WASI 0.2.x and 0.3.x wasi:cli, wasi:clocks, wasi:filesystem, wasi:random and wasi:sockets (and 0.2’s wasi:io), plus eryx:process/[email protected] and eryx:process/[email protected] for commands registered with allow_spawn: run runs a command to completion, and pipe starts one with live pipes to its stdin and stdout (as git talks to its remote-https helper). A piped command runs only while its caller is in a pipe call (writing, reading or waiting on any of its piped commands), so a caller blocked on something else that depends on it waits until the timeout. Nothing else: no wasi:http (children reach the network over sockets, through the proxy below), and no WASI prereleases. A command importing anything else is refused when it’s loaded (Command::from_file and friends, or eryx-precompile compile), with each such import named. Check a CLI before registering it with eryx-precompile commands inspect cli.wasm (--json for a script; Command::inspect in Rust), which lists its imports and whether children get each, and exits 1 if eryx can’t run it (2 if it can’t read the file as a command at all).

  • Files: a child sees the shell’s filesystem (above): the read-only root, /tmp, /dev and, with unstable-vfs, the session’s VFS mounts, and nothing else of the host. Files a child writes are the shell’s, and last as long as the shell’s own.

  • Network: none by default. A child without network that tries to resolve a name or open a socket gets eryx: networking not enabled for commands in this sandbox (curl has no network) on its stderr (for this command when only its command’s network is taken away), once, before its own error. With the sandbox’s network, children can get some through a proxy on the host, and never more than the sandbox’s policy allows: in Rust with_child_network(ChildNetwork::Inherit) (that policy) or ChildNetwork::Narrow(config) (only what both allow); in Python child_network="inherit" or a NetConfig; in eryx-server network_config.child_network. A narrowing config starts from the defaults, which block localhost and private networks, so it must repeat any allowed networks or internal hosts its children need. In Rust, a command can have less from registration on, with Command::with_network(ChildNetwork::None | Inherit | Narrow(config)) (the same narrowing, in every execution and session call); an execution’s CommandOptions::with_network replaces it for that execution. A command run by another (allow_spawn) gets only what both its own network and its caller’s allow, so narrowing a command holds everything it runs too. build fails if a command is registered with network when the sandbox gives children none, or with an invalid narrowing config. Children get HTTPS_PROXY/HTTP_PROXY and the proxy’s CA at /etc/ssl/certs/ca-certificates.crt, and see secrets only as their placeholders, which the proxy replaces in requests to each secret’s hosts. A command allowed tunnels (Command::allow_tunnels, allow_tunnels=True, --shell-command-tunnels) can open blind CONNECT tunnels instead, for protocols the proxy can’t inspect: no secret substitution and no HTTP rules in them, and hosts with rules never get one.

  • Credentials: a Credential is a header the proxy adds to some commands’ requests to some hosts, from a secret the sandbox never sees, not even as a placeholder, so git and gh authenticate with no token in their env or files:

    Sandbox::embedded().shell()
        .with_command("git", git.allow_spawn())
        .with_network(network)
        .with_child_network(ChildNetwork::Inherit)
        .with_credential(
            Credential::basic("x-access-token", token)
                .for_hosts(["github.com"])
                .for_paths(["/my-org/"])
                .for_commands(["git"]),
        )

    bearer, token (Authorization: token …), basic(user, …) and header(name, template, …) build the value. for_hosts is required, and takes exact names, IP addresses, or *. and a name of two labels or more (*.github.com, not *.com), no other *, port, path or non-ASCII character (write punycode); it doesn’t scope by port. for_paths and for_commands narrow it (with no for_commands, every child gets it). Give one execution its own with ExecuteOptions::with_credential (a hosted service’s per-user token): where it and a sandbox’s both set a header on a request, the execution’s wins. Take them from one command with CommandOptions::without_credentials().

    • Where: only on requests the proxy inspects: over the TLS it terminates, or plain HTTP with allow_plaintext(). A connection to a credential’s host refuses Upgrade and CONNECT requests outright, so those hosts can’t be used for WebSockets or other upgrades. Any header of the same name the child sent is replaced, so gh can run with a dummy GH_TOKEN. A command opening blind tunnels can’t carry one: naming it fails the execution, and a tunnelling proxy refuses a credential’s hosts.
    • Confined to its commands: a command with credentials gets a proxy of its own, which wants a password from its HTTPS_PROXY URL (scrubbed from the output like the credential), and no connection, the sandbox’s or a child’s, may reach a child proxy, even with allow_localhost. Other commands and the script’s own requests never get the header.
    • Responses: on a connection with a credential, requests ask for Accept-Encoding: identity and a compressed or transfer-coded response ends the connection, since the credential can’t be found in an encoded body, as does any 101. Range and If-Range are dropped from every request on such a connection, whether it gets the credential or not. The value (and for Basic its base64 payload, and the secret) is masked out as [REDACTED], as secrets’ real values are, and scrubbed from stdout, stderr and traces too in case any reaches them. Masking only hides whole, verbatim echoes: one in another form (its base64 alone, hex, JSON’s \/ for /) or in pieces isn’t masked, so don’t give credentials for hosts that echo request headers. Output scrubbing is defence in depth, not a boundary (see Credentials).
    • Limits: a command with a credential can do anything with it its hosts and paths allow, whatever the script asks: scope it as narrowly as you can. Credentials are Rust-only for now.
  • Limits: children count against the execution’s max_fuel as they run (a child may burn all the fuel the execution has left, so with no max_fuel only the timeout bounds it), and stop at its execution_timeout and cancellation, even mid-computation. They’re charged once per 10 ms epoch tick, so together they can overshoot max_fuel by at most one tick of work per running child (at most 64). The running children share one pool of memory, ResourceLimits::max_child_memory_bytes (default 256 MiB), outside max_memory_bytes; a child that can’t grow fails like one out of memory, and one that can’t start says so on the shell’s stderr (eryx: not enough memory for <command> (child memory pool full: ...)). A child holds at most 16,384 resource handles (open files, streams, sockets) at once. Children run on an engine of their own that allocates on demand, so they take none of the pooling allocator’s slots (ERYX_POOL_INSTANCES). The host memory children’s arguments and environment hold is capped per execution by ResourceLimits::max_child_host_bytes (default 64 MiB), with at most 64 children spawned but not yet finished and 2 MiB of arguments and environment per spawn. Each argument and variable counts its host overhead as well as its text (24 bytes per string on 64-bit hosts). Past a limit the spawn fails and the shell reports <command>: limit-exceeded, after a line saying which limit (eryx: too many commands running (limit 64), say).

  • Pipes: a child’s stdin, stdout and stderr stream through 64 KiB pipes, so pipeline stages run together and a full pipe makes its writer wait: yes | head -n 1 stops once head exits. A loop of builtins writing into a pipe (while true; do echo y; done | head -n 1) still runs until its timeout, since the shell has no SIGPIPE to stop it.

  • Precompiling: Command::from_precompiled{,_file} loads one precompiled with Executor::precompile or eryx-precompile compile (without --language). It carries the same version stamp as precompiled runtimes, so one from another eryx version fails with ErrorKind::IncompatiblePrecompiled.

The gRPC server serves every language it has a pool for (--languages), and each request picks one with ExecuteRequest.language.

Sandbox Isolation

Each sandbox runs in complete isolation:

  • Memory isolation: No access to host memory
  • Filesystem isolation: No access to host filesystem (see VFS for virtual filesystem)
  • Network isolation: Disabled by default (see Networking to enable)
  • Process isolation: Cannot spawn processes or execute system commands
extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    // Host filesystem is not accessible
    let result = sandbox.execute(r#"
import os
try:
    files = os.listdir('/etc')
    print(f"Found {len(files)} files")
except Exception as e:
    print(f"Access blocked: {type(e).__name__}")
    "#).await?;

    println!("{}", result.stdout_text());
    // Output: "Access blocked: FileNotFoundError" or shows empty virtual directory

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()

# Host filesystem is not accessible
result = sandbox.execute("""
import os
try:
    files = os.listdir('/etc')
    print(f"Found {len(files)} files")
except Exception as e:
    print(f"Access blocked: {type(e).__name__}")
""")

print(result.stdout_text)
# Output: "Access blocked: FileNotFoundError" or shows empty virtual directory

Execution Results

When you execute code, you get back an ExecuteResult with useful information:

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    let result = sandbox.execute("x = sum(range(1000))").await?;

    println!("stdout: {}", result.stdout_text());
    println!("Duration: {:?}", result.stats.duration);
    println!("Peak memory: {:?} bytes", result.stats.peak_memory_bytes);
    println!("Fuel consumed: {:?}", result.stats.fuel_consumed);

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()

result = sandbox.execute("x = sum(range(1000))")

print(f"stdout: {result.stdout}")
print(f"Duration: {result.duration_ms}ms")
print(f"Peak memory: {result.peak_memory_bytes} bytes")
print(f"Callback invocations: {result.callback_invocations}")

Trace Collection

In Rust, the sandbox can also record line-level execution events in ExecuteResult::trace. This is off by default because it installs Python’s sys.settrace hook, whose cost scales with how much Python runs: pass costs about 20% extra per execution, a small json + string.Template render goes from 0.9 ms to 3.7 ms, and sum(i * i for i in range(20_000)) from 3.8 ms to 369 ms. Enable it when you read the trace:

extern crate eryx;
use eryx::Sandbox;

fn main() -> Result<(), eryx::Error> {
let sandbox = Sandbox::embedded().with_trace_collection(true).build()?;
Ok(())
}

Each execution queues at most 16 MiB of trace events and 16 MiB of streamed output for handlers, counting a fixed 64-byte overhead per event or chunk. Past that, further events are dropped and ExecuteResult::stream_truncated is set; the captured stdout/stderr in the result are complete. Direct fd 1/2 writes are captured separately, up to 1 MiB per stream, and streamed once at the end of the execution, so a handler receives at most 16 MiB + 2 × 1 MiB of output per execution.

A TraceHandler set with with_trace_handler still receives events when collection is disabled. Sessions created from the sandbox inherit the setting.

The Python bindings never collect traces (ExecuteResult does not expose them), so no option is needed there.

Error Handling

Sandbox execution can fail for various reasons. Eryx provides typed errors to help you handle them:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ErrorKind};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    match sandbox.execute("raise ValueError('oops')").await.map_err(eryx::Error::into_kind) {
        Ok(result) => println!("Success: {}", result.stdout_text()),
        Err(ErrorKind::Execution(message)) => {
            println!("Python error: {}", message);
        }
        Err(ErrorKind::Timeout(duration)) => {
            println!("Execution timed out after {:?}", duration);
        }
        Err(e) => println!("Other error: {}", e),
    }

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()

try:
    sandbox.execute("raise ValueError('oops')")
except eryx.ExecutionError as e:
    print(f"Python error: {e}")
except eryx.TimeoutError as e:
    print(f"Timeout: {e}")
except eryx.EryxError as e:
    print(f"Other error: {e}")

Reusing Sandboxes

Sandboxes can be reused for multiple executions. Each execution starts fresh without any state from previous executions:

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    // First execution
    sandbox.execute("x = 42").await?;

    // Second execution - x is NOT available (fresh state each time)
    let result = sandbox.execute(r#"
try:
    print(x)
except NameError:
    print("x is not defined")
    "#).await?;

    println!("{}", result.stdout_text());  // "x is not defined"

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()

# First execution
sandbox.execute("x = 42")

# Second execution - x is NOT available (fresh state each time)
result = sandbox.execute("""
try:
    print(x)
except NameError:
    print("x is not defined")
""")

print(result.stdout_text)  # "x is not defined"

If you need state to persist across executions, use a Session.

SandboxFactory for Fast Creation

When creating many sandboxes, use SandboxFactory to pre-initialize Python and packages once, then quickly instantiate sandboxes from that snapshot. Executions on short-lived sandboxes also pick up a pre-instantiated WebAssembly instance from a process-wide pool; see Performance Tuning for how that works and how to size it.

extern crate eryx;
extern crate tokio;
// SandboxFactory is primarily useful in the Python bindings
// In Rust, use Sandbox::embedded() which already uses pre-compiled WASM
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Sandbox::embedded() is already optimized for fast creation
    for i in 0..5 {
        let sandbox = Sandbox::embedded().build()?;
        let result = sandbox.execute(&format!("print('sandbox {}')", i)).await?;
        println!("{}", result.stdout_text());
    }
    Ok(())
}
import eryx

# Create a factory (takes ~2s to initialize Python)
factory = eryx.SandboxFactory()

print(f"Factory size: {factory.size_bytes} bytes")

# Create sandboxes quickly from the factory (~1ms each)
for i in range(5):
    sandbox = factory.create_sandbox()
    result = sandbox.execute(f"print('sandbox {i}')")
    print(result.stdout_text)

Factory with Pre-installed Packages

You can create a factory with packages pre-installed:

import eryx

# Create a factory with packages
factory = eryx.SandboxFactory(
    packages=[
        "path/to/jinja2.whl",
        "path/to/markupsafe.whl",
    ],
    imports=["jinja2"],  # Pre-import these modules
)

# Sandboxes created from this factory have packages ready
sandbox = factory.create_sandbox()
result = sandbox.execute("""
from jinja2 import Template
t = Template("Hello {{ name }}")
print(t.render(name="World"))
""")
print(result.stdout_text)  # "Hello World"

Saving and Loading Factories

Factories can be serialized for later use:

import eryx
from pathlib import Path

# Create and save
factory = eryx.SandboxFactory()
factory.save(Path("factory.bin"))

# Load later
loaded = eryx.SandboxFactory.load(Path("factory.bin"))
sandbox = loaded.create_sandbox()

Next Steps

Building Commands

A shell sandbox runs WASI command programs as external commands. This page takes a CLI from source to a command a shell sandbox runs: building it for WASI, checking it, registering it from Rust, Python or eryx-server, and publishing it. External Commands is the reference for what a running command gets.

In short:

  1. Build the CLI as a WASI command: wasm32-wasip2 for Rust, wasi-sdk for C.
  2. Check it with eryx-precompile commands inspect.
  3. Register it on a shell sandbox by name.
  4. Publish the .wasm, and have hosts pin it by its sha256 digest.

eryx-build does step 1 from a manifest and fixes the start-up differences below. eryx’s own published commands (ripgrep, jq, curl, git, gh and the rest) are built with it.

A Rust command

A small wc-like CLI, count:

//! `count`: lines, words and bytes of stdin or of each file named.
use std::io::Read;

fn count(name: &str, mut input: impl Read) -> std::io::Result<()> {
    let mut text = Vec::new();
    input.read_to_end(&mut text)?;
    let lines = text.iter().filter(|&&b| b == b'\n').count();
    let words = text.split(u8::is_ascii_whitespace).filter(|w| !w.is_empty()).count();
    println!("{lines} {words} {} {name}", text.len());
    Ok(())
}

fn main() {
    // WASI programs start in `/`: move to the shell's directory, which
    // eryx passes in $PWD.
    if let Ok(pwd) = std::env::var("PWD") {
        let _ = std::env::set_current_dir(pwd);
    }
    let files: Vec<String> = std::env::args().skip(1).collect();
    if files.is_empty() {
        if count("-", std::io::stdin()).is_err() {
            std::process::exit(1);
        }
        return;
    }
    let mut status = 0;
    for file in &files {
        if let Err(e) = std::fs::File::open(file).and_then(|f| count(file, f)) {
            eprintln!("count: {file}: {e}");
            status = 2;
        }
    }
    // Not `ExitCode` from `main`: built without eryx-build, that reports
    // only 0 or 1 on wasm32-wasip2.
    std::process::exit(status);
}

Build it as a WASI 0.2 component. Rust’s wasm32-wasip2 target writes one directly:

rustup target add wasm32-wasip2
cargo build --release --target wasm32-wasip2
eryx-precompile commands inspect target/wasm32-wasip2/release/count.wasm

commands inspect (from cargo binstall eryx-precompile) lists what the command imports and whether a shell’s children get each:

target/wasm32-wasip2/release/count.wasm: WASI 0.2 command
imports:
  wasi:cli/[email protected]: provided
  wasi:cli/[email protected]: provided
  ...
  wasi:filesystem/[email protected]: provided
  wasi:filesystem/[email protected]: provided
exports:
  wasi:cli/[email protected]
eryx can run it as a shell command

Register it on a shell sandbox. This needs eryx’s shell feature, and with embedded the shell runtime set up once with eryx-precompile setup --language shell (see Pre-compiling Runtimes):

[dependencies]
eryx = { version = "0.16", features = ["embedded", "shell"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
use eryx::{Command, Sandbox};

let sandbox = Sandbox::embedded()
    .shell()
    .with_command("count", Command::from_file("count.wasm")?)
    .build()?;

let result = sandbox
    .execute("printf 'one two\\nthree\\n' | count")
    .await?;
assert_eq!(result.stdout_text(), "2 3 14 -\n");

// A failing script is an error carrying its exit status.
let err = sandbox.execute("count /nope").await.unwrap_err();
assert!(matches!(err.kind(), eryx::ErrorKind::ScriptFailed { exit_code: Some(2), .. }));

Command::from_file compiles the command once; register the same Command under several names for a multicall binary, which picks its tool from argv[0].

Exit status

The shell sees a command’s exit status as $?, and a script’s last one is the execution’s. Two things in common toolchains lose it:

  • Rust without eryx-build: returning an ExitCode from main on wasm32-wasip2 or wasm32-wasip3 reports only success or failure, so any non-zero status becomes 1. std::process::exit(n) keeps n, so use it for plain builds. eryx-build’s Rust lane keeps an ExitCode (below).
  • C with plain wasi-sdk: wasi-libc’s exit reports only success or failure too. eryx-build’s C lane fixes this (below).

A WASI preview 1 module (wasm32-wasip1) reports only 0 or 1 whatever it does, because eryx adapts it into a component when it loads it.

Starting directory

A command gets the shell’s directory as PWD, but WASI has no working directory of its own, so a plain wasi-libc program (Rust, C) starts in / (WebAssembly/wasi-libc#915): cd /tmp/work && count notes.txt looks for /notes.txt. Either move to PWD at start-up, as count does with std::env::set_current_dir, or build with eryx-build, which links a constructor that does it for you. Absolute paths work either way.

Building with eryx-build

eryx-build builds a command from a TOML manifest that pins its source. On top of a plain build, it:

  • links a start-up constructor that moves the command into $PWD (Rust and C);
  • in the C lane, links a shim that exits with wasi:cli/exit.exit-with-code, and in the Rust lane passes an ExitCode returned from main on to it, so statuses above 1 reach the shell;
  • writes provenance.json next to the component: the source pins, patches, the eryx-build version, the built file’s sha256, and the WIT packages it imports;
  • drives the C (wasi-sdk: single files, CMake, autotools or make) and Go toolchains, with [[deps]] for libraries built before the main project.

It doesn’t write third-party notices; produce those with your usual tools (such as cargo about).

It isn’t on crates.io yet. Install it from an eryx release tag:

cargo install --locked --git https://github.com/eryx-org/eryx --tag eryx-v0.16.0 eryx-build

A manifest for count, as clis/count.toml:

name = "count"
description = "count: lines, words and bytes"
license = "MIT"
lang = "rust"

[source]
repo = "https://github.com/you/count.git"
ref = "v0.1.0"
commit = "<40-digit commit hash>"
dir = "scratch/count"

[build]
bin = "count"

[output]
dir = "out/count"
eryx-build count     # or: eryx-build clis/count.toml

Run it from the directory holding clis/: every path in a manifest is relative to it. A git source must be pinned by commit (an archive URL by sha256 instead), and the Rust lane builds with --locked, so commit a Cargo.lock. To build a local tree you’re working on, set [source] path = "../my-cli" instead; nothing is pinned, so --check and anything that publishes builds refuse such a manifest. The component lands in out/count/component.wasm, next to provenance.json.

The eryx-build README covers the lanes, what each needs installed, the output, and how to number revisions of a built command; the Manifest type in its src/manifest.rs documents every field.

C commands

wasi-sdk’s clang builds a WASI 0.2 command directly:

$WASI_SDK_PATH/bin/clang --target=wasm32-wasip2 -O2 -o hello.wasm hello.c

Such a program starts in / and reports any non-zero status as 1. Build it with eryx-build’s C lane instead to get the working directory and exit status right:

name = "hello"
description = "hello (C)"
license = "MIT"
lang = "c"

[source]
repo = "https://github.com/you/hello.git"
ref = "v0.1.0"
commit = "<40-digit commit hash>"
dir = "scratch/hello"

[build]
# `system` defaults to "single": one clang call over `sources`.
sources = ["hello.c"]
cflags = ["-O2"]

[output]
dir = "out/hello"
WASI_SDK_PATH=/path/to/wasi-sdk eryx-build hello

The C lane also needs wit-bindgen and rustc with the wasm32-wasip2 target, for the shims. For CMake, autotools and make projects, set [build] system and artifact; libraries such as oniguruma (for jq) or mbedTLS (for curl) go in [[deps]]. Projects often need wasi-sdk’s emulation libraries (-D_WASI_EMULATED_SIGNAL with -lwasi-emulated-signal, and the like) or a vendor_patch script that stubs out what WASI lacks.

Go commands

Go is experimental. Upstream Go’s GOOS=wasip1 builds preview 1 modules, which eryx adapts but which report only 0 or 1 as their status. eryx-build’s Go lane instead builds WASI 0.3 commands with a fork of Go ported to WASI 0.3 (as implemented by the wasmtime eryx uses), and componentizes them with wasm-tools. The fork is the wasip3-0.3.0-go1.27.4-exit-code branch of sd2k/go at a commit eryx-build pins. Run eryx-build toolchain go once: it fetches and builds the pinned fork (with GOWASM=widearith) into eryx-build’s cache, where the lane finds it. Set ERYX_GO_WASIP3_ROOT (or pass --dir) only to use another location, and [build.go_toolchain] in a manifest to pin another commit of the fork. A manifest’s Go-specific parts:

lang = "go"

[build]
package = "./cmd/tool"

[component]
world = "command"

eryx’s gh is built this way. Commands built with that branch start in the shell’s directory and keep their os.Exit status; earlier builds of the fork report any non-zero status as 1.

When a command won’t load

Command::from_file (and pyeryx’s Command.from_file, eryx-server’s --shell-command, eryx-precompile compile) refuses a command that imports what children don’t get, naming each import. commands inspect shows the same before you register it, and exits 1:

httpcli.wasm: WASI 0.2 command
imports:
  wasi:cli/[email protected]: provided
  ...
  wasi:http/[email protected]: not provided: children get no wasi:http; they reach the network over sockets, through the sandbox's proxy (HTTPS_PROXY), when it gives them network
exports:
  wasi:cli/[email protected]
eryx can't run it: it imports what children don't get (above)
  • wasi:http: children have no wasi:http. Use an HTTP client that works over wasi:sockets (Rust’s sockets, or libcurl in C) and honours HTTPS_PROXY; with network, the sandbox’s proxy carries its requests.
  • WASI prereleases (0.2.0-rc-…, 0.3.0-rc-…): not provided; rebuild with a toolchain that targets a released WASI version.
  • eryx:process/run or pipe: provided, but only to commands registered with allow_spawn (see below).
  • A preview 1 module: commands inspect says it adapts it, and lists what the adapted component imports. It runs, but reports only 0 or 1 as its status.

Registering elsewhere

  • Python (pyeryx):

    import eryx
    
    count = eryx.Command.from_file("count.wasm")
    sandbox = eryx.Sandbox(language="shell", commands={"count": count})
    print(sandbox.execute("printf 'one two\\nthree\\n' | count").stdout_text)
    

    A script that fails raises eryx.PythonExceptionError, whose exit_code is the status. Command.from_bytes and Command.from_precompiled_file load one from bytes or a precompiled file; allow_tunnels=True lets it open blind tunnels through the proxy.

  • eryx-server: --shell-command count=/commands/count.wasm@sha256:<hex> (repeatable, or ERYX_SHELL_COMMANDS), with --languages python,shell. A pinned file that doesn’t match fails startup, and the server compiles it once into its cache directory. --shell-command-spawn NAME and --shell-command-tunnels NAME grant spawning and tunnels. See Commands from a registry.

  • JavaScript (@eryx-org/eryx): a shell sandbox’s commands takes each command as the URL of its jco transpile --instantiation async output; commands there run in batch rather than as a live pipeline (see the package’s README).

  • Hosted SDKs for eryx.run don’t take your own command files.

Precompiling

Compiling a command takes time at every start. To pay it once:

  • Command::load_cached(path, Some("sha256:<hex>")) checks the digest and compiles the command once into eryx’s cache directory (commands/ under ~/.cache/eryx on Linux), so later loads of the same file skip compiling. Command::from_file_expecting(path, "sha256:<hex>") checks without caching.
  • eryx-precompile compile count.wasm --output count.cwasm writes a precompiled command, which Command::from_precompiled_file (unsafe: only load files you trust) and pyeryx’s Command.from_precompiled_file load. It only loads in the eryx version that built it, so recompile after every eryx upgrade.

Commands that run commands

A command registered with allow_spawn can run the sandbox’s other commands through eryx:process, as git runs git and its helpers: run runs one to completion with its output captured (up to 16 MiB each of stdout and stderr), and pipe starts one with live pipes to its stdin and stdout. Without allow_spawn, calls fail with spawn-failed.

Vendor the WIT from the eryx release you target, crates/eryx-runtime/wit/deps/process.wit at eryx-v0.16.0, as wit/deps/process.wit, next to a world importing what you use:

// wit/world.wit
package example:each;

world each {
    import eryx:process/[email protected];
}

Then, with wit-bindgen = "0.63", a command that runs CMD ARG... LINE for each line of its stdin:

use std::io::{BufRead, Write};

wit_bindgen::generate!({ world: "each", path: "wit", generate_all });
use crate::eryx::process::run::run;

fn main() {
    let mut args = std::env::args().skip(1);
    let Some(cmd) = args.next() else {
        eprintln!("usage: each CMD [ARG]...");
        std::process::exit(2);
    };
    let args: Vec<String> = args.collect();
    let env: Vec<(String, String)> = std::env::vars().collect();
    let cwd = std::env::var("PWD").unwrap_or_else(|_| "/".into());
    let mut status = 0;
    for line in std::io::stdin().lock().lines() {
        let mut argv = args.clone();
        argv.push(line.expect("reading stdin"));
        match run(&cmd, &argv, &env, &cwd, &[]) {
            Ok(out) => {
                std::io::stdout().write_all(&out.stdout).unwrap();
                std::io::stderr().write_all(&out.stderr).unwrap();
                if out.status != 0 {
                    status = out.status;
                }
            }
            Err(e) => {
                eprintln!("each: {cmd}: {e:?}");
                std::process::exit(126);
            }
        }
    }
    std::process::exit(status);
}
let sandbox = Sandbox::embedded()
    .shell()
    .with_command("each", Command::from_file("each.wasm")?.allow_spawn())
    .with_command("count", Command::from_file("count.wasm")?)
    .build()?;
sandbox.execute("printf 'a b\\n' > /tmp/a.txt; ls /tmp/*.txt | each count").await?;
  • cmd is a registered name (or sh/bash), not a path. Pass PWD as cwd so the command it runs starts where it does.
  • sh -c '...' and bash work from a spawning command: they run the embedded shell, with the commands the execution allows.
  • Children may spawn four levels deep (the shell’s own commands are the first), share the execution’s fuel, timeout, memory pool and child limits, and a spawned command’s network is only what both it and its caller are allowed (see External Commands).

Distributing

  • A file and its digest: publish the .wasm with its sha256, and have hosts pin it: Command::load_cached(path, Some("sha256:<hex>")) or from_file_expecting in Rust, @sha256:<hex> on eryx-server’s --shell-command. Publish the .wasm, not a .cwasm: a precompiled file is native code tied to one eryx version and CPU, and can’t be validated.

  • An OCI registry: wkg pushes a component as a single-layer Wasm artifact, and pulls it back to a file:

    wkg oci push ghcr.io/you/commands/count:0.1.0-r.1 out/count/component.wasm
    wkg oci pull ghcr.io/you/commands/count:0.1.0-r.1 -o count.wasm
    

    The pin is the layer digest, which is the sha256 of the .wasm itself. It isn’t the manifest digest that wkg oci push prints. eryx has no registry client: fetch commands before the host starts (an init container for eryx-server), then load them pinned. With oras, fetch the layer with oras blob fetch; oras pull skips it, since wkg’s layer has no file name. See Commands from a Registry.

  • Versions: <upstream>-r.<n> (for example 15.1.0-r.2) tells a rebuild of the same upstream release apart; the eryx-build README says when to start a new revision.

  • Licensing: a command keeps its own licence. A sandbox loads commands at run time, so a GPL command can stay a separate artifact rather than part of an MIT or Apache-licensed host binary; eryx publishes its GPL commands (git) apart from the others, with their source alongside. Ship each command’s licence and third-party notices with it.

Callbacks

Callbacks allow sandboxed Python code to call functions on the host. This enables controlled interaction with external resources like databases, APIs, or system services while maintaining the security of the sandbox.

Overview

From Python’s perspective, callbacks appear as async functions that can be awaited:

# Inside the sandbox
result = await get_weather(city="London")
print(result["temperature"])

The host defines these callbacks and controls exactly what the sandbox can access.

Defining Callbacks

[dependencies]
eryx = { version = "0.3", features = ["embedded", "macros"] }
extern crate eryx;
extern crate tokio;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError, Sandbox};
use serde_json::{json, Value};

/// Returns the current Unix timestamp
#[callback]
async fn get_time() -> Result<Value, CallbackError> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| CallbackError::ExecutionFailed(e.to_string()))?
        .as_secs();
    Ok(json!({ "timestamp": now }))
}

/// Echoes the message back with optional repetition
#[callback]
async fn echo(message: String, repeat: Option<u32>) -> Result<Value, CallbackError> {
    let repeat = repeat.unwrap_or(1) as usize;
    Ok(json!({ "echoed": message.repeat(repeat) }))
}

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded()
        .with_callback(get_time)
        .with_callback(echo)
        .build()?;

    let result = sandbox.execute(r#"
t = await get_time()
print(f"Time: {t['timestamp']}")

msg = await echo(message="hi", repeat=3)
print(msg['echoed'])  # "hihihi"
    "#).await?;

    println!("{}", result.stdout_text());
    Ok(())
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Returns current Unix timestamp")
def get_time():
    import time
    return {"timestamp": time.time()}

@registry.callback(description="Echoes the message back")
def echo(message: str, repeat: int = 1):
    return {"echoed": message * repeat}

sandbox = eryx.Sandbox(callbacks=registry)

result = sandbox.execute("""
t = await get_time()
print(f"Time: {t['timestamp']}")

msg = await echo(message="hi", repeat=3)
print(msg['echoed'])  # "hihihi"
""")

Callback names must be unique: building a sandbox with two callbacks of the same name (including those added by libraries) fails with an error naming it.

Reserved Names

A guest installs each callback under its name (for a dotted name like http.get, under its first part, http), and keeps what it already has, so a callback named like something of the guest’s could only be called through invoke("name"). Building such a sandbox fails instead, naming the callback and what it collides with:

  • JavaScript: the guest’s globals (fetch, crypto, URL, setTimeout, console, require, invoke, the built-ins like JSON and Map, …), including as a dotted name’s first part (fetch.get, crypto.*).
  • Shell: the builtins (echo, cd, test, read, …, and eryx’s invoke, grep, env, xargs, chmod, kill, timeout, sh and bash), the reserved words (time, select, function, [[, …), which are parsed as syntax, and the sandbox’s commands (the embedded coreutils, with_command ones), which a callback of the same name would hide.
  • Python: the builtins (print, list, open, …) and the names the guest defines (invoke, list_callbacks, asyncio, json, …), including as a dotted name’s first part (json.dumps).

In JavaScript, process is reserved even in a sandbox without secrets, where the guest only defines it when there are some.

The lists are in crates/eryx/src/reserved/. Give the callback another name (fetch_user, http_fetch), or put it under a prefix (tools.fetch).

Callback Namespace

To keep callbacks out of the guest’s top-level names altogether, install them under one name. It’s off by default, so existing scripts keep working:

BindingOption
RustSandboxBuilder::with_callback_namespace("tools") (or wrap each in NamespacedCallback)
pyeryxSandbox(callback_namespace="tools"), also Session and the factory’s create_sandbox/create_session
gRPCExecuteRequest.callback_namespace
@eryx-org/eryxnew Sandbox({ callbackNamespace: "tools" })

A callback get_time is then await tools.get_time() in Python, await tools.get_time() in JavaScript, and the command tools.get_time in the shell. A prefix callback mcp.* nests under it as tools.mcp.<server>.<tool>. Only the namespace has to stay clear of the reserved names above, so tools.fetch builds in JavaScript; the namespace must be an identifier. list_callbacks(), trace events and callback journals show the namespaced names (tools.get_time), while the callback itself (and a gRPC client’s CallbackRequest.name) sees its own name. A pool built with a namespace puts each lease’s callbacks under it too. Code written against the bare names, such as a library preamble that calls get_time() or invoke("get_time"), has to use the namespaced ones.

Parameters and Types

Callback parameters are passed as JSON from the sandbox. Parameters must be deserializable types.

#![allow(unused)]
fn main() {
extern crate eryx;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError};
use serde_json::{json, Value};

/// Searches for users matching the criteria
#[callback]
async fn search_users(
    query: String,              // Required parameter
    limit: Option<u32>,         // Optional with default (via unwrap_or)
    include_inactive: Option<bool>,
) -> Result<Value, CallbackError> {
    let limit = limit.unwrap_or(10);
    let _include_inactive = include_inactive.unwrap_or(false);

    // ... perform search ...
    let _ = query;
    Ok(json!({ "users": [], "total": 0 }))
}
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Searches for users")
def search_users(
    query: str,
    limit: int = 10,
    include_inactive: bool = False
):
    # ... perform search ...
    return {"users": [], "total": 0}

Positional Arguments

Sandboxed code can pass a callback’s arguments by name or by position. Positional arguments bind to the callback’s parameters in the order of its schema’s properties, in the order the schema declares them (the order list_callbacks() shows), the way a Python function binds them:

  • In Python, await add(1, 2) and await add(a=1, b=2) are the same call.
  • In JavaScript, a single plain object whose keys are all parameter names is keyword arguments, await add({a: 1, b: 2}), and anything else is positional, await add(1, 2). So for a callback whose first parameter, options, takes an object, await configure({retries: 3}) passes that object as options, while await configure({options: {retries: 3}}) names it. Keyword and positional arguments can’t be mixed in one call. Trailing undefined arguments count as not passed, and an undefined before another argument is sent as null.
  • The shell guest follows the same rule once #808 lands: add 1 2 is positional.

More positional arguments than parameters, or one that is also passed by name, fail the call without running the callback: add() takes 2 positional arguments but 3 were given, add() got multiple values for argument 'a'.

The Python guest binds positional arguments itself. The other guests send them to the host under the reserved key __eryx_args__ (eryx::POSITIONAL_ARGS_KEY), and the host binds them with the same rules. A prefix callback (a.b.*) gets its positional arguments unbound instead (see PrefixCallback).

Error Handling

Return errors to indicate failures to the sandbox.

#![allow(unused)]
fn main() {
extern crate eryx;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use eryx::{callback, CallbackError};
use serde_json::{json, Value};

/// Divides two numbers
#[callback]
async fn divide(a: f64, b: f64) -> Result<Value, CallbackError> {
    if b == 0.0 {
        return Err(CallbackError::InvalidArguments("Cannot divide by zero".into()));
    }
    Ok(json!({ "result": a / b }))
}
}
import eryx

registry = eryx.CallbackRegistry()

@registry.callback(description="Divides two numbers")
def divide(a: float, b: float):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return {"result": a / b}

Parallel Execution

Multiple callbacks can run concurrently using asyncio.gather():

# Inside the sandbox
import asyncio

# These run in parallel on the host
results = await asyncio.gather(
    fetch_user(id=1),
    fetch_user(id=2),
    fetch_posts(user_id=1),
)
user1, user2, posts = results

Timers

asyncio.sleep, asyncio.wait_for and asyncio.timeout work inside the sandbox, so scripts can bound their own callbacks or back off between retries:

# Inside the sandbox
import asyncio

try:
    user = await asyncio.wait_for(fetch_user(id=1), timeout=2)
except TimeoutError:
    user = None

Each pending timer is a host-side sleep; the guest is suspended while it waits. Timers fire only when the event loop regains control, so blocking code (time.sleep, a CPU-bound loop) delays them rather than being interrupted. Timers still pending when an execution finishes are cancelled with it, and never extend the execution timeout.

asyncio.run()

Code runs on an event loop that is already running, so top-level await is the natural way to call callbacks. Scripts written in the usual asyncio.run(main()) style work too: a top-level asyncio.run(coro) call (including one under if __name__ == "__main__":) awaits coro on the sandbox’s loop and returns its result.

# Inside the sandbox
import asyncio

async def main():
    return await fetch_user(id=1)

user = asyncio.run(main())

Only calls written as asyncio.run(...) at the top level are handled this way. Inside a function, which can’t await, asyncio.run() raises a RuntimeError; use await there instead.

Introspection

The sandbox can discover available callbacks at runtime:

# Inside the sandbox
import eryx_callbacks

# List all available callbacks
for name in dir(eryx_callbacks):
    callback = getattr(eryx_callbacks, name)
    print(f"{name}: {callback.__doc__}")

Callbacks in the Shell

In a shell sandbox, every callback is a command. A shell function or builtin of the same name wins, as in bash, and invoke NAME still reaches the callback. Arguments become the callback’s JSON arguments, and its result is printed to stdout, so callbacks compose with pipes and $(...):

weather London --days 3          # positional, then a flag
weather --city=London --metric   # --key=value, and a bare boolean flag
weather --json '{"city": "London"}' --days 3
invoke weather '{"city": "London"}'
forecast=$(weather London | grep -i rain)
  • Typing: flag values are typed by the callback’s parameters schema. A string property keeps the exact text (--id 007 is "007"). integer, number and boolean values are parsed, and an invalid one is a usage error. object and array values are JSON. A property with no type, or one that isn’t in the schema, is JSON if it parses and a string otherwise.
  • Boolean flags: a boolean property can be given bare (--metric), which means true, unless the next argument is true or false.
  • Positional arguments: the host binds these to the schema’s properties in order, like the Python guest’s weather("London"). eryx serializes schemas with their properties in alphabetical order. Each one is typed by the property at its position. Too many positionals, or one for a property also given as a flag, fails the call, so the command exits 1.
  • Repeated keys: repeating a key collects into a list for an array property, and is a usage error otherwise.
  • --json: gives a base object, and flags override its keys. -- ends the flags.
  • invoke: invoke NAME ... takes the same arguments. With a single JSON object argument, the object is passed as the arguments as is. invoke also reaches names under a prefix callback (invoke ns.tool --x 1).
  • NAME --help: prints the callback’s description and its arguments.
  • stdin: not read.

The result prints as a line on stdout: a string as raw text, anything else other than null as compact JSON, and null as nothing.

Exit statuses:

StatusMeaning
0The callback succeeded.
1The call failed: the callback returned an error, or the host rejected the arguments. That covers too many positionals, or a positional for a property also given as a flag. NAME: message goes to stderr.
2A usage error the shell found before calling: a bad flag value, a repeated key, malformed --json. NAME: problem, then the usage line, go to stderr.
127invoke of an unknown name.

A callback that suspends (see Replay and Suspension) stops the whole script, whatever surrounds the call: approve || true doesn’t swallow it.

Alternative APIs

Rust: Manual TypedCallback

For more control, implement TypedCallback directly:

extern crate eryx;
extern crate tokio;
extern crate serde;
extern crate serde_json;
extern crate schemars;
use std::{future::Future, pin::Pin};
use eryx::{TypedCallback, CallbackError, Sandbox, JsonSchema};
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Deserialize, JsonSchema)]
struct GreetArgs {
    name: String,
    #[serde(default)]
    formal: bool,
}

struct Greet;

impl TypedCallback for Greet {
    type Args = GreetArgs;

    fn name(&self) -> &str { "greet" }
    fn description(&self) -> &str { "Generates a greeting" }

    fn invoke_typed(
        &self,
        args: GreetArgs,
    ) -> Pin<Box<dyn Future<Output = Result<Value, CallbackError>> + Send + '_>> {
        Box::pin(async move {
            let greeting = if args.formal {
                format!("Good day, {}.", args.name)
            } else {
                format!("Hey {}!", args.name)
            };
            Ok(json!({ "greeting": greeting }))
        })
    }
}

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
let sandbox = Sandbox::embedded()
    .with_callback(Greet)
    .build()?;
    Ok(())
}

Rust: DynamicCallback

For runtime-defined callbacks without compile-time types:

extern crate eryx;
extern crate tokio;
extern crate serde_json;
use eryx::{DynamicCallback, Sandbox};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
let callback = DynamicCallback::builder(
    "get_config",
    "Returns application configuration",
    |_args| Box::pin(async move {
        Ok(json!({
            "version": "1.0.0",
            "debug": false
        }))
    })
).build();

let sandbox = Sandbox::embedded()
    .with_callback(callback)
    .build()?;
    Ok(())
}

Python: Dict API

For simple cases, use a list of dictionaries:

import eryx

def my_callback(args):
    return {"result": args.get("value", 0) * 2}

sandbox = eryx.Sandbox(
    callbacks=[
        {
            "name": "double",
            "fn": my_callback,
            "description": "Doubles a value"
        }
    ]
)

Prefix Callbacks

A prefix callback handles every dotted name under a prefix with one handler, which receives the full name the sandbox called, its keyword arguments and its positional arguments. Use it for large or lazily discovered tool sets, where registering each tool separately would be costly: the sandbox installs one callback however many names it serves, and nothing under the prefix is looked up until it is called.

extern crate eryx;
extern crate tokio;
extern crate serde_json;
use eryx::{CallbackError, PrefixCallback, Sandbox};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
// Registers `mcp.grafana.*`.
let tools = PrefixCallback::new("mcp.grafana", "Grafana MCP tools", |name, kwargs, args| {
    Box::pin(async move {
        match name.as_str() {
            "mcp.grafana.user_info" => Ok(json!({ "login": "admin" })),
            // Bind a positional query, or take it by keyword.
            "mcp.grafana.search-docs" => {
                let query = args.first().unwrap_or(&kwargs["query"]).clone();
                Ok(json!({ "query": query }))
            }
            _ => Err(CallbackError::NotFound(name)),
        }
    })
});

let sandbox = Sandbox::embedded().with_callback(tools).build()?;
let output = sandbox
    .execute(
        r#"
user = await mcp.grafana.user_info()
docs = await mcp.grafana["search-docs"](query="alerts")
more = await mcp.grafana["search-docs"]("panels")
print(user["login"], docs["query"], more["query"])
"#,
    )
    .await?;
assert_eq!(output.stdout_text().trim(), "admin alerts panels");
    Ok(())
}
  • A name registered as an ordinary callback is called directly, so exact callbacks win over prefixes. Other names go to the longest matching prefix (mcp.grafana.* before mcp.*); a name under no prefix fails as unknown.
  • The sandbox has no schema for the names under a prefix, so it passes positional arguments to the handler, in order, rather than binding them. The handler can bind them itself (e.g. to an MCP tool’s input schema properties, in declared order) or reject them with CallbackError::InvalidArguments. A keyword-only call gets an empty list. An exact callback under the prefix still binds positional arguments from its own schema.
  • list_callbacks() lists the prefix (mcp.grafana.*) with its description, not the names under it.
  • JavaScript guest code calls them the same way: await mcp.grafana.user_info(), await mcp.grafana["search-docs"]("panels"). Any name below the prefix, at any depth, is a function. A single plain object is keyword arguments; anything else goes positionally. Looking at a namespace never calls the host, so then, toJSON (which JSON.stringify and console.log ask for), call, apply, bind and Object.prototype’s names (toString, …) aren’t tool names there: call those through invoke("mcp.grafana.toJSON"). console.log prints a namespace as [Namespace mcp.grafana]. listCallbacks() lists the prefix as is.
  • Any callback whose name ends in .* is a prefix callback, and gets the invoked name through Callback::invoke_named. In the JavaScript package, declare a callback named mcp.grafana.*: the callback handler already receives every call’s full name.
  • On the wire, positional arguments travel in the arguments object under the reserved key __eryx_args__ (eryx::POSITIONAL_ARGS_KEY), only when there are any: f(1, k=2) sends {"__eryx_args__":[1],"k":2}. PrefixCallback takes the key out; a custom prefix callback, or a JavaScript handler, sees it as is. Python code can’t pass a keyword argument of that name (it’s a TypeError), and an ordinary callback that receives the key fails with InvalidArguments without being called.
  • Journals, trace events and max_callback_invocations see the full name of each call. Journals key on the arguments text, positional ones included, so only identical calls replay.

MCP Tools as Callbacks

Eryx can also bridge MCP (Model Context Protocol) servers into the sandbox as callbacks. This lets sandboxed code call tools from external MCP servers (GitHub, filesystem, databases, etc.) using the same async callback mechanism.

See MCP Integration for details.

Replay and Suspension

When a script drives expensive callbacks (tool calls, API requests, database queries), eryx can journal callback results on one run and replay them on the next, so a re-run only re-executes the callbacks that haven’t run yet. A callback can also suspend execution — returning a “retry later” signal that halts the guest and lets the run resume once a dependency is ready.

See Callback Replay & Suspension for details.

Best Practices

  1. Keep callbacks focused - Each callback should do one thing well
  2. Validate inputs - Don’t trust data from the sandbox
  3. Handle errors gracefully - Return meaningful error messages
  4. Use descriptive names - Callbacks appear as functions in Python
  5. Document with descriptions - Help sandbox code understand what’s available
  6. Consider timeouts - Long-running callbacks can block sandbox execution

Callback Replay & Suspension

When an LLM iterates on a Python script that drives expensive callbacks — tool calls, API requests, database queries — a failure late in the script normally forces a full re-run, re-invoking every callback that already succeeded. Callback replay avoids this by journaling callback results during a run and replaying them on a subsequent run, so only the callbacks that haven’t run yet (or whose inputs changed) actually execute.

Suspension is the companion feature: a callback can return CallbackError::Suspend to halt execution (“I can’t answer yet — retry later”). Eryx records what was waiting on, stops the guest immediately, and the recorded journal lets you resume from where you left off once the dependency is ready.

Availability. This guide covers the Rust library API, the Python bindings (Sandbox, Session and pooled sandboxes) and the JavaScript bindings (@eryx-org/eryx, which implement the same matching, divergence guard and suspension semantics in the JS host). The gRPC server also implements both features — including HMAC-signed journals — over its callback_journal field and CALLBACK_OUTCOME_SUSPEND outcome; see the gRPC Server guide for the wire-level details.

How replay works

Rather than checkpointing the Python interpreter (which can’t capture mid-execution frames), eryx records each callback invocation and its result. On resubmission the entire script is re-executed, but callbacks that match the recorded journal short-circuit to the cached result instead of making a real call. Because callbacks are the expensive part and the Python between them is comparatively free, this is both fast and robust to arbitrary code structure — loops, conditionals, nested functions all work, because the journal operates on the callback invocations, not on the code.

Replay is implemented entirely as a callback wrapper: there are no changes to the WASM runtime, the WIT interface, or the Python code.

Matching model

Callbacks are matched by their name plus canonicalized arguments, treated as a FIFO multiset:

  • When a journal is loaded, each recorded result is bucketed by its (name, args) key in recorded order. Each live invocation pops the next cached result for its key, so repeated identical calls replay in their original order.
  • While replay is active, matching is independent of invocation order — a concurrently launched batch (asyncio.gather) replays correctly no matter which future the scheduler polls first, because a call is matched by what it is, not by its position.
  • The canonical arguments are the guest’s argument JSON verbatim: Python emits them with json.dumps(kwargs, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False), and no host re-encodes them. So a journal matches the same way in the Rust, Python and JavaScript hosts and the gRPC server. In the Python guest, passing NaN or infinity as a callback argument raises ValueError in the script; the JavaScript guest sends them as null, as JSON.stringify does.
  • Every guest writes its arguments with sorted keys, so a call matches whatever order its keys (or, in the shell, its flags) were written in: the JavaScript guest with JSON.stringify and every object’s keys sorted, the shell with its flags’ keys sorted. Each guest has its own canonical form (number formatting differs between them), so a journal replays in the guest language that recorded it.

If a dict has keys that can’t be compared with each other (e.g. int with str, None with anything), they can’t be sorted, so the whole payload is emitted unsorted, in insertion order.

Journals recorded before #529 keyed arguments as serde_json re-serialized them. Those entries still match for strings, booleans, 64-bit integers, str-keyed dicts and most floats, but miss where the two forms differ:

  • integers beyond 64 bits (serde turned them into floats);
  • floats with exponents -5 to -9: Python writes 1e-05 / 1e-07 / 2.5e-08 where serde wrote 0.00001 / 1e-7 / 2.5e-8;
  • dicts with non-str keys whose numeric order differs from their string order (multi-digit, negative, bool or float keys): Python sorts {10: .., 9: ..} numerically, serde sorted the keys as strings;
  • dicts with keys that can’t be compared with each other, e.g. int with str or None with anything (now insertion order).

A miss is sticky: it trips the divergence guard, so that call and every later callback in the run execute live, including non-idempotent ones. Nothing stale is replayed, but side effects the old journal had recorded can happen again.

Divergence guard

The first invocation that does not match a remaining cached result for its key — a miss — is treated as a divergence from the recorded run: replay stops, and that call and every subsequent call run live for the rest of the execution. This prevents a stale cached result from being replayed across a real divergence (for example, a script edited to write before it reads). It does not prevent re-execution: see Live re-runs and idempotency.

A caller that signs journals and binds the signature to the exact script (as the gRPC server layer does) rejects an edited script’s journal before matching even runs, restricting replay to re-runs of the same script.

Recording a journal

Use Sandbox::execute_with_journal instead of execute (executeWithJournal in JavaScript). It returns a ReplayOutcome whose journal field holds every callback that completed — even if the script itself errored partway through.

use eryx::Sandbox;

let sandbox = Sandbox::embedded()
    .with_callback(fetch_user)
    .with_callback(charge_card)
    .build()?;

let outcome = sandbox.execute_with_journal(code, None).await;

// `journal` is always populated, even on error — persist it to resume later.
let journal = outcome.journal;
println!("recorded {} callbacks", journal.len());
import json
import eryx

def fetch_user(id: int):
    return {"id": id, "name": "Ada"}

def charge_card(user_id: int, cents: int):
    return {"charged": cents}

code = """
user = await fetch_user(id=1)
await charge_card(user_id=user["id"], cents=500)
"""

sandbox = eryx.Sandbox(callbacks=[
    {"name": "fetch_user", "fn": fetch_user},
    {"name": "charge_card", "fn": charge_card},
])

# Never raises for execution failures: check outcome.error instead.
outcome = sandbox.execute_with_journal(code)

# `journal` is a JSON-compatible dict, always populated, even on error.
saved = json.dumps(outcome.journal)
print(f"recorded {len(outcome.journal['entries'])} callbacks")
import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();

// Never rejects for execution failures: check outcome.error instead.
const outcome = await sandbox.executeWithJournal(code);

// `journal` is a JSON string, always populated, even on error. Store it as-is.
await db.save("journal", outcome.journal);

ReplayOutcome carries:

FieldMeaning
resultThe execution result, exactly as execute would return it.
journalThe CallbackJournal recorded during this run (always present).
replayed_callbacksHow many callbacks were served from a previous journal (cache hits).
suspendedSome(SuspendedCallback) if a callback requested suspension.

The CallbackJournal derives serde::Serialize/Deserialize, so you can persist it (database, cache, etc.) between runs.

In Python, ReplayOutcome has result (an ExecuteResult, or None on failure), error (the exception execute() would have raised, or None), journal (a dict; treat it as opaque), replayed_callbacks, and suspended (a SuspendedCallback or None).

In JavaScript, the outcome has the same fields in camelCase: result (an ExecuteResult, or undefined), error, journal, replayedCallbacks and suspended ({ name, argsJson, reason }). journal is a JSON string in the serde format of CallbackJournal, so journals are portable between hosts. Pass it back unmodified: results are stored as their exact JSON text, which a JSON.parse/JSON.stringify round trip could alter (1.0 would become 1, and large integers would lose precision). A JavaScript callback’s outcome is journaled as follows:

  • A returned value becomes {"Ok": value}, as the JSON Python got: BigInts are exact, and a value wrapped in JSON.rawJSON keeps its text (JSON.rawJSON("1.0") stays a float).
  • A thrown value becomes {"Err": message} ("RangeError: ..." for an Error) and replays as the same Python exception.
  • Only SuspendCallback is not journaled (see Suspension).

Journals from @bsull/eryx may have entries with "thrown": true, from a thrown Error, which then halted the guest: replay halts at them the same way.

Replaying a journal

Pass the previously-recorded journal to execute_with_journal (journal= in Python, options.journal in JavaScript) and execute the same code again:

use eryx::Sandbox;

let sandbox = Sandbox::embedded()
    .with_callback(fetch_user)
    .with_callback(charge_card)
    .build()?;

// `previous_journal` holds the results recorded earlier.
let outcome = sandbox
    .execute_with_journal(code, Some(previous_journal))
    .await;

// Callbacks that matched the journal returned cached results instead of
// running live.
println!("replayed {} callbacks", outcome.replayed_callbacks);
import eryx

def fetch_user(id: int):
    return {"id": id, "name": "Ada"}

callbacks = [{"name": "fetch_user", "fn": fetch_user}]
code = "user = await fetch_user(id=1)"
sandbox = eryx.Sandbox(callbacks=callbacks)
previous = sandbox.execute_with_journal(code).journal

outcome = sandbox.execute_with_journal(code, journal=previous)  # results recorded earlier

# Callbacks that matched the journal returned cached results instead of
# running live.
print(f"replayed {outcome.replayed_callbacks} callbacks")
const outcome = await sandbox.executeWithJournal(code, {
  journal: await db.load("journal"), // the string recorded earlier
});

// Callbacks that matched the journal returned cached results instead of
// running live.
console.log(`replayed ${outcome.replayedCallbacks} callbacks`);

Plain Sandbox::execute never journals or replays (likewise JavaScript’s execute). Each call to execute_with_journal uses fresh replay state, so one sandbox can record, replay and resume different journals without being rebuilt. Sessions (InProcessSession in Rust, Session in Python) and pooled sandboxes have the same execute_with_journal method. In a session, Python state persists across journaled calls as usual, and a plain execute in between runs its callbacks live. In Rust, the sandbox preamble runs as part of a session’s first call, so if that call is journaled, callbacks the preamble invokes are journaled too.

Concurrent identity

The replay identity is exactly (callback name, canonical args). FIFO ordering is guaranteed for sequential identical calls, but it is not a stable per-task identity for concurrent identical calls — replay can’t preserve which gather task happened to get which result without an invocation id. If you need a stable assignment, make each call’s identity unique by including a nonce or correlation key in the callback args so the calls no longer share a key.

Suspension

Replay and suspension work the same way in the Python, JavaScript and shell guests: a callback that suspends halts the guest, even where the script catches the call’s failure (try/catch in JavaScript, || true in the shell).

A callback can defer its work by returning CallbackError::Suspend (raising eryx.SuspendCallback in Python, from a sync or async callback; throwing SuspendCallback in JavaScript) with an opaque reason string:

use eryx::{callback, CallbackError};
use serde_json::Value;

/// Requests human approval for an action.
#[callback]
async fn request_approval(action: String) -> Result<Value, CallbackError> {
    match approval_status(&action).await {
        Status::Granted(value) => Ok(value),
        Status::Pending => Err(CallbackError::Suspend(
            format!("awaiting approval for {action}"),
        )),
    }
}
import eryx

APPROVED: set[str] = set()  # stand-in for your approval store

def request_approval(action: str):
    """Requests human approval for an action."""
    if action not in APPROVED:
        raise eryx.SuspendCallback(f"awaiting approval for {action}")
    return {"approved": action}
import { Sandbox, SuspendCallback } from "@eryx-org/eryx";

const approved = new Set(); // stand-in for your approval store

const sandbox = new Sandbox({
  callbacks: {
    request_approval: ({ action }) => {
      if (!approved.has(action)) {
        throw new SuspendCallback(`awaiting approval for ${action}`);
      }
      return { approved: action };
    },
    // ... other callbacks ...
  },
});

When a callback suspends, eryx:

  1. Records a SuspendedCallback (callback name, arguments, reason) — but does not journal the call, so it re-runs live on resume.
  2. Halts the guest synchronously, so no further Python runs, no further callbacks dispatch, and no I/O happens after the suspension point. The Rust host poisons the WASM fuel; in JavaScript the thrown SuspendCallback propagates out of the host import, which rejects the execution immediately (Python cannot catch it).

Two layers guarantee nothing runs after a suspension: a synchronous gate rejects any callback dispatched after the first suspension (covering later gather siblings), and the halt stops the guest before it can do anything else.

Because the guest is halted, outcome.result will be an Err (in Python, result is None and error is an ExecutionError; in JavaScript, result is undefined and error is the SuspendCallback) when a suspension occurs — branch on suspended first and treat that error as the expected consequence of the suspend rather than a failure:

let outcome = sandbox.execute_with_journal(code, None).await;

if let Some(suspended) = &outcome.suspended {
    // Persist outcome.journal, wait for the dependency named by
    // suspended.reason / suspended.name / suspended.args_json, then resume.
    save_for_later(&outcome.journal, suspended);
    return;
}

let result = outcome.result?; // only reached if not suspended
import eryx

def request_approval(action: str):
    raise eryx.SuspendCallback(f"awaiting approval for {action}")

sandbox = eryx.Sandbox(callbacks=[{"name": "request_approval", "fn": request_approval}])
outcome = sandbox.execute_with_journal('await request_approval(action="deploy")')

if outcome.suspended:
    # Persist outcome.journal, wait for the dependency named by
    # suspended.reason / suspended.name / suspended.args_json, then resume.
    print("suspended:", outcome.suspended.reason)
elif outcome.error:
    raise outcome.error
else:
    print(outcome.result.stdout_text)
const outcome = await sandbox.executeWithJournal(code);

if (outcome.suspended) {
  // Persist outcome.journal, wait for the dependency named by
  // suspended.reason / suspended.name / suspended.argsJson, then resume.
  console.log("suspended:", outcome.suspended.reason);
} else if (outcome.error) {
  throw outcome.error;
} else {
  console.log(outcome.result.stdout);
}

Resuming

To resume, execute the same code again with the journal from the suspended run (execute_with_journal(code, Some(outcome.journal)) in Rust, execute_with_journal(code, journal=outcome.journal) in Python, executeWithJournal(code, { journal: outcome.journal }) in JavaScript). The recorded prefix replays from cache; the previously-suspended callback re-runs live (it was never journaled) and, assuming its dependency is now ready, returns a real value so the script continues past the suspension point.

A session can resume in place. A suspension (like a timeout, fuel exhaustion or a trap) halts the guest, so before each journaled call a session snapshots its Python globals, and if the run halts it resets the instance and restores that snapshot. The resume then starts from the state before the suspended call, so Python code that ran before the suspension (such as n += 1) is not applied twice. The rollback covers Python globals only: VFS and volume writes and network calls made before the suspension are not undone.

Some caveats:

  • The snapshot behaves like snapshot_state: imported modules are restored (re-imported by reference), but objects that can’t be serialized, such as open files or sockets, are dropped.
  • Each journaled session call costs one snapshot. Sessions without callbacks skip it, since nothing can suspend.
  • If the snapshot fails (for example, it exceeds the snapshot size limit), the call runs without rollback protection and a warning is logged. A halt then resets the session so it stays usable, but its state is lost.
  • If the rollback itself fails, the session is unusable. The outcome then reports that error and no suspension, so it isn’t mistaken for something resumable in place. The journal is still valid for resuming in a new session.
  • In Rust, the preamble is not re-run after rolling back a later call, so preamble setup that can’t be serialized is lost.

Live re-runs and idempotency

Replay never replays a stale result, but it also does not guarantee that a callback runs at most once. A call runs live again whenever it is not served from the journal:

  • calls that miss — the first divergent call and every call after it;
  • the previously-suspended call, on resume (it was never journaled);
  • calls that never completed into the journal: those cut off by the host’s callback timeout, those that never reached the handler, and any call started after the suspending call (the journal is truncated at the suspension point) — for example a gather sibling of the suspending call. A call still in flight when the run fails, times out or suspends is otherwise awaited by the host and journaled, as is one the script stopped waiting for (wait_for, task.cancel()).

Callbacks with side effects (charging a card, sending a message, writing a record) must therefore be idempotent, or deduplicate on their side — for example with an idempotency key passed in the callback args. Because a suspending callback is invoked again on resume, it should only check readiness before suspending, and perform its side effects only on the call that returns a value.

Every call that completed is journaled, including failures: an error result replays as the same error instead of re-running the callback. In JavaScript this includes a handler that threw an Error (which halts the run): replay halts at the same point without calling the handler again.

Determinism and limitations

Replay short-circuits callbacks — the Python between callbacks always re-executes live on every run. Replay therefore reproduces callback results, not whole-program state, and it assumes the script is deterministic given the same callback results. Nondeterminism in the script itself — an unseeded random, wall-clock time (time.time(), datetime.now()), or anything else that varies run to run — is recomputed fresh each time, with these consequences:

  • If it feeds callback arguments, the recomputed args won’t match what was journaled, so those calls miss — the divergence guard then runs them, and everything after them, live (re-incurring their cost).
  • If it drives control flow, the replayed run may take a different path than the recorded one, dispatching a different set of callbacks.
  • Timers are not journaled — asyncio.sleep, wait_for and asyncio.timeout deadlines are not callbacks, so a replayed run waits through its sleeps again in real time, while replayed callbacks return instantly. A timeout (or task.cancel()) only stops Python waiting: the host callback still completes and is journaled. On replay it returns instantly from cache, so a wait_for that timed out on the recording run can now succeed and take a different path. Only a callback that hit the host’s callback timeout, or never reached the handler, is missing from the journal.
  • Non-callback output is not reproduced — values the script computes itself rather than via a callback are recomputed, so stdout or the result variable can differ even when every callback replayed.

The divergence guard ensures a recomputed argument that misses falls back to live execution rather than injecting a stale cached result — which means that call, and everything after it, runs live again (see Live re-runs and idempotency). But replay is only fully transparent for scripts whose callback names, arguments, and control flow are deterministic given the same callback results.

To make a nondeterministic input replayable, route it through a callback so it lands in the journal — fetch the current time or a random seed via a callback rather than reading it inside the sandbox, and it will replay deterministically like any other recorded result.

A built-in deterministic mode (a seedable RNG and a mockable clock, captured in the journal) is being explored in issue #244 to cover these cases without routing each input through a callback.

Security: journals are a trusted input

Replayed journal entries are returned to Python verbatim — eryx does not re-execute the callback to validate them. A crafted journal can therefore inject arbitrary values into a script’s execution. Treat the journal as a trusted input.

The core eryx crate is agnostic to signing and trusts whatever journal it receives, so only replay journals from a source you control (a previous run of the same sandbox). When journals round-trip through an untrusted boundary — stored externally, or returned to a client and echoed back — verify integrity first. The gRPC server layer provides HMAC-SHA256 signing that binds a journal to the exact script for exactly this purpose.

See also

Sessions

Sessions maintain Python state across multiple executions, enabling REPL-style interactive usage. Unlike regular sandbox executions which start fresh each time, sessions preserve variables, functions, classes, and imports.

Creating a Session

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    // Execute code in the session
    session.execute("x = 42").await?;
    let result = session.execute("print(x)").await?;
    println!("{}", result.stdout_text());  // "42"

    Ok(())
}
import eryx

session = eryx.Session()

# Execute code in the session
session.execute("x = 42")
result = session.execute("print(x)")
print(result.stdout_text)  # "42"

State Persistence

Sessions preserve all Python state between executions:

Variables

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("x = 42").await?;
    session.execute("y = x * 2").await?;
    let result = session.execute("print(f'{x}, {y}')").await?;
    println!("{}", result.stdout_text());  // "42, 84"

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("x = 42")
session.execute("y = x * 2")
result = session.execute("print(f'{x}, {y}')")
print(result.stdout_text)  # "42, 84"

Functions and Classes

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    // Define a function
    session.execute(r#"
def greet(name):
    return f"Hello, {name}!"
    "#).await?;

    // Use it later
    let result = session.execute("print(greet('World'))").await?;
    println!("{}", result.stdout_text());  // "Hello, World!"

    // Define a class
    session.execute(r#"
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
    "#).await?;

    // Create and use instances
    session.execute("c = Counter()").await?;
    let result = session.execute("print(c.increment(), c.increment(), c.increment())").await?;
    println!("{}", result.stdout_text());  // "1 2 3"

    Ok(())
}
import eryx

session = eryx.Session()

# Define a function
session.execute("""
def greet(name):
    return f"Hello, {name}!"
""")

# Use it later
result = session.execute("print(greet('World'))")
print(result.stdout_text)  # "Hello, World!"

# Define a class
session.execute("""
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
""")

# Create and use instances
session.execute("c = Counter()")
result = session.execute("print(c.increment(), c.increment(), c.increment())")
print(result.stdout_text)  # "1 2 3"

Imports

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("import json").await?;
    let result = session.execute(r#"print(json.dumps({"a": 1}))"#).await?;
    println!("{}", result.stdout_text());  // '{"a": 1}'

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("import json")
result = session.execute('print(json.dumps({"a": 1}))')
print(result.stdout_text)  # '{"a": 1}'

Execution Count

Sessions track how many executions have been performed:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    println!("Count: {}", session.execution_count());  // 0

    session.execute("x = 1").await?;
    println!("Count: {}", session.execution_count());  // 1

    session.execute("y = 2").await?;
    println!("Count: {}", session.execution_count());  // 2

    Ok(())
}
import eryx

session = eryx.Session()

print(f"Count: {session.execution_count}")  # 0

session.execute("x = 1")
print(f"Count: {session.execution_count}")  # 1

session.execute("y = 2")
print(f"Count: {session.execution_count}")  # 2

Clearing and Resetting State

clear_state()

Clears Python variables while keeping the session instance:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("x = 42").await?;
    session.clear_state().await?;

    // x is no longer defined
    let result = session.execute("print('x' in dir())").await?;
    println!("{}", result.stdout_text());  // "False"

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("x = 42")
session.clear_state()

# x is no longer defined
result = session.execute("print('x' in dir())")
print(result.stdout_text)  # "False"

reset()

Completely resets the session by creating a new WebAssembly instance:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("x = 42").await?;
    session.reset().await?;  // Full reset

    // x is no longer defined
    let result = session.execute(r#"
try:
    print(x)
except NameError:
    print("x not defined")
    "#).await?;
    println!("{}", result.stdout_text());  // "x not defined"

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("x = 42")
session.reset()

# x is no longer defined
result = session.execute("""
try:
    print(x)
except NameError:
    print("x not defined")
""")
print(result.stdout_text)  # "x not defined"

Automatic resets

If a call is cancelled mid-run (its future dropped, e.g. by tokio::select! or tokio::time::timeout, or cancelled through its token) or halts (runs past the execution timeout, runs out of fuel, suspends or traps), the instance it was running on is lost. The next call on the session, including snapshot_state(), restore_state() and clear_state(), resets the session instead of failing, so its Python state is gone and the preamble runs again. The first successful result after such a reset has state_was_reset set to true (ExecuteResult.state_was_reset in Python and over gRPC, stateWasReset in JavaScript), so callers can tell their variables are gone.

Snapshots

Sessions support snapshotting and restoring state, enabling features like checkpoints or undo:

Taking a Snapshot

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("x = 10").await?;
    session.execute("y = 20").await?;

    // Take a snapshot
    let snapshot = session.snapshot_state().await?;
    println!("Snapshot size: {} bytes", snapshot.size());

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("x = 10")
session.execute("y = 20")

# Take a snapshot
snapshot = session.snapshot_state()
print(f"Snapshot size: {len(snapshot.data)} bytes")

Globals that can’t be serialized (open sockets, generators, objects dill rejects) are left out of the snapshot, so they raise NameError after a restore. In a JavaScript session that’s functions, promises, and values holding a class instance (a Buffer, an EventEmitter), which would otherwise come back as plain objects. The snapshot names them: snapshot.skipped() in Rust, snapshot.skipped_globals in Python, snapshot.skippedGlobals in JavaScript, and ExecuteResult.state_skipped_globals from the gRPC server. The serialized bytes to store are snapshot.to_bytes() in Rust and snapshot.data in Python and JavaScript. restore_state()/restoreState() take either the snapshot or those bytes.

The bytes record the eryx version that wrote them: snapshot.metadata().eryx_version in Rust, after StateSnapshot::from_bytes(). Use it to find stored snapshots that predate a runtime upgrade. Restoring doesn’t check it, since whether a snapshot restores depends on the Python runtime and on what the state holds. eryx reads snapshots from any earlier version. eryx before 0.15.0 can’t read snapshots from 0.15.0 or later. Python snapshots are still written in 0.15’s format, so eryx 0.15 reads them and a rolling deploy or a rollback keeps its sessions; JavaScript and shell snapshots use a newer format that needs eryx 0.16 or later. Bytes in a format newer than the reader knows fail with ErrorKind::IncompatibleSnapshot.

Restoring a Snapshot

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, session::{InProcessSession, Session}};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;
    let mut session = InProcessSession::new(&sandbox).await?;

    session.execute("x = 10").await?;
    let snapshot = session.snapshot_state().await?;

    // Modify the state
    session.execute("x = 999").await?;
    let result = session.execute("print(x)").await?;
    println!("{}", result.stdout_text());  // "999"

    // Restore the snapshot
    session.restore_state(&snapshot).await?;
    let result = session.execute("print(x)").await?;
    println!("{}", result.stdout_text());  // "10"

    Ok(())
}
import eryx

session = eryx.Session()

session.execute("x = 10")
snapshot = session.snapshot_state()

# Modify the state
session.execute("x = 999")
result = session.execute("print(x)")
print(result.stdout_text)  # "999"

# Restore the snapshot
session.restore_state(snapshot)
result = session.execute("print(x)")
print(result.stdout_text)  # "10"

Snapshots Across Sessions

Snapshots can be restored in different session instances:

import eryx

# Create first session and build up state
session1 = eryx.Session()
session1.execute("data = [1, 2, 3]")
session1.execute("total = sum(data)")
snapshot = session1.snapshot_state()

# Restore in a completely new session
session2 = eryx.Session()
session2.restore_state(snapshot)

result = session2.execute("print(f'{data}, {total}')")
print(result.stdout_text)  # "[1, 2, 3], 6"

Time and Fuel Bounds

snapshot_state(), restore_state() and clear_state() run Python code (__reduce__, __setstate__, __del__, …), so they are bounded like an execution. The time bound is the session’s execution timeout raised to at least 5 seconds (eryx::session::MIN_STATE_OP_TIMEOUT), because the first snapshot loads the serializer. A session with no execution timeout uses 30 seconds (eryx::session::DEFAULT_STATE_OP_TIMEOUT). The fuel bound is the session’s fuel limit raised to at least eryx::session::MIN_STATE_OP_FUEL. In Rust, SessionExecutor::set_state_op_timeout sets the time bound directly, and SessionExecutor::set_state_op_cancellation lets a CancellationToken stop a state operation (ErrorKind::Cancelled). A state operation that overruns returns ErrorKind::Timeout or ErrorKind::FuelExhausted, and the next call resets the session, as after a cancelled call. The gRPC server cancels the restore and snapshot when the client disconnects.

Session with VFS

Sessions can be configured with a virtual filesystem for persistent file storage. See VFS and File Persistence for details. The in-memory storage is capped at 64 MiB and 65,536 files and directories by default (see resource limits); put large trees on a host-directory volume.

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Files written in the session persist
session.execute("open('/data/test.txt', 'w').write('hello')")
result = session.execute("print(open('/data/test.txt').read())")
print(result.stdout_text)  # "hello"

Execution Timeout

Sessions inherit timeout configuration from the sandbox’s resource limits:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits, session::{InProcessSession, Session}};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Configure timeout via resource limits
    let limits = ResourceLimits::default()
        .with_execution_timeout(Duration::from_millis(500));

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    let mut session = InProcessSession::new(&sandbox).await?;

    // This will timeout
    match session.execute("while True: pass").await.map_err(eryx::Error::into_kind) {
        Err(eryx::ErrorKind::Timeout(_)) => {
            println!("Execution timed out as expected");
        }
        _ => {}
    }

    Ok(())
}
import eryx

session = eryx.Session(execution_timeout_ms=500)

try:
    session.execute("while True: pass")
except eryx.TimeoutError:
    print("Execution timed out as expected")

Sessions with Callbacks

Sessions work with callbacks just like sandboxes:

import eryx

counter = {"value": 0}

def increment():
    counter["value"] += 1
    return {"count": counter["value"]}

session = eryx.Session(
    callbacks=[
        {"name": "increment", "fn": increment, "description": "Increment counter"}
    ]
)

# Callbacks work across multiple executions
session.execute("c1 = await increment()")
session.execute("c2 = await increment()")
result = session.execute("c3 = await increment(); print(c3['count'])")
print(result.stdout_text)  # "3"

Next Steps

Sandbox Pool

A SandboxPool manages a bounded set of warm sandbox instances for high-throughput concurrent execution. Instead of creating a new sandbox per request, you lease one from the pool, execute code, and return it automatically.

Use a pool when you serve concurrent requests and want to bound resource usage while avoiding per-request sandbox creation cost.

Creating a Pool

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::PoolError> {
    let config = PoolConfig::default()
        .with_max_size(4)
        .with_min_idle(1)
        .with_acquire_timeout(Duration::from_secs(5))
        .with_idle_timeout(Duration::from_secs(300));

    let pool = SandboxPool::new(Sandbox::embedded(), config).await?;

    // Or with a custom builder for more control:
    let pool = SandboxPool::with_builder(
        || Sandbox::embedded().with_trace_collection(true).build(),
        PoolConfig::default(),
    ).await?;

    Ok(())
}
import eryx

factory = eryx.SandboxFactory(cache=True)
pool = factory.create_pool(
    max_size=4,          # at most 4 concurrent sandboxes
    min_idle=1,          # keep 1 warm sandbox ready
    acquire_timeout_ms=5000,   # wait up to 5s for a sandbox
    idle_timeout_ms=300_000,   # evict idle sandboxes after 5min
)

In Python, the pool reuses the factory’s precompiled artifact and shared Tokio runtime. When the pool needs a new sandbox (because the idle queue is empty), creation is fast since the precompiled artifact avoids re-deserializing the WASM component.

Acquiring and Releasing Leases

Acquire a sandbox, use it, and return it to the pool. The sandbox is returned automatically when the scope ends:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
// Acquire a sandbox from the pool
let sandbox = pool.acquire().await?;

let result = sandbox.execute("print('Hello from pool!')").await?;
println!("{}", result.stdout_text());

// Sandbox is returned to the pool when dropped
drop(sandbox);
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

with pool.acquire() as sandbox:
    result = sandbox.execute('print("Hello from pool!")')
    print(result.stdout_text)
# sandbox is returned to the pool here

In Python, use-after-release raises ValueError, and repeated release is safe (idempotent):

with pool.acquire() as sandbox:
    sandbox.execute('pass')

sandbox.execute('pass')  # raises ValueError: sandbox has been released

# Explicit release is also available:
sandbox = pool.acquire()
sandbox.execute('print(42)')
sandbox.release()   # returned to pool
sandbox.release()   # no-op

Per-Request Configuration

Each acquisition accepts per-request callbacks, output handlers, and resource limits. These are cleared automatically on release so the next borrower gets a clean sandbox:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};
use eryx::ResourceLimits;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
let limits = ResourceLimits::default()
    .with_execution_timeout(Duration::from_secs(2));
let sandbox = pool.acquire().await?
    .with_resource_limits(limits);

let result = sandbox.execute("print('with limits')").await?;
// Limits are cleared when sandbox is returned to pool
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

def handle_output(chunk: bytes):
    print(f"[stdout] {chunk.decode()}", end="")

with pool.acquire(
    resource_limits=eryx.ResourceLimits(execution_timeout_ms=2000),
    on_stdout=handle_output,
    callbacks=[{"name": "greet", "fn": lambda: {"msg": "hi"}, "description": "greet"}],
) as sandbox:
    result = sandbox.execute('import json; print(json.dumps(await greet()))')

If you don’t pass callbacks in Python, the factory’s default callbacks (baked into the snapshot) are used.

Network and Secrets

In Rust, a lease can have its own network configuration and secrets, which replace the pool’s (by default, no network) until it’s returned:

use std::collections::HashMap;
use eryx::{NetConfig, SecretConfig};

let secret = SecretConfig::new("sk-xxx", vec!["api.example.com".to_string()]);
let sandbox = pool.acquire().await?.with_network(
    NetConfig::default().allow_host("api.example.com"),
    HashMap::from([("API_KEY".to_string(), secret)]),
)?;

with_network checks them as build does. Create new SecretConfigs for each lease, so each gets its own placeholder.

A shell pool’s commands can reach the network through each lease’s network too (with_child_network, see External commands). SandboxPool::new sets this up. Sandboxes built in a SandboxPool::with_builder closure need with_network_per_lease() alongside with_child_network, or build fails asking for with_network:

use eryx::{ChildNetwork, PoolConfig, Sandbox, SandboxPool};

let pool = SandboxPool::with_builder(
    move || {
        Sandbox::embedded()
            .shell()
            .with_command("curl", curl.clone())
            .with_child_network(ChildNetwork::Inherit)
            .with_network_per_lease()
            .build()
    },
    PoolConfig::default(),
)
.await?;

A lease without a network fails closed: its children get no proxy and no network, whatever the child network and the commands’ networks say, and the execution still runs.

For networking and secrets that every pooled sandbox gets, for the pool’s lifetime, configure them in the closure passed to SandboxPool::with_builder. In Python, that’s the only way: pass them to create_pool:

import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(
    max_size=4,
    network=eryx.NetConfig(allowed_hosts=["api.example.com"]),
    secrets={"API_KEY": {"value": "sk-xxx", "allowed_hosts": ["api.example.com"]}},
)

As with Sandbox, scrub_stdout, scrub_stderr and scrub_files default to True when secrets are given and can be overridden on create_pool.

Non-Blocking Acquire

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
if let Some(sandbox) = pool.try_acquire()? {
    let result = sandbox.execute("print('got one')").await?;
} else {
    println!("pool is busy");
}
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

sandbox = pool.try_acquire()
if sandbox is not None:
    with sandbox:
        sandbox.execute('print("got one")')
else:
    print("pool is busy")

Pool Stats and Eviction

Monitor pool usage and evict idle sandboxes that have exceeded the idle timeout (respects min_idle):

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
let stats = pool.stats();
println!("idle={}, in_use={}, total={}", stats.idle, stats.in_use, stats.total);

let evicted = pool.evict_idle();
println!("evicted {} idle sandboxes", evicted);
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

stats = pool.stats()
print(f"idle={stats.idle}, in_use={stats.in_use}, total={stats.total}")
print(f"acquisitions={stats.total_acquisitions}, avg_wait={stats.average_wait_time_ms:.1f}ms")

evicted = pool.evict_idle()

Closing the Pool

close() prevents new acquisitions, wakes any threads blocked on acquire(), and drops idle sandboxes. Existing leases continue to work but are not returned on release:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig, PoolError};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
pool.close();
assert!(pool.is_closed());

match pool.acquire().await {
    Err(PoolError::Closed) => println!("pool is closed"),
    _ => unreachable!(),
}
    Ok(())
}
import eryx

factory = eryx.SandboxFactory(cache=True)
pool = factory.create_pool(max_size=1)

pool.close()
try:
    pool.acquire()
except eryx.PoolClosedError:
    print("pool is closed")

# The pool is also a context manager:
with factory.create_pool(max_size=4) as pool:
    with pool.acquire() as sandbox:
        sandbox.execute('print("ok")')
# pool.close() called automatically

Thread Safety

The pool is safe to use from multiple threads. In Python, the GIL is released while waiting for a sandbox and during guest code execution, so other threads can make progress — including returning their own leases to unblock waiting acquirers.

import threading

def worker(pool, idx):
    with pool.acquire() as sandbox:
        result = sandbox.execute(f'print("worker {idx}")')

threads = [threading.Thread(target=worker, args=(pool, i)) for i in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()

Pool Exceptions

ExceptionWhen
PoolTimeoutErroracquire() timed out waiting for a sandbox
PoolClosedErrorPool has been closed

All inherit from PoolError (Rust: eryx::PoolError, Python: eryx.PoolError).

Next Steps

VFS and File Persistence

Eryx provides a Virtual Filesystem (VFS) that allows sandboxed Python code to read and write files without accessing the host filesystem. This is essential for applications that need file I/O while maintaining security isolation.

Overview

The VFS provides:

  • Isolated file storage - Files exist only within the VFS, not on the host
  • Persistence across executions - Files survive multiple execute() calls in a session
  • Shared storage - Multiple sessions can share the same VFS storage
  • Full filesystem API - Standard Python file operations work (open, read, write, mkdir, etc.)
  • SQLite support - SQLite databases can be stored in the VFS
  • Bounded size - Total size is capped (64 MB by default, counting file contents plus a small charge per file and directory) so scripts cannot exhaust host memory; see Virtual Filesystem Size

Creating a Session with VFS

To use the VFS, create a VfsStorage and attach it to a session:

import eryx

# Create VFS storage
storage = eryx.VfsStorage()

# Create a session with VFS enabled
session = eryx.Session(vfs=storage)

# Now you can read/write files in the sandbox
session.execute("""
with open('/data/hello.txt', 'w') as f:
    f.write('Hello, VFS!')
""")

result = session.execute("""
with open('/data/hello.txt', 'r') as f:
    print(f.read())
""")
print(result.stdout_text)  # "Hello, VFS!"

Default Mount Path

By default, the VFS is mounted at /data. You can customize this:

import eryx

storage = eryx.VfsStorage()

# Use default mount path (/data)
session1 = eryx.Session(vfs=storage)
print(session1.vfs_mount_path)  # "/data"

# Use custom mount path
session2 = eryx.Session(vfs=storage, vfs_mount_path="/myfiles")
print(session2.vfs_mount_path)  # "/myfiles"

session2.execute("open('/myfiles/test.txt', 'w').write('custom path')")

The same storage is also mounted at /tmp, so tempfile and code that writes to /tmp work. Files there are kept apart from the mount path’s, under their own /tmp/... paths, but count towards the same size limit. A volume mounted at /tmp replaces it.

File Operations

The VFS supports standard Python file operations:

Reading and Writing Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Write a file
session.execute("""
with open('/data/example.txt', 'w') as f:
    f.write('Line 1\\n')
    f.write('Line 2\\n')
""")

# Read the file
result = session.execute("""
with open('/data/example.txt', 'r') as f:
    content = f.read()
    print(content)
""")
print(result.stdout_text)
# Line 1
# Line 2

Appending to Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("open('/data/log.txt', 'w').write('Entry 1\\n')")
session.execute("open('/data/log.txt', 'a').write('Entry 2\\n')")
session.execute("open('/data/log.txt', 'a').write('Entry 3\\n')")

result = session.execute("print(open('/data/log.txt').read())")
print(result.stdout_text)
# Entry 1
# Entry 2
# Entry 3

Binary Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
# Write binary data
data = bytes([0, 1, 2, 255, 254, 253])
with open('/data/binary.bin', 'wb') as f:
    f.write(data)
""")

result = session.execute("""
with open('/data/binary.bin', 'rb') as f:
    data = f.read()
print(list(data))
""")
print(result.stdout_text)  # "[0, 1, 2, 255, 254, 253]"

Using pathlib

The VFS works with Python’s pathlib:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
from pathlib import Path

# Write using pathlib
p = Path('/data/pathlib_test.txt')
p.write_text('Written with pathlib')
""")

result = session.execute("""
from pathlib import Path
print(Path('/data/pathlib_test.txt').read_text())
""")
print(result.stdout_text)  # "Written with pathlib"

Directory Operations

Creating Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os
os.makedirs('/data/nested/deep/directory', exist_ok=True)

with open('/data/nested/deep/directory/file.txt', 'w') as f:
    f.write('Deep file')
""")

result = session.execute("print(open('/data/nested/deep/directory/file.txt').read())")
print(result.stdout_text)  # "Deep file"

Listing Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os
open('/data/a.txt', 'w').write('a')
open('/data/b.txt', 'w').write('b')
open('/data/c.txt', 'w').write('c')
""")

result = session.execute("""
import os
files = sorted(os.listdir('/data'))
print(files)
""")
print(result.stdout_text)  # "['a.txt', 'b.txt', 'c.txt']"

Deleting Files and Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os

# Create file
open('/data/temp.txt', 'w').write('temporary')

# Delete file
os.remove('/data/temp.txt')

# Check if deleted
print(f"exists: {os.path.exists('/data/temp.txt')}")
""")

Sharing Storage Between Sessions

Multiple sessions can share the same VFS storage:

import eryx

# Create shared storage
storage = eryx.VfsStorage()

# Session 1 writes a file
session1 = eryx.Session(vfs=storage)
session1.execute("open('/data/shared.txt', 'w').write('from session 1')")

# Session 2 can read the same file
session2 = eryx.Session(vfs=storage)
result = session2.execute("print(open('/data/shared.txt').read())")
print(result.stdout_text)  # "from session 1"

Isolated Storage

Each VfsStorage instance is independent:

import eryx

# Two separate storage instances
storage1 = eryx.VfsStorage()
storage2 = eryx.VfsStorage()

session1 = eryx.Session(vfs=storage1)
session1.execute("open('/data/isolated.txt', 'w').write('only in storage1')")

session2 = eryx.Session(vfs=storage2)
result = session2.execute("""
import os
print(f"exists: {os.path.exists('/data/isolated.txt')}")
""")
print(result.stdout_text)  # "exists: False"

VFS Persistence Across Reset

VFS data persists even when you reset the session’s Python state:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Write a file
session.execute("open('/data/persist.txt', 'w').write('before reset')")

# Reset Python state (clears variables, etc.)
session.reset()

# VFS data is still there
result = session.execute("print(open('/data/persist.txt').read())")
print(result.stdout_text)  # "before reset"

Bringing Your Own Storage (Rust)

With the unstable-vfs feature, a Rust caller can give a sandbox the storage for its next executions, for example to restore files saved from an earlier run and save them again afterwards. execute() and any InProcessSession created from the sandbox use it instead of a fresh, empty one:

use std::sync::Arc;
use eryx::Sandbox;
use eryx::vfs::{InMemoryStorage, VfsStorage};

let storage = Arc::new(InMemoryStorage::new());
storage.mkdir("/data").await?;
storage.write("/data/input.txt", b"saved earlier").await?;

let mut sandbox = Sandbox::embedded().build()?;
sandbox.set_vfs_storage(storage.clone());
sandbox.execute("open('/data/output.txt', 'w').write('new')").await?;

let saved = storage.snapshot().await; // e.g. to persist it

The storage keeps its own size and entry limits (InMemoryStorage::with_max_bytes and with_max_entries); max_vfs_bytes and max_vfs_entries only apply to storage eryx creates. On a pooled sandbox, use PooledSandbox::with_vfs_storage, which the pool clears when the sandbox goes back.

SQLite Databases in VFS

The VFS supports SQLite databases, allowing persistent structured data:

In-Memory Databases

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

result = session.execute("""
import sqlite3

conn = sqlite3.connect(':memory:')
cursor = conn.cursor()

cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute("INSERT INTO users (name) VALUES ('Bob')")

cursor.execute('SELECT name FROM users ORDER BY id')
names = [row[0] for row in cursor.fetchall()]
conn.close()

print(names)
""")
print(result.stdout_text)  # "['Alice', 'Bob']"

File-Based Databases

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Create database and insert data
session.execute("""
import sqlite3
conn = sqlite3.connect('/data/app.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)')
cursor.execute("INSERT INTO products (name, price) VALUES ('Widget', 9.99)")
cursor.execute("INSERT INTO products (name, price) VALUES ('Gadget', 19.99)")
conn.commit()
conn.close()
""")

# Query in a separate execution
result = session.execute("""
import sqlite3
conn = sqlite3.connect('/data/app.db')
cursor = conn.cursor()
cursor.execute('SELECT name, price FROM products')
for name, price in cursor.fetchall():
    print(f"{name}: ${price}")
conn.close()
""")
print(result.stdout_text)
# Widget: $9.99
# Gadget: $19.99

Database Persistence Across Sessions

import eryx

storage = eryx.VfsStorage()

# Session 1: Create database
session1 = eryx.Session(vfs=storage)
session1.execute("""
import sqlite3
conn = sqlite3.connect('/data/shared.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE messages (id INTEGER PRIMARY KEY, text TEXT)')
cursor.execute("INSERT INTO messages (text) VALUES ('Hello from session 1')")
conn.commit()
conn.close()
""")

# Session 2: Read from same database
session2 = eryx.Session(vfs=storage)
result = session2.execute("""
import sqlite3
conn = sqlite3.connect('/data/shared.db')
cursor = conn.cursor()
cursor.execute('SELECT text FROM messages')
print(cursor.fetchone()[0])
conn.close()
""")
print(result.stdout_text)  # "Hello from session 1"

Host Filesystem Isolation

The VFS is completely isolated from the host filesystem:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

result = session.execute("""
import os

# Try to access real /etc (should fail or be virtual)
try:
    files = os.listdir('/etc')
    has_passwd = 'passwd' in files
    print(f"has_real_passwd: {has_passwd}")
except Exception as e:
    print(f"access_denied: {type(e).__name__}")
""")
# Should show "has_real_passwd: False" or "access_denied: ..."

Host Volume Mounts

In addition to the in-memory VFS, Eryx supports mounting host filesystem directories into the sandbox. This allows sandboxed code to read and write real files on the host, with optional read-only enforcement.

Python API

Pass a list of (host_path, guest_path, read_only) tuples:

import eryx

# Read-write mount
sandbox = eryx.Sandbox(
    volumes=[("/home/user/data", "/mnt/data", False)],
)

# Read-only mount
sandbox = eryx.Sandbox(
    volumes=[("/home/user/data", "/mnt/data", True)],
)

# Multiple mounts
sandbox = eryx.Sandbox(
    volumes=[
        ("/home/user/input", "/input", True),
        ("/home/user/output", "/output", False),
    ],
)

Volume mounts also work with sessions:

session = eryx.Session(
    volumes=[("/home/user/data", "/mnt/data", False)],
)

Rust API

Use VolumeMount::new() for read-write or VolumeMount::read_only() for read-only:

use eryx::{Sandbox, VolumeMount};

let sandbox = Sandbox::embedded()
    .with_volume(VolumeMount::new("/home/user/data", "/mnt/data"))
    .with_volume(VolumeMount::read_only("/home/user/config", "/config"))
    .build()?;

CLI

Use Docker-style -v syntax:

# Read-write
python -m eryx -v /host/path:/sandbox/path script.py

# Read-only (append :ro)
python -m eryx -v /host/path:/sandbox/path:ro script.py

# Multiple mounts
python -m eryx -v ./input:/input:ro -v ./output:/output script.py

How It Works

Volume mounts use capability-based security (cap-std) to provide controlled access to host directories. The sandbox can only access the specific directories that were explicitly mounted — it cannot traverse outside the mount point or access other host paths.

Read-only mounts enforce that sandboxed code cannot modify any files in the mounted directory.

A few more rules apply to volumes:

  • Single files - Mounting a host file (rather than a directory) exposes just that file. The script can read, write, replace or delete it, as the mount allows, but can’t list, open or create anything else next to it on the host.
  • No symlinks - Scripts can’t create symbolic links in a volume, just as in the VFS.
  • Open files - A sandbox holds at most 256 host files and directories open at once (across the stdlib, packages and volumes); opening more fails with EDQUOT until some are closed. Set max_open_host_files in resource limits to change it. All sandboxes in the process also share one total, by default half the soft RLIMIT_NOFILE (at least 256).
  • Size - Volumes are the place for large trees: max_vfs_bytes and max_vfs_entries (see resource limits) only apply to in-memory storage, and a volume keeps its contents on the host disk rather than in host memory.
  • File size - max_vfs_bytes doesn’t apply to volumes, so by default a writable volume can fill the host disk. Give the mount a max_file_size to cap how large any one file in it may grow; writes past it fail. The cap is per file, not a total for the volume.
import eryx

# (host_path, guest_path, read_only, max_file_size)
sandbox = eryx.Sandbox(volumes=[("/home/user/out", "/mnt/out", False, 16 * 1024 * 1024)])

The eryx CLI takes --volume-max-file-size BYTES, applied to every --volume.

Storage Volumes

A volume can also be served from any VfsStorage instead of the host filesystem: an InMemoryStorage you fill and read back, or your own implementation (one backed by object storage, a database, or a remote client). Files are at their full guest paths in the storage, so the volume at /mnt/repo reads /mnt/repo/src/main.py from it.

use std::sync::Arc;
use eryx::VolumeMount;
use eryx::vfs::InMemoryStorage;

let repo = Arc::new(InMemoryStorage::new());
let sandbox = Sandbox::embedded()
    .with_volume(VolumeMount::read_only_storage("/mnt/repo", repo.clone()))
    .build()?;

The storage’s own limits apply, not max_vfs_bytes or max_file_size, and files written to it aren’t scrubbed of secrets, as with storage given to set_vfs_storage. A writable volume’s directory is created in the storage if it’s missing; a read-only volume’s storage is never changed, so it should already contain the directory. Renaming a file between a storage volume and another mount fails with EXDEV, as a rename between filesystems does (Python’s shutil.move copies instead).

Volumes can also be added for a single request, alongside the built ones: with Sandbox::add_volume, or PooledSandbox::with_volume on a pooled sandbox, which removes them when the sandbox goes back to the pool. An InProcessSession created from the sandbox mounts them too. Two mounts at the same guest path (including /data) fail the execution.

Best Practices

  1. Use shared storage for multi-session workflows - When sessions need to share data
  2. Use separate storage for isolation - When sessions should be independent
  3. Prefer file-based SQLite over in-memory - For data that needs to persist
  4. Use appropriate mount paths - Customize for your application’s needs
  5. Handle file errors gracefully - Files may not exist or paths may be invalid
  6. Use read-only mounts for input data - Prevent sandboxed code from modifying source files
  7. Prefer VFS for ephemeral data - Use volume mounts when you need access to real host files, or for large trees (see resource limits)

Next Steps

Resource Limits

Eryx provides fine-grained control over resource consumption to prevent runaway code from exhausting system resources. You can limit execution time, memory usage, callback invocations, and WASM instruction counts.

Default Limits

By default, sandboxes have sensible limits applied:

ResourceDefault Value
Execution timeout30 seconds
Callback timeout10 seconds
Memory128 MB
Callback invocations1000
Virtual filesystem64 MB
FuelUnlimited (opt-in, see Fuel Limits)

Configuring Resource Limits

In Rust, start from ResourceLimits::default() and adjust with the with_* methods. Each one takes either a value or None to remove that limit; ResourceLimits::unlimited() removes them all at once. (ResourceLimits is #[non_exhaustive] so that new limits can be added without breaking callers, which means it cannot be built with a struct literal.)

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let limits = ResourceLimits::default()
        .with_execution_timeout(Duration::from_secs(5))
        .with_max_memory_bytes(64 * 1024 * 1024);  // 64 MB

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    let result = sandbox.execute("print('hello')").await?;
    println!("{}", result.stdout_text());

    Ok(())
}
import eryx

# Configure custom limits
limits = eryx.ResourceLimits(
    execution_timeout_ms=5000,      # 5 seconds
    callback_timeout_ms=2000,       # 2 seconds per callback
    max_memory_bytes=64_000_000,    # 64 MB
    max_callback_invocations=100,   # Max 100 callback calls
)

sandbox = eryx.Sandbox(resource_limits=limits)
result = sandbox.execute("print('hello')")
print(result.stdout_text)

Execution Timeout

The execution timeout limits how long Python code can run before being terminated:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits, ErrorKind};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let limits = ResourceLimits::default()
        .with_execution_timeout(Duration::from_millis(500));

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    match sandbox.execute("while True: pass").await.map_err(eryx::Error::into_kind) {
        Err(ErrorKind::Timeout(duration)) => {
            println!("Timed out after {:?}", duration);
        }
        _ => {}
    }

    Ok(())
}
import eryx

limits = eryx.ResourceLimits(execution_timeout_ms=500)
sandbox = eryx.Sandbox(resource_limits=limits)

try:
    sandbox.execute("while True: pass")
except eryx.TimeoutError:
    print("Execution timed out")

The timeout covers time spent waiting as well as running: an await asyncio.sleep(...) or a slow callback cannot keep an execution alive past it. A sleeping execution is suspended, so it consumes no fuel while it waits.

Callback Timeout

When sandboxed code calls host callbacks, you can limit how long each callback can take:

import eryx
import time

def slow_callback():
    time.sleep(5)  # This will exceed the callback timeout
    return {"result": "done"}

limits = eryx.ResourceLimits(callback_timeout_ms=1000)  # 1 second per callback

sandbox = eryx.Sandbox(
    resource_limits=limits,
    callbacks=[
        {"name": "slow", "fn": slow_callback, "description": "A slow callback"}
    ]
)

try:
    sandbox.execute("await slow()")
except eryx.TimeoutError:
    print("Callback timed out")

Memory Limits

Control the maximum memory the WebAssembly instance can use:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let limits = ResourceLimits::default()
        .with_max_memory_bytes(32 * 1024 * 1024);  // 32 MB

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    // This will fail if it tries to allocate too much memory
    let result = sandbox.execute(r#"
try:
    big_list = [0] * 10_000_000
    print("Allocated successfully")
except MemoryError:
    print("Memory limit exceeded")
    "#).await?;

    println!("{}", result.stdout_text());

    Ok(())
}
import eryx

limits = eryx.ResourceLimits(max_memory_bytes=32_000_000)  # 32 MB
sandbox = eryx.Sandbox(resource_limits=limits)

result = sandbox.execute("""
try:
    big_list = [0] * 10_000_000
    print("Allocated successfully")
except MemoryError:
    print("Memory limit exceeded")
""")
print(result.stdout_text)

Virtual Filesystem Size

max_vfs_bytes caps the total bytes the virtual filesystem holds: all file contents, plus each file’s and directory’s path length (twice for a directory) and a 64-byte charge per entry, so empty files and long names aren’t free. Names over 255 bytes or paths over 4096 bytes fail with ENAMETOOLONG. Unlike max_memory_bytes, which bounds the WebAssembly instance’s linear memory, VFS contents live in host memory - and the script picks its own write offsets, so f.seek(2**40) followed by a one-byte write would otherwise ask the host to materialize a terabyte of zeroes. Scripts that hit the cap see ENOSPC (OSError), the same as a full disk.

#![allow(unused)]
fn main() {
extern crate eryx;
use eryx::ResourceLimits;

let limits = ResourceLimits::default()
    .with_max_vfs_bytes(256 * 1024 * 1024); // 256 MB of in-memory files
}
import eryx

limits = eryx.ResourceLimits(max_vfs_bytes=256 * 1024 * 1024)

This applies to the storage eryx creates for you. If you construct storage yourself, set the limit there instead:

import eryx

storage = eryx.VfsStorage(max_bytes=256 * 1024 * 1024)
session = eryx.Session(vfs=storage)

A second limit, max_vfs_entries, caps the number of files and directories, 65,536 by default. Each entry already counts against max_vfs_bytes, so this mostly bounds operations that visit every entry: listing, removing or renaming a directory gets slower as the tree grows. Creating an entry past the limit also fails with ENOSPC. In Rust:

#![allow(unused)]
fn main() {
extern crate eryx;
use eryx::ResourceLimits;

let limits = ResourceLimits::default()
    .with_max_vfs_bytes(256 * 1024 * 1024)
    .with_max_vfs_entries(200_000);
}

For storage you construct yourself, use InMemoryStorage::with_max_bytes(..).with_max_entries(..).

Because both caps protect host memory rather than the guest, neither is disabled by ResourceLimits::unlimited(); raise them explicitly if you need more.

Large trees belong on a volume

In-memory storage suits scratch files and small working sets. Host memory grows faster than the content: about 60 MiB of files added about 97 MiB to the host’s resident memory in one measurement. For a source checkout, a package directory or anything with tens of thousands of files, mount a host-directory volume instead. Neither cap applies to a volume, which keeps its contents on the host disk; give it a max_file_size to bound how large a file in it may grow.

Open Host Files

Every file or directory a script opens under a host mount (the stdlib, site-packages and volumes) holds a host file descriptor until the script closes it. max_open_host_files caps how many one sandbox may hold at once (256 by default); opens past it fail with EDQUOT (OSError). Like max_vfs_bytes, it is not disabled by ResourceLimits::unlimited().

#![allow(unused)]
fn main() {
extern crate eryx;
use eryx::ResourceLimits;

let limits = ResourceLimits::default().with_max_open_host_files(64);
}
import eryx

limits = eryx.ResourceLimits(max_open_host_files=64)

All sandboxes in the process also share one total, so many concurrent sandboxes can’t use up the process’s descriptor limit. It defaults to half the soft RLIMIT_NOFILE, but never less than 256. The limit is read once, the first time a sandbox opens a host file, so raise RLIMIT_NOFILE before then to get a larger default. A forked child starts with its own count. Rust embedders can change it with eryx::vfs::set_process_max_open_host_files. The gRPC server sets both with --max-open-host-files and --max-open-host-files-total.

Child Processes

A shell sandbox’s commands run as child processes, whose memory is outside max_memory_bytes. Two limits bound it per execution:

  • max_child_memory_bytes (default 256 MiB) is the pool of memory the running commands share: their linear memories, tables and instance metadata. Each running command reserves its initial memory, about 4 MiB for a coreutils command and 17 MiB for python3, so the default fits about 60 concurrent coreutils commands or 15 python3 runs. A command that doesn’t fit isn’t started, and the shell’s stderr says why: eryx: not enough memory for sleep (child memory pool full: 14 of 16 MiB in use; 7 commands running).
  • max_child_host_bytes (default 64 MiB) is the host memory the commands’ arguments and environments may hold.

At most 64 commands may be running at once (eryx: too many commands running (limit 64)), whatever the pool’s size. Raising max_child_memory_bytes raises how much host memory one execution can use, so size it for the host’s memory and the number of concurrent executions. Neither limit is cleared by ResourceLimits::unlimited(). pyeryx can’t set them yet; the gRPC server takes them as resource_limits.max_child_memory_bytes and max_child_host_bytes, capped by --max-child-memory-bytes and --max-child-host-bytes.

#![allow(unused)]
fn main() {
extern crate eryx;
use eryx::ResourceLimits;

let limits = ResourceLimits::default().with_max_child_memory_bytes(512 * 1024 * 1024);
}

Callback Invocation Limits

Limit the total number of callback invocations to prevent abuse:

import eryx

def noop():
    return {}

limits = eryx.ResourceLimits(max_callback_invocations=5)

sandbox = eryx.Sandbox(
    resource_limits=limits,
    callbacks=[{"name": "noop", "fn": noop, "description": ""}]
)

result = sandbox.execute("""
for i in range(10):
    try:
        await noop()
        print(f"Call {i+1} succeeded")
    except Exception as e:
        print(f"Call {i+1} failed: {type(e).__name__}")
        break
""")
print(result.stdout_text)

Fuel Limits (Instruction Counting)

Fuel limits provide fine-grained control over execution by limiting the number of WebAssembly instructions that can be executed. This is useful for:

  • Deterministic execution bounds (time limits vary with system load, fuel doesn’t)
  • Billing based on actual computation performed
  • Preventing CPU-intensive attacks

Fuel is opt-in everywhere: ResourceLimits::default(), the Python bindings and the gRPC server (unless started with --max-fuel) leave it unset. How much fuel a script needs depends entirely on the workload, so no default value suits everyone. The default bound on CPU use is wall-clock time, the execution timeout; add a fuel limit when you need deterministic or metered bounds.

Fuel counts the instructions your code executes; instantiating the sandbox’s WebAssembly instance is not charged, so the number does not depend on whether the execution ran on a fresh or a pre-instantiated instance.

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Set a fuel limit via resource limits
    let limits = ResourceLimits::default()
        .with_max_fuel(500_000_000);  // 500M instructions

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    // Simple operations succeed
    let result = sandbox.execute("x = 1 + 1").await?;
    println!("Fuel consumed: {:?}", result.stats.fuel_consumed);

    // Large loops may exhaust fuel
    let result = sandbox.execute("for i in range(1000000): pass").await;

    match result.map_err(eryx::Error::into_kind) {
        Err(eryx::ErrorKind::FuelExhausted { consumed, limit, .. }) => {
            println!("Fuel exhausted: consumed {}, limit {}", consumed, limit);
        }
        Ok(r) => println!("Completed with fuel: {:?}", r.stats.fuel_consumed),
        Err(e) => println!("Other error: {}", e),
    }

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()
result = sandbox.execute("x = sum(range(1000))")

# Execution stats are available (fuel tracking is Rust-only currently)
print(f"Duration: {result.duration_ms}ms")
print(f"Peak memory: {result.peak_memory_bytes} bytes")

Fuel Consumption is Deterministic

The same code always consumes the same amount of fuel:

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    let code = "x = sum(range(100))";

    // Run multiple times - each sandbox execution is independent
    let mut fuel_values = Vec::new();
    for _ in 0..3 {
        let result = sandbox.execute(code).await?;
        if let Some(fuel) = result.stats.fuel_consumed {
            fuel_values.push(fuel);
        }
    }

    // All runs consume the same fuel
    if !fuel_values.is_empty() {
        assert!(fuel_values.iter().all(|&f| f == fuel_values[0]));
        println!("Consistent fuel consumption: {:?}", fuel_values[0]);
    }

    Ok(())
}

Unlimited Resources

For trusted code or development environments, you can disable limits. eryx.ResourceLimits is a frozen dataclass whose fields default to None, meaning the defaults above; unlimited() makes None mean no limit instead. The virtual filesystem and open host file caps keep their defaults, since they bound host memory. Fields you set still apply:

import dataclasses
import eryx

# Remove all limits (use with caution!)
limits = eryx.ResourceLimits.unlimited()

# Or all but one
timeout_only = dataclasses.replace(limits, execution_timeout_ms=5000)

sandbox = eryx.Sandbox(resource_limits=limits)
result = sandbox.execute("print('no limits!')")
print(result.stdout_text)

Resource Usage Reporting

Execution results include resource usage statistics:

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded().build()?;

    let result = sandbox.execute("x = [i for i in range(10000)]").await?;

    println!("Duration: {:?}", result.stats.duration);
    println!("Peak memory: {:?} bytes", result.stats.peak_memory_bytes);
    println!("Fuel consumed: {:?}", result.stats.fuel_consumed);

    Ok(())
}
import eryx

sandbox = eryx.Sandbox()
result = sandbox.execute("x = [i for i in range(10000)]")

print(f"Duration: {result.duration_ms}ms")
print(f"Peak memory: {result.peak_memory_bytes} bytes")
print(f"Callback invocations: {result.callback_invocations}")

Recovery After Resource Exhaustion

Sessions can recover after hitting resource limits by resetting:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, ResourceLimits, session::{InProcessSession, Session}};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    // Configure a short timeout
    let limits = ResourceLimits::default()
        .with_execution_timeout(Duration::from_millis(100));

    let sandbox = Sandbox::embedded()
        .with_resource_limits(limits)
        .build()?;

    let mut session = InProcessSession::new(&sandbox).await?;

    // First execution times out
    let result = session.execute("while True: pass").await;
    assert!(result.is_err());

    // Reset the session
    session.reset().await?;

    // Session works again
    let result = session.execute("print('recovered')").await?;
    println!("{}", result.stdout_text());  // "recovered"

    Ok(())
}

Best Practices

  1. Always set timeouts - Prevent infinite loops from hanging your application
  2. Use appropriate memory limits - Consider your use case and available system resources
  3. Monitor fuel consumption - Use fuel stats to understand computational costs
  4. Limit callbacks - Especially if callbacks have side effects or external costs
  5. Test with limits - Ensure your code works within the constraints you set

Next Steps

  • Sandboxes - Creating and using sandboxes
  • Sessions - Stateful execution with resource limits
  • Networking - Network configuration and limits

Networking

By default, sandboxes have no network access. You can enable and configure networking by providing a NetConfig when creating a sandbox.

Enabling Network Access

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, NetConfig};

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded()
        .with_network(NetConfig::default().allow_host("example.com"))
        .build()?;

    let result = sandbox.execute(r#"
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("example.com", 80))
sock.send(b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
response = sock.recv(100)
sock.close()
print("Connected!" if b"HTTP" in response else "Failed")
    "#).await?;

    println!("{}", result.stdout_text());

    Ok(())
}
import eryx

# Enable networking, allowing connections to example.com
config = eryx.NetConfig(allowed_hosts=["example.com"])
sandbox = eryx.Sandbox(network=config)

result = sandbox.execute("""
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("example.com", 80))
sock.send(b"GET / HTTP/1.1\\r\\nHost: example.com\\r\\nConnection: close\\r\\n\\r\\n")
response = sock.recv(100)
sock.close()
print("Connected!" if b"HTTP" in response else "Failed")
""")

print(result.stdout_text)  # "Connected!"

Default Network Configuration

The default NetConfig has sensible security defaults:

SettingDefault ValueDescription
max_connections10Maximum simultaneous connections
connect_timeout_ms30,000Connection timeout (30 seconds)
io_timeout_ms60,000Read/write timeout (60 seconds)
allow_all_hostsfalseWhen true, all non-blocked hosts are allowed
allowed_hosts[]Whitelist of allowed hosts (used when allow_all_hosts is false)
blocked_hostslocalhost, private networksHost patterns that are always refused
blocked_networksevery non-public rangeCIDRs that resolved addresses must not fall in
allowed_networks[]CIDRs exempt from blocked_networks
internal_hosts[]Host patterns allowed to resolve into blocked_networks
allow_plaintext_secretsfalseAlso substitute secrets over plain TCP (sends them unencrypted)
http_rules[]Method and path rules for HTTP requests

A bare NetConfig() allows no hosts: list them in allowed_hosts, or pass allow_all_hosts=True to allow any host that isn’t blocked.

import eryx

config = eryx.NetConfig()
print(f"Max connections: {config.max_connections}")       # 10
print(f"Connect timeout: {config.connect_timeout_ms}ms")  # 30000
print(f"I/O timeout: {config.io_timeout_ms}ms")           # 60000
print(f"Blocked hosts: {config.blocked_hosts}")           # ['localhost', '127.*', ...]

Host Filtering

Host Patterns

allowed_hosts, blocked_hosts, internal_hosts, secrets’ allowed_hosts and HTTP rules all match host names the same way. * matches any run of characters (*.example.com, api.*.com), and a pattern without * matches only that host. Case, one trailing dot and IPv6 brackets are ignored on both sides, so API.example.com. matches api.example.com, and a blocked host stays blocked with a trailing dot. IP addresses match in their canonical form, whatever spelling the resolver accepts: 2130706433, 0x7f.1 and 127.1 all match 127.0.0.1, ::ffff:127.0.0.1 matches it too, and a zone (fe80::1%lo, 127.0.0.1%lo) is ignored.

Allowing Specific Hosts (Whitelist)

When you specify allowed_hosts, only those hosts can be accessed:

import eryx

# Only allow connections to specific hosts
config = eryx.NetConfig(allowed_hosts=["api.example.com", "api.openai.com"])
sandbox = eryx.Sandbox(network=config)

# This works
result = sandbox.execute("""
import _eryx_async
tcp = await _eryx_async.await_tcp_connect("api.example.com", 80)
print("Connected to api.example.com")
_eryx_async.tcp_close(tcp)
""")

# This fails - google.com is not in the allowed list
result = sandbox.execute("""
import _eryx_async
try:
    tcp = await _eryx_async.await_tcp_connect("google.com", 80)
except OSError as e:
    print(f"Blocked: {e}")
""")

Blocking Specific Hosts

Block specific hosts while allowing others:

import eryx

# Allow any host, start fresh with no blocked hosts, then add some
config = eryx.NetConfig(allow_all_hosts=True, blocked_hosts=[])
config = config.block_host("*.internal.corp").block_host("*.local")

sandbox = eryx.Sandbox(network=config)

Allowing Localhost

By default, localhost is blocked for security. You can explicitly allow it:

import eryx

config = eryx.NetConfig(allowed_hosts=["localhost"])
print("localhost" in config.blocked_hosts)  # True

# Allow localhost connections
config = config.allow_localhost()
print("localhost" in config.blocked_hosts)  # False

sandbox = eryx.Sandbox(network=config)

allow_localhost() also removes the IPv4 loopback range (127.0.0.0/8) from blocked_networks and adds ::1/128 to allowed_networks.

Address Filtering

Host patterns only see the name the sandbox asked for. A public name can point at an internal address (evil.example → 169.254.169.254), so every connection is also checked by the address it resolves to. The sandbox connects only to an address that passed the check, so a DNS answer can’t swap in a different one.

By default blocked_networks covers every range that isn’t publicly routable: loopback, private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7), link-local (169.254.0.0/16, fe80::/10, which includes cloud metadata endpoints), carrier-grade NAT (100.64.0.0/10), 0.0.0.0/8, IPv4-compatible (::/96, which includes :: and ::1), site-local (fec0::/10), Teredo (2001::/32), documentation (2001:db8::/32), multicast, reserved, benchmarking, local-use NAT64 and 6to4 ranges. IPv4-mapped (::ffff:127.0.0.1), IPv4-compatible (::a00:1), NAT64 (64:ff9b::a00:1) and Teredo addresses are also checked by the IPv4 address they stand for. Refusals tell sandboxed code only that the host resolves to a blocked network; the address is logged on the host at debug level. This applies even with allow_all_hosts, and even when a host matches allowed_hosts.

Allowing Internal Addresses

To reach an internal service on purpose, either exempt its addresses or trust its name:

import eryx

# Exempt a CIDR, e.g. one internal subnet
config = eryx.NetConfig(allowed_hosts=["metrics.internal.example.com"])
config = config.allow_network("10.96.0.0/12")

# Or trust a name routed internally (e.g. through cluster DNS), whatever
# address it resolves to. Only list names whose DNS you control.
config = eryx.NetConfig(allowed_hosts=["api.example.com"])
config = config.allow_internal_host("api.example.com")
print(config.internal_hosts)  # ['api.example.com']

internal_hosts only skips the address check: the host must still pass blocked_hosts and allowed_hosts. Prefer it over allowed_networks for Kubernetes services, whose cluster IPs can change.

From Rust, NetConfig::with_resolver replaces the system resolver with your own Resolver (for example to use specific nameservers). The address check still applies to whatever it returns.

In JavaScript, the same options are blockedNetworks, allowedNetworks and internalHosts. They’re enforced in Node.js only: browsers don’t expose the address a request connects to.

Method and Path Rules

Allowing a host allows every endpoint on it. To narrow that, add HTTP rules: a host that any rule matches only accepts requests matching one of its rules. Hosts no rule matches are unaffected.

import eryx

config = eryx.NetConfig(
    allowed_hosts=["api.github.com"],
    http_rules=[
        eryx.HttpRule("api.github.com", methods=["GET", "POST"], paths=["/repos/org/repo"]),
    ],
)

From Rust, use NetConfig::allow_http(HttpRule::new(host).with_methods(..).with_paths(..)); over gRPC, NetworkConfig.http_rules.

How requests match:

  • Methods are compared ignoring case. No methods means any method.
  • Paths match whole segments: /repos/org/repo matches it and anything under /repos/org/repo/, but not /repos/org/repo-evil. A path ending in / matches anything under it. No paths means any path.
  • The query string is ignored, and percent-escapes are decoded before matching (/repos/org/%72epo is /repos/org/repo).
  • A path a server could resolve somewhere else never matches: one with a . or .. segment (escaped as %2e or not, or with ; parameters, as in ..;), an empty segment (//), an escaped / or \, or a malformed escape. So does a target that isn’t a path or an absolute URL (CONNECT, OPTIONS *).
  • A rule’s own paths must be normalized absolute paths: no such segments, query or escapes. A rule that breaks this is rejected when the sandbox is built.

A refused request is never sent: the write fails in the sandbox (an OSError in Python) and the connection’s request can’t continue.

Once any rule is set, every connection’s HTTP/1.1 requests are parsed and checked against both the connected host and every host the request names (its Host header and an absolute-form target), so another allowed host on the same server can’t be used to reach a ruled one. Host names are compared ignoring case, a port, a trailing dot and IPv6 brackets, and a request with more than one Host header, or a Host that disagrees with its absolute-form target, is refused. Requests whose framing a server could read differently are refused: bare CR or LF, folded header lines, a Transfer-Encoding other than chunked, both that and Content-Length, or more than one length. Only HTTP/1.1 may be sent to a host with rules, so HTTP/2, WebSockets after the upgrade, and TLS done by the sandboxed code itself are refused there.

Every request is recognised by its request line, for any method token (PROPFIND and custom methods too), and a request line preceded by an empty line is refused, since servers skip those. Bytes that aren’t a request are refused once a request has been sent on the connection. After any refusal, the connection refuses every later write.

Setting any rule therefore stops WebSocket traffic after an Upgrade, CONNECT tunnels and HTTP/2 to every host, not only ruled ones, on connections that start with an HTTP request: what follows isn’t a request the host can check.

A first line shaped like a request (a method token, then a target starting with / or * or containing ://, or HTTP/ anywhere on the line) is parsed strictly and refused unless it’s a valid HTTP/1.x request line, so HTTP/0.9 requests are refused too.

Limitation: rules are enforced on what the host can frame. A connection to a host without rules whose first line has another shape (e.g. a Redis SET k v) is passed through unparsed from then on, so other protocols keep working. One cost of the shape rule: an inline command like that whose first argument starts with / is refused instead. If sandboxed code does its own TLS (e.g. with a pure-Python TLS library) to another allowed host served by the same server as a ruled one, the host can’t see the requests inside, so the rules don’t apply to them. Avoid allowing other names on a server whose ruled name matters.

The JavaScript package doesn’t parse requests, so it refuses httpRules rather than ignoring them.

Permissive Configuration

For testing or trusted environments, use permissive mode:

import eryx

# No restrictions (use with caution!)
config = eryx.NetConfig.permissive()
print(f"Max connections: {config.max_connections}")  # 100
print(f"Blocked hosts: {config.blocked_hosts}")      # []
print(f"Blocked networks: {config.blocked_networks}")  # []

sandbox = eryx.Sandbox(network=config)

Timeout Configuration

Configure connection and I/O timeouts:

import eryx

config = eryx.NetConfig(
    allowed_hosts=["api.example.com"],
    connect_timeout_ms=5000,   # 5 second connection timeout
    io_timeout_ms=10000,       # 10 second read/write timeout
)

sandbox = eryx.Sandbox(network=config)

Using HTTP Libraries

Eryx provides socket and SSL shims that allow popular Python HTTP libraries to work:

Using requests

import eryx

# Create a sandbox factory with requests installed
factory = eryx.SandboxFactory(
    packages=["path/to/requests.whl", "path/to/urllib3.whl", ...],
    imports=["requests"],
)

config = eryx.NetConfig.permissive()
sandbox = factory.create_sandbox(network=config)

result = sandbox.execute("""
import requests
response = requests.get("https://api.example.com/data", timeout=5)
print(f"Status: {response.status_code}")
print(f"Body: {response.json()}")
""")

Using httpx

import eryx

factory = eryx.SandboxFactory(
    packages=["path/to/httpx.whl", ...],
    imports=["httpx"],
)

config = eryx.NetConfig.permissive()
sandbox = factory.create_sandbox(network=config)

result = sandbox.execute("""
import httpx
response = httpx.get("https://example.com/", timeout=5)
print(f"Status: {response.status_code}")
""")

Using urllib (Standard Library)

import eryx

config = eryx.NetConfig.permissive()
sandbox = eryx.Sandbox(network=config)

result = sandbox.execute("""
import urllib.request

with urllib.request.urlopen("https://example.com/", timeout=10) as response:
    print(f"Status: {response.status}")
    body = response.read().decode()
    if "Example Domain" in body:
        print("Got expected content")
""")

TLS/SSL Support

Eryx includes a TLS implementation that provides secure HTTPS connections:

import eryx

config = eryx.NetConfig.permissive()
sandbox = eryx.Sandbox(network=config)

result = sandbox.execute("""
import socket
import ssl

# Create TCP connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(15)
sock.connect(("example.com", 443))

# Upgrade to TLS
ctx = ssl.create_default_context()
ssl_sock = ctx.wrap_socket(sock, server_hostname="example.com")
print("TLS handshake complete")

# Send HTTPS request
ssl_sock.send(b"GET / HTTP/1.1\\r\\nHost: example.com\\r\\nConnection: close\\r\\n\\r\\n")
response = ssl_sock.recv(1024)
ssl_sock.close()

print("Got HTTPS response" if b"HTTP" in response else "Failed")
""")

server_hostname must be the host passed to connect(), ignoring case and a trailing dot; any other name fails the upgrade with PermissionError. The certificate is checked for the host the policy allowed, so a connection to one allowed address can’t reach a different site behind it. As a result, HTTPS through an HTTP CONNECT proxy tunnel isn’t supported.

Custom Root Certificates

Add custom CA certificates for internal services:

import eryx

# Load your custom CA certificate
with open("internal-ca.pem", "rb") as f:
    ca_cert = f.read()

config = eryx.NetConfig(allowed_hosts=["internal.example.com"]).with_root_cert(ca_cert)
sandbox = eryx.Sandbox(network=config)

fetch in JavaScript

JavaScript sandboxes have a fetch that goes through the same host-side networking as Python’s sockets: the host does the TLS and applies everything on this page (allowed hosts, address filtering, method and path rules, timeouts, traffic limits) and secret substitution. The guest never sees a certificate.

const res = await fetch("https://api.example.com/items?page=2", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "widget" }),
    signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const items = await res.json();

fetch blocks the sandbox. The host’s network calls are synchronous for the guest, so a fetch holds up the whole sandbox until its response, after any redirects, has been read in full. Requests never overlap: Promise.all([fetch(a), fetch(b)]) runs them one after the other, and no other code (callbacks, other promises) runs meanwhile. For the same reason, nothing can call controller.abort() while a request is on the wire: an abort takes effect before the request starts. Use AbortSignal.timeout(ms) to bound a request, which passes its deadline to every network call.

What’s there, and what isn’t:

  • fetch(input, init), Request, Response (status, ok, statusText, headers, url, redirected, text(), json(), arrayBuffer(), bytes(), clone(), Response.json()), Headers, AbortController and AbortSignal (abort(), timeout(), any()).
  • HTTP/1.1 only, one connection per request (no keep-alive), and no compression: requests send accept-encoding: identity unless the script sets it, and bodies aren’t decompressed.
  • Bodies are buffered, not streamed: response.body is always null, and a request body is a string, ArrayBuffer or typed array (no FormData, Blob or streams). The host’s traffic limit caps the total.
  • Redirects follow the fetch standard: redirect: "follow" (up to 20), "error" or "manual" (which returns the 3xx response itself). A 301/302 POST or a 303 becomes a GET without its body, and Authorization is dropped on a redirect to another origin.
  • Headers the transport owns (Host, Content-Length, Connection, Transfer-Encoding and the like) are set by fetch; ones the script passes are ignored.
  • Host names must be ASCII: write internationalized names in their punycode (xn--) form. URLs with credentials (https://user:pass@...) are refused.
  • A network failure or a refusal by the host’s policy rejects with TypeError("fetch failed"), whose cause.code says why: not-permitted (a blocked host or address, or a method or path the rules don’t allow), timed-out, host-not-found, connection-refused, certificate-error, too-many-redirects, and so on. An aborted request rejects with the signal’s reason, a DOMException named AbortError or TimeoutError.
  • QuickJS has no timers, so an AbortSignal.timeout() signal turns aborted when it’s next looked at rather than firing its listeners on time.

Low-Level Async API

For advanced use cases, Eryx exposes a low-level async networking API via the _eryx_async module:

import eryx

config = eryx.NetConfig.permissive()
sandbox = eryx.Sandbox(network=config)

result = sandbox.execute("""
import _eryx_async

# TCP connection
tcp_handle = await _eryx_async.await_tcp_connect("example.com", 80)
print(f"Connected with handle: {tcp_handle}")

# Send data
request = b"GET / HTTP/1.1\\r\\nHost: example.com\\r\\nConnection: close\\r\\n\\r\\n"
written = await _eryx_async.await_tcp_write(tcp_handle, request)
print(f"Wrote {written} bytes")

# Read response
response = await _eryx_async.await_tcp_read(tcp_handle, 1024)
print(f"Read {len(response)} bytes")

# Close
_eryx_async.tcp_close(tcp_handle)
print("Connection closed")
""")

TLS with Low-Level API

import eryx

config = eryx.NetConfig.permissive()
sandbox = eryx.Sandbox(network=config)

result = sandbox.execute("""
import _eryx_async

# Connect TCP first
tcp_handle = await _eryx_async.await_tcp_connect("example.com", 443)

# Upgrade to TLS
tls_handle = await _eryx_async.await_tls_upgrade(tcp_handle, "example.com")
print("TLS upgraded")

# Use TLS connection
request = b"GET / HTTP/1.1\\r\\nHost: example.com\\r\\nConnection: close\\r\\n\\r\\n"
await _eryx_async.await_tls_write(tls_handle, request)
response = await _eryx_async.await_tls_read(tls_handle, 1024)

_eryx_async.tls_close(tls_handle)
print(f"Got {len(response)} bytes via HTTPS")
""")

Connection Limits

Limit the number of simultaneous connections:

import eryx

config = eryx.NetConfig(allow_all_hosts=True, max_connections=5)
sandbox = eryx.Sandbox(network=config)

# Attempting more than 5 connections will fail

Traffic Limits

In Rust, NetConfig::with_max_bytes caps the bytes an execution sends and receives, in all, across its connections, a shell’s child processes’ included. Reads stop at the cap, and past it reads and writes raise OSError (network limit reached); a child’s request gets a 403 from its proxy, or its connection closes if a response had started. Either way, the result’s stats.network_bytes_sent and stats.network_bytes_received say how much it moved, children included, as the code wrote and read it. TLS overhead isn’t counted, except through a child’s blind CONNECT tunnel (a command allowed tunnels), where the proxy only sees the encrypted bytes: there the handshake and record overhead count too:

let sandbox = Sandbox::embedded()
    .with_network(NetConfig::default().allow_host("api.example.com").with_max_bytes(16 << 20))
    .build()?;
let result = sandbox.execute(code).await?;
println!("{} bytes in", result.stats.network_bytes_received);

Best Practices

  1. Use allowlists in production - Only allow connections to known, trusted hosts
  2. Keep localhost blocked - Unless you specifically need it for testing
  3. Set appropriate timeouts - Prevent hung connections from blocking execution
  4. Limit connections - Prevent resource exhaustion from too many connections
  5. Use HTTPS - Always prefer encrypted connections for sensitive data

Next Steps

Packages

Eryx supports installing Python packages in sandboxes. This allows sandboxed code to use third-party libraries like requests, jinja2, numpy, and more.

Supported Package Formats

Eryx supports two package formats:

FormatExtensionDescription
Wheel.whlStandard Python wheel format (recommended)
Tar.gz.tar.gz, .tgzCompressed archive format

Adding Packages with SandboxFactory

The recommended way to use packages is with SandboxFactory, which pre-installs packages once and creates fast sandbox instances:

import eryx

# Create a factory with packages pre-installed
factory = eryx.SandboxFactory(
    packages=[
        "path/to/jinja2-3.1.2-py3-none-any.whl",
        "path/to/markupsafe-2.1.3-py3-none-any.whl",
    ],
    imports=["jinja2"],  # Pre-import these modules during initialization
)

# Create sandboxes quickly - packages are already installed
sandbox = factory.create_sandbox()
result = sandbox.execute("""
from jinja2 import Template
template = Template("Hello {{ name }}!")
print(template.render(name="World"))
""")
print(result.stdout_text)  # "Hello World!"

Adding Packages to a Sandbox Builder (Rust)

In Rust, use the sandbox builder to add packages:

extern crate eryx;
extern crate tokio;
use eryx::Sandbox;

#[tokio::main]
async fn main() -> Result<(), eryx::Error> {
    let sandbox = Sandbox::embedded()
        .with_package("path/to/jinja2-3.1.2-py3-none-any.whl")?
        .with_package("path/to/markupsafe-2.1.3-py3-none-any.whl")?
        .build()?;

    let result = sandbox.execute(r#"
from jinja2 import Template
template = Template("Hello {{ name }}!")
print(template.render(name="Rust"))
    "#).await?;

    println!("{}", result.stdout_text());

    Ok(())
}

Pre-importing Modules

Pre-importing modules during factory initialization speeds up sandbox creation:

import eryx

# Without pre-import: first import in sandbox is slow
factory_without = eryx.SandboxFactory(
    packages=["path/to/jinja2.whl", "path/to/markupsafe.whl"],
)

# With pre-import: imports are already done
factory_with = eryx.SandboxFactory(
    packages=["path/to/jinja2.whl", "path/to/markupsafe.whl"],
    imports=["jinja2"],  # Import during initialization
)

# Sandboxes from factory_with start faster
sandbox = factory_with.create_sandbox()

Finding WASI-Compatible Packages

Eryx runs Python in WebAssembly, which means packages with native extensions need to be compiled for WASI. Options include:

Pure Python Packages

Pure Python packages (no native extensions) work out of the box:

  • requests
  • jinja2
  • pyyaml
  • httpx
  • beautifulsoup4

WASI-Compiled Packages

Some packages with native extensions have WASI-compiled versions available:

Native Extensions

Packages with native C extensions (like numpy, pandas) require WASI-compiled wheels. Check if WASI builds are available for your specific package.

Baking Callbacks into the Factory

Registering callbacks installs a Python wrapper for each of them inside the guest. A fresh sandbox starts from the factory’s snapshot, and the snapshot only knows the callbacks it was created with — none, by default — so every create_sandbox() re-runs that installation on its first execution (a few milliseconds for a handful of callbacks, more than creating the sandbox itself).

If every sandbox from a factory registers the same callbacks, pass them to the factory instead. Their declarations (name, description, parameter schema) are baked into the snapshot, and create_sandbox() / create_session() register them unless given callbacks of their own:

import eryx

def get_time():
    import time
    return {"timestamp": time.time()}

factory = eryx.SandboxFactory(
    callbacks=[{"name": "get_time", "fn": get_time, "description": "Returns current time"}],
)

sandbox = factory.create_sandbox()  # get_time() is ready; no per-sandbox setup
result = sandbox.execute("print((await get_time())['timestamp'] > 0)")

A sandbox that is given a different set of callbacks still works; it installs them itself as before. Setup code cannot invoke the callbacks, since nothing answers them while the snapshot is being built. A saved factory keeps the baked declarations but not the Python functions, so pass the same callbacks= to SandboxFactory.load().

Package Dependencies

When installing packages, you must include all dependencies:

import eryx

# requests requires urllib3, certifi, idna, charset-normalizer
factory = eryx.SandboxFactory(
    packages=[
        "requests-2.31.0-py3-none-any.whl",
        "urllib3-2.1.0-py3-none-any.whl",
        "certifi-2024.2.2-py3-none-any.whl",
        "idna-3.6-py3-none-any.whl",
        "charset_normalizer-3.3.2-py3-none-any.whl",
    ],
    imports=["requests"],
)

Error Handling

Package installation errors are caught at factory/sandbox creation time:

import eryx

try:
    factory = eryx.SandboxFactory(
        packages=["nonexistent-package.whl"],
    )
except FileNotFoundError as e:
    print(f"Package not found: {e}")

try:
    factory = eryx.SandboxFactory(
        packages=["file.unknown"],  # Unknown format
    )
except ValueError as e:
    print(f"Invalid format: {e}")

Caching Compiled Components

Eryx caches compiled WebAssembly components to speed up repeated sandbox creation:

Saving and Loading Factories

Save pre-configured factories for fast loading:

import eryx
from pathlib import Path

# Create factory with packages
factory = eryx.SandboxFactory(
    packages=["jinja2.whl", "markupsafe.whl"],
    imports=["jinja2"],
)

# Save to disk
factory.save(Path("jinja2-factory.bin"))

# Later: load quickly
loaded_factory = eryx.SandboxFactory.load(Path("jinja2-factory.bin"))
sandbox = loaded_factory.create_sandbox()

Standard Library Availability

The Python standard library is automatically available:

import eryx

sandbox = eryx.Sandbox()
result = sandbox.execute("""
import json
import base64
import hashlib
import re
import datetime

data = json.dumps({"key": "value"})
encoded = base64.b64encode(b"hello").decode()
hash_val = hashlib.md5(b"test").hexdigest()[:8]
match = re.search(r'\\d+', '123abc')

print(f"json: {data}")
print(f"base64: {encoded}")
print(f"hash: {hash_val}")
print(f"regex: {match.group()}")
""")
print(result.stdout_text)

Common Package Examples

Jinja2 (Templating)

import eryx

factory = eryx.SandboxFactory(
    packages=["jinja2.whl", "markupsafe.whl"],
    imports=["jinja2"],
)

sandbox = factory.create_sandbox()
result = sandbox.execute("""
from jinja2 import Template
t = Template("{% for item in items %}{{ item }}{% endfor %}")
print(t.render(items=[1, 2, 3]))
""")
print(result.stdout_text)  # "123"

Requests (HTTP Client)

import eryx

factory = eryx.SandboxFactory(
    packages=[
        "requests.whl",
        "urllib3.whl",
        "certifi.whl",
        "idna.whl",
        "charset_normalizer.whl",
    ],
    imports=["requests"],
)

config = eryx.NetConfig.permissive()
sandbox = factory.create_sandbox(network=config)

result = sandbox.execute("""
import requests
r = requests.get("https://httpbin.org/get", timeout=10)
print(f"Status: {r.status_code}")
""")

PyYAML (YAML Parser)

import eryx

factory = eryx.SandboxFactory(
    packages=["pyyaml.whl"],
    imports=["yaml"],
)

sandbox = factory.create_sandbox()
result = sandbox.execute("""
import yaml

data = yaml.safe_load('''
name: John
age: 30
items:
  - apple
  - banana
''')
print(f"Name: {data['name']}, Items: {data['items']}")
""")

Best Practices

  1. Use SandboxFactory - Pre-install packages once, create sandboxes quickly
  2. Pre-import common modules - Speeds up sandbox initialization
  3. Include all dependencies - Packages don’t auto-resolve dependencies
  4. Cache compiled components - Use filesystem cache for production
  5. Save/load factories - Avoid repeated initialization costs
  6. Prefer pure Python packages - They work without WASI compilation

Next Steps

Environments

An environment is a set of packages installed and packed ahead of time, in CI or a deploy step, into a directory that sandboxes mount read-only. Sandboxes never see package names or a registry: they import what the environment provides. JavaScript is supported today (npm packages); Python and the shell will use the same format and the same with_environment.

Getting the packages

eryx doesn’t resolve or fetch packages. Install them with your package manager, or let a service do it:

  • npm or pnpm: npm ci --ignore-scripts --omit=dev (or pnpm install --prod --ignore-scripts) from a committed lockfile, then pack the tree as below.
  • eryx-run: the hosted service resolves and fetches packages from a definition (package specs, a registry, a minimum release age, a lockfile) and packs them with eryx, so its environments are the same format.

Packing them

env pack turns the installed packages into an environment, without resolving or fetching anything:

npm ci --ignore-scripts --omit=dev
eryx-precompile env pack . --name data-tools --entry date-fns/format \
    --lockfile package-lock.json --out envs/data-tools
  • Entries: what’s importable. Without --entry, the tree’s package.json dependencies, skipping (with a warning in the manifest) any with nothing to import, such as @types/* or CLI-only packages; with it, exactly the entries given.

  • Layouts: npm’s, and pnpm’s isolated one (node_modules/.pnpm), work as installed, symlinks included. Packages are looked for in node_modules from the tree up to --root (default: the tree itself), as Node does, so for a workspace member with hoisted dependencies, workspace packages or file: dependencies outside the tree, pass a --root that holds them (a monorepo’s root, say). Every package symlink must be relative and lead inside the root. An absolute symlink, or one that leads outside the root, fails before bundling, naming the link. Links that aren’t packages (node_modules/.bin) and links that lead nowhere are left alone. Yarn’s Plug’n’Play has no node_modules, so use its nodeLinker: node-modules.

  • Safety: the bundler parses the packages in a sandbox. What it can read, and so what can end up in the environment, is exactly:

    • the contents of the node_modules dirs from the tree up to the root;
    • the whole directory each package symlink points at (a workspace member’s or file: package’s directory, everything in it).

    Nothing else of the tree or the root is visible: a package that imports the app’s own files (a ../../service-account.json), or a workspace member that imports a file beside its directory, fails the pack instead. (The bundler reads a mirror of just those paths, hard-linked next to the output, so links resolve from packages’ real paths as Node’s do.)

  • Unresolved imports fail the pack: an import the installed packages don’t provide is an error listing each one, rather than an environment that fails when imported. Two kinds stay external, with a warning in the manifest, so they fail only if the code imports them at run time: one the importing package declares optional (optionalDependencies, or an optional peer in peerDependenciesMeta), which npm ci --omit=dev leaves out, and one passed to --allow-unresolved (repeatable). A require in a try/catch, the usual way to use an optional dependency (ws and bufferutil), is left external without a warning. Nothing is fetched, and pass --ignore-scripts to the install so no package code runs there either.

  • --lockfile copies the given file into the environment and records it and its hash in the manifest’s inputs, with the installed versions of the entries’ packages. None of that is part of the hash: packing the same installed tree again gives the same environment.

In Rust, the same is eryx::environment::pack(tree, out, &PackOptions::new(name, Language::JavaScript)), with the env-pack feature. The directory format is described in Environment Format.

The env-pack feature embeds the bundler if it’s there at build time (ERYX_BUNDLER_CWASM, the setup cache, or the workspace). Otherwise, as in a crates.io build or a released eryx-precompile, it’s loaded at run time from the cache eryx-precompile setup --bundler writes, checked against its checksum; without one, packing fails saying to run that.

With a released eryx-precompile, run eryx-precompile setup --bundler once before the first env pack.

The result is a directory with a manifest (eryx-environment.json: language, inputs, what it exports, and a hash of everything sandboxes rely on), the lockfile if given, and the modules.

Using it

use eryx::environment::Environment;
use eryx::Sandbox;

// Pin the hash CI built, so a different environment at the path is refused.
let environment = Environment::load_expecting("envs/data-tools", "sha256-…")?;
let sandbox = Sandbox::embedded()
    .javascript()
    .with_environment(&environment)
    .build()?;

sandbox.execute(r#"
    import { z } from "zod";
    import { format } from "date-fns";
    import _ from "lodash";
    console.log(format(new Date(0), "yyyy-MM-dd"), _.chunk([1, 2, 3], 2));
"#).await?;

Loading and mounting only need eryx’s environment feature, which doesn’t include the bundler. The sandbox builder’s build() refuses an environment for another language, and checks the environment still hashes to what it did when it was loaded, as pools and factories do for every sandbox they make.

eryx-server serves a directory of environments with --environments, and requests pick one by name; see gRPC Server.

Importing in JavaScript

  • import declarations at the top of a script work as usual: eryx rewrites them into dynamic imports, since scripts run as global code so their variables persist across a session. Only leading imports are rewritten, and only forms eryx fully understands; anything else (an import after other statements, import attributes) is QuickJS’s syntax error. Running the same import again in a session is fine. A session snapshot records these imports rather than the modules, and restoring it imports them again (so the restoring sandbox needs the same environment); a variable reassigned since its import keeps its new value. Values that hold a class instance (a Buffer, an EventEmitter, a TextDecoder) can’t be kept with their class, so they’re left out and named in the snapshot’s skipped(), like functions. Only imports from executes that succeeded are recorded: if an execute throws after its imports ran, run those imports again after a restore.
  • await import("…") works anywhere.
  • require("…") imports synchronously, for CommonJS-style code. A module that can’t finish without awaiting (top-level await on something asynchronous) can’t be required; use await import(). require settles the import by running queued promise jobs, so pending callbacks may run earlier than they otherwise would.
  • CommonJS packages (lodash, say) are bundled as a module whose default export is module.exports. Named imports of its properties work too: import { chunk } from "lodash".
  • Only what the environment exports is importable, plus the shared chunks its modules import from each other. Anything else fails with “Cannot find module”, naming what the environment provides.
  • Node built-ins: node:buffer, node:events, node:path, node:string_decoder (the npm polyfills, vendored), node:util (a subset: format, inspect, inherits, promisify, types, …) and node:crypto (random values only: randomBytes, randomUUID, randomInt, getRandomValues) and node:url (URL, URLSearchParams, fileURLToPath, pathToFileURL, urlToHttpOptions, domainToASCII, domainToUnicode, and a subset of the legacy parse, format and resolve) and node:fs (a subset: whole-file reads and writes, directories, stat, rename, copy and remove, sync, with callbacks and as fs/promises, on the sandbox’s files) work, with or without node:, and with require too. They don’t need an environment. The rest (net, child_process, http, os, …) throw “node:net isn’t available in eryx yet” on import, so a package that imports one statically fails when it’s imported. Packages written for browsers or Workers generally avoid them.
  • Web globals: crypto.getRandomValues() and crypto.randomUUID() (from the host’s random source, so uuid and nanoid work), TextEncoder and TextDecoder (UTF-8 only), and timers (setTimeout and friends, with node:timers and node:timers/promises; see Timers in JavaScript).
  • URL and URLSearchParams follow the WHATWG URL standard (core-js’s implementation), with one gap: a non-ASCII host is lowercased and punycode-encoded, without the full IDNA mapping a browser applies. fetch takes a URL, but checks its href with its own stricter parser, so a URL fetch can’t use (credentials, a scheme other than http/https) is refused as before. A URL kept in session state is a class instance, so snapshots skip it; keep its href instead.
  • Imports are checked like ES modules: importing a name a module doesn’t export (or a default from a module without one) throws a SyntaxError naming the export and the module.

What isn’t supported yet

  • Python and shell environments (pack returns Unsupported).
  • The other Node built-ins (above), crypto.subtle and node:crypto’s hashes and ciphers. A package that imports a missing built-in fails when it’s imported; one that uses a missing API fails when it calls it.
  • Node’s globals: there’s no global Buffer or process.nextTick. Code that uses Buffer without importing it (common in packages written for Node) throws ReferenceError: Buffer is not defined; import { Buffer } from "node:buffer" works.
  • Packages with native addons or WebAssembly.

Secrets Management

Eryx provides secure secrets handling for sandboxed Python code. Secrets are never directly exposed to the sandbox — instead, Python code sees opaque placeholders, and real values are only substituted when making HTTP requests to authorized hosts.

How It Works

  1. You register a secret with a name, real value, and list of allowed hosts
  2. Eryx generates a random placeholder (e.g., ERYX_SECRET_PLACEHOLDER_a1b2c3...)
  3. The placeholder is set as an environment variable inside the sandbox
  4. Python code reads and uses the placeholder like a normal value
  5. When making HTTPS requests to an allowed host, Eryx transparently substitutes the real value
  6. Any placeholders in stdout, stderr, or files are scrubbed to [REDACTED]

This design means sandboxed code cannot exfiltrate secrets to unauthorized hosts, even if the code is malicious.

Python API

import eryx

sandbox = eryx.Sandbox(
    secrets={
        "API_KEY": {
            "value": "sk-real-secret-key",
            "allowed_hosts": ["api.example.com"],
        },
        "TOKEN": {
            "value": "ghp-abc123",
            "allowed_hosts": ["api.github.com"],
        },
    },
    network=eryx.NetConfig(allowed_hosts=["api.example.com", "api.github.com"]),
)

result = sandbox.execute("""
import os
key = os.environ["API_KEY"]
print(f"Key is: {key}")  # Prints: Key is: [REDACTED]
""")

Each secret dict requires a "value" key and accepts an optional "allowed_hosts" list (defaults to []).

JavaScript

JavaScript sandboxes read the placeholders from process.env, as Python reads os.environ, and use them with fetch:

const res = await fetch("https://api.github.com/user", {
    headers: { Authorization: `Bearer ${process.env.TOKEN}` },
});
console.log(process.env.TOKEN); // Prints: [REDACTED]

process only exists when the sandbox has secrets, and only has env. The shell exports each placeholder as a variable, for its commands; with child network, their proxy substitutes the real values.

Rust API

use eryx::{Sandbox, NetConfig};

let sandbox = Sandbox::embedded()
    .with_secret("API_KEY", "sk-real-key", vec!["api.example.com".to_string()])
    .with_network(NetConfig::default().allow_host("api.example.com"))
    .build()?;

The with_secret method takes:

  • name — The environment variable name visible to Python
  • value — The real secret value (never exposed to sandbox)
  • allowed_hosts — Hosts where the real value can be sent

A secret with an empty allowed_hosts uses NetConfig.allowed_hosts instead, but only while allow_all_hosts is off. A secret left with no hosts either way is never sent anywhere, so building a sandbox with networking enabled fails.

To only send a secret in one header, build its SecretConfig with only_in_header and add it with with_secret_config:

use eryx::{Sandbox, NetConfig, SecretConfig};

let sandbox = Sandbox::embedded()
    .with_secret_config(
        "API_KEY",
        SecretConfig::new("sk-real-key", vec!["api.example.com".to_string()])
            .only_in_header("X-Api-Key"),
    )
    .with_network(NetConfig::default().allow_host("api.example.com"))
    .build()?;

The header name is compared ignoring case. A request with the placeholder in any other header is refused, as for a host the secret isn’t allowed for.

A placeholder can also be the username or password of Authorization: Basic credentials (as git and requests’ auth=(user, password) send them): the host decodes the base64 user:password, substitutes the real value under the same host and header rules, and re-encodes it.

Each SecretConfig gets a new random placeholder. Where state that may hold one outlives a sandbox (e.g. a session restored into a new sandbox for each execution), give the secret the same one each time with with_placeholder, which takes at least 32 ASCII letters, digits and underscores. Keep it unguessable: code that knows it can have the secret substituted without reading it.

Host Binding

The real value is only sent to the host the connection was opened to:

  • The TLS server name must be that host (ignoring case and a trailing dot); wrap_socket(sock, server_hostname=...) with any other name fails.
  • A request whose Host header or absolute-form target names a different host is refused if it carries a placeholder, as is one with a malformed request line or a target containing whitespace, \ or userinfo (user@host).
  • Only the headers of requests the host can frame are substituted. A write that starts with an empty line, or has a malformed request line, is refused, and bytes that aren’t a request leave the connection unparsed, with nothing substituted, from then on, as does a CONNECT or a request asking for an Upgrade once it ends. So a placeholder never reaches the server inside what it reads as another request’s body, or a host a tunnel leads to.

Responses

If a host a secret is allowed for sends its real value back (an echo endpoint, or an error message quoting the key), the sandbox sees the placeholder instead. Other hosts never receive the value, and nor does a connection whose requests don’t get values substituted (plain TCP without allow_plaintext_secrets), so those responses aren’t masked: a host that has the real value some other way (it was given it outside the sandbox, say) shows it to the sandbox as it is. That includes a value the sandbox planted itself, through another connection that did get it substituted: a request-inspection or audit-log endpoint on the secret’s host can store it, and a connection the sandbox opens to read it back without its first write being a request (e.g. with a space before GET, which a lenient server accepts) only gets the best-effort masking of other protocols described below. Don’t allow a secret for a host that hands back what it was sent.

Responses are masked where the sandbox’s HTTP client sees the value whole:

  • Headers are masked as one block once they’ve all arrived.
  • A chunked body is masked after de-chunking, so a value split across chunks is masked too. It’s re-chunked on the way: the body is the server’s, masked, but the chunk sizes are eryx’s.
  • Holding back: the last bytes of a body (one less than the host’s longest secret value) are held back so a value split across reads is whole before any of it reaches the sandbox. Inside a Content-Length body or one chunk’s data they wait for more of it, or for its end, however long that takes, and in a body that ends when the connection closes, for the close. Between chunks they also go out after 100 ms with nothing new, so a token stream’s events are late by at most that, and so do bytes after a 101 or a CONNECT’s 2xx (another protocol, where nothing is substituted). They’re held back whatever they contain, so read sizes and timing don’t reveal whether they match a secret. A value an allowed host splits between chunks, or after a 101, more than 100 ms apart, isn’t masked.
  • Anything else fails closed: on such a connection, a reply that isn’t an HTTP/1.x response to a request the sandbox sent (another protocol, a response nobody asked for) or a response whose framing can’t be followed (malformed chunks, ambiguous lengths) ends the connection: the sandbox’s reads fail from there on, and nothing held back reaches it. (A response nobody asked for on an idle connection, such as a 408 before the server closes it, ends the stream cleanly instead.)
  • Other protocols from the start: a connection whose first write isn’t an HTTP request, or whose server speaks first (Postgres after SSLRequest, SMTP, Redis), never has anything substituted, now or later, so its replies are held back and released the same best-effort way as after a 101 rather than failing.

A secret without allowed_hosts applies to every host the sandbox may reach, so every TLS connection then gets these HTTP-only rules. Give each secret the allowed_hosts it’s for.

Only verbatim copies are replaced; compressed or otherwise encoded copies are passed through unchanged. Masking can change a body’s length: a Content-Length body that contains a real value reaches the sandbox with the placeholder in its place, so its length no longer matches the header.

The sandbox picks the encoding, too: a secret allowed in Authorization can be sent base64-wrapped as Basic credentials (e.g. Basic b64("x:PLACEHOLDER")), so an allowed host that echoes request headers returns the base64 of the real value, which isn’t masked.

To also limit which endpoints a secret can reach on its host, add method and path rules for that host. Like secret substitution, they only apply to requests the host can parse: TLS done by the sandboxed code itself isn’t checked.

Plain HTTP

Placeholders are only substituted on TLS connections (https://). A request over plain TCP (http://) is sent with the placeholder left in place, so the real value never crosses the network unencrypted.

To substitute over plain TCP as well (e.g. for a local test server), opt in on the network config:

let sandbox = Sandbox::embedded()
    .with_secret("API_KEY", "sk-real-key", vec!["localhost".to_string()])
    .with_network(NetConfig::default().allow_localhost().allow_plaintext_secrets(true))
    .build()?;

In Python, pass allow_plaintext_secrets=True to NetConfig (or set the attribute); over gRPC, set network_config.allow_plaintext_secrets (the server rejects such requests unless it was started with --allow-plaintext-secrets). The real value then crosses the network unencrypted, readable by anyone on the path, so only enable it for servers you trust on a network you trust. The JavaScript bindings have no secrets support, so there is nothing to opt in to.

Output Scrubbing

By default, when secrets are configured, Eryx scrubs placeholders from all outputs:

  • stdout — Placeholders are replaced with [REDACTED]
  • stderr — Placeholders are replaced with [REDACTED]
  • VFS files — Placeholders are scrubbed from file writes

Configuring Scrub Policy

You can disable scrubbing for individual streams (useful for debugging):

Python:

sandbox = eryx.Sandbox(
    secrets={"KEY": {"value": "secret", "allowed_hosts": ["example.com"]}},
    scrub_stdout=False,   # Disable stdout scrubbing
    scrub_stderr=True,    # Enable stderr scrubbing (default)
    scrub_files=True,     # Enable file scrubbing (default)
)

Rust:

let sandbox = Sandbox::embedded()
    .with_secret("KEY", "secret", vec!["example.com".to_string()])
    .scrub_stdout(false)   // Disable stdout scrubbing
    .scrub_stderr(true)    // Enable stderr scrubbing (default)
    .scrub_files(true)     // Enable file scrubbing (default)
    .build()?;

Secrets in files

File scrubbing also applies to files the sandboxed code writes for itself, so a secret a program reads back from a file arrives as [REDACTED], and the request it makes isn’t authenticated. git is the common case: git config http.extraHeader, a token in a remote URL (which git stores in .git/config) and credential.helper store all keep the secret in a file. With file scrubbing on, hand it to git per command instead:

git -c "http.extraHeader=Authorization: Bearer $TOKEN" clone https://example.com/repo.git
# or through git's environment
GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
  GIT_CONFIG_VALUE_0="Authorization: Bearer $TOKEN" git -C repo fetch

Alternatively, turn file scrubbing off for that sandbox (scrub_files=False, .scrub_files(false)), accepting that placeholders then persist in its files.

Credentials for Child Processes

A shell’s commands can instead be given a credential: a header the child proxy adds to their requests itself, so the sandbox never holds the secret at all. A few rules and limits worth knowing:

  • Precedence: a credential given to one execution (ExecuteOptions::with_credential) wins over the sandbox’s (SandboxBuilder::with_credential) where both apply to a request and set the same header, so a per-request token overrides a sandbox-wide default. Among one level’s own, the first given wins.
  • Hosts: for_hosts takes exact names (api.github.com), IP addresses, or *. and a name of two labels or more (*.github.com, its subdomains only). Any other * (*, *.*, github.com*, *github.com) is refused, since it could match a host the script controls, and so is *. and a single label (*.com). Names are ASCII letters, digits, hyphens and dots: write internationalized names in punycode (xn--…); a port, path or space is refused rather than never matching. eryx doesn’t carry the public suffix list, so a wildcard under a public suffix (*.co.uk, *.github.io) is accepted but matches names anyone can register: avoiding those is up to you. Hosts aren’t scoped by port: any port the network allows on a credential’s host gets it.
  • No upgrades: a connection to a host a command’s credential applies to refuses Upgrade and CONNECT requests, so those hosts can’t be used for WebSockets (or h2c and other upgrades) by that command, and a 101 response ends the connection: what follows one isn’t framed, so it couldn’t be masked.
  • Masking only hides whole, verbatim echoes. A host that echoes request headers can hand the credential back in a form masking doesn’t see: re-escaped (JSON’s \/ for /), re-encoded, or in pieces (Range and If-Range are dropped from every request on a connection carrying a credential, but other ways to slice a response remain). Don’t give credentials for hosts that echo requests.
  • Output scrubbing is defence in depth, not a boundary. The credential’s value and the password of the proxy holding it (which a command finds in its HTTPS_PROXY) are scrubbed from stdout, stderr, traces, failure messages and (with scrub_result) results, but only verbatim: a script that gets a value can transform it, write it to a file, or split it across streamed writes. Masking the responses, and keeping the secret out of the sandbox, is the control.

Best Practices

  1. Always specify allowed_hosts — Without explicit hosts, the secret falls back to the network config’s allowed hosts, which could be broader than intended.
  2. Combine with NetConfig — Secrets require networking to be useful. Configure both together.
  3. Use separate secrets per service — Each secret should have its own allowed hosts list.
  4. Don’t disable scrubbing in production — Scrubbing prevents accidental leakage through logs and output.
  5. For child processes, prefer credentials — a shell’s commands (git, gh, curl) can authenticate with a credential the child proxy adds itself, so the sandbox never holds even the placeholder.

Security Model

  • Placeholders are randomly generated on each sandbox creation, making them unpredictable
  • Real values are only sent over TLS unless allow_plaintext_secrets is set
  • Host verification uses the TCP connection target; the TLS server name and the HTTP Host header must match it
  • Real values in responses are replaced with the placeholder before the sandbox reads them
  • Scrubbing is applied to stdout, stderr, and VFS file writes
  • Even if sandboxed code tries to print or write the placeholder, it appears as [REDACTED]

Next Steps

Output Streaming

By default, Eryx captures stdout and stderr and returns them in the ExecuteResult after execution completes. This includes writes straight to file descriptors 1 and 2 (os.write(1, ...), sys.__stdout__): they are captured (up to 1 MiB per stream per execution) and appended after the regular output, instead of reaching the host process’s stdout/stderr. Output streaming lets you receive output in real-time as Python code runs, which is useful for long-running scripts, progress reporting, and interactive interfaces.

Python API

Pass on_stdout and/or on_stderr callbacks when creating a sandbox or session:

import eryx

def handle_stdout(chunk: str) -> None:
    print(f"[stdout] {chunk}", end="")

def handle_stderr(chunk: str) -> None:
    print(f"[stderr] {chunk}", end="")

sandbox = eryx.Sandbox(
    on_stdout=handle_stdout,
    on_stderr=handle_stderr,
)

sandbox.execute("""
import sys
print("Hello from stdout")
print("Warning!", file=sys.stderr)
for i in range(5):
    print(f"Step {i}...")
""")

Output handlers also work with sessions:

session = eryx.Session(
    on_stdout=lambda chunk: print(chunk, end=""),
    on_stderr=lambda chunk: print(chunk, end="", file=sys.stderr),
)

Callback Signature

Both on_stdout and on_stderr receive a single str argument — the text chunk written by Python. Chunks may be partial lines or multiple lines, depending on how the sandboxed code writes output.

Rust API

Implement the OutputHandler trait and pass it to the sandbox builder:

use eryx::{Sandbox, OutputHandler};
use async_trait::async_trait;

struct MyOutputHandler;

#[async_trait]
impl OutputHandler for MyOutputHandler {
    async fn on_output(&self, chunk: &str) {
        print!("{chunk}");
    }

    async fn on_stderr(&self, chunk: &str) {
        eprint!("{chunk}");
    }
}

let sandbox = Sandbox::embedded()
    .with_output_handler(MyOutputHandler)
    .build()?;

The OutputHandler trait has two methods:

  • on_output(&self, chunk: &str) — Called for stdout output (required)
  • on_stderr(&self, chunk: &str) — Called for stderr output (optional, default ignores stderr)

How It Works

When an output handler is configured, Eryx sets up a channel between the WASM executor and the handler. As Python writes to sys.stdout or sys.stderr, the output is forwarded to the handler in real-time rather than being buffered until execution completes.

The final ExecuteResult still contains the complete captured stdout and stderr, so you get both real-time streaming and the full result.

Use Cases

  • Progress bars — Show progress as a long computation runs
  • Live logging — Stream log output to a UI
  • Interactive tools — The CLI uses output streaming for real-time REPL output
  • Monitoring — Watch sandbox execution in real-time

Next Steps

MCP Integration

MCP (Model Context Protocol) is a standard for AI assistants to communicate with tool servers. Eryx can discover and connect to MCP servers, exposing their tools as async callbacks inside the sandbox.

This means sandboxed Python code can call tools from any MCP server — filesystem access, GitHub, databases, web search, and more — all while maintaining the security of the sandbox.

How It Works

MCP tools are bridged into the sandbox as async callbacks. The entire call path is handled in Rust, bypassing the Python GIL:

Sandbox Python code
    → await mcp["server"].tool(args)
    → WASM callback invoke
    → Rust DynamicCallback
    → rmcp client
    → MCP server (stdio)

From Python’s perspective, MCP tools appear as async functions under the mcp namespace:

# Inside the sandbox
result = await mcp["github"].search_repos(query="eryx sandbox")
print(result["items"])

result = await mcp["filesystem"].read_file(path="/tmp/data.txt")
print(result["text"])

Config Discovery

When --mcp is passed (or connect_servers() is called), Eryx searches the user-wide MCP server configurations of multiple IDEs and tools. Project configs in the current directory are read only with --mcp-project (or include_project=True), since they name commands that run on your machine. Only stdio-type servers are supported.

Supported Config Files

Global (user-wide):

ToolPathKey
Claude Code~/.claude.jsonmcpServers
Cursor~/.cursor/mcp.jsonmcpServers
Windsurf~/.codeium/windsurf/mcp_config.jsonmcpServers
Zed~/.config/zed/settings.jsoncontext_servers
Gemini CLI~/.gemini/settings.jsonmcpServers
Codex~/.codex/config.tomlmcp_servers

Project (cwd-relative, only with --mcp-project):

ToolPathKey
Claude Code.mcp.jsonmcpServers
Cursor.cursor/mcp.jsonmcpServers
VS Code.vscode/mcp.jsonservers
Zed.zed/settings.jsoncontext_servers
Gemini CLI.gemini/settings.jsonmcpServers
Codex.codex/config.tomlmcp_servers

Later sources override earlier ones, except that a project config never replaces a global server of the same name.

Config Format

Most tools use the same JSON format. Here’s a .mcp.json example:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-filesystem", "/tmp"]
    }
  }
}

Environment variables are expanded in env values using $VAR, ${VAR}, or ${VAR:-default} syntax.

Servers with "disabled": true, "enabled": false, or a non-stdio "type" are skipped.

CLI Usage

Enable MCP with the --mcp flag:

# Auto-discover servers from all supported config files
python -m eryx --mcp -c 'tools = list_callbacks(); print([t["name"] for t in tools])'

# Use a specific config file
python -m eryx --mcp-config .mcp.json -c 'r = await mcp["github"].search_repos(query="eryx"); print(r)'

# Multiple config files (later overrides earlier)
python -m eryx --mcp-config global.json --mcp-config project.json -c '...'
FlagDescription
--mcpEnable MCP server integration (auto-discovers from user-wide configs)
--mcp-projectAlso read project configs in the current directory (implies --mcp)
--mcp-config PATHPath to MCP config file (implies --mcp, can be repeated)

Python API

Using connect_servers (High-Level)

The eryx.mcp module provides a high-level helper that discovers and connects to servers:

import eryx
from eryx.mcp import connect_servers

# Auto-discover and connect to all configured MCP servers
manager = connect_servers()

if manager is not None:
    # List discovered tools
    for tool in manager.list_tools():
        print(f"{tool['name']}: {tool['description']}")

    # Use with a sandbox
    sandbox = eryx.Sandbox(mcp=manager)
    result = sandbox.execute("""
r = await mcp["github"].search_repos(query="python sandbox")
print(f"Found {len(r['items'])} repos")
""")
    print(result.stdout_text)

    # Clean up
    manager.close()

Using MCPManager (Low-Level)

For more control, create and configure the MCPManager directly:

import eryx

manager = eryx.MCPManager()

# Connect to specific servers
manager.connect(
    "my-server",           # server name
    "npx",                 # command
    ["-y", "my-mcp-pkg"],  # args
    {"API_KEY": "sk-..."},  # env
    30.0,                   # timeout (seconds)
)

print(f"Servers: {manager.server_names}")
print(f"Tools: {[t['name'] for t in manager.list_tools()]}")

# Use with Sandbox or Session
sandbox = eryx.Sandbox(mcp=manager)
session = eryx.Session(mcp=manager)

# Always close when done
manager.close()

Combining MCP with Python Callbacks

MCP tools and Python callbacks can be used together:

import eryx
from eryx.mcp import connect_servers

def my_transform(text: str):
    return {"result": text.upper()}

manager = connect_servers()

sandbox = eryx.Sandbox(
    mcp=manager,
    callbacks=[
        {"name": "transform", "fn": my_transform, "description": "Uppercases text"}
    ],
)

result = sandbox.execute("""
# MCP tool
data = await mcp["filesystem"].read_file(path="/tmp/input.txt")

# Python callback
upper = await transform(text=data["text"])
print(upper["result"])
""")

Tool Naming

MCP tools are exposed in the sandbox under the mcp namespace using bracket syntax for server names:

# Inside the sandbox
result = await mcp["github"].search_repos(query="test")
#              ^^^  ^^^^^^^^  ^^^^^^^^^^^^
#              |    |         tool name
#              |    server name
#              mcp namespace

The bracket syntax is unambiguous and works for all server names, including those with hyphens or other special characters:

result = await mcp["my-server"].echo(message="hello")
result = await mcp["my-server"]["some-tool"](arg=1)

Dotted Syntax

When server and tool names are valid Python identifiers, you can also use dotted attribute access:

# Equivalent — only works when names are valid identifiers
await mcp.github.search_repos(query="test")

All styles are equivalent and can be mixed:

# These all call the same tool:
await mcp["github"].search_repos(query="test")         # bracket (recommended)
await mcp["github"]["search_repos"](query="test")     # full bracket
await mcp.github.search_repos(query="test")           # dotted
await invoke("mcp.github.search_repos", query="test")  # invoke()

The invoke() function works with any callback name string, regardless of special characters.

Introspection

Discover available MCP tools at runtime:

# Inside the sandbox
callbacks = list_callbacks()
mcp_tools = [c for c in callbacks if c["name"].startswith("mcp.")]
for tool in mcp_tools:
    print(f"{tool['name']}: {tool['description']}")
    print(f"  Parameters: {tool['schema']}")

Best Practices

  1. Use auto-discovery for convenience — --mcp finds servers from your user-wide IDE configs automatically; add --mcp-project only in directories you trust
  2. Use explicit configs for reproducibility — --mcp-config ensures consistent behavior across machines
  3. Close the manager — Always call manager.close() when done to terminate MCP server processes
  4. Handle missing tools gracefully — Not all servers may be available in every environment
  5. Set appropriate timeouts — The default 30s connection timeout can be adjusted via connect_timeout

Next Steps

  • MCP Server — Expose the sandbox as an MCP tool
  • Callbacks — Define custom host-side callbacks
  • CLI — Full CLI reference
  • Sessions — Persistent state across executions

MCP Server

Eryx can run as an MCP (Model Context Protocol) server, exposing the sandbox as a run_python tool. This lets any MCP-compatible AI assistant execute Python code in a secure sandbox.

Quick Start

# Run directly
uvx --with 'pyeryx[serve]' eryx serve

# Or if pyeryx is installed
eryx serve

This starts an MCP server over stdio with a single run_python tool. Any MCP client (Claude Desktop, Cursor, VS Code, etc.) can connect and execute Python code in the sandbox.

Configuration

Add eryx to your MCP client config. For example, in Claude Desktop’s config (claude_desktop_config.json):

{
  "mcpServers": {
    "eryx": {
      "command": "uvx",
      "args": ["--with", "pyeryx[serve]", "eryx", "serve"]
    }
  }
}

Or with sandbox options:

{
  "mcpServers": {
    "eryx": {
      "command": "uvx",
      "args": [
        "--with", "pyeryx[serve]", "eryx", "serve",
        "--timeout", "60000",
        "--allow-host", "*.example.com"
      ]
    }
  }
}

Flags

eryx serve accepts the same sandbox configuration flags as the main CLI:

FlagDescriptionDefault
--timeout MSExecution timeout in milliseconds30000
--max-memory BYTESMaximum memory in bytes128MB
--netAllow access to any public hostoff
--allow-host PATTERNAllow access only to matching hosts (implies --net)
-v SRC:DST[:ro]Mount host directory at sandbox path
--mcpEnable inner MCP tools (auto-discovers from user-wide IDE configs)off
--mcp-projectAlso read MCP configs in the current directory (implies --mcp)off
--mcp-config PATHPath to inner MCP config file (implies --mcp)

The run_python Tool

The server exposes a single tool:

ParameterTypeDescription
codestringPython code to execute (required)
timeout_msintegerPer-execution timeout in milliseconds (optional, capped at --timeout)

The tool uses a persistent Session under the hood, so variables, imports, and function definitions persist across calls. Output is captured from print() statements and returned as the tool result. Errors (execution errors, timeouts, resource limits) are returned as text rather than MCP errors, so the AI can see and react to them.

Inner MCP Tools

A powerful pattern is running eryx as an MCP server with inner MCP tools. This gives the sandbox access to other MCP servers while still keeping execution sandboxed:

# Sandbox has access to tools from your IDE configs
eryx serve --mcp

# Sandbox has access to tools from a specific config
eryx serve --mcp-config .mcp.json

When inner MCP tools are enabled, the run_python tool description is automatically updated to list the available tools, so the AI knows what’s callable inside the sandbox:

Execute Python code in a persistent sandboxed environment. ...

Available tools inside the sandbox (call with `await`):
- `await mcp["github"].search_repos(...)`: Search GitHub repositories
- `await mcp["filesystem"].read_file(...)`: Read a file from the filesystem

This is useful when you want an AI to have both code execution and tool access, but want all of it to run through a single sandboxed environment.

Examples

# Basic sandbox server
eryx serve

# With a 60-second timeout
eryx serve --timeout 60000

# With access to any public host
eryx serve --net

# With network access restricted to specific hosts
eryx serve --allow-host 'api.example.com' --allow-host '*.example.dev'

# With a mounted directory
eryx serve -v /path/to/data:/data:ro

# With inner MCP tools from IDE configs
eryx serve --mcp

# With inner MCP tools from a specific config
eryx serve --mcp-config path/to/mcp.json

# Combining options
eryx serve --timeout 60000 --net --mcp -v ./workspace:/workspace

Next Steps

gRPC Server

Eryx can run as a standalone gRPC server (eryx-server) that executes Python in a sandbox on behalf of remote clients. A pool of warm sandboxes is shared across requests, and a single bidirectional streaming RPC carries everything a request needs: callbacks, real-time output streaming, execution tracing, secrets, networking, session state, the structured result value, and callback replay & suspension.

It’s the backend for hosted, multi-tenant deployments where sandbox execution runs as a remote service. If you only need to embed the sandbox in a single process, use the Rust API directly; if you want a tool for an AI assistant over stdio, see the MCP Server. The gRPC server is for remote, multi-tenant, networked execution.

The protobuf service definition is the source of truth for the API: crates/eryx-server/proto/eryx/v1/eryx.proto. The fields and messages described below are documented inline there.

Running the server

The easiest way to run the server is the published Docker image, sd2k/eryx-server:

docker run -p 50051:50051 sd2k/eryx-server

The plain tags (latest, X.Y.Z, X.Y) are the image with every guest language: Python, JavaScript and shell. For a smaller Python-only image, add -python to any tag (latest-python, X.Y.Z-python); a request for another language then fails with INVALID_ARGUMENT.

The image sets ENTRYPOINT ["eryx-server"] and listens on [::]:50051 (metrics on 9090); it’s built from crates/eryx-server/Dockerfile. It runs as the unprivileged user eryx (UID/GID 10001), so it works under Kubernetes’ runAsNonRoot. The embedded runtime and stdlib are extracted at startup to $XDG_CACHE_HOME/eryx or ~/.cache/eryx, falling back to $TMPDIR/eryx-<uid> when those can’t be created. With a read-only root filesystem, mount a writable /tmp (or set XDG_CACHE_HOME to a writable directory).

To build from source instead, the server is the eryx-server binary in the eryx-server crate. Build it with the embedded and preinit features so the runtime and stdlib are baked in:

cargo build --release -p eryx-server --features eryx/embedded,eryx/preinit
./target/release/eryx-server

Every flag also has an environment variable, so the server is easy to configure in a container:

FlagEnv varDefaultDescription
--listen-addrERYX_LISTEN_ADDR[::1]:50051Address the gRPC service binds to.
--pool-max-sizeERYX_POOL_MAX_SIZE10Maximum sandboxes in the pool.
--pool-min-idleERYX_POOL_MIN_IDLE1Idle sandboxes kept warm for low-latency acquisition.
--pool-acquire-timeout-secsERYX_POOL_ACQUIRE_TIMEOUT_SECS30How long a request waits for a free sandbox before failing with UNAVAILABLE.
--pool-idle-timeout-secsERYX_POOL_IDLE_TIMEOUT_SECS300How long a sandbox beyond --pool-min-idle may sit idle before it is evicted.
--max-message-sizeERYX_MAX_MESSAGE_SIZE33554432 (32 MiB)Largest gRPC message accepted or sent, in bytes. Clients must raise their own limits to match.
--max-concurrent-streamsERYX_MAX_CONCURRENT_STREAMS200Concurrent RPCs per client connection. Further RPCs on that connection wait for a free stream.
--http2-keepalive-interval-secsERYX_HTTP2_KEEPALIVE_INTERVAL_SECS60Interval between HTTP/2 keepalive pings to each client; 0 disables them.
--http2-keepalive-timeout-secsERYX_HTTP2_KEEPALIVE_TIMEOUT_SECS20How long to wait for a ping acknowledgement before closing the connection.
--metrics-addrERYX_METRICS_ADDR0.0.0.0:9090Address of the Prometheus /metrics endpoint.
--runtime-cwasmERYX_RUNTIME_CWASM(embedded)Path to a pre-compiled runtime (e.g. with numpy/polars baked in).
--stdlibERYX_STDLIB(embedded)Python stdlib directory; only used with --runtime-cwasm.
--site-packagesERYX_SITE_PACKAGES(none)The site-packages directory --runtime-cwasm was pre-initialized with (eryx-precompile compile --preinit --site-packages DIR), mounted at /site-packages for Python and --shell-python. Needed for any module a package imports after pre-initialization (e.g. pandas’ describe() imports numpy.rec); only used with --runtime-cwasm.
--environmentsERYX_ENVIRONMENTS(none)Directory of environments, one per subdirectory, that requests mount by name.
--journal-signing-keyERYX_JOURNAL_SIGNING_KEY(random)Hex-encoded 32-byte HMAC key for signing replay journals. Prefer the env var, which keeps the key out of the process list. See Journal signing.
--journal-ttl-secsERYX_JOURNAL_TTL_SECS604800 (7 days)How long a signed journal can be replayed.
--max-execution-timeout-msERYX_MAX_EXECUTION_TIMEOUT_MS300000Ceiling on resource_limits.execution_timeout_ms.
--max-callback-timeout-msERYX_MAX_CALLBACK_TIMEOUT_MS300000Ceiling on resource_limits.callback_timeout_ms.
--max-memory-bytesERYX_MAX_MEMORY_BYTES536870912 (512 MiB)Ceiling on resource_limits.max_memory_bytes.
--max-fuelERYX_MAX_FUEL(none)Optional ceiling on resource_limits.max_fuel; when set, also the budget for requests that set none. Without it fuel is unlimited and the execution timeout is the CPU bound.
--max-callback-invocationsERYX_MAX_CALLBACK_INVOCATIONS10000Ceiling on resource_limits.max_callback_invocations.
--max-connectionsERYX_MAX_CONNECTIONS100Ceiling on network_config.max_connections.
--max-io-timeout-msERYX_MAX_IO_TIMEOUT_MS300000Ceiling on network_config.io_timeout_ms and connect_timeout_ms.
--max-output-bytesERYX_MAX_OUTPUT_BYTES16777216 (16 MiB)Most stdout plus stderr bytes kept and streamed per execution, at most 16 MiB. See Output cap.
--max-open-host-filesERYX_MAX_OPEN_HOST_FILES256Most host files (stdlib and site-packages) one execution may hold open; opens past it fail with EDQUOT. Not settable per request.
--max-open-host-files-totalERYX_MAX_OPEN_HOST_FILES_TOTAL(half the soft RLIMIT_NOFILE, at least 256)Most host files all executions in the server may hold open together.
--allow-plaintext-secretsERYX_ALLOW_PLAINTEXT_SECRETS(off)Let requests set network_config.allow_plaintext_secrets, which sends real secret values over unencrypted connections. Off by default: such requests are rejected with INVALID_ARGUMENT, so secrets are only substituted over TLS. See Plain HTTP.
--shell-commandERYX_SHELL_COMMANDS (;-separated)(none)A shell command, NAME[,NAME...]=PATH[@sha256:<hex>]: a .wasm or .cwasm file, the .wasm optionally pinned to its digest. Repeatable; empty entries and an empty variable mean none. See Commands from a registry and External Commands.
--shell-command-tunnelsERYX_SHELL_COMMAND_TUNNELS (,-separated)(none)Let a --shell-command name open blind CONNECT tunnels through the child proxy (no secret substitution, no HTTP rules). A request can turn it off (commands), not on.
--shell-command-spawnERYX_SHELL_COMMAND_SPAWN (,-separated)(none)Let a --shell-command name run commands itself, as git runs git. A request can turn it off (commands), not on.
--max-child-host-bytesERYX_MAX_CHILD_HOST_BYTES67108864 (64 MiB)Ceiling on resource_limits.max_child_host_bytes, and the value for requests that set none: the host memory a shell execution’s commands’ arguments and environments may hold at once.
--max-child-memory-bytesERYX_MAX_CHILD_MEMORY_BYTES268435456 (256 MiB)Ceiling on resource_limits.max_child_memory_bytes, and the value for requests that set none: the memory a shell execution’s running commands may hold together, on top of --max-memory-bytes. Raising it raises the host memory one execution can use.
--tls-certERYX_TLS_CERT(off)PEM certificate chain; enables TLS. Requires --tls-key.
--tls-keyERYX_TLS_KEY(off)PEM private key for --tls-cert.
--tls-client-caERYX_TLS_CLIENT_CA(off)PEM CA bundle to verify client certs; enables mutual TLS. See Transport security.

Commands from a registry

eryx-server doesn’t fetch commands: it loads --shell-command files. To run commands published to an OCI registry (such as ghcr.io/eryx-org/commands/eryx/rg), fetch them into a volume first, for example in an init container, and pin each one to its digest:

# Kubernetes: fetch the commands into a shared volume before the server starts.
initContainers:
  - name: commands
    image: <an image with wkg or oras>
    command: ["wkg", "oci", "pull", "ghcr.io/eryx-org/commands/eryx/rg:15.1.0-r.2", "-o", "/commands/rg.wasm"]
    volumeMounts: [{ name: commands, mountPath: /commands }]
containers:
  - name: eryx-server
    env:
      - name: ERYX_SHELL_COMMANDS
        value: "rg=/commands/rg.wasm@sha256:<hex>"
    volumeMounts: [{ name: commands, mountPath: /commands, readOnly: true }]
  • Fetching: Commands from a Registry shows the wkg and oras commands. For a private registry, give the init container credentials the way those tools take them, such as docker login or a mounted Docker config. For ghcr.io, that’s a token with read:packages.
  • The pin: @sha256:<hex> is the digest of the .wasm itself. That’s the manifest’s layer digest, which eryx-commands’ commands.lock records. It isn’t the manifest digest.
  • At startup: a pinned file that doesn’t match fails startup, naming the flag. The command is then checked (a command importing what the shell doesn’t provide is refused) and compiled once into eryx’s cache directory (commands/ under the first usable of $XDG_CACHE_HOME/eryx, the platform cache directory (~/.cache/eryx on Linux) and $TMPDIR/eryx-<uid>), so a later start with the same file skips compiling.
  • The cache directory should be writable and private to the server’s user, so pinned commands compile once; mount it as a volume to keep them across restarts. A read-only root filesystem with a writable /tmp still caches, in $TMPDIR/eryx-<uid>. Only when none of those directories is usable does the server log a warning and compile each pinned command in memory at every start. A wrong pin or a command the shell can’t run still stops startup.
  • Pins and .cwasm: only a .wasm can be pinned. A .cwasm is native code and is trusted as a whole, like --runtime-cwasm.

Shell requests

A request with language = LANGUAGE_SHELL runs a shell script against the server’s commands: the embedded coreutils, unless --no-shell-embedded-commands is set, any --shell-commands, python/python3 with --shell-python (from the server’s Python runtime: --runtime-cwasm, --stdlib and --site-packages, or the embedded one), and node/js with --shell-node (the embedded JavaScript runtime).

  • Which commands: allowed_commands narrows a request to some of them.
  • Per command: commands narrows what each one gets: a narrower network for its children, or no tunnels or spawning. A server older than this field ignores it, as proto3 does any unknown field, so a client can only count on no_tunnels, no_spawn or a narrower network being enforced by a server new enough to know commands.
  • Network: commands only reach it through network_config.child_network. There’s none without it.
  • Limits: resource_limits.max_child_host_bytes bounds their arguments and environments, under --max-child-host-bytes, and resource_limits.max_child_memory_bytes the memory they hold together, under --max-child-memory-bytes.
  • Results: ExecuteResult.exit_code is the script’s exit status. Trace events report each command as process_start and process_end, with pid and exit_code; a command spawned by another command carries its spawner’s pid as ppid.
  • Sessions: persist_state and state_snapshot carry the shell’s variables and functions across requests, as for the other guests.

Environments

--environments <dir> (ERYX_ENVIRONMENTS) serves the environments in dir, one per subdirectory, each packed with eryx-precompile env pack. A request mounts one read-only by its manifest name, in ExecuteRequest.environment, and imports its packages.

eryx-precompile env pack ./tools --name tools --out envs/tools
eryx-server --environments envs
  • At startup: each environment is loaded and its content hash checked. One that fails to load, one with an empty name, two with the same name, or one for a language the server doesn’t serve (not in --languages, or built without its cargo feature) stops the server. Symlinks to environments are followed, and entries starting with . are skipped, so a mounted volume works.
  • Requests: an empty environment mounts none. A name the server doesn’t have, or an environment for another language than the request’s, is INVALID_ARGUMENT.
  • Pools: each environment gets its own sandbox pool, sized by the pool flags like a language’s and created on its first request. The pool metrics have an environment label, empty for the languages’ own pools.
  • Replay: a callback journal is bound to the environment it was recorded under, by name and content hash, so repacking an environment (even under the same name) invalidates the journals recorded with the old one.

Request limits

Each request sets its own limits in resource_limits (and, for networking, network_config). A zero field takes the default documented in the proto (30 s execution timeout, 10 s callback timeout, 128 MiB memory, 1000 callback invocations, unlimited fuel). The --max-* flags cap what a request can ask for: a value above its ceiling is clamped down to it, not rejected, so clients written for a more generous server keep working. Every ceiling must be greater than zero; the server refuses to start otherwise. The memory limit is enforced on the guest, so an allocation past it raises MemoryError inside Python.

Fuel is optional. Without --max-fuel, requests that set no max_fuel run with unlimited fuel, and the execution timeout (capped by --max-execution-timeout-ms) is what bounds CPU use. There is no fuel value that suits every workload, so set --max-fuel only if you need instruction-level bounds.

Health checks

The server implements the standard grpc.health.v1.Health service. Both the overall status (service "") and eryx.v1.Eryx report SERVING once the sandbox pool is warm, so Kubernetes’ built-in gRPC probes or grpc_health_probe work directly:

readinessProbe:
  grpc:
    port: 50051

During shutdown the listener closes, so new probes fail to connect.

Shutdown

On Unix, SIGTERM or SIGINT stops the gRPC listener and drains existing RPCs before the process exits. Active Python execution and callback replies can finish over their existing streams. Ctrl-C also initiates shutdown on other platforms.

Set the container or pod termination grace period to cover the request’s execution and callback deadlines, any pre-stop delay, and telemetry shutdown. The server does not impose an additional drain timeout. A forced kill or client disconnection can still interrupt execution; draining does not make an uncommitted result recoverable or permit replaying external actions.

The Execute RPC

The service exposes a single method:

service Eryx {
  rpc Execute(stream ClientMessage) returns (stream ServerMessage);
}

It is bidirectional streaming. A ClientMessage is either an ExecuteRequest or a CallbackResponse; a ServerMessage is a CallbackRequest, OutputEvent, TraceEvent, or ExecuteResult. The protocol for one execution is:

  1. The client sends an ExecuteRequest as the first message. This is the only ExecuteRequest on the stream — it configures the entire run.
  2. As the script runs, the server streams OutputEvent messages (stdout/stderr chunks) and, when enable_tracing is set, TraceEvent messages.
  3. When the Python code awaits a declared callback, the server sends a CallbackRequest carrying a unique request_id, the callback name, and the JSON-encoded arguments_json.
  4. The client handles the callback and replies with a CallbackResponse echoing the same request_id. Multiple callbacks can be in flight at once (e.g. from asyncio.gather), so responses are matched by request_id, not by order.
  5. When execution finishes, the server sends a single ExecuteResult and closes the stream.

If the client disconnects, the server cancels the in-flight execution, including CPU-bound code, and returns the sandbox to the pool promptly instead of waiting for timeouts. A client may instead half-close its side of the stream (e.g. grpc-go’s CloseSend()) and keep reading: execution then runs to completion, but any callback the script awaits after that fails immediately, since no response can arrive.

Configuring a request

ExecuteRequest mirrors the sandbox configuration available in the Rust API. Each knob maps to a feature documented elsewhere in this guide:

FieldDescription
codeThe Python source to execute (required).
callbacksCallback declarations (name, description, parameters) that become async functions in Python.
resource_limitsExecution timeout, callback timeout, memory cap, max callback count, fuel limit, and for the shell max_child_host_bytes and max_child_memory_bytes. Zero means “use the default”.
network_configNetworking policy. Absent disables networking entirely; present enables it with the configured host allow/block lists and timeouts. Its child_network gives a shell’s commands network through a proxy: MODE_INHERIT (this policy) or MODE_NARROW with narrow (only what both allow; narrow starts from the defaults, so it must repeat any allowed_networks, internal_hosts or blocked_* overrides children need); absent, they have none. Shell requests only. The request’s max_connections covers the guest’s connections and its children’s together. See External Commands.
secretsSecrets injected as environment variables with placeholder values; real values are substituted only in HTTP headers to allowed hosts. The shell exports the placeholders to its commands, and only their child_network proxy substitutes the real values; commands the server allows tunnels (--shell-command-tunnels) send placeholders as they are. With networking on, a secret that has no allowed_hosts of its own and no network_config.allowed_hosts to fall back on (e.g. under allow_all_hosts) is rejected with INVALID_ARGUMENT.
disable_stdout_scrub / disable_stderr_scrubTurn off placeholder scrubbing on stdout/stderr (scrubbing is on by default when secrets are present).
filesSupporting files written into the sandbox VFS — FILE_KIND_MODULE files go on sys.path, FILE_KIND_DATA files are readable but not importable.
persist_state / state_snapshotSession state: when persist_state is true the server snapshots state into ExecuteResult.state_snapshot; supplying state_snapshot restores it before execution.
enable_tracingStream TraceEvent messages for line/call/return/exception/callback events, and for the shell’s child processes (process_start/process_end, with pid, exit_code, and ppid for a nested child). context_json carries a callback_start’s arguments and a process_start’s {"args": [...]}, with secret placeholders replaced by [REDACTED]; context counts against the execution’s trace budget.
result_variable / scrub_resultCapture a result variable (default result) into ExecuteResult.result as JSON. scrub_result opts the result into placeholder scrubbing (off by default — the result is a programmatic side channel).
globalsData for the script: a JSON object, as a string, whose top-level keys become globals before the code runs (Python and JavaScript; the shell rejects it). See Globals.
callback_journalOpt into callback replay. See below.
language / allowed_commandsThe guest language (unset is Python). For the shell, allowed_commands narrows this request to some of the server’s commands: unset allows all, set with no names allows none, and other commands exit 127. The shell’s grep builtin and its nested sh/bash count as commands; other builtins and callbacks aren’t restricted. Setting it for another language is INVALID_ARGUMENT.
environmentThe name of one of the server’s --environments to mount (empty: none). It must be for the request’s language.
commandsShell only: per-command options for this request, by the server’s command names (CommandOptions). network gives that command’s children MODE_NONE, MODE_INHERIT (the request’s child_network) or MODE_NARROW (only what both narrow and the request’s allow, counted against both’s limits); no_tunnels and no_spawn turn off what the server’s --shell-command-tunnels and --shell-command-spawn grant. A command spawned by another gets its own options, not its caller’s, so pair a MODE_NONE or MODE_NARROW network with no_spawn to stop it reaching a command with more network. Options can only take away: a name the server doesn’t have, network for a command when child_network gives children none, or commands on another language is INVALID_ARGUMENT.

Globals

globals hands data to a script without editing its code. Send {"inputs": [1, 2], "args": {"verbose": true}} and the script reads inputs and args as ordinary globals (in JavaScript, properties of globalThis). The server parses the JSON in the guest, after its own preamble, so the code is passed through untouched: a Python script can still start with from __future__ import ..., leading JavaScript imports still work, line numbers in errors match the code, a nested "__proto__" key stays data, and big integers keep their exact value in Python.

  • Each key must match [A-Za-z_][A-Za-z0-9_]*, must not be a keyword of the language, and must not be a name the guest already has (a Python builtin or any __dunder__, a JavaScript global such as fetch or process) or the name a callback is installed under. Those, a value that isn’t a JSON object, or globals on a shell request are INVALID_ARGUMENT. Empty means no globals.
  • It isn’t scrubbed: printing a global prints its value. Put credentials in secrets, not here.
  • With persist_state, globals are saved in the snapshot like any other variable, and the next request’s globals overwrite those with the same names. In JavaScript that includes a restored let; a restored const can’t be overwritten, so the execution fails with a TypeError.
  • It counts towards the server’s message size limit like code.

Reading the result

ExecuteResult is the final message. Its key fields:

FieldDescription
successtrue only when the script ran to completion without an uncaught exception or sandbox failure.
stdout / stderrComplete captured output (scrubbed when scrubbing is on).
errorHuman-readable message for a sandbox failure. Empty for a script exception and on success — branch on failure_kind, not on this string.
failure_kindA FailureKind enum classifying why a run failed (see below).
result / result_errorThe captured result variable (JSON), or why capture failed.
statsDuration, callback count, peak memory, fuel consumed, and replayed_callbacks. Also filled in for failed runs (fuel is 0 for a suspended run).
state_snapshotPost-execution state, when persist_state was set.
state_skipped_globalsNames of the globals state_snapshot left out because they could not be serialized.
state_was_resetSet when restoring state_snapshot was interrupted (e.g. by the execution timeout), so the code ran on a fresh interpreter. The reason is in state_error.
callback_journalThe recorded replay journal, when the request opted in.
suspended / suspended_callbackSet when a callback suspended execution.
output_truncatedSet when output was dropped: stdout plus stderr went past the output cap.

Output cap

The server keeps and streams at most --max-output-bytes (16 MiB by default) of stdout plus stderr per execution. Output past the cap is dropped from both the OutputEvent stream and the final stdout/stderr. The stream that crossed the cap gets a [output truncated: exceeded N bytes] marker, and output_truncated is set. The script itself keeps running.

The sandbox also limits how much output one execution can stream: 16 MiB, with a small overhead charged per write, so a script making very many tiny writes can reach it before the server’s cap. Output past that limit is dropped too and output_truncated is set, but without a marker. That limit is why --max-output-bytes can’t be set above 16 MiB.

Failure classification

Rather than parsing the error string, branch on failure_kind:

FailureKindMeaning
FAILURE_KIND_UNSPECIFIEDSuccess — no failure.
FAILURE_KIND_SCRIPT_FAILEDThe script failed: it raised an uncaught exception (FAILURE_KIND_SCRIPT_EXCEPTION is a deprecated alias with the same number). The traceback is in stderr (CPython-style; JavaScript’s uncaught error and stack likewise) and error is empty.
FAILURE_KIND_TIMEOUTExceeded the configured wall-clock timeout.
FAILURE_KIND_FUEL_EXHAUSTEDExceeded the configured fuel (instruction) limit.
FAILURE_KIND_SANDBOX_ERRORInfrastructure failure: WASM trap, invalid input (e.g. NUL bytes in the code), session creation failure. Details in error.
FAILURE_KIND_CANCELLEDThe client disconnected before completion.
FAILURE_KIND_SUSPENDEDA callback requested suspension — an expected control outcome, not a failure. See Suspension.

This is the distinction between a script failure (the user’s code raised) and a sandbox failure (the machinery couldn’t run it), so a client can show a traceback to the user versus retrying or alerting.

Callback replay

The server implements callback replay — journaling each callback result during a run and replaying it on a subsequent run, so a re-run after a late failure doesn’t re-invoke callbacks that already succeeded. Over gRPC this is controlled entirely through the callback_journal field.

Presence-based opt-in

Journaling is opt-in by the presence of the callback_journal field, not by a boolean:

  • Field absent — no journaling, no replay. Execution behaves exactly as if the feature didn’t exist (backward-compatible).
  • Field present but empty (CallbackJournal{}) — journaling is on. The server records every callback invocation and returns the recorded journal in ExecuteResult.callback_journal. Nothing is replayed (there’s nothing to replay yet).
  • Field present with entries — replay is on. Recorded results are matched against live invocations and served from cache.

So a replay session is: send an empty CallbackJournal{} on the first run, persist the journal that comes back, and echo it on the next run.

The replay loop

On a replay run, callbacks are matched by name + canonicalized arguments, consumed FIFO per key. A matched callback returns its cached result instead of dispatching a CallbackRequest to the client. ExecuteStats.replayed_callbacks reports how many were served from cache.

The first invocation that doesn’t match a remaining cached entry — a miss — is treated as divergence: that call and everything after it run live for the rest of the execution. This divergence guard is what makes replaying a stored journal safe across an edited or non-deterministic script. The matching model, determinism caveats, and concurrency notes are covered in depth in the Callback Replay & Suspension guide.

Suspension

A callback can defer its work instead of returning a value or error. Over gRPC, the client signals this in its CallbackResponse:

  • Set outcome = CALLBACK_OUTCOME_SUSPEND.
  • Carry the opaque reason string in the error field of the result oneof.

When a callback suspends, the server halts the guest immediately (no further Python runs, no further callbacks dispatch) and the ExecuteResult reflects it:

  • suspended is true and suspended_callback carries the callback name, args_json, and reason.
  • failure_kind is FAILURE_KIND_SUSPENDED and success is false.
  • callback_journal holds the prefix journal of everything that completed before the suspension.

Branch on suspended first. Because the guest is halted, error/success will indicate a non-success — but that is the expected consequence of the suspend, not a real failure. To resume once the dependency is ready, send a new ExecuteRequest with the same code and the returned callback_journal: the completed prefix replays from cache and the previously-suspended callback re-runs live (it was never journaled), so the script continues past the suspension point.

Suspension works even without opting into replay (a client can reply CALLBACK_OUTCOME_SUSPEND on any run). In that case there’s no journal to record the prefix, so suspended and the reason are still reported, but there’s nothing to resume from.

Journal signing and the trust boundary

Replayed journal entries are returned to Python verbatim — the server does not re-execute the callback to validate them. A journal is therefore a trusted input: a crafted journal could inject arbitrary values into a script. Because the server hands a recorded journal back to the client (who echoes it on the next run), it must defend against tampering when that journal round-trips through storage or an intermediary.

The server signs every outgoing journal with HMAC-SHA256 (CallbackJournal.signature). The MAC covers the journal entries, the script code, the state_snapshot the run started from (when persist_state is set), the declared callback names, the environment’s name and content hash (when one is set), the request’s globals, and an expiry time (CallbackJournal.expires_at_unix_secs, --journal-ttl-secs after signing). A signature therefore binds a journal to the exact script, starting state, callback set, environment and globals that produced it. On an incoming replay request the server:

  • Verifies the signature against the request’s code, state_snapshot, callback names, environment and globals before matching, and checks the journal has not expired.
  • Rejects an unsigned non-empty, mis-signed, expired, or mismatched journal with FAILED_PRECONDITION before executing Python. A rejected replay never becomes a fresh run: completed callbacks may already have produced external effects.
  • Accepts an empty, unsigned journal to start a new journaling session. An empty journal that carries a signature must still pass verification.

To run an edited script, explicitly start a new execution without the old journal. To resume a suspended run, send the same code, callbacks, environment, globals and state_snapshot as the run that suspended, and echo the journal back unchanged (including expires_at_unix_secs). Journals signed by servers before this binding was added fail verification and must be discarded.

Configure the signing key explicitly so journals are portable:

# 32 bytes, hex-encoded (64 hex chars)
export ERYX_JOURNAL_SIGNING_KEY=$(openssl rand -hex 32)
eryx-server

All replicas must share the same key for journals to verify across instances. If no key is configured, the server generates a random ephemeral key and logs a warning — journals then fail verification after a restart or on another replica, and replay is rejected before execution.

Signing provides provenance and tamper detection; it does not (and cannot) stop a callback-answering client from choosing arbitrary values live — it always could. See Security: journals are a trusted input for the full discussion.

Transport security (TLS / mTLS)

By default the server listens over plaintext, which is appropriate for a trusted local network (e.g. a sidecar on the same host). To secure the transport:

  • Server TLS — provide --tls-cert and --tls-key (a PEM certificate chain and private key). Clients then connect over TLS.
  • Mutual TLS — additionally provide --tls-client-ca (a PEM CA bundle). The server then requires every client to present a certificate signed by one of those CAs and rejects connections that don’t.
# server TLS
eryx-server --tls-cert server.pem --tls-key server.key

# mutual TLS
eryx-server --tls-cert server.pem --tls-key server.key --tls-client-ca clients-ca.pem

This matters for secrets: a SecretConfig.value is transmitted in plaintext within the gRPC message, so the connection must be secured (TLS, mTLS, or a trusted local transport) to protect it in transit.

Observability

  • Metrics — a Prometheus exporter serves /metrics on --metrics-addr, exposing pool gauges (in-use/available/total/max), acquisition and creation counters, and execution counters/histograms.
  • Tracing — the server reads the W3C traceparent/tracestate headers from incoming gRPC metadata, so its spans become children of the caller’s trace. When a callback is dispatched, CallbackRequest.trace_context carries a traceparent so the client can link its callback-handling spans back to the server-side span.

Next Steps

Pre-compiling Runtimes

The eryx-precompile tool generates platform-specific pre-compiled runtimes that dramatically speed up sandbox creation. Instead of compiling WebAssembly at startup, sandboxes load pre-compiled native code directly.

Installation

Install from GitHub Releases using cargo binstall:

cargo binstall eryx-precompile

Or download a binary directly from the GitHub Releases page.

Quick Setup

For most users, the setup subcommand handles everything:

eryx-precompile setup

This will:

  1. Download runtime-python.wasm from the matching GitHub Release and check it against the release’s runtime-python.wasm.sha256
  2. Pre-compile it to native code for your platform
  3. Cache the result in ~/.cache/eryx/, with a checksum file next to it

Running setup again reuses the cached runtime only if it still matches its checksum, so an interrupted run is repaired by running it again.

After this one-time setup, cargo build with features = ["embedded"] finds the cached runtime automatically. The build uses it only if it still matches its checksum file and, on Unix, the file, its checksum file and the cache directory are owned by you and not writable by your group or others. Otherwise it prints a warning, falls back as if no cache existed, and running setup again fixes it. Inside an eryx checkout, a runtime built in the workspace (crates/eryx-runtime/runtime-<language>.cwasm, and likewise coreutils.cwasm and eryx-bundler.cwasm) comes before the cache, so the build embeds the runtime built from those sources rather than the released one.

You can also point to a specific file:

export ERYX_RUNTIME_CWASM=/path/to/runtime-python.cwasm

A file given through ERYX_RUNTIME_CWASM is embedded as is, without those checks, so only point it at a runtime you trust.

Setup Options

# Set up the JavaScript and shell runtimes as well as Python's
eryx-precompile setup --language python --language javascript --language shell

# Check the download against a known hash instead of the release's checksum file
eryx-precompile setup --sha256 <hex>

# Download from a mirror, or a local directory served over HTTP, instead of GitHub
eryx-precompile setup --release-url http://localhost:8000

# Verbose output for debugging
eryx-precompile setup --verbose

With --release-url, the URL must serve this eryx version’s assets: setup stamps what it downloads with its own version, so an older release’s assets would be cached as current. The .sha256 files come from the same URL as the downloads, so they catch corruption but not a hostile mirror; use one you trust. --sha256 pins only the language runtime: with --language shell, coreutils is always checked against the mirror’s checksum, so it is only as trustworthy as the mirror.

--language shell also sets up the shell’s embedded commands: it downloads coreutils.wasm, checks it against coreutils.wasm.sha256, and caches it as coreutils-v<version>-<arch>-<os>.cwasm. The shell feature turns on coreutils, which embeds them, so a build with features = ["embedded", "shell"] needs both. --sha256 only applies to the runtime; coreutils is always checked against its own checksum file.

--bundler sets up the JavaScript bundler that eryx’s env-pack feature embeds to pack environments: it downloads eryx-bundler.wasm, checks it against eryx-bundler.wasm.sha256, and caches it as eryx-bundler-v<version>-<arch>-<os>.cwasm, so a crates.io build with env-pack doesn’t need the bundler built from source. Alone (eryx-precompile setup --bundler) it sets up only the bundler; with --language, both.

A precompiled runtime only loads in the eryx version that built it, so setup always sets up its own version. To set up another, install the matching binary, for example cargo binstall [email protected].

Advanced: The compile Subcommand

For cross-compilation, custom CPU targets, or bundling packages into the runtime, use compile:

eryx-precompile compile [input.wasm] [OPTIONS]

The input is the component to compile. With --preinit for Python, compile builds from the Python runtime built into eryx-precompile instead, so it takes no input (one given is ignored) and needs -o.

Pre-initialization

Pre-initialization runs Python’s interpreter startup and captures the memory state, reducing session creation time from ~450ms to ~1-5ms:

eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib

--stdlib is optional: it defaults to the Python stdlib embedded in eryx-precompile, which matches its runtime.

To produce an architecture-independent .wasm (for later compilation on different targets):

eryx-precompile compile -o runtime-preinit.wasm \
  --preinit --stdlib ./python-stdlib --wasm-only

The JavaScript runtime pre-initializes too: it creates the QuickJS runtime and context and evaluates the eryx prelude, cutting a stateless execution from ~0.5ms to ~0.1ms. The embedded runtime-javascript.cwasm is built this way. It takes no stdlib, packages, imports, setup code or callbacks:

eryx-precompile compile runtime-javascript.wasm -o runtime-javascript.cwasm \
  --language javascript --preinit

CPU Target Selection

Control which CPU features the compiled runtime uses:

# Use host CPU features (default, fastest but not portable)
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm --target native

# AVX2/FMA — recommended for cloud VMs (Fly.io, AWS, GCP)
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm --target x86-64-v3

# Broad compatibility (~2008+ x86 CPUs)
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm --target x86-64-v2

# Baseline x86 (maximum compatibility)
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm --target x86-64

# Full target triple for cross-compilation
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm \
  --target aarch64-unknown-linux-gnu
TargetCPU FeaturesUse Case
nativeHost CPU (default)Local development
x86-64-v3AVX2, FMA, BMI1/2Cloud VMs (no AVX-512)
x86-64-v2SSE4.2, POPCNTOlder servers
x86-64Baseline SSE2Maximum compatibility
<triple>Native for target archCross-compilation

Bundling Packages

Bundle Python packages into the pre-compiled runtime so they’re instantly available without installation at runtime:

# Bundle a single package
eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package numpy-2.2.3-wasi.tar.gz --import numpy

# Bundle multiple packages
eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package jinja2-3.1.2-py3-none-any.whl \
  --package markupsafe-2.1.3-py3-none-any.whl \
  --import jinja2

# Use a site-packages directory
eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib \
  --site-packages ./my-site-packages --import jinja2

Supported package formats: .whl, .tar.gz, and directories. Native extensions (.so files) are detected and linked automatically.

The snapshot holds only the modules imported during pre-initialization. A sandbox running the runtime still needs the packages mounted at /site-packages for anything they import later (pandas’ describe() imports numpy.rec, for example): SandboxBuilder::with_site_packages in Rust, or --site-packages for the gRPC server.

Setup Code

Beyond importing modules, you can execute arbitrary Python code during pre-initialization. The resulting state (variables, objects, environments) is captured in the memory snapshot — each sandbox starts with that state in copy-on-write memory, preserving full isolation.

This is useful when your sandboxes all need the same expensive setup that doesn’t change between requests:

# Bake a Jinja2 SandboxedEnvironment with custom filters into the snapshot
eryx-precompile compile -o jinja2.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package jinja2.whl --package markupsafe.whl \
  --import jinja2 --import jinja2.sandbox \
  --setup-code "
from jinja2.sandbox import SandboxedEnvironment
env = SandboxedEnvironment()
"

# For longer setup scripts, use --setup-file
eryx-precompile compile -o jinja2.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package jinja2.whl --package markupsafe.whl \
  --import jinja2 \
  --setup-file setup.py

Each sandbox created from the resulting artifact starts with env already defined. Per-request code only needs to handle the request-specific work (deserializing data, compiling the template, rendering).

Callbacks

Registering callbacks on a sandbox installs a Python wrapper for each of them inside the guest. A persistent session pays for that once, but a fresh sandbox per request starts from the snapshot, and the snapshot only knows the callbacks it was taken with — none, by default — so every request re-runs the installation (a few milliseconds of Python for a handful of callbacks, more than the instantiation itself).

If the set of callbacks is fixed per deployment, declare it at pre-initialization and the wrappers are part of the snapshot. A sandbox that registers callbacks with the same names, descriptions and parameter schemas (in any order) then skips the installation; one that registers a different set still works, it just installs as before.

# callbacks.json: what the sandboxes will register at runtime
# [
#   {"name": "get_time", "description": "Current time", "parameters": {"type": "object", "properties": {}}},
#   {"name": "fetch", "description": "HTTP GET", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}}}
# ]
eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib \
  --callbacks callbacks.json

parameters defaults to {} when omitted. The schemas are compared as text, so list each schema’s keys (properties included) in the same order as the schema the host registers: that order is also the order positional arguments bind in. Setup code cannot invoke the callbacks: there is no host to answer them during pre-initialization. In Rust, pass PreInitOptions::callbacks (build the declarations with eryx::preinit::callback_declaration); in Python, pass callbacks= to SandboxFactory.

Verification

By default, compile verifies the output: a runtime by creating a test sandbox (with the same --site-packages or --package contents mounted, as a sandbox using it would have, so --verify-code can reach modules the snapshot didn’t import), and a command (no --language, a component exporting wasi:cli/run) by loading it as a shell sandbox would, which checks its version stamp and that it links. Verification is skipped for a target this machine can’t run. For a runtime you can add custom verification (--verify-code is Python, so a command refuses it):

# Verify that numpy actually works, not just imports
eryx-precompile compile -o numpy.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package numpy-wasi.tar.gz --import numpy \
  --verify-code "import numpy; print(numpy.array([1,2,3]).sum())"

# Skip verification (faster, use when you know the input is good)
eryx-precompile compile runtime-python.wasm -o runtime-python.cwasm --no-verify

Checking Shell Commands

commands inspect reads a .wasm command (it doesn’t compile it) and prints its WASI version, each interface it imports with whether shell children get it, its exports, and whether eryx can run it. It exits 1 if eryx can’t run the command, and 2 if the file can’t be inspected at all (unreadable, a .cwasm, or neither a component nor a WASI preview 1 module); with --json, that prints {"error": "..."}:

eryx-precompile commands inspect rg.wasm
eryx-precompile commands inspect --json rg.wasm

compile without --language runs the same check on a command (a component exporting wasi:cli/run) and refuses one eryx couldn’t run. See External Commands for what children get.

Commands from a Registry

eryx doesn’t fetch commands itself: get the .wasm with an OCI client, check it against your pinned digest, then check and precompile it. Commands are published as single-layer Wasm OCI artifacts, so wkg writes one straight to a file:

wkg oci pull ghcr.io/eryx-org/commands/eryx/rg:15.1.0-r.2 -o rg.wasm

With oras, fetch the layer by its digest. oras pull skips it, because the layer carries no file name, but oras blob fetch gets it and checks the digest:

oras blob fetch ghcr.io/eryx-org/commands/eryx/rg@sha256:<layer digest> --output rg.wasm

The pin is the digest of the .wasm itself, which is the manifest’s layer digest and what wkg.lock records. It isn’t the manifest digest that wkg oci push prints. Check it, then check and compile the command:

echo "<hex>  rg.wasm" | sha256sum -c
eryx-precompile commands inspect rg.wasm
eryx-precompile compile rg.wasm --output rg.cwasm

A Rust host can skip the separate steps: Command::load_cached(path, Some("sha256:<hex>")) checks the digest, refuses a command eryx can’t run, and compiles it once into eryx’s cache directory (commands/ under the first usable of $XDG_CACHE_HOME/eryx, the platform cache directory (~/.cache/eryx on Linux) and $TMPDIR/eryx-<uid>; with none usable, it compiles in memory and warns). Command::from_file_expecting(path, "sha256:<hex>") checks the digest without caching.

Upgrading to a New eryx Version

A precompiled runtime records the eryx version that built it and only loads in that version. Loading it in any other fails with an error naming both versions, so precompiled runtimes have to be rebuilt after every eryx upgrade, patch releases included.

An eryx built from a git checkout also records the hash of the guest’s sources (eryx-guest-python, eryx-guest-js or eryx-guest-shell, and the code and WIT they share) in each runtime it precompiles, and refuses a runtime built from other guest sources, with an error naming the language and its mise run precompile-runtime-<language> task. Between releases the version stays the same, so this is what catches a stale runtime in development. Builds from crates.io have no guest sources, so they only check the version.

The output of compile --preinit stores what it was built from after the component: its site-packages, imports, setup code, callback declarations, target and CPU feature level. upgrade rebuilds it with the installed eryx-precompile’s version, without the original packages or flags:

cargo binstall [email protected]
eryx-precompile upgrade numpy-runtime.cwasm -o numpy-runtime-0.13.0.cwasm

The output must be a new file: processes still on the old version may have the old file mapped, and keeping it lets you roll back. Pre-initialization uses the runtime built into eryx-precompile and its embedded stdlib, so upgrade needs no download.

Storing the build inputs adds about the compressed size of the packages to the file (around 9 MB for numpy, whose native extensions are most of it, and a few hundred bytes without packages). It adds nothing to memory use, because only the component is mapped. Pass --no-build-inputs to compile to write the bare component instead; upgrade then can’t rebuild it.

pyeryx’s saved factories are the same format, so upgrade rebuilds them too. pyeryx also has its own command, python -m eryx factory upgrade OLD NEW, and SandboxFactory.load(path, rebuild_if_incompatible=True).

Runtimes precompiled before eryx 0.13.0 don’t store their build inputs: build those once more with compile.

Common Recipes

Local Development (Rust)

# One-time setup
cargo binstall eryx-precompile
eryx-precompile setup

# Then in your project
cargo build --features embedded

Fly.io Deployment

# Pre-compile for x86-64-v3 (matches Fly.io hardware)
eryx-precompile compile -o runtime-python.cwasm \
  --preinit --stdlib ./python-stdlib \
  --target x86-64-v3

Two-stage Cross-compilation

Create an architecture-independent snapshot, then compile for each target:

# Stage 1: Pre-initialize (architecture-independent)
eryx-precompile compile -o runtime-preinit.wasm \
  --preinit --stdlib ./python-stdlib --wasm-only

# Stage 2: AOT compile for each target
eryx-precompile compile runtime-preinit.wasm -o runtime-x86.cwasm \
  --target x86-64-v3
eryx-precompile compile runtime-preinit.wasm -o runtime-arm.cwasm \
  --target aarch64-unknown-linux-gnu

Custom Runtime with Packages

# Build a runtime with numpy baked in
eryx-precompile compile -o numpy-runtime.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package numpy-2.2.3-wasi.tar.gz \
  --import numpy \
  --verify-code "import numpy; print(numpy.zeros((2,2)))"

Environment Variables for CPU Targeting

When using eryx as a library — from Python (pyeryx), Rust (Sandbox::embedded()), or JavaScript — the embedded runtime is compiled to native code at build time. By default it targets the host CPU, which may include instructions (e.g. AVX-512) that aren’t available on the machine where your application actually runs.

If the build machine has different CPU features from the deployment target, the sandbox will fail to initialize at runtime with an error like:

Compilation settings are not compatible with the native host

Set these environment variables at build time (when the .cwasm is generated) or at import time (when the library first loads its embedded runtime) to control which CPU features the compiled code uses:

ERYX_CPU_FEATURES

Choose an x86-64 microarchitecture level:

ValueCPU FeaturesUse Case
nativeHost CPU (default)Local development
x86-64-v3AVX2, FMA, BMI1/2Recommended for cloud VMs (Fly.io, AWS, GCP)
x86-64-v2SSE4.2, POPCNT, SSSE3Older servers (~2008+)
x86-64Baseline SSE2 onlyMaximum compatibility
x86-64-v4AVX-512Skylake-X and newer

Example with Python:

ERYX_CPU_FEATURES=x86-64-v3 python my_app.py

Example with Rust:

ERYX_CPU_FEATURES=x86-64-v3 cargo build --features embedded --release

ERYX_TARGET

For cross-compilation, specify a full target triple:

ERYX_TARGET=aarch64-unknown-linux-gnu cargo build --features embedded --release

ERYX_CRANELIFT_FLAGS

For fine-grained control over individual Cranelift compiler flags:

ERYX_CRANELIFT_FLAGS=has_avx512f=false,has_avx512bw=false cargo build --features embedded --release

Tip: For most deployments, ERYX_CPU_FEATURES=x86-64-v3 is the right choice. It covers all cloud VMs from the last decade while avoiding AVX-512 instructions that many virtualized environments don’t expose.

Cache Location

The setup command caches compiled runtimes at:

PlatformPath
Linux/macOS~/.cache/eryx/ (or $XDG_CACHE_HOME/eryx/)
Windows%USERPROFILE%\.cache\eryx\

Files are named runtime-{language}-v{version}-{arch}-{os}.cwasm. To force a re-download, delete the cached file and run setup again.

Next Steps

Performance Tuning

Most of the cost of a short Sandbox::execute() is not running Python. It is creating the WebAssembly instance the code runs on and tearing it down again: mapping the pre-initialized heap image, building a function reference for every entry in the runtime’s ~6k-entry function table, and, afterwards, resetting the memory slot. Running pass on a fresh instance takes about 1.3 ms on a fast workstation; the Python part of that is roughly 0.2 ms.

Eryx hides that cost in two ways, both on by default. This page explains what they do and the settings that tune them.

Every sandbox in a process runs on one shared wasmtime engine and one shared pool of warm instances, created the first time the process needs them. Their settings are read once, at that point, so set them in the environment of the process that embeds eryx (for pyeryx, the Python process), or from code before the first sandbox is created. Like rayon’s build_global, this configures the process-wide instance; it cannot be changed afterwards:

eryx::configure_shared_engine(
    eryx::SharedEngineConfig::default()
        .with_warm_instances(4)
        .with_pool_instances(256),
)?;
eryx.configure_shared_engine(warm_instances=4, pool_instances=256)

Every variable below has a matching SharedEngineConfig::with_* method and configure_shared_engine keyword argument (ERYX_POOL_INSTANCES is with_pool_instances / pool_instances, and so on). An explicit setting takes precedence over its variable; anything left unset still falls back to the environment. configure_shared_engine fails if a setting is invalid, if it was already called, or once a sandbox has been created. Per-sandbox engines with their own settings are not supported yet; the “shared” naming leaves room for an explicit engine handle later.

Warm instances

After every stateless execution, a background task instantiates a replacement store for the same runtime and parks it in a process-wide pool. The next execute() takes it instead of instantiating, and the used store is dropped on the background task too. Every execution still runs on an instance that has never run user code, so isolation is unchanged; only the timing moves.

The pool is keyed by runtime component rather than by Sandbox, so the common pattern of building a short-lived sandbox per request (for example SandboxFactory.create_sandbox() from Python) benefits from it: the first request in a process pays for instantiation, later ones do not. Executors that load their own copy of a component (from_file, from_binary, with_precompiled_file) each get a separate entry, so the pool keeps warm instances for at most four components and evicts the least recently used. Loading a new copy of the component for every request (for example SandboxFactory(cache=False)) defeats the pool: each execution warms an instance for a component that is never used again. Load the component once and reuse it.

VariableDefaultEffect
ERYX_WARM_INSTANCES1Instances to keep ready per runtime. 0 disables the pool.

One ready instance is enough for a caller that executes serially. If several tasks execute concurrently, raise it towards that concurrency; each ready instance costs about the resident size of the pre-initialized heap (tens of megabytes, mostly shared copy-on-write pages) plus wasmtime’s per-instance metadata.

The pool is only used on a multi-threaded Tokio runtime, where the background work actually runs in parallel. On a current-thread runtime it would only add to the next request’s latency, so it stays off. Executor::warm_instances_ready() reports how many instances are waiting for that executor’s runtime.

Instance allocation

Wasmtime can allocate each instance’s linear memory, tables, and async stacks on demand (a fresh mmap per instance) or from a pool of pre-reserved slots. Eryx uses the pooling allocator (except on Windows, see below): a slot that has just been released is reused by the next instance, so its pages are still mapped, and on Linux only the pages the previous instance dirtied are reset.

VariableDefaultEffect
ERYX_ALLOCATORpooling (on-demand on Windows)pooling or on-demand.
ERYX_POOL_INSTANCES1000Maximum sandbox instances alive at once. Every running execute(), every live session and every warm instance holds one, and a finished execution keeps its slot until the background task drops it; instantiation fails once the pool is full. Allow at least concurrency + 2 × ERYX_WARM_INSTANCES per component. A shell’s external commands don’t count: they run on an on-demand engine of their own.
ERYX_POOL_KEEP_RESIDENT_MB64How much of each linear memory to keep mapped between uses.
ERYX_POOL_PAGEMAP_SCAN11: reset only dirty pages (Linux 6.7+, via PAGEMAP_SCAN). 0: memcpy the whole keep-resident budget instead, which trades a larger copy for fewer page faults on the next execution.
ERYX_POOL_RELEASE_INTERVAL_SECS30Every this many seconds, return the memory kept resident for unused slots to the OS. 0 keeps it resident indefinitely.

Keeping memory resident is what makes slot reuse cheap, but after a burst of concurrent executions every slot the burst used stays resident. The periodic release returns that memory. Live instances, including warm ones, are not affected; a released slot that is used again pays for its page faults once, so under steady traffic the cost is one slower instantiation per slot per interval.

On Windows the default is on-demand: Windows has no overcommit, and wasmtime commits the whole table pool when the engine is created, which at the default limits is gigabytes of commit charge per process.

The pool reserves virtual address space for every slot up front — several terabytes with the defaults, which is normal for wasmtime deployments but can be refused by a host with a low ulimit -v. If the pool cannot be created, eryx logs a warning and falls back to on-demand allocation; execution behaves identically either way.

If a process holds more than ERYX_POOL_INSTANCES sessions open at once, raise the limit or switch to on-demand. Note that the choice of allocator does not affect precompiled .cwasm artifacts; only compilation settings do.

Measuring

crates/eryx/examples/profile_stateless.rs times the stateless path and is a convenient target for perf or samply:

cargo build --example profile_stateless --features embedded --release
# 2000 executions of `pass`, with a 2 ms gap between them so the background
# replenishment gets the same chance it has between real requests
./target/release/examples/profile_stateless 2000 pass 2000
ERYX_WARM_INSTANCES=0 ./target/release/examples/profile_stateless 2000 pass 2000

The criterion benchmarks (cargo bench --package eryx --features embedded) cover the same paths with callbacks registered.

Command-Line Interface

Eryx includes a CLI for running Python code in a sandbox directly from the terminal. It supports an interactive REPL, script execution, inline code, and stdin.

Installation

The CLI is included with the Python package:

pip install pyeryx

Or run without installing using uvx:

uvx --with pyeryx eryx

Usage Modes

Interactive REPL

Start an interactive session with persistent state:

python -m eryx
Eryx 0.3.1 (sandbox REPL)
Type "exit()" or Ctrl-D to quit.
>>> x = 42
>>> print(x * 2)
84
>>> exit()

The REPL uses a Session under the hood, so variables, functions, and classes persist between inputs. Multi-line blocks (functions, classes, loops) are detected automatically.

Execute a Script File

python -m eryx script.py

Execute Inline Code

python -m eryx -c 'print("Hello from the sandbox!")'

Read from Stdin

echo 'print(1 + 1)' | python -m eryx -

Or pipe without the - flag:

echo 'import sys; print(sys.version)' | python -m eryx

Flags

Resource Limits

FlagDescriptionDefault
--timeout MSExecution timeout in milliseconds30000
--max-memory BYTESMaximum memory in bytes128MB
python -m eryx --timeout 5000 -c 'print("quick")'
python -m eryx --max-memory 67108864 script.py   # 64MB limit

Runtime

FlagDescription
-s, --precompiled PATHRun in the precompiled Python runtime (.cwasm) at PATH instead of the built-in one

Build one with packages baked in using eryx-precompile, then run code in it. Only use files you trust: a precompiled runtime is native code.

eryx-precompile compile -o numpy.cwasm \
  --preinit --stdlib ./python-stdlib \
  --package numpy-2.2.3-wasi.tar.gz --import numpy

python -m eryx --precompiled numpy.cwasm -c 'import numpy; print(numpy.array([1, 2, 3]).sum())'

Networking

FlagDescription
--netAllow access to any public host
--allow-host PATTERNAllow access only to hosts matching pattern (repeatable, implies --net)

Either way, localhost and private networks stay blocked (the default NetConfig blocks).

python -m eryx --net -c 'import urllib.request; ...'
python -m eryx --allow-host '*.example.com' -c '...'

Filesystem

FlagDescription
-v SRC:DST[:ro]Mount host directory SRC at sandbox path DST
# Mount current directory read-write
python -m eryx -v $(pwd):/mnt/data script.py

# Mount read-only
python -m eryx -v /path/to/files:/input:ro -c 'print(open("/input/data.txt").read())'

MCP (Model Context Protocol)

FlagDescription
--mcpEnable MCP server integration (auto-discovers from user-wide IDE configs)
--mcp-projectAlso read MCP configs in the current directory (implies --mcp)
--mcp-config PATHPath to MCP config file (implies --mcp, can be repeated)
# Auto-discover MCP servers from user-wide Claude, Cursor, Zed, Windsurf, Codex, Gemini configs
python -m eryx --mcp -c 'r = await mcp["github"].search_repos(query="test"); print(r)'

# Also use .mcp.json, .vscode/mcp.json, ... in the current (trusted) directory
python -m eryx --mcp-project -c '...'

# Use a specific config file
python -m eryx --mcp-config .mcp.json -c '...'

See MCP Integration for details on config discovery and supported IDEs.

Other

FlagDescription
--versionPrint version and exit
-h, --helpShow help message

Subcommands

eryx serve

Start an MCP server that exposes the sandbox as a run_python tool:

eryx serve                              # basic sandbox server
eryx serve --timeout 60000 --net        # with options
eryx serve --mcp                        # with inner MCP tools

The serve subcommand accepts all the same sandbox flags listed above. See MCP Server for full documentation.

Examples

# Quick one-liner
uvx --with pyeryx eryx -c 'import sys; print(f"Python {sys.version}")'

# Run a script with timeout
uvx --with pyeryx eryx --timeout 5000 script.py

# Network-enabled execution
uvx --with pyeryx eryx --allow-host 'httpbin.org' -c '
import urllib.request
resp = urllib.request.urlopen("https://httpbin.org/get")
print(resp.read().decode())
'

# Mount a local directory (read-only)
uvx --with pyeryx eryx -v ./data:/data:ro -c '
import os
print(os.listdir("/data"))
'

Next Steps

Rust API Reference

For detailed API documentation, see the self-hosted documentation.

Latest Version

Key Types

  • Sandbox - Main sandbox type for executing Python code
  • TypedCallback - Strongly-typed callback trait
  • InProcessSession - Stateful sessions with persistent Python state
  • ResourceLimits - Resource limit configuration
  • NetConfig - Network configuration
  • SandboxPool - Managed pool of sandbox instances

Python API Reference

The Python bindings provide a Pythonic interface to Eryx functionality.

For detailed API documentation, see docs.eryx.run/latest/api/python/.

Core Classes

  • Sandbox - Main class for isolated Python execution
  • Session - Persistent state across executions
  • SandboxFactory - Pre-initialize sandboxes with packages
  • SandboxPool - Bounded pool of warm sandboxes for concurrent execution
  • PooledSandbox - A sandbox lease from a pool (context manager)
  • PoolStats - Pool usage statistics
  • VfsStorage - Virtual filesystem storage
  • ResourceLimits - Configure execution constraints
  • NetConfig - Configure network access
  • CallbackRegistry - Decorator-based callback registration
  • CancelToken - Cancel an execution from any thread
  • ReplayOutcome - Result of Sandbox.execute_with_journal() (result/error, journal, suspension)
  • SuspendedCallback - Details of a callback that suspended execution
  • SuspendCallback - Exception a callback raises to suspend execution

Installation

pip install pyeryx

Alternatively, see the PyPI package page.

Returning a structured result

Assign a variable named result in the executed script and Eryx JSON-serializes it and returns it on ExecuteResult.result — a structured channel separate from stdout:

import eryx

sandbox = eryx.Sandbox()
out = sandbox.execute('result = {"answer": 42, "items": [1, 2, 3]}')
print(out.result)  # {'answer': 42, 'items': [1, 2, 3]}

If the value is not JSON-serializable, result is None and result_error explains why — execution still succeeds. Pass result_variable="name" to Sandbox(...) or Session(...) to capture a different variable name.

Async execution and cancellation

execute_async() on Sandbox, Session and PooledSandbox returns an awaitable, so the asyncio event loop keeps running while code executes. Concurrent calls on one Session run one at a time, in call order.

Pass cancel=CancelToken() to execute() or execute_async() and call token.cancel() from any thread to stop the run; it raises eryx.CancelledError. Cancelling the asyncio task also stops the run, and Ctrl-C stops a blocking execute() and raises KeyboardInterrupt. A cancelled Session run loses its Python state, and the next call starts from a fresh interpreter.

import asyncio
import eryx

async def main():
    token = eryx.CancelToken()
    asyncio.get_running_loop().call_later(1.0, token.cancel)
    try:
        await eryx.Sandbox().execute_async("while True: pass", cancel=token)
    except eryx.CancelledError:
        print("cancelled")

asyncio.run(main())

Callback replay & suspension

Sandbox.execute_with_journal(code) records every callback result in a journal (a JSON-compatible dict). Pass that journal back as execute_with_journal(code, journal=...) and callbacks that match it return the recorded result instead of running live. A callback can raise eryx.SuspendCallback(reason) to halt the run; resume later by replaying the journal from the suspended run. Session and pooled sandboxes have the same method.

import eryx

def approve(item: str):
    if not is_approved(item):
        raise eryx.SuspendCallback(f"awaiting approval for {item}")
    return True

callbacks = [{"name": "fetch", "fn": fetch}, {"name": "approve", "fn": approve}]
sandbox = eryx.Sandbox(callbacks=callbacks)
outcome = sandbox.execute_with_journal(code)

if outcome.suspended:
    # Later, once approved: completed callbacks replay, `approve` runs live.
    outcome = sandbox.execute_with_journal(code, journal=outcome.journal)

execute_with_journal does not raise for execution failures; check outcome.error. Journals are a trusted input (replayed values reach the sandbox verbatim), and calls that are not replayed — including the suspended call on resume — run live again, so side-effecting callbacks must be idempotent. See the Callback Replay & Suspension guide.

JavaScript API

Eryx provides JavaScript bindings via WebAssembly, allowing you to run sandboxed Python code in browsers and Node.js.

Installation

npm install @eryx-org/eryx

Requirement: WebAssembly JSPI (JavaScript Promise Integration) support is required. In Node.js 24–25, use --experimental-wasm-jspi (on by default in Node.js 26+). In browsers, Chrome 133+ and Edge 133+ are supported.

Sandbox Class

The Sandbox class provides an isolated Python environment. Each instance is its own WebAssembly instance, with its own interpreter, filesystem, network connections, callback handlers and journal, and keeps its state across execute() calls. The compiled code is shared, but each instance has its own memory (about 20 MB idle on Node.js 24). Call sandbox.close() (or declare it with using) when you’re done: it closes the sandbox’s connections, terminates its Worker if it has one, and makes later calls reject. A sandbox that is only dropped is freed whenever the garbage collector gets to it.

import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();

new Sandbox(options) takes the sandbox’s callbacks, and can give it its own traceHandler and outputHandler. Any it omits follow the module-wide defaults set by the handler functions.

timeoutMs runs the sandbox in its own Worker (worker_threads in Node.js) and terminates it when a call takes longer. The call rejects with a TimeoutError (executeWithJournal() reports it as outcome.error), and the sandbox starts over with fresh Python state. Without it, nothing interrupts a call that never finishes. The Worker costs about 70 MB on top of the sandbox’s memory.

const sandbox = new Sandbox({ timeoutMs: 5_000 });
await sandbox.execute("while True: pass"); // rejects with TimeoutError

execute(code: string): Promise<ExecuteResult>

Execute Python code in the sandbox. Variables and imports persist across calls.

await sandbox.execute('x = 42');
const result = await sandbox.execute('print(x + 1)');
console.log(result.stdout);  // "43\n"
console.log(result.stderr);  // ""

Returns: ExecuteResult with stdout and stderr string fields, plus an optional result (the script’s result variable parsed from JSON) and resultError (set when the value could not be JSON-serialized).

Throws: If the Python code raises an unhandled exception.

Returning a structured result

Assign a variable named result and it is JSON-serialized and returned as result.result — a structured channel separate from stdout:

const result = await sandbox.execute('result = {"answer": 42, "items": [1, 2, 3]}');
console.log(result.result); // { answer: 42, items: [ 1, 2, 3 ] }

If the value is not JSON-serializable, result.result is undefined and result.resultError explains why. Use sandbox.setResultVariable("name") to capture a different variable name.

executeWithJournal(code: string, options?): Promise<ReplayOutcome>

Execute code while journaling callback results, so a later run can replay them instead of re-invoking the callbacks. Pass a previously recorded journal as options.journal to replay it. A callback handler can throw SuspendCallback to halt execution. See Callback Replay & Suspension.

import { Sandbox, SuspendCallback } from "@eryx-org/eryx";

const first = await sandbox.executeWithJournal(code);
// Later, with the same code:
const second = await sandbox.executeWithJournal(code, { journal: first.journal });
console.log(second.replayedCallbacks);

ReplayOutcome has result (the ExecuteResult, or undefined on failure), error, journal, replayedCallbacks, and suspended ({ name, argsJson, reason } if a callback suspended). It never rejects for script failures — check suspended, then error.

journal is always present. It is a JSON string in the same format as the Rust CallbackJournal; store it and pass it back unmodified, since results are kept as their exact JSON text.

A top-level executeWithJournal(code, options?) convenience function is also exported.

snapshotState(): Promise<StateSnapshot>

Capture a snapshot of the current Python session state. Returns { data, skippedGlobals }: the serialized state (a Uint8Array) that can be restored later, and the names of the globals left out because they could not be serialized.

await sandbox.execute('x = 42');
const snapshot = await sandbox.snapshotState();
console.log(snapshot.skippedGlobals);  // []
// Save snapshot.data for later use

restoreState(snapshot: StateSnapshot | Uint8Array): Promise<void>

Restore Python session state from a previously captured snapshot, or from its data.

await sandbox.restoreState(snapshot);
const result = await sandbox.execute('print(x)');
console.log(result.stdout);  // "42\n"

clearState(): Promise<void>

Clear all persistent state from the session.

await sandbox.execute('x = 42');
await sandbox.clearState();
// x is no longer defined

Convenience Function

execute(code: string): Promise<ExecuteResult>

Execute Python code in a default sandbox, created on first use, whose state persists across calls. It shares nothing with Sandbox instances you create. executeWithJournal() and setResultVariable() also have module-level versions that use the same default sandbox.

import { execute } from "@eryx-org/eryx";

const result = await execute('print("Hello!")');
console.log(result.stdout);  // "Hello!\n"

Handler Functions

Callbacks

A Sandbox’s callbacks option is an object of functions by name, which the code can await with keyword arguments. Each is a function of those arguments, or { handler, description } (what list_callbacks() shows), and returns JSON. If it throws, the code gets a RuntimeError with its message. It’s the same option as eryx.run’s client, @eryx-org/eryx-run.

import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox({
  callbacks: {
    get_time: { description: "Returns current timestamp", handler: () => ({ timestamp: Date.now() }) },
  },
});
await sandbox.execute(`print((await get_time())["timestamp"])`);

setOutputHandler(handler)

Set the default handler for streaming stdout/stderr output in real-time.

import { setOutputHandler } from "@eryx-org/eryx";

setOutputHandler((stream, data) => {
  // stream: 0 = stdout, 1 = stderr
  if (stream === 0) {
    console.log("[stdout]", data);
  } else {
    console.error("[stderr]", data);
  }
});

Note: Output handlers have the same jco 1.16.1 limitation as callback handlers.

setTraceHandler(handler)

Set the default handler for execution trace events.

import { setTraceHandler } from "@eryx-org/eryx";

setTraceHandler((lineno, eventJson, contextJson) => {
  const event = JSON.parse(eventJson);
  console.log(`Line ${lineno}: ${event.type}`);
});

Note: Trace handlers have the same jco 1.16.1 limitation as callback handlers.

Browser Usage

In browsers, import the package normally. The WASM binary and Python stdlib are loaded automatically.

<script type="module">
import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();
const result = await sandbox.execute('print("Hello from the browser!")');
document.getElementById("output").textContent = result.stdout;
</script>

A live demo is available at eryx.bsull.dev.

Browser Requirements

  • Chrome 133+ or Edge 133+ (WebAssembly JSPI support)
  • The stdlib tarball (python-stdlib.tar.gz) is fetched and decompressed on first load

Node.js Usage

Node.js 24–25 require the --experimental-wasm-jspi flag (Node.js 26+ enables JSPI by default):

node --experimental-wasm-jspi your-script.mjs
import { Sandbox } from "@eryx-org/eryx";

const sandbox = new Sandbox();
const result = await sandbox.execute(`
import json
data = {"message": "Hello from Node.js!"}
print(json.dumps(data, indent=2))
`);
console.log(result.stdout);

ExecuteResult

interface ExecuteResult {
  /** Captured standard output */
  stdout: string;
  /** Captured standard error */
  stderr: string;
}

Next Steps

Environment Format

An environment is a directory that eryx’s pack writes and Environment::load reads. The two may be different eryx versions, for example when a service packs environments and servers of another version mount them. This page is the contract between them.

Layout

<environment>/
  eryx-environment.json   the manifest
  <lockfile>              optional: what was installed (package-lock.json, pnpm-lock.yaml)
  modules/                the content directory: what sandboxes import

Sandboxes see the directory read-only at /eryx/environment.

The manifest

eryx-environment.json is a JSON object. Fields marked identity are covered by the hash, so changing any of them changes the environment. Informational fields aren’t: they record how it was made.

FieldKindMeaning
formatidentityAlways "eryx-environment"
formatVersionidentityThe format version, 1 today
nameidentityThe environment’s name
languageidentity"javascript", "python" or "shell". A sandbox for another language refuses it
content.diridentityThe content directory, relative to the root ("modules")
exportsidentityWhat’s importable: specifier → file, relative to the root and inside content.dir ("date-fns/format": "modules/date-fns__format.js")
the files in content.diridentityEvery regular file’s path and bytes
content.hash—The identity hash, below. Pin it with Environment::load_expecting
content.files, content.bytesinformationalThe content directory’s file count and size
inputsinformationalpackages, and optionally registry, lockfile (its file name in the environment) and lockfileHash
builderinformationaleryx (the version that wrote it) and tools (e.g. "bundler": "rolldown 1.3.2")
warningsinformationalWhat the build warned about, if anything

Every informational field is optional: a writer may leave out inputs, builder, warnings, content.files or content.bytes (or any field inside inputs and builder), and readers fill in empty values.

Paths use /, are relative, and must stay inside the environment. The content directory may only hold regular files and directories: a symlink is refused.

The identity hash

content.hash is sha256-<hex> of, in order:

  1. Each of "eryx-environment", the formatVersion in decimal, name, language and content.dir, as UTF-8, each followed by a 0 byte.
  2. For each export in byte order of its specifier: the specifier, a 0 byte, its path, a 0 byte.
  3. files, a 0 byte, then the content hash as a sha256-<hex> string.

The content hash is SHA-256 over every regular file under content.dir, in byte order of its /-separated path relative to content.dir. For each file it takes the path, a 0 byte, the file’s length as a little-endian u64, and its bytes.

Environment::load recomputes it, and refuses an environment whose files or identity fields no longer match. eryx’s tests pin the hash of a fixed environment, so it can’t change by accident.

What the JavaScript guest reads

The guest reads only exports and content.hash from the manifest. A bare specifier in exports is importable, and its modules import each other’s shared chunks by relative path. How chunks are named isn’t part of the format: everything goes through exports.

Versioning

  • formatVersion changes when an identity field, the hash, or anything the loader needs changes. A reader refuses a version it doesn’t know, naming both versions.
  • New informational fields are added without a new version. Readers ignore fields they don’t know.
  • A new format version is read before it’s written: an eryx release that reads both the old and the new version ships first, and builders move to writing the new one after the servers that load their environments have it. builder.eryx says which eryx wrote an environment.

Contributing

Contributions are welcome! Please see the main GitHub repository for contribution guidelines.

Development Setup

This project uses mise for tooling:

mise install
mise run setup  # Build Wasm + precompile (one-time)

Running Tests

mise run test       # Run tests with embedded Wasm
mise run test-all   # Run tests with all features

Code Quality

mise run fmt        # Format code
mise run lint       # Run clippy lints
mise run ci         # Run all CI checks

License

MIT OR Apache-2.0