Skip to main content
This guide covers using Session to manage multiple sandboxes with shared configuration. It’s for client developers who need to coordinate groups of sandboxes, apply common defaults, and ensure consistent cleanup across a workload.

Choose authentication

These examples run on serverless capacity unless a section specifies CKS. Choose the credential for the account that owns your sandboxes. See Choose and get credentials to obtain a key or token. Run the installation commands in an active Python virtual environment. Save the Python code from your credential tab as sandbox_auth.py beside the Python scripts you run from this page. It stores the authentication choice, not your credential. The examples import AUTH from that file and pass it explicitly to each new sandbox or session.
Use your Forge API key through the SDK’s W&B authentication strategy:
sandbox_auth.py
For CKS placement, choose the CoreWeave token, enable a runner, and set placement_mode="cks" on sandbox creation or in SandboxDefaults. Creating a session with auth=AUTH also authenticates the sandboxes it owns. Keep the same credential when reconnecting, listing, or cleaning up sandboxes.

Session overview

A Session provides:
  • Shared default configuration for all sandboxes.
  • Automatic cleanup when the session closes.
  • A scope for the @session.function() decorator.

Basic usage

Create sandboxes

The following sections describe how to create sandboxes through a session and override session defaults.

session.sandbox()

Creates a sandbox with session defaults. The sandbox doesn’t start until first use:
For explicit control over when the start RPC fires:

Override defaults

Pass additional arguments to override session defaults:
See the Sandbox configuration guide for all available options.

Multiple sandbox management

Sessions work well for managing sandbox pools:
To prepare sandboxes before requests arrive, see Implement a warm pool. The recipe maintains a buffer of ready sandboxes, gives each workload a separate sandbox, and replenishes the buffer as workloads claim them.

Session lifecycle

The following sections describe how to close a session, what close() does, and how to handle errors.

Manual close

When you don’t use a context manager, close a session explicitly:

What close() does

Calling close() performs the following actions:
  1. Stops all sandboxes created through or adopted by the session.
  2. Waits for cleanup to complete.
  3. Returns OperationRef[None].

Error handling

Sessions clean up even if exceptions occur:

Adopt external sandboxes

Bring sandboxes created outside the session under session management:

Session properties

Inspect session state with built-in properties such as sandbox_count:

When to use sessions

Without sessions

You don’t need sessions for single sandboxes:
Last modified on October 23, 2026