Metadata-Version: 2.4
Name: stratabox
Version: 0.1.0
Summary: Unified async and sync Python SDK for StrataBox elastic sandboxes
Author-email: veralbor <openstrata@gmail.com>
License: MIT OR Apache-2.0
Project-URL: Homepage, https://github.com/stratabox/stratabox
Project-URL: Repository, https://github.com/stratabox/stratabox-sdk-python
Project-URL: Issues, https://github.com/stratabox/stratabox-sdk-python/issues
Keywords: stratabox,sandbox,agentic-rl,firecracker,microvm,container,erofs,async
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Requires-Dist: httpx>=0.27
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# StrataBox Python SDK (`stratabox`)

**Unified async & sync Python SDK for [StrataBox](https://github.com/stratabox/stratabox) — high-density, composable elastic sandboxes for agentic RL and large-scale evaluation.**

[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB.svg)](pyproject.toml)
[![Typing: PEP 561](https://img.shields.io/badge/Typing-PEP%20561%20Typed-blue.svg)](stratabox/py.typed)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-green.svg)](LICENSE-MIT)
[![CI](https://github.com/stratabox/stratabox-sdk-python/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml)

[English](README.md) | [简体中文](README_CN.md)

---

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
  - [Async Client (`StrataBoxClient`) & Batch Rollouts (`SandboxGroup`)](#async-client-strataboxclient--batch-rollouts-sandboxgroup)
  - [Synchronous Client (`SyncStrataBoxClient`) for TRL, Jupyter & OpenRLHF](#synchronous-client-syncstrataboxclient-for-trl-jupyter--openrlhf)
- [Core Workflows](#core-workflows)
  - [Immutable Layer Catalog & Upload (`upload_layer`)](#immutable-layer-catalog--upload-upload_layer)
  - [Batch File Writes, Tar Upload & Upperdir Diff](#batch-file-writes-tar-upload--upperdir-diff)
  - [Unified Backend Switching (`run_sandbox`) & Idle Auto-Pause](#unified-backend-switching-run_sandbox--idle-auto-pause)
  - [Fleet Listing, Project Cleanup & Scoped IAM](#fleet-listing-project-cleanup--scoped-iam)
  - [Stateless Fast Path (`FnCall`), Streaming, HTTP Proxy, Firewall & `pack_diff`](#stateless-fast-path-fncall-streaming-http-proxy-firewall--pack_diff)
- [Resilience: `429` / `503` Backoff & High-Concurrency Pooling](#resilience-429--503-backoff--high-concurrency-pooling)
- [Typed Error Hierarchy & O(1) `SandboxId` Codec](#typed-error-hierarchy--o1-sandboxid-codec)
- [Testing & Live Cluster Integration](#testing--live-cluster-integration)
- [Official StrataBox SDKs](#official-stratabox-sdks)
- [License](#license)

---

## 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+**.

```bash
# 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`)

```python
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.

```python
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:

```python
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:

```python
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`:

```python
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:

```python
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`

```python
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 |

```python
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:

```python
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):

```bash
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:

```bash
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](https://github.com/stratabox/stratabox) | `stratabox-daemon` / `stratabox-agent` |
| **Python (this repo)** | [stratabox/stratabox-sdk-python](https://github.com/stratabox/stratabox-sdk-python) | `stratabox` (`import stratabox`) |
| **Rust** | [stratabox/stratabox-sdk-rust](https://github.com/stratabox/stratabox-sdk-rust) | `stratabox-sdk` |
| **Go** | [stratabox/stratabox-sdk-go](https://github.com/stratabox/stratabox-sdk-go) | `github.com/stratabox/stratabox-sdk-go` |
| **JavaScript / TypeScript** | [stratabox/stratabox-sdk-js](https://github.com/stratabox/stratabox-sdk-js) | `@stratabox/sdk` |

---

## License

Dual-licensed under either of:

- **MIT License** ([`LICENSE-MIT`](LICENSE-MIT))
- **Apache License, Version 2.0** ([`LICENSE-APACHE`](LICENSE-APACHE))

at your option.
