Skip to content

An open-source, faster Devin alternative

TypeScript

Add benchmark suite comparing OpenSandbox vs E2B

motatoesf8a38fd3ca9f
diff --git a/benchmarks/README.md b/benchmarks/README.md
new file mode 100644
index 00000000..4b9bef92
--- /dev/null
+++ b/benchmarks/README.md
@@ -0,0 +1,250 @@
+# OpenSandbox vs E2B Benchmarks
+
+Benchmark suite to compare OpenSandbox with E2B cloud sandboxes.
+
+## Results Summary
+
+Benchmarks run against OpenSandbox deployed on Fly.io (`https://opensandbox-test.fly.dev`) and E2B cloud.
+
+### 1. Sandbox Creation Time
+
+| Provider | Create Avg (ms) | Destroy Avg (ms) |
+|----------|-----------------|------------------|
+| OpenSandbox | 131 | 85 |
+| E2B | 274 | 113 |
+
+**OpenSandbox is ~2x faster** at creating new sandbox sessions.
+
+### 2. Command Execution Latency
+
+| Command | OpenSandbox (ms) | E2B (ms) | Winner |
+|---------|------------------|----------|--------|
+| echo | 67 | 61 | E2B |
+| pwd | 89 | 39 | E2B |
+| ls | 93 | 42 | E2B |
+| uname | 65 | 38 | E2B |
+| git --version | 110 | 62 | E2B |
+| **Overall Avg** | **111** | **51** | **E2B** |
+
+**E2B is ~2x faster** for individual command execution. This is likely due to E2B's native SDK vs OpenSandbox's HTTP API overhead.
+
+### 3. File Operations
+
+| Operation | OpenSandbox (ms) | E2B (ms) |
+|-----------|------------------|----------|
+| Write 100B | 209 | 34 |
+| Write 1KB | 68 | 62 |
+| Read 100B | 114 | 33 |
+| Read 1KB | 204 | 32 |
+
+**E2B is faster** for file operations. OpenSandbox uses shell commands (base64 encoding) for file transfers while E2B has native file APIs.
+
+### 4. Realistic Workflow (Git Clone + Edit)
+
+| Step | OpenSandbox (ms) | E2B (ms) |
+|------|------------------|----------|
+| sandbox_create | 122 | 125 |
+| mkdir | 220 | 130 |
+| git_clone | 374 | 648 |
+| list_files | 69 | 43 |
+| write_file | 211 | 34 |
+| read_readme | 88 | 38 |
+| git_status | 67 | 38 |
+| git_diff | 73 | 60 |
+| cleanup | 95 | 45 |
+| sandbox_destroy | 201 | 107 |
+| **Total** | **1529** | **1268** |
+
+Mixed results. **OpenSandbox is faster for git clone** (374ms vs 648ms), but E2B wins on file operations and overall workflow time.
+
+### 5. Concurrency (Parallel Sandboxes)
+
+| Concurrency | OpenSandbox Wall Time | OpenSandbox Throughput/s | E2B Wall Time | E2B Throughput/s |
+|-------------|----------------------|--------------------------|---------------|------------------|
+| 1 | 505ms | 1.98 | 483ms | 2.07 |
+| 2 | 408ms | 4.90 | 652ms | 3.07 |
+| 4 | 460ms | 8.69 | 584ms | 6.85 |
+| 8 | 537ms | **14.90** | 3139ms | 2.55 |
+
+**OpenSandbox scales much better** with concurrent workloads:
+- At 8 concurrent sandboxes, OpenSandbox maintains ~537ms wall time while E2B degrades to 3.1 seconds
+- OpenSandbox achieves **14.9 sandboxes/sec** throughput vs E2B's **2.55 sandboxes/sec** at high concurrency
+- E2B appears to hit rate limiting or queuing at 8 concurrent requests
+
+### Key Takeaways
+
+| Metric | Winner | Notes |
+|--------|--------|-------|
+| Sandbox creation | OpenSandbox | 2x faster startup |
+| Command execution | E2B | 2x lower latency per command |
+| File operations | E2B | Native SDK vs HTTP+shell |
+| Git clone | OpenSandbox | Faster network/clone performance |
+| Concurrency | OpenSandbox | 6x better throughput at scale |
+| Total workflow | E2B | 17% faster end-to-end |
+
+**Choose OpenSandbox when:**
+- Running many sandboxes in parallel (agent workloads)
+- Git operations are the bottleneck
+- Self-hosting is preferred
+
+**Choose E2B when:**
+- Single-sandbox workflows
+- Many small file operations
+- Minimal infrastructure management desired
+
+> **Note:** These benchmarks compare E2B's native Python SDK against OpenSandbox's HTTP API. The command execution and file operation differences are largely due to SDK vs HTTP overhead. A native OpenSandbox SDK is planned, which should significantly reduce per-operation latency and provide a more direct comparison. Results will be updated once the SDK is available.
+
+---
+
+## Prerequisites
+
+### 1. OpenSandbox (Local)
+Must be running locally:
+```bash
+# From the repository root
+docker compose up --build
+```
+
+### 2. E2B (Cloud)
+Requires an E2B API key:
+```bash
+export E2B_API_KEY=your_api_key
+```
+
+### 3. Python Dependencies
+```bash
+cd benchmarks
+pip install -r requirements.txt
+```
+
+## Quick Test
+
+Before running full benchmarks, verify connectivity:
+
+```bash
+# Test OpenSandbox
+python quick_test.py
+
+# Test E2B
+python quick_test.py --provider e2b
+
+# Test both
+python quick_test.py --provider all
+```
+
+## Running Benchmarks
+
+### Full Suite
+```bash
+# Run all benchmarks for all available providers
+python run_benchmarks.py
+
+# Run with more iterations for better accuracy
+python run_benchmarks.py --iterations 5
+```
+
+### Provider-Specific
+```bash
+# Only test OpenSandbox
+python run_benchmarks.py --provider opensandbox
+
+# Only test E2B
+python run_benchmarks.py --provider e2b
+```
+
+### Individual Benchmarks
+```bash
+# Run specific benchmarks only
+python run_benchmarks.py --only creation
+python run_benchmarks.py --only creation commands
+python run_benchmarks.py --only workflow
+
+# Or run them directly
+python benchmark_creation.py --provider opensandbox --iterations 5
+python benchmark_commands.py --provider e2b --iterations 3
+python benchmark_files.py --provider opensandbox
+python benchmark_workflow.py --provider opensandbox
+python benchmark_concurrency.py --provider opensandbox
+```
+
+## Benchmark Categories
+
+### 1. Creation (`benchmark_creation.py`)
+Measures sandbox startup and teardown time.
+- **Create time**: How long to spin up a new sandbox session
+- **Destroy time**: How long to tear down and cleanup
+
+### 2. Commands (`benchmark_commands.py`)
+Measures command execution latency for various operations:
+- Simple commands (echo, pwd, ls)
+- System info (uname, env)
+- Tool availability (git, python versions)
+- Loops and calculations
+
+### 3. Files (`benchmark_files.py`)
+Measures file read/write performance across different sizes:
+- Tiny: 100 bytes
+- Small: 1 KB
+- Medium: 10 KB
+- Large: 100 KB
+- XLarge: 1 MB
+
+### 4. Workflow (`benchmark_workflow.py`)
+Measures a realistic git workflow:
+1. Create sandbox
+2. Git clone (shallow)
+3. List files
+4. Write a new file
+5. Read README
+6. Git status/diff
+7. Cleanup and destroy
+
+### 5. Concurrency (`benchmark_concurrency.py`)
+Measures parallel sandbox operations:
+- Tests 1, 2, 4, 8 concurrent sandboxes
+- Measures wall clock time and throughput
+- Identifies bottlenecks in parallel workloads
+
+## Output
+
+Results are saved to the `results/` directory:
+- `results/benchmark_YYYYMMDD_HHMMSS.json` - Raw JSON results
+- `results/benchmark_YYYYMMDD_HHMMSS.md` - Formatted markdown report
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `OPENSANDBOX_URL` | `https://opensandbox-test.fly.dev` | OpenSandbox server URL |
+| `E2B_API_KEY` | - | E2B API key (required for E2B tests) |
+
+## Example Output
+
+```
+============================================================
+SUMMARY
+============================================================
+
+## 1. Sandbox Creation Time
+
+| Provider | Create Avg (ms) | Create Std | Destroy Avg (ms) |
+|----------|-----------------|------------|------------------|
+| opensandbox | 45.23 | 5.12 | 12.45 |
+| e2b | 2345.67 | 234.56 | 156.78 |
+
+## 2. Command Execution Latency
+
+| Command | opensandbox (ms) | e2b (ms) |
+|---------|------------------|----------|
+| echo | 15.23 | 89.45 |
+| pwd | 14.56 | 87.23 |
+| ls | 18.34 | 95.67 |
+...
+```
+
+## Notes
+
+- OpenSandbox benchmarks require Docker with `--privileged` mode
+- E2B benchmarks require internet connectivity and valid API key
+- File operations on OpenSandbox use commands (cat, base64) while E2B uses native SDK
+- Concurrency tests may hit rate limits on E2B free tier
diff --git a/benchmarks/benchmark_commands.py b/benchmarks/benchmark_commands.py
new file mode 100755
index 00000000..6a4be5b6
--- /dev/null
+++ b/benchmarks/benchmark_commands.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Benchmark: Command execution latency."""
+
+import time
+import statistics
+from typing import Optional
+from dataclasses import dataclass, field
+
+from sandbox_interface import get_sandbox, BaseSandbox
+
+
+# Test commands to benchmark (name, command, description)
+TEST_COMMANDS = [
+ ("echo", "echo 'hello world'", "Simple echo command"),
+ ("pwd", "pwd", "Print working directory"),
+ ("ls", "ls -la /", "List root directory"),
+ ("env", "env | head -20", "Show environment variables"),
+ ("python_version", "python3 --version 2>&1 || python --version 2>&1 || echo 'no python'", "Check Python version"),
+ ("git_version", "git --version", "Check Git version"),
+ ("uname", "uname -a", "System information"),
+ ("cat_etc_os", "cat /etc/os-release 2>/dev/null || cat /etc/debian_version 2>/dev/null || echo 'unknown'", "OS release info"),
+ ("loop_100", "for i in $(seq 1 100); do echo $i; done | tail -1", "Loop 100 iterations"),
+ ("calculate", "echo $((12345 * 67890))", "Simple calculation"),
+]
+
+
+@dataclass
+class CommandBenchmark:
+ """Results for a single command."""
+ name: str
+ command: str
+ times_ms: list[float] = field(default_factory=list)
+ success_count: int = 0
+ fail_count: int = 0
+
+ @property
+ def avg_ms(self) -> float:
+ return statistics.mean(self.times_ms) if self.times_ms else 0
+
+ @property
+ def std_ms(self) -> float:
+ return statistics.stdev(self.times_ms) if len(self.times_ms) > 1 else 0
+
+ def to_dict(self) -> dict:
+ return {
+ "name": self.name,
+ "command": self.command,
+ "avg_ms": round(self.avg_ms, 2),
+ "std_ms": round(self.std_ms, 2),
+ "min_ms": round(min(self.times_ms), 2) if self.times_ms else 0,
+ "max_ms": round(max(self.times_ms), 2) if self.times_ms else 0,
+ "success": self.success_count,
+ "fail": self.fail_count,
+ }
+
+
+@dataclass
+class CommandsResult:
+ """Results from command benchmark."""
+ provider: str
+ iterations: int
+ commands: list[CommandBenchmark]
+ setup_time_ms: float
+ teardown_time_ms: float
+ errors: list[str]
+
+ @property
+ def total_avg_ms(self) -> float:
+ """Average execution time across all commands."""
+ all_times = []
+ for cmd in self.commands:
+ all_times.extend(cmd.times_ms)
+ return statistics.mean(all_times) if all_times else 0
+
+ def to_dict(self) -> dict:
+ return {
+ "provider": self.provider,
+ "iterations": self.iterations,
+ "setup_time_ms": round(self.setup_time_ms, 2),
+ "teardown_time_ms": round(self.teardown_time_ms, 2),
+ "total_avg_ms": round(self.total_avg_ms, 2),
+ "commands": [cmd.to_dict() for cmd in self.commands],
+ "errors": self.errors,
+ }
+
+
+def run_benchmark(provider: str, iterations: int = 3, **kwargs) -> CommandsResult:
+ """
+ Benchmark command execution latency.
+
+ Args:
+ provider: "opensandbox" or "e2b"
+ iterations: Number of times to run each command
+
+ Returns:
+ CommandsResult with timing data
+ """
+ print(f"\n{'='*60}")
+ print(f"Command Execution Benchmark: {provider}")
+ print(f"{'='*60}")
+
+ errors = []
+ commands = [CommandBenchmark(name=name, command=cmd) for name, cmd, _ in TEST_COMMANDS]
+
+ # Create sandbox
+ sandbox: Optional[BaseSandbox] = None
+ try:
+ sandbox = get_sandbox(provider, **kwargs)
+ print("\nCreating sandbox...")
+ start = time.perf_counter()
+ sandbox.create(timeout=300)
+ setup_time_ms = (time.perf_counter() - start) * 1000
+ print(f" Setup time: {setup_time_ms:.2f} ms")
+ except Exception as e:
+ errors.append(f"Failed to create sandbox: {e}")
+ print(f" ERROR: {e}")
+ return CommandsResult(
+ provider=provider,
+ iterations=iterations,
+ commands=commands,
+ setup_time_ms=0,
+ teardown_time_ms=0,
+ errors=errors,
+ )
+
+ # Run benchmarks
+ print(f"\nRunning {len(TEST_COMMANDS)} commands x {iterations} iterations...")
+
+ for iteration in range(iterations):
+ print(f"\n--- Iteration {iteration + 1}/{iterations} ---")
+
+ for i, (name, cmd, desc) in enumerate(TEST_COMMANDS):
+ try:
+ result = sandbox.run_command(cmd)
+ commands[i].times_ms.append(result.duration_ms)
+ if result.exit_code == 0:
+ commands[i].success_count += 1
+ else:
+ commands[i].fail_count += 1
+ print(f" {name}: {result.duration_ms:.2f} ms (exit={result.exit_code})")
+ except Exception as e:
+ commands[i].fail_count += 1
+ errors.append(f"{name}: {e}")
+ print(f" {name}: ERROR - {e}")
+
+ # Destroy sandbox
+ print("\nDestroying sandbox...")
+ start = time.perf_counter()
+ try:
+ sandbox.destroy()
+ except Exception as e:
+ errors.append(f"Destroy error: {e}")
+ teardown_time_ms = (time.perf_counter() - start) * 1000
+ print(f" Teardown time: {teardown_time_ms:.2f} ms")
+
+ result = CommandsResult(
+ provider=provider,
+ iterations=iterations,
+ commands=commands,
+ setup_time_ms=setup_time_ms,
+ teardown_time_ms=teardown_time_ms,
+ errors=errors,
+ )
+
+ # Summary
+ print(f"\n--- Summary for {provider} ---")
+ print(f"{'Command':<20} {'Avg (ms)':<12} {'Std (ms)':<12} {'Min':<10} {'Max':<10}")
+ print("-" * 64)
+ for cmd in commands:
+ print(f"{cmd.name:<20} {cmd.avg_ms:<12.2f} {cmd.std_ms:<12.2f} "
+ f"{min(cmd.times_ms) if cmd.times_ms else 0:<10.2f} "
+ f"{max(cmd.times_ms) if cmd.times_ms else 0:<10.2f}")
+ print("-" * 64)
+ print(f"{'OVERALL':<20} {result.total_avg_ms:<12.2f}")
+
+ return result
+
+
+if __name__ == "__main__":
+ import argparse
+ import json
+
+ parser = argparse.ArgumentParser(description="Benchmark command execution latency")
+ parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--iterations", type=int, default=3)
+ parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
+
+ args = parser.parse_args()
+
+ result = run_benchmark(
+ args.provider,
+ iterations=args.iterations,
+ base_url=args.opensandbox_url
+ )
+
+ print("\n\nFinal Results (JSON):")
+ print(json.dumps(result.to_dict(), indent=2))
diff --git a/benchmarks/benchmark_concurrency.py b/benchmarks/benchmark_concurrency.py
new file mode 100755
index 00000000..246a02e8
--- /dev/null
+++ b/benchmarks/benchmark_concurrency.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Benchmark: Concurrent sandbox operations."""
+
+import time
+import statistics
+import concurrent.futures
+from typing import Optional
+from dataclasses import dataclass, field
+
+from sandbox_interface import get_sandbox, BaseSandbox
+
+
+@dataclass
+class ConcurrencyResult:
+ """Results from concurrency benchmark."""
+ provider: str
+ concurrency_levels: list[int]
+ results: dict[int, dict] # level -> {total_time, avg_per_sandbox, errors}
+ errors: list[str]
+
+ def to_dict(self) -> dict:
+ return {
+ "provider": self.provider,
+ "concurrency_levels": self.concurrency_levels,
+ "results": self.results,
+ "errors": self.errors,
+ }
+
+
+def run_single_sandbox_workflow(provider: str, index: int, **kwargs) -> dict:
+ """
+ Run a single sandbox workflow.
+
+ Returns timing info dict.
+ """
+ result = {
+ "index": index,
+ "success": False,
+ "create_ms": 0,
+ "command_ms": 0,
+ "destroy_ms": 0,
+ "total_ms": 0,
+ "error": None,
+ }
+
+ sandbox: Optional[BaseSandbox] = None
+ total_start = time.perf_counter()
+
+ try:
+ sandbox = get_sandbox(provider, **kwargs)
+
+ # Create
+ start = time.perf_counter()
+ sandbox.create(timeout=300)
+ result["create_ms"] = (time.perf_counter() - start) * 1000
+
+ # Run commands
+ start = time.perf_counter()
+ sandbox.run_command("echo 'hello from sandbox'")
+ sandbox.run_command("ls -la /")
+ sandbox.run_command("uname -a")
+ result["command_ms"] = (time.perf_counter() - start) * 1000
+
+ # Destroy
+ start = time.perf_counter()
+ sandbox.destroy()
+ result["destroy_ms"] = (time.perf_counter() - start) * 1000
+ sandbox = None
+
+ result["success"] = True
+
+ except Exception as e:
+ result["error"] = str(e)
+ if sandbox:
+ try:
+ sandbox.destroy()
+ except Exception:
+ pass
+
+ result["total_ms"] = (time.perf_counter() - total_start) * 1000
+ return result
+
+
+def run_benchmark(provider: str, iterations: int = 1, **kwargs) -> ConcurrencyResult:
+ """
+ Benchmark concurrent sandbox operations.
+
+ Tests creating multiple sandboxes in parallel.
+
+ Args:
+ provider: "opensandbox" or "e2b"
+ iterations: Not used for concurrency (uses predefined levels)
+
+ Returns:
+ ConcurrencyResult with timing data
+ """
+ print(f"\n{'='*60}")
+ print(f"Concurrency Benchmark: {provider}")
+ print(f"{'='*60}")
+
+ # Test different concurrency levels
+ concurrency_levels = [1, 2, 4, 8]
+ errors = []
+ results = {}
+
+ for level in concurrency_levels:
+ print(f"\n--- Testing {level} concurrent sandbox(es) ---")
+
+ level_results = []
+ total_start = time.perf_counter()
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=level) as executor:
+ futures = [
+ executor.submit(run_single_sandbox_workflow, provider, i, **kwargs)
+ for i in range(level)
+ ]
+
+ for future in concurrent.futures.as_completed(futures):
+ try:
+ res = future.result()
+ level_results.append(res)
+ status = "OK" if res["success"] else f"FAIL: {res['error']}"
+ print(f" Sandbox {res['index']}: {res['total_ms']:.2f}ms - {status}")
+ except Exception as e:
+ errors.append(f"Level {level}: {e}")
+ print(f" ERROR: {e}")
+
+ total_time = (time.perf_counter() - total_start) * 1000
+
+ # Calculate stats
+ successful = [r for r in level_results if r["success"]]
+ if successful:
+ avg_create = statistics.mean([r["create_ms"] for r in successful])
+ avg_command = statistics.mean([r["command_ms"] for r in successful])
+ avg_destroy = statistics.mean([r["destroy_ms"] for r in successful])
+ avg_total = statistics.mean([r["total_ms"] for r in successful])
+ else:
+ avg_create = avg_command = avg_destroy = avg_total = 0
+
+ results[level] = {
+ "concurrency": level,
+ "total_wall_time_ms": round(total_time, 2),
+ "successful": len(successful),
+ "failed": level - len(successful),
+ "avg_create_ms": round(avg_create, 2),
+ "avg_command_ms": round(avg_command, 2),
+ "avg_destroy_ms": round(avg_destroy, 2),
+ "avg_total_ms": round(avg_total, 2),
+ "throughput_per_sec": round(len(successful) / (total_time / 1000), 2) if total_time > 0 else 0,
+ }
+
+ print(f"\n Total wall time: {total_time:.2f} ms")
+ print(f" Successful: {len(successful)}/{level}")
+ print(f" Avg per sandbox: {avg_total:.2f} ms")
+ print(f" Throughput: {results[level]['throughput_per_sec']:.2f} sandboxes/sec")
+
+ result = ConcurrencyResult(
+ provider=provider,
+ concurrency_levels=concurrency_levels,
+ results=results,
+ errors=errors,
+ )
+
+ # Summary
+ print(f"\n--- Summary for {provider} ---")
+ print(f"{'Concurrency':<15} {'Wall Time':<15} {'Avg/Sandbox':<15} {'Throughput':<15}")
+ print("-" * 60)
+ for level in concurrency_levels:
+ r = results[level]
+ print(f"{level:<15} {r['total_wall_time_ms']:<15.2f} "
+ f"{r['avg_total_ms']:<15.2f} {r['throughput_per_sec']:<15.2f}")
+
+ return result
+
+
+if __name__ == "__main__":
+ import argparse
+ import json
+
+ parser = argparse.ArgumentParser(description="Benchmark concurrent sandbox operations")
+ parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
+
+ args = parser.parse_args()
+
+ result = run_benchmark(
+ args.provider,
+ base_url=args.opensandbox_url
+ )
+
+ print("\n\nFinal Results (JSON):")
+ print(json.dumps(result.to_dict(), indent=2))
diff --git a/benchmarks/benchmark_creation.py b/benchmarks/benchmark_creation.py
new file mode 100755
index 00000000..17524862
--- /dev/null
+++ b/benchmarks/benchmark_creation.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""Benchmark: Sandbox creation and destruction time."""
+
+import time
+import statistics
+from typing import Optional
+from dataclasses import dataclass
+
+from sandbox_interface import get_sandbox, BaseSandbox
+
+
+@dataclass
+class CreationResult:
+ """Results from creation benchmark."""
+ provider: str
+ create_times_ms: list[float]
+ destroy_times_ms: list[float]
+ errors: list[str]
+
+ @property
+ def avg_create_ms(self) -> float:
+ return statistics.mean(self.create_times_ms) if self.create_times_ms else 0
+
+ @property
+ def avg_destroy_ms(self) -> float:
+ return statistics.mean(self.destroy_times_ms) if self.destroy_times_ms else 0
+
+ @property
+ def std_create_ms(self) -> float:
+ return statistics.stdev(self.create_times_ms) if len(self.create_times_ms) > 1 else 0
+
+ @property
+ def std_destroy_ms(self) -> float:
+ return statistics.stdev(self.destroy_times_ms) if len(self.destroy_times_ms) > 1 else 0
+
+ def to_dict(self) -> dict:
+ return {
+ "provider": self.provider,
+ "iterations": len(self.create_times_ms),
+ "create": {
+ "avg_ms": round(self.avg_create_ms, 2),
+ "std_ms": round(self.std_create_ms, 2),
+ "min_ms": round(min(self.create_times_ms), 2) if self.create_times_ms else 0,
+ "max_ms": round(max(self.create_times_ms), 2) if self.create_times_ms else 0,
+ "all_ms": [round(t, 2) for t in self.create_times_ms],
+ },
+ "destroy": {
+ "avg_ms": round(self.avg_destroy_ms, 2),
+ "std_ms": round(self.std_destroy_ms, 2),
+ "min_ms": round(min(self.destroy_times_ms), 2) if self.destroy_times_ms else 0,
+ "max_ms": round(max(self.destroy_times_ms), 2) if self.destroy_times_ms else 0,
+ "all_ms": [round(t, 2) for t in self.destroy_times_ms],
+ },
+ "errors": self.errors,
+ }
+
+
+def run_benchmark(provider: str, iterations: int = 3, **kwargs) -> CreationResult:
+ """
+ Benchmark sandbox creation and destruction time.
+
+ Args:
+ provider: "opensandbox" or "e2b"
+ iterations: Number of create/destroy cycles
+
+ Returns:
+ CreationResult with timing data
+ """
+ create_times = []
+ destroy_times = []
+ errors = []
+
+ print(f"\n{'='*60}")
+ print(f"Creation Benchmark: {provider}")
+ print(f"{'='*60}")
+
+ for i in range(iterations):
+ print(f"\nIteration {i+1}/{iterations}...")
+
+ sandbox: Optional[BaseSandbox] = None
+ try:
+ # Measure creation time
+ sandbox = get_sandbox(provider, **kwargs)
+ start = time.perf_counter()
+ sandbox.create(timeout=300)
+ create_time_ms = (time.perf_counter() - start) * 1000
+ create_times.append(create_time_ms)
+ print(f" Create: {create_time_ms:.2f} ms")
+
+ # Measure destruction time
+ start = time.perf_counter()
+ sandbox.destroy()
+ destroy_time_ms = (time.perf_counter() - start) * 1000
+ destroy_times.append(destroy_time_ms)
+ print(f" Destroy: {destroy_time_ms:.2f} ms")
+ sandbox = None
+
+ except Exception as e:
+ error_msg = f"Iteration {i+1}: {str(e)}"
+ errors.append(error_msg)
+ print(f" ERROR: {e}")
+ if sandbox:
+ try:
+ sandbox.destroy()
+ except Exception:
+ pass
+
+ result = CreationResult(
+ provider=provider,
+ create_times_ms=create_times,
+ destroy_times_ms=destroy_times,
+ errors=errors,
+ )
+
+ print(f"\n--- Summary for {provider} ---")
+ print(f"Create: avg={result.avg_create_ms:.2f}ms, std={result.std_create_ms:.2f}ms")
+ print(f"Destroy: avg={result.avg_destroy_ms:.2f}ms, std={result.std_destroy_ms:.2f}ms")
+
+ return result
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Benchmark sandbox creation time")
+ parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--iterations", type=int, default=3)
+ parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
+
+ args = parser.parse_args()
+
+ result = run_benchmark(
+ args.provider,
+ iterations=args.iterations,
+ base_url=args.opensandbox_url
+ )
+
+ print("\n\nFinal Results:")
+ import json
+ print(json.dumps(result.to_dict(), indent=2))
diff --git a/benchmarks/benchmark_files.py b/benchmarks/benchmark_files.py
new file mode 100755
index 00000000..6cc3a3cd
--- /dev/null
+++ b/benchmarks/benchmark_files.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+"""Benchmark: File read/write operations."""
+
+import time
+import statistics
+import string
+import random
+from typing import Optional
+from dataclasses import dataclass, field
+
+from sandbox_interface import get_sandbox, BaseSandbox
+
+
+def generate_content(size_bytes: int) -> str:
+ """Generate random content of specified size."""
+ chars = string.ascii_letters + string.digits + "\n "
+ return ''.join(random.choice(chars) for _ in range(size_bytes))
+
+
+# File sizes to test (name, size in bytes)
+FILE_SIZES = [
+ ("tiny", 100), # 100 bytes
+ ("small", 1024), # 1 KB
+ # ("medium", 10240), # 10 KB - skipped
+ # ("large", 51200), # 50 KB - skipped
+ # ("xlarge", 1048576), # 1 MB - skipped
+]
+
+
+@dataclass
+class FileBenchmark:
+ """Results for a single file size."""
+ name: str
+ size_bytes: int
+ write_times_ms: list[float] = field(default_factory=list)
+ read_times_ms: list[float] = field(default_factory=list)
+ success_count: int = 0
+ fail_count: int = 0
+
+ @property
+ def avg_write_ms(self) -> float:
+ return statistics.mean(self.write_times_ms) if self.write_times_ms else 0
+
+ @property
+ def avg_read_ms(self) -> float:
+ return statistics.mean(self.read_times_ms) if self.read_times_ms else 0
+
+ @property
+ def write_throughput_kbps(self) -> float:
+ """Write throughput in KB/s."""
+ if not self.write_times_ms:
+ return 0
+ avg_sec = self.avg_write_ms / 1000
+ if avg_sec == 0:
+ return 0
+ return (self.size_bytes / 1024) / avg_sec
+
+ @property
+ def read_throughput_kbps(self) -> float:
+ """Read throughput in KB/s."""
+ if not self.read_times_ms:
+ return 0
+ avg_sec = self.avg_read_ms / 1000
+ if avg_sec == 0:
+ return 0
+ return (self.size_bytes / 1024) / avg_sec
+
+ def to_dict(self) -> dict:
+ return {
+ "name": self.name,
+ "size_bytes": self.size_bytes,
+ "write": {
+ "avg_ms": round(self.avg_write_ms, 2),
+ "min_ms": round(min(self.write_times_ms), 2) if self.write_times_ms else 0,
+ "max_ms": round(max(self.write_times_ms), 2) if self.write_times_ms else 0,
+ "throughput_kbps": round(self.write_throughput_kbps, 2),
+ },
+ "read": {
+ "avg_ms": round(self.avg_read_ms, 2),
+ "min_ms": round(min(self.read_times_ms), 2) if self.read_times_ms else 0,
+ "max_ms": round(max(self.read_times_ms), 2) if self.read_times_ms else 0,
+ "throughput_kbps": round(self.read_throughput_kbps, 2),
+ },
+ "success": self.success_count,
+ "fail": self.fail_count,
+ }
+
+
+@dataclass
+class FilesResult:
+ """Results from file benchmark."""
+ provider: str
+ iterations: int
+ files: list[FileBenchmark]
+ setup_time_ms: float
+ teardown_time_ms: float
+ errors: list[str]
+
+ def to_dict(self) -> dict:
+ return {
+ "provider": self.provider,
+ "iterations": self.iterations,
+ "setup_time_ms": round(self.setup_time_ms, 2),
+ "teardown_time_ms": round(self.teardown_time_ms, 2),
+ "files": [f.to_dict() for f in self.files],
+ "errors": self.errors,
+ }
+
+
+def run_benchmark(provider: str, iterations: int = 3, **kwargs) -> FilesResult:
+ """
+ Benchmark file read/write operations.
+
+ Args:
+ provider: "opensandbox" or "e2b"
+ iterations: Number of times to run each test
+
+ Returns:
+ FilesResult with timing data
+ """
+ print(f"\n{'='*60}")
+ print(f"File Operations Benchmark: {provider}")
+ print(f"{'='*60}")
+
+ errors = []
+ files = [FileBenchmark(name=name, size_bytes=size) for name, size in FILE_SIZES]
+
+ # Pre-generate content for each size
+ print("\nGenerating test content...")
+ contents = {}
+ for name, size in FILE_SIZES:
+ contents[name] = generate_content(size)
+ print(f" {name}: {size:,} bytes")
+
+ # Create sandbox
+ sandbox: Optional[BaseSandbox] = None
+ try:
+ sandbox = get_sandbox(provider, **kwargs)
+ print("\nCreating sandbox...")
+ start = time.perf_counter()
+ sandbox.create(timeout=300)
+ setup_time_ms = (time.perf_counter() - start) * 1000
+ print(f" Setup time: {setup_time_ms:.2f} ms")
+
+ # Create test directory
+ sandbox.run_command("mkdir -p /tmp/benchmark")
+
+ except Exception as e:
+ errors.append(f"Failed to create sandbox: {e}")
+ print(f" ERROR: {e}")
+ return FilesResult(
+ provider=provider,
+ iterations=iterations,
+ files=files,
+ setup_time_ms=0,
+ teardown_time_ms=0,
+ errors=errors,
+ )
+
+ # Run benchmarks
+ print(f"\nRunning {len(FILE_SIZES)} file sizes x {iterations} iterations...")
+
+ for iteration in range(iterations):
+ print(f"\n--- Iteration {iteration + 1}/{iterations} ---")
+
+ for i, (name, size) in enumerate(FILE_SIZES):
+ content = contents[name]
+ path = f"/tmp/benchmark/test_{name}_{iteration}.txt"
+
+ try:
+ # Write benchmark
+ write_time = sandbox.write_file(path, content)
+ files[i].write_times_ms.append(write_time)
+
+ # Read benchmark
+ read_content, read_time = sandbox.read_file(path)
+ files[i].read_times_ms.append(read_time)
+
+ # Verify content
+ if read_content.strip() == content.strip():
+ files[i].success_count += 1
+ else:
+ files[i].fail_count += 1
+ errors.append(f"{name}: Content mismatch")
+
+ print(f" {name} ({size:,}B): write={write_time:.2f}ms, read={read_time:.2f}ms")
+
+ except Exception as e:
+ files[i].fail_count += 1
+ errors.append(f"{name}: {e}")
+ print(f" {name}: ERROR - {e}")
+
+ # Destroy sandbox
+ print("\nDestroying sandbox...")
+ start = time.perf_counter()
+ try:
+ sandbox.destroy()
+ except Exception as e:
+ errors.append(f"Destroy error: {e}")
+ teardown_time_ms = (time.perf_counter() - start) * 1000
+ print(f" Teardown time: {teardown_time_ms:.2f} ms")
+
+ result = FilesResult(
+ provider=provider,
+ iterations=iterations,
+ files=files,
+ setup_time_ms=setup_time_ms,
+ teardown_time_ms=teardown_time_ms,
+ errors=errors,
+ )
+
+ # Summary
+ print(f"\n--- Summary for {provider} ---")
+ print(f"{'Size':<10} {'Write Avg':<12} {'Write KB/s':<12} {'Read Avg':<12} {'Read KB/s':<12}")
+ print("-" * 60)
+ for f in files:
+ print(f"{f.name:<10} {f.avg_write_ms:<12.2f} {f.write_throughput_kbps:<12.2f} "
+ f"{f.avg_read_ms:<12.2f} {f.read_throughput_kbps:<12.2f}")
+
+ return result
+
+
+if __name__ == "__main__":
+ import argparse
+ import json
+
+ parser = argparse.ArgumentParser(description="Benchmark file operations")
+ parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--iterations", type=int, default=3)
+ parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
+
+ args = parser.parse_args()
+
+ result = run_benchmark(
+ args.provider,
+ iterations=args.iterations,
+ base_url=args.opensandbox_url
+ )
+
+ print("\n\nFinal Results (JSON):")
+ print(json.dumps(result.to_dict(), indent=2))
diff --git a/benchmarks/benchmark_workflow.py b/benchmarks/benchmark_workflow.py
new file mode 100755
index 00000000..96222445
--- /dev/null
+++ b/benchmarks/benchmark_workflow.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python3
+"""Benchmark: Realistic workflow (git clone, edit, test)."""
+
+import time
+import statistics
+from typing import Optional
+from dataclasses import dataclass, field
+
+from sandbox_interface import get_sandbox, BaseSandbox
+
+
+# Small public repos for testing git clone performance
+TEST_REPOS = [
+ ("tiny", "https://github.com/kelseyhightower/nocode", "~0 files"),
+ ("small", "https://github.com/jlevy/the-art-of-command-line", "~10 files"),
+ # You can add more repos here, but be mindful of rate limits
+]
+
+
+@dataclass
+class WorkflowStep:
+ """Timing for a workflow step."""
+ name: str
+ times_ms: list[float] = field(default_factory=list)
+ success_count: int = 0
+ fail_count: int = 0
+
+ @property
+ def avg_ms(self) -> float:
+ return statistics.mean(self.times_ms) if self.times_ms else 0
+
+ @property
+ def std_ms(self) -> float:
+ return statistics.stdev(self.times_ms) if len(self.times_ms) > 1 else 0
+
+ def to_dict(self) -> dict:
+ return {
+ "name": self.name,
+ "avg_ms": round(self.avg_ms, 2),
+ "std_ms": round(self.std_ms, 2),
+ "min_ms": round(min(self.times_ms), 2) if self.times_ms else 0,
+ "max_ms": round(max(self.times_ms), 2) if self.times_ms else 0,
+ "success": self.success_count,
+ "fail": self.fail_count,
+ }
+
+
+@dataclass
+class WorkflowResult:
+ """Results from workflow benchmark."""
+ provider: str
+ iterations: int
+ steps: dict[str, WorkflowStep]
+ total_times_ms: list[float]
+ errors: list[str]
+
+ @property
+ def avg_total_ms(self) -> float:
+ return statistics.mean(self.total_times_ms) if self.total_times_ms else 0
+
+ def to_dict(self) -> dict:
+ return {
+ "provider": self.provider,
+ "iterations": self.iterations,
+ "total_avg_ms": round(self.avg_total_ms, 2),
+ "total_times_ms": [round(t, 2) for t in self.total_times_ms],
+ "steps": {name: step.to_dict() for name, step in self.steps.items()},
+ "errors": self.errors,
+ }
+
+
+def run_workflow(sandbox: BaseSandbox, repo_url: str) -> dict[str, float]:
+ """
+ Run a single workflow iteration.
+
+ Returns dict of step_name -> duration_ms
+ """
+ timings = {}
+
+ # Step 1: Create directory
+ start = time.perf_counter()
+ result = sandbox.run_command("mkdir -p /tmp/workspace && cd /tmp/workspace && rm -rf repo")
+ timings["mkdir"] = (time.perf_counter() - start) * 1000
+ if result.exit_code != 0:
+ raise RuntimeError(f"mkdir failed: {result.stderr}")
+
+ # Step 2: Git clone (shallow)
+ start = time.perf_counter()
+ result = sandbox.run_command(f"cd /tmp/workspace && git clone --depth 1 {repo_url} repo 2>&1")
+ timings["git_clone"] = (time.perf_counter() - start) * 1000
+ if result.exit_code != 0:
+ raise RuntimeError(f"git clone failed: {result.stderr}")
+
+ # Step 3: List files
+ start = time.perf_counter()
+ result = sandbox.run_command("cd /tmp/workspace/repo && find . -type f | head -50")
+ timings["list_files"] = (time.perf_counter() - start) * 1000
+ if result.exit_code != 0:
+ raise RuntimeError(f"list files failed: {result.stderr}")
+
+ # Step 4: Create a new file
+ start = time.perf_counter()
+ sandbox.write_file("/tmp/workspace/repo/benchmark_test.txt", "This is a benchmark test file.\n" * 100)
+ timings["write_file"] = (time.perf_counter() - start) * 1000
+
+ # Step 5: Read README (if exists)
+ start = time.perf_counter()
+ result = sandbox.run_command("cd /tmp/workspace/repo && cat README.md 2>/dev/null || cat README 2>/dev/null || echo 'no readme'")
+ timings["read_readme"] = (time.perf_counter() - start) * 1000
+
+ # Step 6: Git status
+ start = time.perf_counter()
+ result = sandbox.run_command("cd /tmp/workspace/repo && git status")
+ timings["git_status"] = (time.perf_counter() - start) * 1000
+
+ # Step 7: Git diff
+ start = time.perf_counter()
+ result = sandbox.run_command("cd /tmp/workspace/repo && git diff --stat")
+ timings["git_diff"] = (time.perf_counter() - start) * 1000
+
+ # Step 8: Cleanup
+ start = time.perf_counter()
+ result = sandbox.run_command("rm -rf /tmp/workspace/repo")
+ timings["cleanup"] = (time.perf_counter() - start) * 1000
+
+ return timings
+
+
+def run_benchmark(provider: str, iterations: int = 3, **kwargs) -> WorkflowResult:
+ """
+ Benchmark a realistic git workflow.
+
+ Args:
+ provider: "opensandbox" or "e2b"
+ iterations: Number of complete workflow runs
+
+ Returns:
+ WorkflowResult with timing data
+ """
+ print(f"\n{'='*60}")
+ print(f"Workflow Benchmark: {provider}")
+ print(f"{'='*60}")
+
+ errors = []
+ step_names = ["sandbox_create", "mkdir", "git_clone", "list_files",
+ "write_file", "read_readme", "git_status", "git_diff",
+ "cleanup", "sandbox_destroy"]
+ steps = {name: WorkflowStep(name=name) for name in step_names}
+ total_times = []
+
+ # Use the first (smallest) test repo
+ repo_name, repo_url, repo_desc = TEST_REPOS[0]
+ print(f"\nUsing repo: {repo_name} ({repo_url})")
+ print(f"Description: {repo_desc}")
+
+ for iteration in range(iterations):
+ print(f"\n--- Iteration {iteration + 1}/{iterations} ---")
+
+ sandbox: Optional[BaseSandbox] = None
+ iteration_start = time.perf_counter()
+
+ try:
+ # Create sandbox
+ sandbox = get_sandbox(provider, **kwargs)
+ start = time.perf_counter()
+ sandbox.create(timeout=300)
+ create_time = (time.perf_counter() - start) * 1000
+ steps["sandbox_create"].times_ms.append(create_time)
+ steps["sandbox_create"].success_count += 1
+ print(f" sandbox_create: {create_time:.2f} ms")
+
+ # Run workflow
+ timings = run_workflow(sandbox, repo_url)
+
+ for step_name, duration_ms in timings.items():
+ steps[step_name].times_ms.append(duration_ms)
+ steps[step_name].success_count += 1
+ print(f" {step_name}: {duration_ms:.2f} ms")
+
+ # Destroy sandbox
+ start = time.perf_counter()
+ sandbox.destroy()
+ destroy_time = (time.perf_counter() - start) * 1000
+ steps["sandbox_destroy"].times_ms.append(destroy_time)
+ steps["sandbox_destroy"].success_count += 1
+ print(f" sandbox_destroy: {destroy_time:.2f} ms")
+ sandbox = None
+
+ total_time = (time.perf_counter() - iteration_start) * 1000
+ total_times.append(total_time)
+ print(f" TOTAL: {total_time:.2f} ms")
+
+ except Exception as e:
+ error_msg = f"Iteration {iteration + 1}: {str(e)}"
+ errors.append(error_msg)
+ print(f" ERROR: {e}")
+ if sandbox:
+ try:
+ sandbox.destroy()
+ except Exception:
+ pass
+
+ result = WorkflowResult(
+ provider=provider,
+ iterations=iterations,
+ steps=steps,
+ total_times_ms=total_times,
+ errors=errors,
+ )
+
+ # Summary
+ print(f"\n--- Summary for {provider} ---")
+ print(f"{'Step':<20} {'Avg (ms)':<12} {'Std (ms)':<12} {'Min':<10} {'Max':<10}")
+ print("-" * 64)
+ for step_name in step_names:
+ step = steps[step_name]
+ if step.times_ms:
+ print(f"{step.name:<20} {step.avg_ms:<12.2f} {step.std_ms:<12.2f} "
+ f"{min(step.times_ms):<10.2f} {max(step.times_ms):<10.2f}")
+ print("-" * 64)
+ print(f"{'TOTAL':<20} {result.avg_total_ms:<12.2f}")
+
+ return result
+
+
+if __name__ == "__main__":
+ import argparse
+ import json
+
+ parser = argparse.ArgumentParser(description="Benchmark realistic workflow")
+ parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--iterations", type=int, default=3)
+ parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
+
+ args = parser.parse_args()
+
+ result = run_benchmark(
+ args.provider,
+ iterations=args.iterations,
+ base_url=args.opensandbox_url
+ )
+
+ print("\n\nFinal Results (JSON):")
+ print(json.dumps(result.to_dict(), indent=2))
diff --git a/benchmarks/quick_test.py b/benchmarks/quick_test.py
new file mode 100755
index 00000000..5421f42c
--- /dev/null
+++ b/benchmarks/quick_test.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""
+Quick test to verify sandbox connectivity before running full benchmarks.
+
+Usage:
+ python quick_test.py # Test opensandbox on localhost
+ python quick_test.py --provider e2b # Test e2b (requires E2B_API_KEY)
+"""
+
+import argparse
+import os
+import sys
+import time
+
+from sandbox_interface import get_sandbox
+
+
+def test_provider(provider: str, **kwargs) -> bool:
+ """Test a single provider with basic operations."""
+ print(f"\n{'='*50}")
+ print(f"Testing {provider}")
+ print(f"{'='*50}")
+
+ sandbox = None
+ success = True
+
+ try:
+ # Create
+ print("\n1. Creating sandbox...")
+ sandbox = get_sandbox(provider, **kwargs)
+ start = time.perf_counter()
+ session_id = sandbox.create(timeout=60)
+ create_time = (time.perf_counter() - start) * 1000
+ print(f" OK - Session: {session_id[:20]}... ({create_time:.0f}ms)")
+
+ # Run command
+ print("\n2. Running 'echo hello'...")
+ start = time.perf_counter()
+ result = sandbox.run_command("echo 'Hello from sandbox!'")
+ cmd_time = (time.perf_counter() - start) * 1000
+ if result.exit_code == 0:
+ print(f" OK - Output: {result.stdout.strip()} ({cmd_time:.0f}ms)")
+ else:
+ print(f" FAIL - exit_code={result.exit_code}, stderr={result.stderr}")
+ success = False
+
+ # Write file
+ print("\n3. Writing file...")
+ start = time.perf_counter()
+ sandbox.write_file("/tmp/test.txt", "Hello, World!")
+ write_time = (time.perf_counter() - start) * 1000
+ print(f" OK - Wrote /tmp/test.txt ({write_time:.0f}ms)")
+
+ # Read file
+ print("\n4. Reading file...")
+ start = time.perf_counter()
+ content, _ = sandbox.read_file("/tmp/test.txt")
+ read_time = (time.perf_counter() - start) * 1000
+ if "Hello" in content:
+ print(f" OK - Content: {content.strip()} ({read_time:.0f}ms)")
+ else:
+ print(f" FAIL - Unexpected content: {content}")
+ success = False
+
+ # System info
+ print("\n5. Getting system info...")
+ result = sandbox.run_command("uname -a")
+ print(f" {result.stdout.strip()}")
+
+ # Destroy
+ print("\n6. Destroying sandbox...")
+ start = time.perf_counter()
+ sandbox.destroy()
+ destroy_time = (time.perf_counter() - start) * 1000
+ sandbox = None
+ print(f" OK ({destroy_time:.0f}ms)")
+
+ except Exception as e:
+ print(f"\n ERROR: {e}")
+ success = False
+
+ finally:
+ if sandbox:
+ try:
+ sandbox.destroy()
+ except Exception:
+ pass
+
+ print(f"\n{'='*50}")
+ print(f"Result: {'PASS' if success else 'FAIL'}")
+ print(f"{'='*50}")
+
+ return success
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Quick sandbox connectivity test")
+ parser.add_argument(
+ "--provider",
+ choices=["opensandbox", "e2b", "all"],
+ default="opensandbox",
+ help="Provider to test"
+ )
+ parser.add_argument(
+ "--opensandbox-url",
+ default=os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"),
+ help="OpenSandbox URL"
+ )
+
+ args = parser.parse_args()
+
+ providers = []
+ if args.provider in ["opensandbox", "all"]:
+ providers.append(("opensandbox", {"base_url": args.opensandbox_url}))
+ if args.provider in ["e2b", "all"]:
+ if not os.environ.get("E2B_API_KEY"):
+ print("WARNING: E2B_API_KEY not set, skipping e2b test")
+ else:
+ providers.append(("e2b", {}))
+
+ if not providers:
+ print("No providers to test!")
+ sys.exit(1)
+
+ all_passed = True
+ for provider, kwargs in providers:
+ if not test_provider(provider, **kwargs):
+ all_passed = False
+
+ sys.exit(0 if all_passed else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/requirements.txt b/benchmarks/requirements.txt
new file mode 100644
index 00000000..fe70d4a1
--- /dev/null
+++ b/benchmarks/requirements.txt
@@ -0,0 +1,5 @@
+httpx>=0.27.0
+e2b>=1.0.0
+pydantic>=2.0.0
+pydantic-settings>=2.0.0
+tabulate>=0.9.0
diff --git a/benchmarks/results/benchmark_20260130_172220.json b/benchmarks/results/benchmark_20260130_172220.json
new file mode 100644
index 00000000..3df67823
--- /dev/null
+++ b/benchmarks/results/benchmark_20260130_172220.json
@@ -0,0 +1,360 @@
+{
+ "timestamp": "2026-01-30T17:22:20.720212",
+ "iterations": 3,
+ "providers": {
+ "opensandbox": {}
+ },
+ "benchmarks": {
+ "creation": {
+ "opensandbox": {
+ "provider": "opensandbox",
+ "iterations": 3,
+ "create": {
+ "avg_ms": 131.2,
+ "std_ms": 73.44,
+ "min_ms": 87.29,
+ "max_ms": 215.98,
+ "all_ms": [
+ 87.29,
+ 215.98,
+ 90.33
+ ]
+ },
+ "destroy": {
+ "avg_ms": 84.77,
+ "std_ms": 33.19,
+ "min_ms": 64.9,
+ "max_ms": 123.09,
+ "all_ms": [
+ 123.09,
+ 66.33,
+ 64.9
+ ]
+ },
+ "errors": []
+ }
+ },
+ "commands": {
+ "opensandbox": {
+ "provider": "opensandbox",
+ "iterations": 3,
+ "setup_time_ms": 88.2,
+ "teardown_time_ms": 58.87,
+ "total_avg_ms": 111.35,
+ "commands": [
+ {
+ "name": "echo",
+ "command": "echo 'hello world'",
+ "avg_ms": 67.27,
+ "std_ms": 4.19,
+ "min_ms": 63.38,
+ "max_ms": 71.71,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "pwd",
+ "command": "pwd",
+ "avg_ms": 88.82,
+ "std_ms": 39.75,
+ "min_ms": 65.77,
+ "max_ms": 134.72,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "ls",
+ "command": "ls -la /",
+ "avg_ms": 92.71,
+ "std_ms": 41.82,
+ "min_ms": 67.8,
+ "max_ms": 140.99,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "env",
+ "command": "env | head -20",
+ "avg_ms": 209.79,
+ "std_ms": 256.32,
+ "min_ms": 60.77,
+ "max_ms": 505.77,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "python_version",
+ "command": "python3 --version 2>&1 || python --version 2>&1 || echo 'no python'",
+ "avg_ms": 238.99,
+ "std_ms": 305.79,
+ "min_ms": 62.43,
+ "max_ms": 592.09,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "git_version",
+ "command": "git --version",
+ "avg_ms": 110.21,
+ "std_ms": 82.45,
+ "min_ms": 59.79,
+ "max_ms": 205.36,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "uname",
+ "command": "uname -a",
+ "avg_ms": 64.67,
+ "std_ms": 1.11,
+ "min_ms": 63.64,
+ "max_ms": 65.85,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "cat_etc_os",
+ "command": "cat /etc/os-release 2>/dev/null || cat /etc/debian_version 2>/dev/null || echo 'unknown'",
+ "avg_ms": 62.25,
+ "std_ms": 2.33,
+ "min_ms": 60.89,
+ "max_ms": 64.94,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "loop_100",
+ "command": "for i in $(seq 1 100); do echo $i; done | tail -1",
+ "avg_ms": 90.74,
+ "std_ms": 46.29,
+ "min_ms": 63.4,
+ "max_ms": 144.19,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "calculate",
+ "command": "echo $((12345 * 67890))",
+ "avg_ms": 88.07,
+ "std_ms": 47.28,
+ "min_ms": 60.29,
+ "max_ms": 142.67,
+ "success": 3,
+ "fail": 0
+ }
+ ],
+ "errors": []
+ }
+ },
+ "files": {
+ "opensandbox": {
+ "provider": "opensandbox",
+ "iterations": 3,
+ "setup_time_ms": 599.87,
+ "teardown_time_ms": 58.08,
+ "files": [
+ {
+ "name": "tiny",
+ "size_bytes": 100,
+ "write": {
+ "avg_ms": 209.11,
+ "min_ms": 63.96,
+ "max_ms": 489.59,
+ "throughput_kbps": 0.47
+ },
+ "read": {
+ "avg_ms": 114.31,
+ "min_ms": 111.81,
+ "max_ms": 117.25,
+ "throughput_kbps": 0.85
+ },
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "small",
+ "size_bytes": 1024,
+ "write": {
+ "avg_ms": 67.6,
+ "min_ms": 65.17,
+ "max_ms": 71.79,
+ "throughput_kbps": 14.79
+ },
+ "read": {
+ "avg_ms": 204.31,
+ "min_ms": 63.91,
+ "max_ms": 483.01,
+ "throughput_kbps": 4.89
+ },
+ "success": 3,
+ "fail": 0
+ }
+ ],
+ "errors": []
+ }
+ },
+ "workflow": {
+ "opensandbox": {
+ "provider": "opensandbox",
+ "iterations": 3,
+ "total_avg_ms": 1528.6,
+ "total_times_ms": [
+ 1769.87,
+ 1352.44,
+ 1463.49
+ ],
+ "steps": {
+ "sandbox_create": {
+ "name": "sandbox_create",
+ "avg_ms": 122.0,
+ "std_ms": 27.35,
+ "min_ms": 93.36,
+ "max_ms": 147.84,
+ "success": 3,
+ "fail": 0
+ },
+ "mkdir": {
+ "name": "mkdir",
+ "avg_ms": 219.73,
+ "std_ms": 263.59,
+ "min_ms": 66.0,
+ "max_ms": 524.09,
+ "success": 3,
+ "fail": 0
+ },
+ "git_clone": {
+ "name": "git_clone",
+ "avg_ms": 373.68,
+ "std_ms": 140.98,
+ "min_ms": 284.63,
+ "max_ms": 536.22,
+ "success": 3,
+ "fail": 0
+ },
+ "list_files": {
+ "name": "list_files",
+ "avg_ms": 68.72,
+ "std_ms": 6.2,
+ "min_ms": 63.74,
+ "max_ms": 75.67,
+ "success": 3,
+ "fail": 0
+ },
+ "write_file": {
+ "name": "write_file",
+ "avg_ms": 211.08,
+ "std_ms": 247.5,
+ "min_ms": 67.18,
+ "max_ms": 496.87,
+ "success": 3,
+ "fail": 0
+ },
+ "read_readme": {
+ "name": "read_readme",
+ "avg_ms": 88.26,
+ "std_ms": 41.55,
+ "min_ms": 62.24,
+ "max_ms": 136.18,
+ "success": 3,
+ "fail": 0
+ },
+ "git_status": {
+ "name": "git_status",
+ "avg_ms": 67.45,
+ "std_ms": 1.58,
+ "min_ms": 65.81,
+ "max_ms": 68.96,
+ "success": 3,
+ "fail": 0
+ },
+ "git_diff": {
+ "name": "git_diff",
+ "avg_ms": 73.46,
+ "std_ms": 9.99,
+ "min_ms": 67.25,
+ "max_ms": 84.98,
+ "success": 3,
+ "fail": 0
+ },
+ "cleanup": {
+ "name": "cleanup",
+ "avg_ms": 94.64,
+ "std_ms": 46.35,
+ "min_ms": 63.47,
+ "max_ms": 147.9,
+ "success": 3,
+ "fail": 0
+ },
+ "sandbox_destroy": {
+ "name": "sandbox_destroy",
+ "avg_ms": 201.2,
+ "std_ms": 241.54,
+ "min_ms": 59.97,
+ "max_ms": 480.11,
+ "success": 3,
+ "fail": 0
+ }
+ },
+ "errors": []
+ }
+ },
+ "concurrency": {
+ "opensandbox": {
+ "provider": "opensandbox",
+ "concurrency_levels": [
+ 1,
+ 2,
+ 4,
+ 8
+ ],
+ "results": {
+ "1": {
+ "concurrency": 1,
+ "total_wall_time_ms": 505.06,
+ "successful": 1,
+ "failed": 0,
+ "avg_create_ms": 83.73,
+ "avg_command_ms": 279.25,
+ "avg_destroy_ms": 112.76,
+ "avg_total_ms": 483.85,
+ "throughput_per_sec": 1.98
+ },
+ "2": {
+ "concurrency": 2,
+ "total_wall_time_ms": 408.35,
+ "successful": 2,
+ "failed": 0,
+ "avg_create_ms": 89.2,
+ "avg_command_ms": 248.41,
+ "avg_destroy_ms": 59.38,
+ "avg_total_ms": 405.41,
+ "throughput_per_sec": 4.9
+ },
+ "4": {
+ "concurrency": 4,
+ "total_wall_time_ms": 460.13,
+ "successful": 4,
+ "failed": 0,
+ "avg_create_ms": 93.72,
+ "avg_command_ms": 247.29,
+ "avg_destroy_ms": 78.89,
+ "avg_total_ms": 428.81,
+ "throughput_per_sec": 8.69
+ },
+ "8": {
+ "concurrency": 8,
+ "total_wall_time_ms": 536.99,
+ "successful": 8,
+ "failed": 0,
+ "avg_create_ms": 110.57,
+ "avg_command_ms": 267.7,
+ "avg_destroy_ms": 78.88,
+ "avg_total_ms": 511.07,
+ "throughput_per_sec": 14.9
+ }
+ },
+ "errors": []
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/benchmarks/results/benchmark_20260130_172220.md b/benchmarks/results/benchmark_20260130_172220.md
new file mode 100644
index 00000000..1c6a348f
--- /dev/null
+++ b/benchmarks/results/benchmark_20260130_172220.md
@@ -0,0 +1,73 @@
+# Sandbox Benchmark Results
+
+**Date:** 2026-01-30T17:22:20.720212
+**Iterations:** 3
+
+## 1. Sandbox Creation Time
+
+| Provider | Create Avg (ms) | Create Std | Destroy Avg (ms) |
+|----------|-----------------|------------|------------------|
+| opensandbox | 131.2 | 73.44 | 84.77 |
+
+## 2. Command Execution Latency
+
+| Command | opensandbox (ms) |
+|---------|----------|
+| echo | 67.27 |
+| pwd | 88.82 |
+| ls | 92.71 |
+| env | 209.79 |
+| python_version | 238.99 |
+| git_version | 110.21 |
+| uname | 64.67 |
+| cat_etc_os | 62.25 |
+| loop_100 | 90.74 |
+| calculate | 88.07 |
+
+### Overall Command Execution Average
+
+- **opensandbox:** 111.35 ms
+
+## 3. File Operations
+
+### Write Performance
+
+| Size | opensandbox (ms) |
+|------|----------|
+| tiny (100B) | 209.11 |
+| small (1,024B) | 67.6 |
+
+### Read Performance
+
+| Size | opensandbox (ms) |
+|------|----------|
+| tiny (100B) | 114.31 |
+| small (1,024B) | 204.31 |
+
+## 4. Realistic Workflow (Git Clone + Edit)
+
+| Step | opensandbox (ms) |
+|------|----------|
+| sandbox_create | 122.0 |
+| mkdir | 219.73 |
+| git_clone | 373.68 |
+| list_files | 68.72 |
+| write_file | 211.08 |
+| read_readme | 88.26 |
+| git_status | 67.45 |
+| git_diff | 73.46 |
+| cleanup | 94.64 |
+| sandbox_destroy | 201.2 |
+
+### Total Workflow Time
+
+- **opensandbox:** 1528.6 ms
+
+## 5. Concurrency (Parallel Sandboxes)
+
+| Concurrency | opensandbox Wall Time (ms) | opensandbox Throughput/s |
+|-------------|------------------|------------------|
+| 1 | 505.06 | 1.98 |
+| 2 | 408.35 | 4.9 |
+| 4 | 460.13 | 8.69 |
+| 8 | 536.99 | 14.9 |
diff --git a/benchmarks/results/benchmark_20260130_172241.json b/benchmarks/results/benchmark_20260130_172241.json
new file mode 100644
index 00000000..3b4bf265
--- /dev/null
+++ b/benchmarks/results/benchmark_20260130_172241.json
@@ -0,0 +1,360 @@
+{
+ "timestamp": "2026-01-30T17:22:41.494429",
+ "iterations": 3,
+ "providers": {
+ "e2b": {}
+ },
+ "benchmarks": {
+ "creation": {
+ "e2b": {
+ "provider": "e2b",
+ "iterations": 3,
+ "create": {
+ "avg_ms": 274.37,
+ "std_ms": 317.71,
+ "min_ms": 88.18,
+ "max_ms": 641.21,
+ "all_ms": [
+ 641.21,
+ 88.18,
+ 93.72
+ ]
+ },
+ "destroy": {
+ "avg_ms": 112.99,
+ "std_ms": 25.28,
+ "min_ms": 97.54,
+ "max_ms": 142.17,
+ "all_ms": [
+ 97.54,
+ 99.26,
+ 142.17
+ ]
+ },
+ "errors": []
+ }
+ },
+ "commands": {
+ "e2b": {
+ "provider": "e2b",
+ "iterations": 3,
+ "setup_time_ms": 93.6,
+ "teardown_time_ms": 101.4,
+ "total_avg_ms": 50.59,
+ "commands": [
+ {
+ "name": "echo",
+ "command": "echo 'hello world'",
+ "avg_ms": 60.82,
+ "std_ms": 45.83,
+ "min_ms": 33.77,
+ "max_ms": 113.74,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "pwd",
+ "command": "pwd",
+ "avg_ms": 38.5,
+ "std_ms": 3.37,
+ "min_ms": 35.21,
+ "max_ms": 41.94,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "ls",
+ "command": "ls -la /",
+ "avg_ms": 41.5,
+ "std_ms": 3.39,
+ "min_ms": 39.4,
+ "max_ms": 45.42,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "env",
+ "command": "env | head -20",
+ "avg_ms": 42.6,
+ "std_ms": 6.9,
+ "min_ms": 38.22,
+ "max_ms": 50.56,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "python_version",
+ "command": "python3 --version 2>&1 || python --version 2>&1 || echo 'no python'",
+ "avg_ms": 51.92,
+ "std_ms": 23.15,
+ "min_ms": 37.39,
+ "max_ms": 78.61,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "git_version",
+ "command": "git --version",
+ "avg_ms": 61.91,
+ "std_ms": 40.13,
+ "min_ms": 38.5,
+ "max_ms": 108.26,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "uname",
+ "command": "uname -a",
+ "avg_ms": 38.07,
+ "std_ms": 3.04,
+ "min_ms": 35.13,
+ "max_ms": 41.2,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "cat_etc_os",
+ "command": "cat /etc/os-release 2>/dev/null || cat /etc/debian_version 2>/dev/null || echo 'unknown'",
+ "avg_ms": 67.77,
+ "std_ms": 48.69,
+ "min_ms": 38.45,
+ "max_ms": 123.98,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "loop_100",
+ "command": "for i in $(seq 1 100); do echo $i; done | tail -1",
+ "avg_ms": 64.79,
+ "std_ms": 37.86,
+ "min_ms": 38.76,
+ "max_ms": 108.22,
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "calculate",
+ "command": "echo $((12345 * 67890))",
+ "avg_ms": 37.99,
+ "std_ms": 0.55,
+ "min_ms": 37.44,
+ "max_ms": 38.55,
+ "success": 3,
+ "fail": 0
+ }
+ ],
+ "errors": []
+ }
+ },
+ "files": {
+ "e2b": {
+ "provider": "e2b",
+ "iterations": 3,
+ "setup_time_ms": 92.17,
+ "teardown_time_ms": 239.58,
+ "files": [
+ {
+ "name": "tiny",
+ "size_bytes": 100,
+ "write": {
+ "avg_ms": 33.69,
+ "min_ms": 32.94,
+ "max_ms": 34.97,
+ "throughput_kbps": 2.9
+ },
+ "read": {
+ "avg_ms": 33.04,
+ "min_ms": 32.06,
+ "max_ms": 33.98,
+ "throughput_kbps": 2.96
+ },
+ "success": 3,
+ "fail": 0
+ },
+ {
+ "name": "small",
+ "size_bytes": 1024,
+ "write": {
+ "avg_ms": 61.64,
+ "min_ms": 30.98,
+ "max_ms": 120.33,
+ "throughput_kbps": 16.22
+ },
+ "read": {
+ "avg_ms": 31.88,
+ "min_ms": 31.02,
+ "max_ms": 32.66,
+ "throughput_kbps": 31.37
+ },
+ "success": 3,
+ "fail": 0
+ }
+ ],
+ "errors": []
+ }
+ },
+ "workflow": {
+ "e2b": {
+ "provider": "e2b",
+ "iterations": 3,
+ "total_avg_ms": 1268.46,
+ "total_times_ms": [
+ 1388.84,
+ 1225.63,
+ 1190.92
+ ],
+ "steps": {
+ "sandbox_create": {
+ "name": "sandbox_create",
+ "avg_ms": 125.16,
+ "std_ms": 44.56,
+ "min_ms": 92.77,
+ "max_ms": 175.98,
+ "success": 3,
+ "fail": 0
+ },
+ "mkdir": {
+ "name": "mkdir",
+ "avg_ms": 130.0,
+ "std_ms": 30.19,
+ "min_ms": 100.66,
+ "max_ms": 160.97,
+ "success": 3,
+ "fail": 0
+ },
+ "git_clone": {
+ "name": "git_clone",
+ "avg_ms": 648.47,
+ "std_ms": 110.47,
+ "min_ms": 577.13,
+ "max_ms": 775.72,
+ "success": 3,
+ "fail": 0
+ },
+ "list_files": {
+ "name": "list_files",
+ "avg_ms": 42.84,
+ "std_ms": 2.29,
+ "min_ms": 40.91,
+ "max_ms": 45.37,
+ "success": 3,
+ "fail": 0
+ },
+ "write_file": {
+ "name": "write_file",
+ "avg_ms": 33.93,
+ "std_ms": 2.7,
+ "min_ms": 32.06,
+ "max_ms": 37.03,
+ "success": 3,
+ "fail": 0
+ },
+ "read_readme": {
+ "name": "read_readme",
+ "avg_ms": 37.72,
+ "std_ms": 2.0,
+ "min_ms": 35.42,
+ "max_ms": 39.11,
+ "success": 3,
+ "fail": 0
+ },
+ "git_status": {
+ "name": "git_status",
+ "avg_ms": 37.5,
+ "std_ms": 2.09,
+ "min_ms": 35.85,
+ "max_ms": 39.84,
+ "success": 3,
+ "fail": 0
+ },
+ "git_diff": {
+ "name": "git_diff",
+ "avg_ms": 60.28,
+ "std_ms": 38.09,
+ "min_ms": 36.99,
+ "max_ms": 104.24,
+ "success": 3,
+ "fail": 0
+ },
+ "cleanup": {
+ "name": "cleanup",
+ "avg_ms": 45.16,
+ "std_ms": 3.69,
+ "min_ms": 41.45,
+ "max_ms": 48.83,
+ "success": 3,
+ "fail": 0
+ },
+ "sandbox_destroy": {
+ "name": "sandbox_destroy",
+ "avg_ms": 107.23,
+ "std_ms": 12.57,
+ "min_ms": 99.0,
+ "max_ms": 121.7,
+ "success": 3,
+ "fail": 0
+ }
+ },
+ "errors": []
+ }
+ },
+ "concurrency": {
+ "e2b": {
+ "provider": "e2b",
+ "concurrency_levels": [
+ 1,
+ 2,
+ 4,
+ 8
+ ],
+ "results": {
+ "1": {
+ "concurrency": 1,
+ "total_wall_time_ms": 482.76,
+ "successful": 1,
+ "failed": 0,
+ "avg_create_ms": 103.86,
+ "avg_command_ms": 273.52,
+ "avg_destroy_ms": 100.06,
+ "avg_total_ms": 477.45,
+ "throughput_per_sec": 2.07
+ },
+ "2": {
+ "concurrency": 2,
+ "total_wall_time_ms": 652.2,
+ "successful": 2,
+ "failed": 0,
+ "avg_create_ms": 184.27,
+ "avg_command_ms": 231.9,
+ "avg_destroy_ms": 120.66,
+ "avg_total_ms": 536.84,
+ "throughput_per_sec": 3.07
+ },
+ "4": {
+ "concurrency": 4,
+ "total_wall_time_ms": 583.93,
+ "successful": 4,
+ "failed": 0,
+ "avg_create_ms": 111.25,
+ "avg_command_ms": 294.38,
+ "avg_destroy_ms": 116.54,
+ "avg_total_ms": 522.18,
+ "throughput_per_sec": 6.85
+ },
+ "8": {
+ "concurrency": 8,
+ "total_wall_time_ms": 3138.83,
+ "successful": 8,
+ "failed": 0,
+ "avg_create_ms": 467.79,
+ "avg_command_ms": 474.69,
+ "avg_destroy_ms": 134.27,
+ "avg_total_ms": 1076.79,
+ "throughput_per_sec": 2.55
+ }
+ },
+ "errors": []
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/benchmarks/results/benchmark_20260130_172241.md b/benchmarks/results/benchmark_20260130_172241.md
new file mode 100644
index 00000000..8d16038e
--- /dev/null
+++ b/benchmarks/results/benchmark_20260130_172241.md
@@ -0,0 +1,73 @@
+# Sandbox Benchmark Results
+
+**Date:** 2026-01-30T17:22:41.494429
+**Iterations:** 3
+
+## 1. Sandbox Creation Time
+
+| Provider | Create Avg (ms) | Create Std | Destroy Avg (ms) |
+|----------|-----------------|------------|------------------|
+| e2b | 274.37 | 317.71 | 112.99 |
+
+## 2. Command Execution Latency
+
+| Command | e2b (ms) |
+|---------|----------|
+| echo | 60.82 |
+| pwd | 38.5 |
+| ls | 41.5 |
+| env | 42.6 |
+| python_version | 51.92 |
+| git_version | 61.91 |
+| uname | 38.07 |
+| cat_etc_os | 67.77 |
+| loop_100 | 64.79 |
+| calculate | 37.99 |
+
+### Overall Command Execution Average
+
+- **e2b:** 50.59 ms
+
+## 3. File Operations
+
+### Write Performance
+
+| Size | e2b (ms) |
+|------|----------|
+| tiny (100B) | 33.69 |
+| small (1,024B) | 61.64 |
+
+### Read Performance
+
+| Size | e2b (ms) |
+|------|----------|
+| tiny (100B) | 33.04 |
+| small (1,024B) | 31.88 |
+
+## 4. Realistic Workflow (Git Clone + Edit)
+
+| Step | e2b (ms) |
+|------|----------|
+| sandbox_create | 125.16 |
+| mkdir | 130.0 |
+| git_clone | 648.47 |
+| list_files | 42.84 |
+| write_file | 33.93 |
+| read_readme | 37.72 |
+| git_status | 37.5 |
+| git_diff | 60.28 |
+| cleanup | 45.16 |
+| sandbox_destroy | 107.23 |
+
+### Total Workflow Time
+
+- **e2b:** 1268.46 ms
+
+## 5. Concurrency (Parallel Sandboxes)
+
+| Concurrency | e2b Wall Time (ms) | e2b Throughput/s |
+|-------------|------------------|------------------|
+| 1 | 482.76 | 2.07 |
+| 2 | 652.2 | 3.07 |
+| 4 | 583.93 | 6.85 |
+| 8 | 3138.83 | 2.55 |
diff --git a/benchmarks/run_benchmarks.py b/benchmarks/run_benchmarks.py
new file mode 100755
index 00000000..d6e856dc
--- /dev/null
+++ b/benchmarks/run_benchmarks.py
@@ -0,0 +1,381 @@
+#!/usr/bin/env python3
+"""
+Main benchmark runner for OpenSandbox vs E2B comparison.
+
+Usage:
+ python run_benchmarks.py # Run all benchmarks for both providers
+ python run_benchmarks.py --provider opensandbox # Only test opensandbox
+ python run_benchmarks.py --only creation commands # Only run specific benchmarks
+ python run_benchmarks.py --iterations 5 # Run 5 iterations per test
+"""
+
+import argparse
+import json
+import os
+import sys
+from datetime import datetime
+from pathlib import Path
+
+# Import benchmarks
+import benchmark_creation
+import benchmark_commands
+import benchmark_files
+import benchmark_workflow
+import benchmark_concurrency
+
+
+BENCHMARKS = {
+ "creation": benchmark_creation,
+ "commands": benchmark_commands,
+ "files": benchmark_files,
+ "workflow": benchmark_workflow,
+ "concurrency": benchmark_concurrency,
+}
+
+
+def check_opensandbox_available(url: str) -> bool:
+ """Check if OpenSandbox server is running."""
+ import httpx
+ try:
+ response = httpx.get(f"{url}/health", timeout=5)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def check_e2b_available() -> bool:
+ """Check if E2B API key is configured."""
+ api_key = os.environ.get("E2B_API_KEY", "")
+ return len(api_key) > 10
+
+
+def generate_markdown_report(results: dict, output_path: Path) -> str:
+ """Generate a markdown report from benchmark results."""
+ lines = [
+ "# Sandbox Benchmark Results",
+ "",
+ f"**Date:** {results['timestamp']}",
+ f"**Iterations:** {results['iterations']}",
+ "",
+ ]
+
+ providers = list(results.get("providers", {}).keys())
+
+ # Creation benchmark
+ if "creation" in results.get("benchmarks", {}):
+ lines.extend([
+ "## 1. Sandbox Creation Time",
+ "",
+ "| Provider | Create Avg (ms) | Create Std | Destroy Avg (ms) |",
+ "|----------|-----------------|------------|------------------|",
+ ])
+ for provider in providers:
+ data = results["benchmarks"]["creation"].get(provider, {})
+ if data:
+ create = data.get("create", {})
+ destroy = data.get("destroy", {})
+ lines.append(
+ f"| {provider} | {create.get('avg_ms', 'N/A')} | "
+ f"{create.get('std_ms', 'N/A')} | {destroy.get('avg_ms', 'N/A')} |"
+ )
+ lines.append("")
+
+ # Commands benchmark
+ if "commands" in results.get("benchmarks", {}):
+ lines.extend([
+ "## 2. Command Execution Latency",
+ "",
+ "| Command | " + " | ".join([f"{p} (ms)" for p in providers]) + " |",
+ "|---------|" + "|".join(["----------" for _ in providers]) + "|",
+ ])
+
+ # Get command names from first available provider
+ cmd_names = []
+ for provider in providers:
+ data = results["benchmarks"]["commands"].get(provider, {})
+ if data and "commands" in data:
+ cmd_names = [c["name"] for c in data["commands"]]
+ break
+
+ for cmd_name in cmd_names:
+ row = [cmd_name]
+ for provider in providers:
+ data = results["benchmarks"]["commands"].get(provider, {})
+ cmd_data = next(
+ (c for c in data.get("commands", []) if c["name"] == cmd_name),
+ {}
+ )
+ row.append(str(cmd_data.get("avg_ms", "N/A")))
+ lines.append("| " + " | ".join(row) + " |")
+
+ lines.extend(["", "### Overall Command Execution Average", ""])
+ for provider in providers:
+ data = results["benchmarks"]["commands"].get(provider, {})
+ lines.append(f"- **{provider}:** {data.get('total_avg_ms', 'N/A')} ms")
+ lines.append("")
+
+ # Files benchmark
+ if "files" in results.get("benchmarks", {}):
+ lines.extend([
+ "## 3. File Operations",
+ "",
+ "### Write Performance",
+ "",
+ "| Size | " + " | ".join([f"{p} (ms)" for p in providers]) + " |",
+ "|------|" + "|".join(["----------" for _ in providers]) + "|",
+ ])
+
+ # Get file sizes from first available provider
+ file_names = []
+ for provider in providers:
+ data = results["benchmarks"]["files"].get(provider, {})
+ if data and "files" in data:
+ file_names = [(f["name"], f["size_bytes"]) for f in data["files"]]
+ break
+
+ for file_name, size_bytes in file_names:
+ row = [f"{file_name} ({size_bytes:,}B)"]
+ for provider in providers:
+ data = results["benchmarks"]["files"].get(provider, {})
+ file_data = next(
+ (f for f in data.get("files", []) if f["name"] == file_name),
+ {}
+ )
+ row.append(str(file_data.get("write", {}).get("avg_ms", "N/A")))
+ lines.append("| " + " | ".join(row) + " |")
+
+ lines.extend([
+ "",
+ "### Read Performance",
+ "",
+ "| Size | " + " | ".join([f"{p} (ms)" for p in providers]) + " |",
+ "|------|" + "|".join(["----------" for _ in providers]) + "|",
+ ])
+
+ for file_name, size_bytes in file_names:
+ row = [f"{file_name} ({size_bytes:,}B)"]
+ for provider in providers:
+ data = results["benchmarks"]["files"].get(provider, {})
+ file_data = next(
+ (f for f in data.get("files", []) if f["name"] == file_name),
+ {}
+ )
+ row.append(str(file_data.get("read", {}).get("avg_ms", "N/A")))
+ lines.append("| " + " | ".join(row) + " |")
+ lines.append("")
+
+ # Workflow benchmark
+ if "workflow" in results.get("benchmarks", {}):
+ lines.extend([
+ "## 4. Realistic Workflow (Git Clone + Edit)",
+ "",
+ "| Step | " + " | ".join([f"{p} (ms)" for p in providers]) + " |",
+ "|------|" + "|".join(["----------" for _ in providers]) + "|",
+ ])
+
+ # Get step names from first available provider
+ step_names = []
+ for provider in providers:
+ data = results["benchmarks"]["workflow"].get(provider, {})
+ if data and "steps" in data:
+ step_names = list(data["steps"].keys())
+ break
+
+ for step_name in step_names:
+ row = [step_name]
+ for provider in providers:
+ data = results["benchmarks"]["workflow"].get(provider, {})
+ step_data = data.get("steps", {}).get(step_name, {})
+ row.append(str(step_data.get("avg_ms", "N/A")))
+ lines.append("| " + " | ".join(row) + " |")
+
+ lines.extend(["", "### Total Workflow Time", ""])
+ for provider in providers:
+ data = results["benchmarks"]["workflow"].get(provider, {})
+ lines.append(f"- **{provider}:** {data.get('total_avg_ms', 'N/A')} ms")
+ lines.append("")
+
+ # Concurrency benchmark
+ if "concurrency" in results.get("benchmarks", {}):
+ lines.extend([
+ "## 5. Concurrency (Parallel Sandboxes)",
+ "",
+ "| Concurrency | " + " | ".join([f"{p} Wall Time (ms)" for p in providers]) + " | " + " | ".join([f"{p} Throughput/s" for p in providers]) + " |",
+ "|-------------|" + "|".join(["------------------" for _ in providers]) + "|" + "|".join(["------------------" for _ in providers]) + "|",
+ ])
+
+ # Get concurrency levels from first available provider
+ levels = []
+ for provider in providers:
+ data = results["benchmarks"]["concurrency"].get(provider, {})
+ if data and "concurrency_levels" in data:
+ levels = data["concurrency_levels"]
+ break
+
+ for level in levels:
+ row = [str(level)]
+ for provider in providers:
+ data = results["benchmarks"]["concurrency"].get(provider, {})
+ level_data = data.get("results", {}).get(str(level), data.get("results", {}).get(level, {}))
+ row.append(str(level_data.get("total_wall_time_ms", "N/A")))
+ for provider in providers:
+ data = results["benchmarks"]["concurrency"].get(provider, {})
+ level_data = data.get("results", {}).get(str(level), data.get("results", {}).get(level, {}))
+ row.append(str(level_data.get("throughput_per_sec", "N/A")))
+ lines.append("| " + " | ".join(row) + " |")
+ lines.append("")
+
+ # Errors
+ all_errors = []
+ for bench_name, bench_data in results.get("benchmarks", {}).items():
+ for provider, data in bench_data.items():
+ errors = data.get("errors", [])
+ for err in errors:
+ all_errors.append(f"[{bench_name}/{provider}] {err}")
+
+ if all_errors:
+ lines.extend([
+ "## Errors",
+ "",
+ ])
+ for err in all_errors:
+ lines.append(f"- {err}")
+ lines.append("")
+
+ report = "\n".join(lines)
+
+ with open(output_path, "w") as f:
+ f.write(report)
+
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Run OpenSandbox vs E2B benchmarks",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python run_benchmarks.py # Run all benchmarks
+ python run_benchmarks.py --provider opensandbox # Only test opensandbox
+ python run_benchmarks.py --only creation # Only creation benchmark
+ python run_benchmarks.py --iterations 5 # 5 iterations per test
+ """
+ )
+
+ parser.add_argument(
+ "--provider",
+ choices=["opensandbox", "e2b", "all"],
+ default="all",
+ help="Which provider to benchmark (default: all)"
+ )
+ parser.add_argument(
+ "--only",
+ nargs="+",
+ choices=list(BENCHMARKS.keys()),
+ default=list(BENCHMARKS.keys()),
+ help="Which benchmarks to run (default: all)"
+ )
+ parser.add_argument(
+ "--iterations",
+ type=int,
+ default=3,
+ help="Number of iterations per benchmark (default: 3)"
+ )
+ parser.add_argument(
+ "--opensandbox-url",
+ default=os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"),
+ help="OpenSandbox server URL"
+ )
+ parser.add_argument(
+ "--output-dir",
+ default="results",
+ help="Output directory for results (default: results)"
+ )
+
+ args = parser.parse_args()
+
+ # Determine which providers to test
+ providers = []
+ if args.provider in ["opensandbox", "all"]:
+ if check_opensandbox_available(args.opensandbox_url):
+ providers.append("opensandbox")
+ print(f"✓ OpenSandbox available at {args.opensandbox_url}")
+ else:
+ print(f"✗ OpenSandbox not available at {args.opensandbox_url}")
+ if args.provider == "opensandbox":
+ print(" Start it with: docker compose up --build")
+ sys.exit(1)
+
+ if args.provider in ["e2b", "all"]:
+ if check_e2b_available():
+ providers.append("e2b")
+ print("✓ E2B API key configured")
+ else:
+ print("✗ E2B API key not configured")
+ if args.provider == "e2b":
+ print(" Set it with: export E2B_API_KEY=your_key")
+ sys.exit(1)
+
+ if not providers:
+ print("\nNo providers available. Please ensure at least one is configured.")
+ sys.exit(1)
+
+ print(f"\nRunning benchmarks for: {', '.join(providers)}")
+ print(f"Benchmarks: {', '.join(args.only)}")
+ print(f"Iterations: {args.iterations}")
+
+ # Create output directory
+ output_dir = Path(args.output_dir)
+ output_dir.mkdir(exist_ok=True)
+
+ # Initialize results
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ results = {
+ "timestamp": datetime.now().isoformat(),
+ "iterations": args.iterations,
+ "providers": {p: {} for p in providers},
+ "benchmarks": {},
+ }
+
+ # Run benchmarks
+ for bench_name in args.only:
+ bench_module = BENCHMARKS[bench_name]
+ results["benchmarks"][bench_name] = {}
+
+ print(f"\n{'#'*60}")
+ print(f"# Running {bench_name} benchmark")
+ print(f"{'#'*60}")
+
+ for provider in providers:
+ try:
+ result = bench_module.run_benchmark(
+ provider,
+ iterations=args.iterations,
+ base_url=args.opensandbox_url
+ )
+ results["benchmarks"][bench_name][provider] = result.to_dict()
+ except Exception as e:
+ print(f"ERROR running {bench_name} for {provider}: {e}")
+ results["benchmarks"][bench_name][provider] = {"error": str(e)}
+
+ # Save results
+ json_path = output_dir / f"benchmark_{timestamp}.json"
+ with open(json_path, "w") as f:
+ json.dump(results, f, indent=2)
+ print(f"\n\nResults saved to: {json_path}")
+
+ # Generate markdown report
+ md_path = output_dir / f"benchmark_{timestamp}.md"
+ report = generate_markdown_report(results, md_path)
+ print(f"Report saved to: {md_path}")
+
+ # Print summary
+ print("\n" + "="*60)
+ print("SUMMARY")
+ print("="*60)
+ print(report)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/sandbox_interface.py b/benchmarks/sandbox_interface.py
new file mode 100755
index 00000000..ece8155b
--- /dev/null
+++ b/benchmarks/sandbox_interface.py
@@ -0,0 +1,199 @@
+"""Simplified sandbox interfaces for benchmarking."""
+
+import os
+import time
+import httpx
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class CommandResult:
+ """Result of a command execution."""
+ stdout: str
+ stderr: str
+ exit_code: int
+ duration_ms: float = 0.0
+
+
+class BaseSandbox(ABC):
+ """Base sandbox interface for benchmarking."""
+
+ @property
+ @abstractmethod
+ def name(self) -> str:
+ """Provider name."""
+ pass
+
+ @abstractmethod
+ def create(self, timeout: int = 300) -> str:
+ """Create a sandbox, return session ID."""
+ pass
+
+ @abstractmethod
+ def run_command(self, command: str) -> CommandResult:
+ """Run a command in the sandbox."""
+ pass
+
+ @abstractmethod
+ def write_file(self, path: str, content: str) -> float:
+ """Write a file, return duration in ms."""
+ pass
+
+ @abstractmethod
+ def read_file(self, path: str) -> tuple[str, float]:
+ """Read a file, return (content, duration_ms)."""
+ pass
+
+ @abstractmethod
+ def destroy(self) -> None:
+ """Destroy the sandbox."""
+ pass
+
+
+class OpenSandboxClient(BaseSandbox):
+ """OpenSandbox HTTP client for benchmarking."""
+
+ def __init__(self, base_url: str = "http://localhost:8080"):
+ self.base_url = base_url
+ self.session_id: Optional[str] = None
+ self.client = httpx.Client(timeout=300)
+
+ @property
+ def name(self) -> str:
+ return "opensandbox"
+
+ def create(self, timeout: int = 300) -> str:
+ response = self.client.post(
+ f"{self.base_url}/sessions",
+ json={"env": {}}
+ )
+ response.raise_for_status()
+ self.session_id = response.json()["session_id"]
+ return self.session_id
+
+ def run_command(self, command: str) -> CommandResult:
+ if not self.session_id:
+ raise RuntimeError("Session not created")
+
+ start = time.perf_counter()
+ response = self.client.post(
+ f"{self.base_url}/sessions/{self.session_id}/run",
+ json={
+ "command": ["/bin/sh", "-c", command],
+ "time": 300000,
+ "mem": 2097152,
+ }
+ )
+ duration_ms = (time.perf_counter() - start) * 1000
+
+ if response.status_code != 200:
+ return CommandResult(
+ stdout="",
+ stderr=response.text,
+ exit_code=1,
+ duration_ms=duration_ms
+ )
+
+ data = response.json()
+ exit_code = data.get("exit_code", 0)
+ if data.get("signal"):
+ exit_code = 128 + data["signal"]
+
+ return CommandResult(
+ stdout=data.get("stdout", ""),
+ stderr=data.get("stderr", ""),
+ exit_code=exit_code,
+ duration_ms=duration_ms
+ )
+
+ def write_file(self, path: str, content: str) -> float:
+ import base64
+ b64_content = base64.b64encode(content.encode()).decode()
+ result = self.run_command(f"echo '{b64_content}' | base64 -d > {path}")
+ return result.duration_ms
+
+ def read_file(self, path: str) -> tuple[str, float]:
+ result = self.run_command(f"cat {path}")
+ return result.stdout, result.duration_ms
+
+ def destroy(self) -> None:
+ if self.session_id:
+ try:
+ self.client.delete(f"{self.base_url}/sessions/{self.session_id}")
+ except Exception:
+ pass
+ self.session_id = None
+ self.client.close()
+
+
+class E2BSandboxClient(BaseSandbox):
+ """E2B sandbox client for benchmarking."""
+
+ def __init__(self):
+ self._sandbox = None
+ self._sandbox_id: Optional[str] = None
+
+ @property
+ def name(self) -> str:
+ return "e2b"
+
+ def create(self, timeout: int = 300) -> str:
+ from e2b import Sandbox
+ self._sandbox = Sandbox.create(timeout=timeout)
+ self._sandbox_id = self._sandbox.sandbox_id
+ return self._sandbox_id
+
+ def run_command(self, command: str) -> CommandResult:
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created")
+
+ start = time.perf_counter()
+ result = self._sandbox.commands.run(command, timeout=300)
+ duration_ms = (time.perf_counter() - start) * 1000
+
+ return CommandResult(
+ stdout=result.stdout,
+ stderr=result.stderr,
+ exit_code=result.exit_code,
+ duration_ms=duration_ms
+ )
+
+ def write_file(self, path: str, content: str) -> float:
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created")
+
+ start = time.perf_counter()
+ self._sandbox.files.write(path, content)
+ duration_ms = (time.perf_counter() - start) * 1000
+ return duration_ms
+
+ def read_file(self, path: str) -> tuple[str, float]:
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created")
+
+ start = time.perf_counter()
+ content = self._sandbox.files.read(path)
+ duration_ms = (time.perf_counter() - start) * 1000
+ return content, duration_ms
+
+ def destroy(self) -> None:
+ if self._sandbox:
+ try:
+ self._sandbox.kill()
+ except Exception:
+ pass
+ self._sandbox = None
+ self._sandbox_id = None
+
+
+def get_sandbox(provider: str, **kwargs) -> BaseSandbox:
+ """Factory function to get a sandbox instance."""
+ if provider == "opensandbox":
+ base_url = kwargs.get("base_url", os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"))
+ return OpenSandboxClient(base_url=base_url)
+ elif provider == "e2b":
+ return E2BSandboxClient()
+ else:
+ raise ValueError(f"Unknown provider: {provider}")