stratabox 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 veralbor <openstrata@gmail.com>
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 veralbor <openstrata@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,455 @@
1
+ Metadata-Version: 2.4
2
+ Name: stratabox
3
+ Version: 0.1.0
4
+ Summary: Unified async and sync Python SDK for StrataBox elastic sandboxes
5
+ Author-email: veralbor <openstrata@gmail.com>
6
+ License: MIT OR Apache-2.0
7
+ Project-URL: Homepage, https://github.com/stratabox/stratabox
8
+ Project-URL: Repository, https://github.com/stratabox/stratabox-sdk-python
9
+ Project-URL: Issues, https://github.com/stratabox/stratabox-sdk-python/issues
10
+ Keywords: stratabox,sandbox,agentic-rl,firecracker,microvm,container,erofs,async
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: System :: Distributed Computing
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE-APACHE
27
+ License-File: LICENSE-MIT
28
+ Requires-Dist: httpx>=0.27
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # StrataBox Python SDK (`stratabox`)
35
+
36
+ **Unified async & sync Python SDK for [StrataBox](https://github.com/stratabox/stratabox) — high-density, composable elastic sandboxes for agentic RL and large-scale evaluation.**
37
+
38
+ [![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB.svg)](pyproject.toml)
39
+ [![Typing: PEP 561](https://img.shields.io/badge/Typing-PEP%20561%20Typed-blue.svg)](stratabox/py.typed)
40
+ [![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-green.svg)](LICENSE-MIT)
41
+ [![CI](https://github.com/stratabox/stratabox-sdk-python/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml)
42
+
43
+ [English](README.md) | [简体中文](README_CN.md)
44
+
45
+ ---
46
+
47
+ ## Table of Contents
48
+
49
+ - [Features](#features)
50
+ - [Installation](#installation)
51
+ - [Quick Start](#quick-start)
52
+ - [Async Client (`StrataBoxClient`) & Batch Rollouts (`SandboxGroup`)](#async-client-strataboxclient--batch-rollouts-sandboxgroup)
53
+ - [Synchronous Client (`SyncStrataBoxClient`) for TRL, Jupyter & OpenRLHF](#synchronous-client-syncstrataboxclient-for-trl-jupyter--openrlhf)
54
+ - [Core Workflows](#core-workflows)
55
+ - [Immutable Layer Catalog & Upload (`upload_layer`)](#immutable-layer-catalog--upload-upload_layer)
56
+ - [Batch File Writes, Tar Upload & Upperdir Diff](#batch-file-writes-tar-upload--upperdir-diff)
57
+ - [Unified Backend Switching (`run_sandbox`) & Idle Auto-Pause](#unified-backend-switching-run_sandbox--idle-auto-pause)
58
+ - [Fleet Listing, Project Cleanup & Scoped IAM](#fleet-listing-project-cleanup--scoped-iam)
59
+ - [Stateless Fast Path (`FnCall`), Streaming, HTTP Proxy, Firewall & `pack_diff`](#stateless-fast-path-fncall-streaming-http-proxy-firewall--pack_diff)
60
+ - [Resilience: `429` / `503` Backoff & High-Concurrency Pooling](#resilience-429--503-backoff--high-concurrency-pooling)
61
+ - [Typed Error Hierarchy & O(1) `SandboxId` Codec](#typed-error-hierarchy--o1-sandboxid-codec)
62
+ - [Testing & Live Cluster Integration](#testing--live-cluster-integration)
63
+ - [Official StrataBox SDKs](#official-stratabox-sdks)
64
+ - [License](#license)
65
+
66
+ ---
67
+
68
+ ## Features
69
+
70
+ - **Async + Sync API Parity & Zero-Config Startup**:
71
+ - `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.
72
+ - `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`.
73
+ - `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`).
74
+ - `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.
75
+ - **All Four StrataBox Execution Backends**:
76
+ - `FnCall` (`run_fncall`) for `< 5 ms` warm-pool stateless invocations.
77
+ - `Container` (`run_container`), `MicroVm` (`run_microvm`), and `FullVm` (`run_vm`) — or switch backends seamlessly with unified `run_sandbox(StrataBoxSandboxRunArgs(backend=..., base_layer=..., init_dirs=[...]))`.
78
+ - **RL Rollout Group Orchestration (`SandboxGroup` & `SyncSandboxGroup`)**:
79
+ - 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`).
80
+ - **Immutable Layer CRUD & Zero-Disk Streaming Upload (`/v1/layers`)**:
81
+ - 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`.
82
+ - **Single-RPC Batch Filesystem, Tar Transfer & Upperdir Diff**:
83
+ - `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`.
84
+ - **Idle Auto-Pause & Transparent Auto-Resume**:
85
+ - 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`).
86
+ - **Production Backoff & Type Safety**:
87
+ - 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.
88
+
89
+ ---
90
+
91
+ ## Installation
92
+
93
+ Package name on PyPI is **`stratabox`**; the import package is **`stratabox`**. Requires **Python 3.11+**.
94
+
95
+ ```bash
96
+ # Install from PyPI
97
+ pip install stratabox
98
+
99
+ # Or install directly from GitHub
100
+ pip install git+https://github.com/stratabox/stratabox-sdk-python.git
101
+
102
+ # Local development & test dependencies
103
+ pip install -e ".[dev]"
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Quick Start
109
+
110
+ ### Async Client (`StrataBoxClient`) & Batch Rollouts (`SandboxGroup`)
111
+
112
+ ```python
113
+ import asyncio
114
+ from stratabox import (
115
+ QoSClass,
116
+ StrataBoxClient,
117
+ StrataBoxContainerRunArgs,
118
+ )
119
+
120
+
121
+ async def main() -> None:
122
+ # Zero-arg resolution: explicit arg > STRATABOX_ENDPOINT / STRATABOX_TOKEN > http://127.0.0.1:18080
123
+ async with StrataBoxClient() as client:
124
+ args = StrataBoxContainerRunArgs(
125
+ base_layer="base:default",
126
+ memory_limit_mb=512,
127
+ cpu_cores_limit=2,
128
+ qos_class=QoSClass.LS,
129
+ idle_auto_pause_ms=30_000,
130
+ )
131
+
132
+ # Direct `async with` (no extra `await` required) — automatically stops on exit
133
+ async with client.run_container(args) as sbx:
134
+ res = await sbx.run_shell("echo 'hello from stratabox' && python3 -V")
135
+ print(res.stdout.strip())
136
+
137
+ # Batch GRPO / RL rollout group with bounded concurrency and rollback on partial failure
138
+ async with client.run_container_group(
139
+ args,
140
+ count=8,
141
+ concurrency=8,
142
+ cleanup_on_error=True,
143
+ ) as group:
144
+ outputs = await group.run_shell_all([f"echo rollout-{i}" for i in range(len(group))])
145
+ print([o.stdout.strip() for o in outputs if not isinstance(o, BaseException)])
146
+
147
+ await group.pause_all()
148
+ await group.resume_all()
149
+
150
+
151
+ if __name__ == "__main__":
152
+ asyncio.run(main())
153
+ ```
154
+
155
+ ### Synchronous Client (`SyncStrataBoxClient`) for TRL, Jupyter & OpenRLHF
156
+
157
+ `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.
158
+
159
+ ```python
160
+ from stratabox import StrataBoxContainerRunArgs, SyncStrataBoxClient
161
+
162
+ with SyncStrataBoxClient(
163
+ endpoint="http://127.0.0.1:18080",
164
+ token="stratabox-root-token",
165
+ ) as client:
166
+ with client.run_container(
167
+ StrataBoxContainerRunArgs(base_layer="base:default", memory_limit_mb=512)
168
+ ) as sbx:
169
+ sbx.write_files({"/workspace/check.py": "print('sync ok')\n"})
170
+ result = sbx.run_shell("python3 /workspace/check.py")
171
+ print(result.stdout.strip())
172
+
173
+ with client.run_container_group(
174
+ StrataBoxContainerRunArgs(base_layer="base:default", memory_limit_mb=256),
175
+ count=4,
176
+ ) as group:
177
+ group.pause_all()
178
+ group.resume_all()
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Core Workflows
184
+
185
+ ### Immutable Layer Catalog & Upload (`upload_layer`)
186
+
187
+ 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:
188
+
189
+ ```python
190
+ from stratabox import AlreadyExistsError, LayerKind, StrataBoxContainerRunArgs
191
+
192
+ layer_id = "ws/my-repo:v1"
193
+
194
+ if not await client.layer_exists(layer_id):
195
+ info = await client.upload_layer(
196
+ layer_id,
197
+ "./my-repo-dir", # Local dir, .tar/.tar.gz path, or raw bytes
198
+ kind=LayerKind.WORKSPACE,
199
+ overwrite=False, # Raises AlreadyExistsError (HTTP 409) if layer exists
200
+ )
201
+ print(f"Uploaded {info.layer_id} ({info.size_bytes}B, sha256={info.sha256[:12]})")
202
+
203
+ # Inspect & list layers across healthy edges
204
+ meta = await client.get_layer(layer_id)
205
+ layers = await client.list_layers(kind=LayerKind.WORKSPACE, prefix="ws/my-repo")
206
+
207
+ # Mount in any sandbox
208
+ async with client.run_container(
209
+ StrataBoxContainerRunArgs(base_layer="base:default", workspace_layers=[layer_id])
210
+ ) as sbx:
211
+ print((await sbx.run_shell("ls -la /workspace")).stdout)
212
+
213
+ # Delete across all edges once no longer needed
214
+ await client.delete_layer(layer_id)
215
+ ```
216
+
217
+ ### Batch File Writes, Tar Upload & Upperdir Diff
218
+
219
+ Avoid dozens of sequential file RPCs when injecting patches or test harnesses, and inspect exact OverlayFS upperdir mutations at grading time:
220
+
221
+ ```python
222
+ from stratabox import FileChangeKind
223
+
224
+ async with client.run_container(
225
+ StrataBoxContainerRunArgs(base_layer="base:default", workspace_layers=["ws/my-repo:v1"])
226
+ ) as sbx:
227
+ # 1. Write multiple files in a single HTTP request
228
+ written = await sbx.write_files(
229
+ {
230
+ "/workspace/solution.py": "def solve(x): return x * 2\n",
231
+ "/workspace/tests/test_solution.py": "from solution import solve\nassert solve(21) == 42\n",
232
+ }
233
+ )
234
+ print(f"Wrote {written.files_written} files ({written.bytes_written} bytes)")
235
+
236
+ # 2. Pack and stream a local directory or tarball into the sandbox in one RPC
237
+ await sbx.upload_tar("./local-fixtures", dest_dir="/workspace/fixtures")
238
+
239
+ # 3. Inspect exact filesystem diff (`added` / `modified` / `deleted` / `opaque_dir`)
240
+ for entry in await sbx.list_modified_files():
241
+ if entry.change == FileChangeKind.MODIFIED:
242
+ print(f"MODIFIED: {entry.path} ({entry.size_bytes}B)")
243
+ else:
244
+ print(f"{entry.change.value.upper()}: {entry.path}")
245
+ ```
246
+
247
+ ### Unified Backend Switching (`run_sandbox`) & Idle Auto-Pause
248
+
249
+ 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`:
250
+
251
+ ```python
252
+ from stratabox import BackendKind, StrataBoxSandboxRunArgs
253
+
254
+ for backend in (BackendKind.CONTAINER, BackendKind.MICROVM):
255
+ args = StrataBoxSandboxRunArgs(
256
+ backend=backend,
257
+ base_layer="base:default",
258
+ memory_limit_mb=512,
259
+ cpu_cores_limit=2,
260
+ idle_auto_pause_ms=15_000, # Auto-pause after 15s idle; next RPC auto-resumes!
261
+ )
262
+ async with client.run_sandbox(args) as sbx:
263
+ r = await sbx.run_shell("uname -srm")
264
+ print(f"[{sbx.backend.value}] {r.stdout.strip()}")
265
+
266
+ # Manual pause also exposes accurate physical cgroup delta vs scanned VMA bytes
267
+ paused = await sbx.pause()
268
+ print(
269
+ f"reclaimed={paused.cgroup_reclaimed_bytes}B "
270
+ f"advised_vma={paused.advised_vma_bytes}B"
271
+ )
272
+ # Transparent auto-resume on the next shell/file/stream/HTTP call
273
+ r2 = await sbx.run_shell("echo resumed-transparently")
274
+ assert r2.ok
275
+ ```
276
+
277
+ ### Fleet Listing, Project Cleanup & Scoped IAM
278
+
279
+ Inspect active sandboxes across the fleet, enforce nested project quotas, and cleanly tear down orphaned rollouts to immediately release IAM quota:
280
+
281
+ ```python
282
+ from stratabox import Permission, ProjectQuotas, SandboxState
283
+
284
+ # Create a scoped subproject with strict quotas and an initial bearer token
285
+ sub = await client.create_project(
286
+ name="RL Run 42",
287
+ project_id="proj-rl-42",
288
+ quotas=ProjectQuotas(
289
+ max_sandboxes_total=64,
290
+ max_cpu_cores=128,
291
+ max_memory_mb=65536,
292
+ max_sandboxes_per_backend={"container": 64},
293
+ ),
294
+ permissions=[Permission.CREATE, Permission.DELETE, Permission.PAUSE],
295
+ issue_initial_token=True,
296
+ )
297
+
298
+ # List running sandboxes across the fleet or filtered by project/state/backend/task_id
299
+ active = await client.list_sandboxes(
300
+ project_id="proj-rl-42",
301
+ state=SandboxState.RUNNING,
302
+ )
303
+ print(f"Active sandboxes: {[s.sandbox_id for s in active]}")
304
+
305
+ # Stop every active sandbox belonging to a project in one call & free its IAM quota
306
+ stopped = await client.stop_project_sandboxes("proj-rl-42")
307
+ print(f"Stopped {len(stopped.stopped_ids)} sandboxes, failed={stopped.failed}")
308
+ ```
309
+
310
+ ### Stateless Fast Path (`FnCall`), Streaming, HTTP Proxy, Firewall & `pack_diff`
311
+
312
+ ```python
313
+ from stratabox import LayerKind, StrataBoxFnCallArgs, StreamChannel
314
+
315
+ # 1. Sub-5 ms stateless FnCall using the pre-warmed Python worker pool
316
+ fn = await client.run_fncall(
317
+ StrataBoxFnCallArgs(
318
+ language="python",
319
+ code="import math; print(math.factorial(10))",
320
+ use_warm_python=True,
321
+ )
322
+ )
323
+ print(f"stdout={fn.stdout.strip()} warm_hit={fn.warm_hit}")
324
+
325
+ async with client.run_container(
326
+ StrataBoxContainerRunArgs(
327
+ base_layer="base:default",
328
+ network_rules={"pypi": True, "npm": False},
329
+ )
330
+ ) as sbx:
331
+ # 2. Interactive streaming I/O with stdin & live frames
332
+ async for frame in sbx.stream_shell(
333
+ "python3 -c 'import sys; print(sys.stdin.read().upper())'",
334
+ stdin="hello stream\n",
335
+ stdin_eof=True,
336
+ ):
337
+ if frame.channel == StreamChannel.STDOUT:
338
+ print(frame.text, end="")
339
+
340
+ # 3. In-sandbox localhost HTTP proxy
341
+ # resp = await sbx.http_request("GET", "http://127.0.0.1:8080/health")
342
+
343
+ # 4. Stage-aware egress firewall hot reload (lock down network before grading)
344
+ await sbx.update_network_rules({"pypi": False, "npm": False})
345
+
346
+ # 5. Scrub residual secrets & snapshot writable upperdir as a new immutable EROFS layer
347
+ packed = await sbx.pack_diff(
348
+ layer_id="ws/built-env:v1",
349
+ layer_kind=LayerKind.WORKSPACE,
350
+ scrub_paths=["/tmp/build_secret.txt", "/root/.bash_history"],
351
+ )
352
+ print(f"Packed {packed.layer_id} (scrubbed {packed.scrubbed_entries} entries)")
353
+ ```
354
+
355
+ ---
356
+
357
+ ## Resilience: `429` / `503` Backoff & High-Concurrency Pooling
358
+
359
+ `StrataBoxClient` and `SyncStrataBoxClient` are tuned out of the box for high-burst agentic RL training workloads:
360
+
361
+ | Parameter | Default | Behavior |
362
+ | :--- | :--- | :--- |
363
+ | `max_retries` | `4` | Retries transient `retry_statuses` and transport/pool errors on idempotent & creation requests |
364
+ | `retry_statuses` | `(429, 503)` | Honors server `Retry-After` headers; otherwise applies equal-jitter exponential backoff |
365
+ | `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)` |
366
+ | `max_connections` / `max_keepalive_connections` | `1024` / `256` | High-concurrency `httpx.Limits` pool sized for 512+ concurrent rollouts |
367
+ | `trust_env` | `False` | Ignores host `HTTP_PROXY` / `HTTPS_PROXY` env vars so local cluster traffic is never intercepted |
368
+
369
+ ```python
370
+ client = StrataBoxClient(
371
+ endpoint="http://127.0.0.1:18080",
372
+ token="stratabox-root-token",
373
+ max_retries=6,
374
+ retry_base_delay=0.05,
375
+ retry_max_delay=2.0,
376
+ retry_statuses=(429, 503),
377
+ max_connections=1024,
378
+ max_keepalive_connections=256,
379
+ )
380
+ ```
381
+
382
+ ---
383
+
384
+ ## Typed Error Hierarchy & O(1) `SandboxId` Codec
385
+
386
+ Every API error decodes into a typed subclass of `StrataBoxError` carrying `.code`, `.status_code`, `.message`, `.edge_id`, and `.details`:
387
+
388
+ | Wire `ErrorCode` | HTTP Status | Exception Class (and `StrataBox*` Alias) |
389
+ | :--- | :--- | :--- |
390
+ | `INVALID_ARGUMENT` | `400` | `InvalidArgumentError` (`StrataBoxInvalidArgumentError`) / `InvalidSandboxIdError` |
391
+ | `UNAUTHORIZED` | `401` | `UnauthorizedError` (`StrataBoxUnauthorizedError`) |
392
+ | `FORBIDDEN` | `403` | `ForbiddenError` (`StrataBoxForbiddenError`) |
393
+ | `NOT_FOUND` | `404` | `NotFoundError` (`StrataBoxNotFoundError`) |
394
+ | `ALREADY_EXISTS` | `409` | `AlreadyExistsError` (`StrataBoxAlreadyExistsError`) |
395
+ | `QUOTA_EXCEEDED` | `429` | `QuotaExceededError` (`StrataBoxQuotaExceededError`) |
396
+ | `INTERNAL` | `500` | `InternalError` (`StrataBoxInternalError`) / `TransportError` (`StrataBoxTransportError`) / `TransportTimeoutError` (`StrataBoxTransportTimeoutError`, client HTTP transport timeout; does NOT subclass `builtins.TimeoutError`) |
397
+ | `SANDBOX_FAILED` | `502` | `SandboxFailedError` (`StrataBoxSandboxFailedError`) |
398
+ | `RESOURCE_EXHAUSTED` | `503` | `ResourceExhaustedError` (`StrataBoxResourceExhaustedError`) |
399
+ | `TIMEOUT` | `504` | `TimeoutError` (`StrataBoxTimeoutError`, server/command timeout; also subclasses `builtins.TimeoutError`) |
400
+
401
+ Client-side O(1) `SandboxId` parsing matches `stratabox-proto` byte-for-byte:
402
+
403
+ ```python
404
+ from stratabox import extract_edge_id, parse_sandbox_id
405
+
406
+ parts = parse_sandbox_id("stratabox-edge-01-ctr-0123456789abcdef")
407
+ assert parts.edge_id == "edge-01"
408
+ assert parts.backend.value == "container"
409
+ assert extract_edge_id(parts.raw) == "edge-01"
410
+ ```
411
+
412
+ ---
413
+
414
+ ## Testing & Live Cluster Integration
415
+
416
+ ### Offline Unit Tests (Mock Control/Data Plane)
417
+
418
+ 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):
419
+
420
+ ```bash
421
+ pytest -v -W error::RuntimeWarning tests
422
+ ```
423
+
424
+ ### Live Cluster Integration Tests
425
+
426
+ Point `STRATABOX_ENDPOINT` (and optionally `STRATABOX_TOKEN`, defaulting to `stratabox-root-token`) at any running `stratabox-daemon cluster` or `stratabox-daemon control` instance:
427
+
428
+ ```bash
429
+ STRATABOX_ENDPOINT=http://127.0.0.1:18080 \
430
+ STRATABOX_TOKEN=stratabox-root-token \
431
+ pytest -v tests/test_live_cluster.py
432
+ ```
433
+
434
+ ---
435
+
436
+ ## Official StrataBox SDKs
437
+
438
+ | Language | Repository | Package |
439
+ | :--- | :--- | :--- |
440
+ | **Core Platform (Rust)** | [stratabox/stratabox](https://github.com/stratabox/stratabox) | `stratabox-daemon` / `stratabox-agent` |
441
+ | **Python (this repo)** | [stratabox/stratabox-sdk-python](https://github.com/stratabox/stratabox-sdk-python) | `stratabox` (`import stratabox`) |
442
+ | **Rust** | [stratabox/stratabox-sdk-rust](https://github.com/stratabox/stratabox-sdk-rust) | `stratabox-sdk` |
443
+ | **Go** | [stratabox/stratabox-sdk-go](https://github.com/stratabox/stratabox-sdk-go) | `github.com/stratabox/stratabox-sdk-go` |
444
+ | **JavaScript / TypeScript** | [stratabox/stratabox-sdk-js](https://github.com/stratabox/stratabox-sdk-js) | `@stratabox/sdk` |
445
+
446
+ ---
447
+
448
+ ## License
449
+
450
+ Dual-licensed under either of:
451
+
452
+ - **MIT License** ([`LICENSE-MIT`](LICENSE-MIT))
453
+ - **Apache License, Version 2.0** ([`LICENSE-APACHE`](LICENSE-APACHE))
454
+
455
+ at your option.