Skip to main content

StrataBox Python SDK (stratabox)

Unified async & sync Python SDK for StrataBox — high-density, composable elastic sandboxes for agentic RL and large-scale evaluation.

Python 3.11+ Typing: PEP 561 License: MIT OR Apache-2.0 CI

English | 简体中文


Table of Contents


Features

  • Async + Sync API Parity & Zero-Config Startup:
    • StrataBoxClient() and SyncStrataBoxClient() resolve STRATABOX_ENDPOINT / STRATABOX_TOKEN automatically (defaulting to http://127.0.0.1:18080 and stratabox-root-token) — zero boilerplate arguments required.
    • stratabox.local_cluster() boots and tears down a managed local stratabox-daemon cluster with ephemeral port allocation (127.0.0.1:0) via either async with or with.
    • StrataBoxClient built on httpx.AsyncClient with dual awaitable + async context-manager handles (async with client.run_container(...) as sbx: — no redundant await, while remaining 100% compatible with await and async with await).
    • SyncStrataBoxClient backed by a private daemon event-loop thread so synchronous reward functions, Jupyter Notebooks, TRL, and OpenRLHF work cleanly even inside an already-running asyncio loop.
  • All Four StrataBox Execution Backends:
    • FnCall (run_fncall) for < 5 ms warm-pool stateless invocations.
    • Container (run_container), MicroVm (run_microvm), and FullVm (run_vm) — or switch backends seamlessly with unified run_sandbox(StrataBoxSandboxRunArgs(backend=..., base_layer=..., init_dirs=[...])).
  • RL Rollout Group Orchestration (SandboxGroup & SyncSandboxGroup):
    • Provision homogeneous (count=G) or heterogeneous ([args_0, ...]) sandbox groups with bounded concurrency, strict index order preservation, run_shell_all() / write_file_all() / refresh_all() / pause_all() / resume_all() / stop_all(), and automatic rollback (cleanup_on_error=True).
  • Immutable Layer CRUD & Zero-Disk Streaming Upload (/v1/layers):
    • Upload local directories, .tar/.tar.gz archives, raw bytes (upload_layer), or zero-temp-file async/sync byte streams (upload_layer_stream(layer_id=..., source_stream=...)), plus layer_exists, get_layer, list_layers, and delete_layer.
  • Single-RPC Batch Filesystem, Tar Transfer & Upperdir Diff:
    • write_files, upload_tar, download_tar (with safe tar-slip / symlink-escape validation), and list_modified_files (added / modified / deleted / opaque_dir), alongside read_file, read_text, write_file, list_dir, stat_file, and delete_file.
  • Idle Auto-Pause & Transparent Auto-Resume:
    • Configure idle_auto_pause_ms on any run-args dataclass or invoke pause() manually; subsequent shell, file, stream, or HTTP RPCs transparently resume the sandbox with accurate physical memory reclamation telemetry (cgroup_reclaimed_bytes vs advised_vma_bytes).
  • Production Backoff & Type Safety:
    • Built-in equal-jitter exponential backoff for 429 / 503 (honoring Retry-After), high-concurrency connection pooling (max_connections=1024), trust_env=False (host proxy immunity), full PEP 561 typing (stratabox/py.typed), and typed exceptions mapped 1:1 from StrataBox wire error codes.

Installation

Package name on PyPI is stratabox; the import package is stratabox. Requires Python 3.11+.

# Install from PyPI
pip install stratabox

# Or install directly from GitHub
pip install git+https://github.com/stratabox/stratabox-sdk-python.git

# Local development & test dependencies
pip install -e ".[dev]"

Quick Start

Async Client (StrataBoxClient) & Batch Rollouts (SandboxGroup)

import asyncio
from stratabox import (
    QoSClass,
    StrataBoxClient,
    StrataBoxContainerRunArgs,
)


async def main() -> None:
    # Zero-arg resolution: explicit arg > STRATABOX_ENDPOINT / STRATABOX_TOKEN > http://127.0.0.1:18080
    async with StrataBoxClient() as client:
        args = StrataBoxContainerRunArgs(
            base_layer="base:default",
            memory_limit_mb=512,
            cpu_cores_limit=2,
            qos_class=QoSClass.LS,
            idle_auto_pause_ms=30_000,
        )

        # Direct `async with` (no extra `await` required) — automatically stops on exit
        async with client.run_container(args) as sbx:
            res = await sbx.run_shell("echo 'hello from stratabox' && python3 -V")
            print(res.stdout.strip())

        # Batch GRPO / RL rollout group with bounded concurrency and rollback on partial failure
        async with client.run_container_group(
            args,
            count=8,
            concurrency=8,
            cleanup_on_error=True,
        ) as group:
            outputs = await group.run_shell_all([f"echo rollout-{i}" for i in range(len(group))])
            print([o.stdout.strip() for o in outputs if not isinstance(o, BaseException)])

            await group.pause_all()
            await group.resume_all()


if __name__ == "__main__":
    asyncio.run(main())

Synchronous Client (SyncStrataBoxClient) for TRL, Jupyter & OpenRLHF

SyncStrataBoxClient exposes the complete StrataBoxClient / Sandbox / SandboxGroup API synchronously and runs on a private daemon asyncio thread — so it never raises RuntimeError: asyncio.run() cannot be called from a running event loop inside Jupyter Notebooks, TRL trainers, or OpenRLHF reward workers.

from stratabox import StrataBoxContainerRunArgs, SyncStrataBoxClient

with SyncStrataBoxClient(
    endpoint="http://127.0.0.1:18080",
    token="stratabox-root-token",
) as client:
    with client.run_container(
        StrataBoxContainerRunArgs(base_layer="base:default", memory_limit_mb=512)
    ) as sbx:
        sbx.write_files({"/workspace/check.py": "print('sync ok')\n"})
        result = sbx.run_shell("python3 /workspace/check.py")
        print(result.stdout.strip())

    with client.run_container_group(
        StrataBoxContainerRunArgs(base_layer="base:default", memory_limit_mb=256),
        count=4,
    ) as group:
        group.pause_all()
        group.resume_all()

Core Workflows

Immutable Layer Catalog & Upload (upload_layer)

Push a local repository directory, .tar/.tar.gz file, or archive bytes straight to the cluster as an immutable read-only EROFS layer, inspect availability, mount across containers, and clean up:

from stratabox import AlreadyExistsError, LayerKind, StrataBoxContainerRunArgs

layer_id = "ws/my-repo:v1"

if not await client.layer_exists(layer_id):
    info = await client.upload_layer(
        layer_id,
        "./my-repo-dir",          # Local dir, .tar/.tar.gz path, or raw bytes
        kind=LayerKind.WORKSPACE,
        overwrite=False,          # Raises AlreadyExistsError (HTTP 409) if layer exists
    )
    print(f"Uploaded {info.layer_id} ({info.size_bytes}B, sha256={info.sha256[:12]})")

# Inspect & list layers across healthy edges
meta = await client.get_layer(layer_id)
layers = await client.list_layers(kind=LayerKind.WORKSPACE, prefix="ws/my-repo")

# Mount in any sandbox
async with client.run_container(
    StrataBoxContainerRunArgs(base_layer="base:default", workspace_layers=[layer_id])
) as sbx:
    print((await sbx.run_shell("ls -la /workspace")).stdout)

# Delete across all edges once no longer needed
await client.delete_layer(layer_id)

Batch File Writes, Tar Upload & Upperdir Diff

Avoid dozens of sequential file RPCs when injecting patches or test harnesses, and inspect exact OverlayFS upperdir mutations at grading time:

from stratabox import FileChangeKind

async with client.run_container(
    StrataBoxContainerRunArgs(base_layer="base:default", workspace_layers=["ws/my-repo:v1"])
) as sbx:
    # 1. Write multiple files in a single HTTP request
    written = await sbx.write_files(
        {
            "/workspace/solution.py": "def solve(x): return x * 2\n",
            "/workspace/tests/test_solution.py": "from solution import solve\nassert solve(21) == 42\n",
        }
    )
    print(f"Wrote {written.files_written} files ({written.bytes_written} bytes)")

    # 2. Pack and stream a local directory or tarball into the sandbox in one RPC
    await sbx.upload_tar("./local-fixtures", dest_dir="/workspace/fixtures")

    # 3. Inspect exact filesystem diff (`added` / `modified` / `deleted` / `opaque_dir`)
    for entry in await sbx.list_modified_files():
        if entry.change == FileChangeKind.MODIFIED:
            print(f"MODIFIED: {entry.path} ({entry.size_bytes}B)")
        else:
            print(f"{entry.change.value.upper()}: {entry.path}")

Unified Backend Switching (run_sandbox) & Idle Auto-Pause

Swap between container, microvm, and fullvm using one unified StrataBoxSandboxRunArgs model with base_layer, and reclaim memory automatically during idle LLM inference gaps with idle_auto_pause_ms:

from stratabox import BackendKind, StrataBoxSandboxRunArgs

for backend in (BackendKind.CONTAINER, BackendKind.MICROVM):
    args = StrataBoxSandboxRunArgs(
        backend=backend,
        base_layer="base:default",
        memory_limit_mb=512,
        cpu_cores_limit=2,
        idle_auto_pause_ms=15_000,   # Auto-pause after 15s idle; next RPC auto-resumes!
    )
    async with client.run_sandbox(args) as sbx:
        r = await sbx.run_shell("uname -srm")
        print(f"[{sbx.backend.value}] {r.stdout.strip()}")

        # Manual pause also exposes accurate physical cgroup delta vs scanned VMA bytes
        paused = await sbx.pause()
        print(
            f"reclaimed={paused.cgroup_reclaimed_bytes}B "
            f"advised_vma={paused.advised_vma_bytes}B"
        )
        # Transparent auto-resume on the next shell/file/stream/HTTP call
        r2 = await sbx.run_shell("echo resumed-transparently")
        assert r2.ok

Fleet Listing, Project Cleanup & Scoped IAM

Inspect active sandboxes across the fleet, enforce nested project quotas, and cleanly tear down orphaned rollouts to immediately release IAM quota:

from stratabox import Permission, ProjectQuotas, SandboxState

# Create a scoped subproject with strict quotas and an initial bearer token
sub = await client.create_project(
    name="RL Run 42",
    project_id="proj-rl-42",
    quotas=ProjectQuotas(
        max_sandboxes_total=64,
        max_cpu_cores=128,
        max_memory_mb=65536,
        max_sandboxes_per_backend={"container": 64},
    ),
    permissions=[Permission.CREATE, Permission.DELETE, Permission.PAUSE],
    issue_initial_token=True,
)

# List running sandboxes across the fleet or filtered by project/state/backend/task_id
active = await client.list_sandboxes(
    project_id="proj-rl-42",
    state=SandboxState.RUNNING,
)
print(f"Active sandboxes: {[s.sandbox_id for s in active]}")

# Stop every active sandbox belonging to a project in one call & free its IAM quota
stopped = await client.stop_project_sandboxes("proj-rl-42")
print(f"Stopped {len(stopped.stopped_ids)} sandboxes, failed={stopped.failed}")

Stateless Fast Path (FnCall), Streaming, HTTP Proxy, Firewall & pack_diff

from stratabox import LayerKind, StrataBoxFnCallArgs, StreamChannel

# 1. Sub-5 ms stateless FnCall using the pre-warmed Python worker pool
fn = await client.run_fncall(
    StrataBoxFnCallArgs(
        language="python",
        code="import math; print(math.factorial(10))",
        use_warm_python=True,
    )
)
print(f"stdout={fn.stdout.strip()} warm_hit={fn.warm_hit}")

async with client.run_container(
    StrataBoxContainerRunArgs(
        base_layer="base:default",
        network_rules={"pypi": True, "npm": False},
    )
) as sbx:
    # 2. Interactive streaming I/O with stdin & live frames
    async for frame in sbx.stream_shell(
        "python3 -c 'import sys; print(sys.stdin.read().upper())'",
        stdin="hello stream\n",
        stdin_eof=True,
    ):
        if frame.channel == StreamChannel.STDOUT:
            print(frame.text, end="")

    # 3. In-sandbox localhost HTTP proxy
    # resp = await sbx.http_request("GET", "http://127.0.0.1:8080/health")

    # 4. Stage-aware egress firewall hot reload (lock down network before grading)
    await sbx.update_network_rules({"pypi": False, "npm": False})

    # 5. Scrub residual secrets & snapshot writable upperdir as a new immutable EROFS layer
    packed = await sbx.pack_diff(
        layer_id="ws/built-env:v1",
        layer_kind=LayerKind.WORKSPACE,
        scrub_paths=["/tmp/build_secret.txt", "/root/.bash_history"],
    )
    print(f"Packed {packed.layer_id} (scrubbed {packed.scrubbed_entries} entries)")

Resilience: 429 / 503 Backoff & High-Concurrency Pooling

StrataBoxClient and SyncStrataBoxClient are tuned out of the box for high-burst agentic RL training workloads:

Parameter Default Behavior
max_retries 4 Retries transient retry_statuses and transport/pool errors on idempotent & creation requests
retry_statuses (429, 503) Honors server Retry-After headers; otherwise applies equal-jitter exponential backoff
retry_base_delay / retry_max_delay 0.05s / 2.0s Backoff window cap * uniform(0.5, 1.0) where cap = min(max_delay, base * 2**attempt)
max_connections / max_keepalive_connections 1024 / 256 High-concurrency httpx.Limits pool sized for 512+ concurrent rollouts
trust_env False Ignores host HTTP_PROXY / HTTPS_PROXY env vars so local cluster traffic is never intercepted
client = StrataBoxClient(
    endpoint="http://127.0.0.1:18080",
    token="stratabox-root-token",
    max_retries=6,
    retry_base_delay=0.05,
    retry_max_delay=2.0,
    retry_statuses=(429, 503),
    max_connections=1024,
    max_keepalive_connections=256,
)

Typed Error Hierarchy & O(1) SandboxId Codec

Every API error decodes into a typed subclass of StrataBoxError carrying .code, .status_code, .message, .edge_id, and .details:

Wire ErrorCode HTTP Status Exception Class (and StrataBox* Alias)
INVALID_ARGUMENT 400 InvalidArgumentError (StrataBoxInvalidArgumentError) / InvalidSandboxIdError
UNAUTHORIZED 401 UnauthorizedError (StrataBoxUnauthorizedError)
FORBIDDEN 403 ForbiddenError (StrataBoxForbiddenError)
NOT_FOUND 404 NotFoundError (StrataBoxNotFoundError)
ALREADY_EXISTS 409 AlreadyExistsError (StrataBoxAlreadyExistsError)
QUOTA_EXCEEDED 429 QuotaExceededError (StrataBoxQuotaExceededError)
INTERNAL 500 InternalError (StrataBoxInternalError) / TransportError (StrataBoxTransportError) / TransportTimeoutError (StrataBoxTransportTimeoutError, client HTTP transport timeout; does NOT subclass builtins.TimeoutError)
SANDBOX_FAILED 502 SandboxFailedError (StrataBoxSandboxFailedError)
RESOURCE_EXHAUSTED 503 ResourceExhaustedError (StrataBoxResourceExhaustedError)
TIMEOUT 504 TimeoutError (StrataBoxTimeoutError, server/command timeout; also subclasses builtins.TimeoutError)

Client-side O(1) SandboxId parsing matches stratabox-proto byte-for-byte:

from stratabox import extract_edge_id, parse_sandbox_id

parts = parse_sandbox_id("stratabox-edge-01-ctr-0123456789abcdef")
assert parts.edge_id == "edge-01"
assert parts.backend.value == "container"
assert extract_edge_id(parts.raw) == "edge-01"

Testing & Live Cluster Integration

Offline Unit Tests (Mock Control/Data Plane)

Runs all wire-contract, retry/backoff, SyncStrataBoxClient, layer CRUD, batch file, and SandboxId unit tests with zero external dependencies (live tests are automatically skipped when STRATABOX_ENDPOINT is unset):

pytest -v -W error::RuntimeWarning tests

Live Cluster Integration Tests

Point STRATABOX_ENDPOINT (and optionally STRATABOX_TOKEN, defaulting to stratabox-root-token) at any running stratabox-daemon cluster or stratabox-daemon control instance:

STRATABOX_ENDPOINT=http://127.0.0.1:18080 \
STRATABOX_TOKEN=stratabox-root-token \
pytest -v tests/test_live_cluster.py

Official StrataBox SDKs

Language Repository Package
Core Platform (Rust) stratabox/stratabox stratabox-daemon / stratabox-agent
Python (this repo) stratabox/stratabox-sdk-python stratabox (import stratabox)
Rust stratabox/stratabox-sdk-rust stratabox-sdk
Go stratabox/stratabox-sdk-go github.com/stratabox/stratabox-sdk-go
JavaScript / TypeScript stratabox/stratabox-sdk-js @stratabox/sdk

License

Dual-licensed under either of:

at your option.

Metadata

Release files for stratabox 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stratabox 0.1.0
File Size Uploaded Provenance Actions
stratabox-0.1.0.tar.gz 112.7 kB With provenance Details for stratabox-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for stratabox 0.1.0
File Interpreter ABI Platform Actions
stratabox-0.1.0-py3-none-any.whl Python 3 none any Details for stratabox-0.1.0-py3-none-any.whl

Total release size: 176.8 kB

Release files / stratabox-0.1.0.tar.gz

Download URL stratabox-0.1.0.tar.gz
Size 112.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3159972e07348976e6fe8f502bde3654cdb4e379610cdec8dee15efc49312653
BLAKE2b-256 checksum
How to use checksums
87355d299af13e6a631cc634f5319a39dba2d42a626415e35d37ad03af70e579
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / stratabox-0.1.0-py3-none-any.whl

Download URL stratabox-0.1.0-py3-none-any.whl
Size 64.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
439c7da19f53b638b49b8bb51fd80b0ee028ff33e2ce73cd2dee44e1c91888e4
BLAKE2b-256 checksum
How to use checksums
a791e6c409385aa635fb8a2c6d2dd3a66fc6d6e0acaa69d39ed0d5e906c7f877
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Security for stratabox 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for stratabox-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page