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

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