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

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