This guide covers resource management and cleanup strategies for sandboxes. Reliable cleanup prevents orphaned sandboxes after a script exits, which keeps costs predictable and avoids unintentional compute resource usage. The patterns here apply to scripts that create one or many sandboxes, with or without an explicit session.
Automatic cleanup
Automatic cleanup ties a sandbox’s lifetime to a Python construct (a context manager or the running process) so the SDK releases resources without explicit stop() calls.
Context managers (recommended)
Context managers are the recommended pattern because they guarantee cleanup even if the enclosed code raises an exception. The SDK stops sandboxes when the context exits:
Sessions clean up all their sandboxes:
Global cleanup handlers
For cases where a context manager isn’t practical, the SDK registers cleanup handlers that run when the process terminates:
Manual cleanup
Use manual cleanup when you need explicit control over when to release a sandbox or session. Manual cleanup lets you pass stop options or coordinate cleanup across long-running code.
Sandbox stop()
Session close()
Batch cleanup
Orphan management
Orphans are sandboxes that outlive the process that created them. The following sections describe how to make orphans easy to find, how to query for them, and how to bring them back under managed cleanup.
Tagging for discovery
The SDK’s automatic cleanup handlers prevent most orphans. Sandboxes can keep running after forced shutdowns (kill -9), network failures, or when you create sandboxes outside of sessions and context managers. Use tags to make any orphans discoverable later.
Good tagging practices:
- Project or application name (
my-project)
- Job or run identifier (
batch-job-123, run-2024-01-15)
- Environment (
dev, staging, prod)
Find orphaned sandboxes
Query by tags to find sandboxes from previous runs:
Session adoption
Adopting an orphan attaches it to a session so the session governs its lifetime. The orphan then receives the same automatic cleanup guarantees as newly created sandboxes:
Delete by ID
When you already know a sandbox’s ID, you can delete it directly without listing or adopting it first:
Last modified on May 29, 2026