Skip to main content
This page shows how to terminate sandboxes reliably so resources are released when your code finishes or exits unexpectedly. Use these patterns to avoid leaving orphaned sandboxes running after your script completes.

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.

Clean up sandboxes

Use a context manager to handle cleanup automatically:
For sandboxes created without a context manager, call .stop() explicitly:
As a safety net, the SDK registers global cleanup handlers for atexit and signals (Ctrl+C, SIGTERM). These handlers stop sandboxes that belong to a Session, so session-managed sandboxes stop even on unexpected exits. A sandbox created directly with Sandbox.run() isn’t part of a session, so it can keep running after the process exits. It still ends when its ordinary main command exits successfully, you stop it, its maximum lifetime expires, or it fails. A nonzero main-command exit can trigger automatic restarts before failure. See Main command lifetime for lifecycle end conditions and Compose exceptions. Set up Claude Code with the Sandboxes SDK shows a workflow that keeps a sandbox running after the client exits. For batch cleanup, tagging strategies, and orphan recovery, see the Cleanup patterns guide.
Last modified on November 6, 2026