Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(sandbox): 同步全部业务修改,使用合规CLA邮箱

feitiandadaddddc0d6c45c
diff --git a/jiuwenbox/tests/system_tests/TEST_GUIDE.md b/jiuwenbox/tests/system_tests/TEST_GUIDE.md
new file mode 100644
index 0000000000..5a28983b87
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/TEST_GUIDE.md
@@ -0,0 +1,410 @@
+# jiuwenbox 沙箱服务自动化测试执行指导书
+
+## 一、测试框架概述
+
+本自动化测试框架基于 Python + pytest 构建,用于验证 jiuwenbox 沙箱服务的性能与可靠性。测试框架包含以下模块:
+
+| 模块 | 文件 | 功能 |
+|------|------|------|
+| 配置管理 | `test_config.py` | 测试配置参数和环境检测 |
+| 工具类 | `test_utils.py` | 资源劣化管理、混沌注入、性能收集等 |
+| 状态机测试 | `test_state_machine.py` | 沙箱生命周期状态转移测试 |
+| 资源劣化测试 | `test_resource_degradation.py` | CPU/内存/网络/磁盘劣化测试 |
+| 混沌工程测试 | `test_chaos_engineering.py` | 故障注入和系统韧性测试 |
+| cgroup 测试 | `test_cgroup_limits.py` | CPU/内存资源限制测试 |
+| 错误边界测试 | `test_error_boundaries.py` | 权限错误、磁盘满、网络超时等边界测试 |
+| 性能测试 | `test_performance.py` | QPS、时延等性能指标测试 |
+| 可靠性测试 | `test_reliability.py` | 自动恢复、fallback、reaper 等可靠性测试 |
+| 配置约束测试 | `test_config_constraints.py` | 参数组合约束测试 |
+| 文件传输测试 | `test_file_transfer.py` | 文件上传/下载速率、成功率、完整性测试 |
+| 并发创建测试 | `test_concurrent_create.py` | 沙箱并发创建性能测试 |
+| 长稳测试 | `test_long_stability.py` | 沙箱带负载长时间稳定性测试 |
+
+## 二、环境要求
+
+### 2.1 基础环境
+
+- Python 3.10+
+- pytest 7.0+
+- httpx 0.24+
+
+### 2.2 可选依赖(Linux 专用)
+
+| 工具 | 用途 | 对应测试模块 |
+|------|------|-------------|
+| stress-ng | CPU/内存劣化 | 资源劣化测试、混沌工程测试 |
+| tc (traffic control) | 网络劣化 | 网络劣化测试 |
+| iproute2 | 网络断开/恢复 | 混沌工程测试 |
+| Docker | 容器级测试 | 可靠性测试(REL-002、REL-007) |
+
+### 2.3 环境检测
+
+运行以下命令检测环境能力:
+
+```bash
+python -c "from tests.system_tests.test_config import EnvironmentDetector; EnvironmentDetector.print_capabilities()"
+```
+
+输出示例:
+
+```
+==================================================
+Environment Capabilities
+==================================================
+ ✓ linux
+ ✗ windows
+ ✗ macos
+ ✓ stress_ng
+ ✓ tc
+ ✓ iproute2
+ ✓ docker
+ ✓ resource_tests
+ ✓ network_tests
+ ✓ chaos_tests
+==================================================
+```
+
+## 三、安装步骤
+
+### 3.1 安装 Python 依赖
+
+```bash
+cd jiuwenbox
+pip install pytest httpx
+```
+
+### 3.2 安装 Linux 专用工具(可选)
+
+```bash
+# Ubuntu/Debian
+sudo apt-get install -y stress-ng iproute2
+
+# CentOS/RHEL
+sudo yum install -y stress-ng iproute2
+
+# 确保 tc 模块可用
+sudo modprobe sch_netem
+```
+
+## 四、配置说明
+
+### 4.1 环境变量配置
+
+所有配置参数均可通过环境变量覆盖:
+
+| 环境变量 | 默认值 | 说明 |
+|----------|--------|------|
+| JIUWENBOX_SERVER | http://localhost:8080 | 沙箱服务地址 |
+| TEST_TIMEOUT | 120 | 测试默认超时(秒) |
+| SANDBOX_READY_TIMEOUT | 30 | 沙箱就绪超时(秒) |
+| EXEC_TIMEOUT | 60 | 命令执行超时(秒) |
+| QPS_SINGLE_THRESHOLD | 50 | 单实例 QPS 阈值 |
+| QPS_MULTI_THRESHOLD | 100 | 多实例 QPS 阈值 |
+| LATENCY_COMMAND_THRESHOLD | 0.05 | 命令执行时延阈值(秒) |
+| LATENCY_STARTUP_THRESHOLD | 0.1 | 沙箱启动时延阈值(秒) |
+| LATENCY_SERVICE_THRESHOLD | 1.0 | 服务启动时延阈值(秒) |
+| P999_SPIKE_THRESHOLD | 0.5 | P999 时延毛刺阈值(秒) |
+| NETWORK_INTERFACE | eth0 | 网络接口名称 |
+| FILE_UPLOAD_SPEED_THRESHOLD | 10 | 文件上传速率阈值(MB/s) |
+| FILE_DOWNLOAD_SPEED_THRESHOLD | 20 | 文件下载速率阈值(MB/s) |
+| FILE_TRANSFER_TIMEOUT | 300 | 文件传输超时(秒) |
+| CONCURRENT_CREATE_TIMEOUT_5 | 10 | 并发创建5个沙箱超时(秒) |
+| CONCURRENT_CREATE_TIMEOUT_10 | 20 | 并发创建10个沙箱超时(秒) |
+| CONCURRENT_CREATE_TIMEOUT_20 | 40 | 并发创建20个沙箱超时(秒) |
+| LONG_STABILITY_DURATION_30MIN | 1800 | 长稳测试30分钟时长(秒) |
+| LONG_STABILITY_DURATION_1HOUR | 3600 | 长稳测试1小时时长(秒) |
+| LONG_STABILITY_SANDBOX_COUNT | 5 | 长稳测试沙箱数量 |
+| LONG_STABILITY_SUCCESS_RATE_THRESHOLD | 0.999 | 长稳测试成功率阈值 |
+| LONG_STABILITY_AVG_LATENCY_THRESHOLD | 0.1 | 长稳测试平均时延阈值(秒) |
+| LONG_STABILITY_P99_LATENCY_THRESHOLD | 0.3 | 长稳测试P99时延阈值(秒) |
+
+### 4.2 配置示例
+
+```bash
+export JIUWENBOX_SERVER=http://192.168.1.100:8080
+export QPS_SINGLE_THRESHOLD=150
+export QPS_MULTI_THRESHOLD=500
+export LATENCY_COMMAND_THRESHOLD=0.05
+export LATENCY_STARTUP_THRESHOLD=0.1
+export LATENCY_SERVICE_THRESHOLD=1.0
+```
+
+## 五、测试执行
+
+### 5.1 运行所有系统测试
+
+```bash
+python -m pytest tests/system_tests/ -v
+```
+
+### 5.2 运行特定模块测试
+
+```bash
+# 状态机测试
+python -m pytest tests/system_tests/test_state_machine.py -v
+
+# 性能测试
+python -m pytest tests/system_tests/test_performance.py -v
+
+# 可靠性测试
+python -m pytest tests/system_tests/test_reliability.py -v
+
+# 资源劣化测试
+python -m pytest tests/system_tests/test_resource_degradation.py -v
+
+# 混沌工程测试
+python -m pytest tests/system_tests/test_chaos_engineering.py -v
+
+# 文件传输测试
+python -m pytest tests/system_tests/test_file_transfer.py -v
+
+# 并发创建测试
+python -m pytest tests/system_tests/test_concurrent_create.py -v
+
+# 长稳测试(30分钟)
+python -m pytest tests/system_tests/test_long_stability.py::TestLongStability::test_ls_001_long_stability_30min -v
+
+# 长稳测试(1小时)
+python -m pytest tests/system_tests/test_long_stability.py::TestLongStability::test_ls_002_long_stability_1hour -v
+```
+
+### 5.3 使用标记运行测试
+
+```bash
+# 运行所有系统测试
+python -m pytest tests/system_tests/ -m system -v
+
+# 运行性能测试
+python -m pytest tests/system_tests/ -m performance -v
+
+# 运行慢速测试(资源劣化、混沌工程等)
+python -m pytest tests/system_tests/ -m slow -v
+
+# 排除慢速测试
+python -m pytest tests/system_tests/ -v --ignore-glob="*slow*"
+```
+
+### 5.4 运行特定测试用例
+
+```bash
+# 运行单个测试用例
+python -m pytest tests/system_tests/test_performance.py::TestPerformanceMetrics::test_perf_001_qps_single_sandbox -v
+
+# 运行多个测试用例
+python -m pytest tests/system_tests/test_reliability.py::TestReliability::test_rel_001_sandbox_process_auto_restart \
+ tests/system_tests/test_reliability.py::TestReliability::test_rel_002_container_process_auto_restart -v
+```
+
+### 5.5 生成测试报告
+
+```bash
+# 生成 HTML 报告
+pip install pytest-html
+python -m pytest tests/system_tests/ -v --html=test_report.html
+
+# 生成 XML 报告(用于 CI/CD)
+pip install pytest-xdist pytest-junitxml
+python -m pytest tests/system_tests/ -v --junitxml=test_results.xml
+
+# 并行运行测试(加速)
+python -m pytest tests/system_tests/ -v -n auto
+```
+
+## 六、测试用例覆盖清单
+
+### 6.1 已实现的测试用例(82/82)
+
+| 测试类别 | 用例数 | 状态 |
+|----------|--------|------|
+| 状态机模型 | 17 | ✅ 完整 |
+| 资源劣化矩阵 | 14 | ✅ 完整 |
+| 混沌工程 | 8 | ✅ 完整 |
+| cgroup 资源限制 | 6 | ✅ 完整 |
+| 错误边界 | 6 | ✅ 完整 |
+| 性能指标 | 7 | ✅ 完整 |
+| 可靠性 | 10 | ✅ 完整 |
+| 配置参数约束 | 6 | ✅ 完整 |
+| 文件传输 | 3 | ✅ 完整 |
+| 并发创建 | 3 | ✅ 完整 |
+| 长稳测试 | 2 | ✅ 完整 |
+
+### 6.2 测试标记说明
+
+| 标记 | 说明 |
+|------|------|
+| @pytest.mark.system | 系统测试 |
+| @pytest.mark.performance | 性能测试 |
+| @pytest.mark.slow | 慢速测试(资源劣化、混沌工程等) |
+
+## 七、测试注意事项
+
+### 7.1 权限要求
+
+部分测试需要 root 权限:
+- cgroup 资源限制测试
+- 网络劣化测试(tc 命令)
+- 网络断开/恢复测试(ip 命令)
+
+建议使用 sudo 运行:
+
+```bash
+sudo python -m pytest tests/system_tests/ -v
+```
+
+### 7.2 环境兼容性
+
+| 测试模块 | Linux | Windows | macOS |
+|----------|-------|---------|-------|
+| 状态机测试 | ✅ | ✅ | ✅ |
+| cgroup 测试 | ✅ | ✗ | ✗ |
+| 资源劣化测试 | ✅(需 stress-ng) | ✗ | ✗ |
+| 混沌工程测试 | ✅(需 stress-ng + iproute2) | ✗ | ✗ |
+| 错误边界测试 | ✅ | ✅ | ✅ |
+| 性能测试 | ✅ | ✅ | ✅ |
+| 可靠性测试 | ✅ | ✅ | ✅ |
+| 配置约束测试 | ✅ | ✅ | ✅ |
+
+非兼容环境下,相关测试会自动跳过,不会报错。
+
+### 7.3 测试顺序
+
+建议按以下顺序执行测试:
+
+1. 状态机测试(基础功能验证)
+2. 配置约束测试(参数验证)
+3. cgroup 测试(资源限制验证)
+4. 错误边界测试(边界条件验证)
+5. 可靠性测试(核心可靠性验证)
+6. 性能测试(性能指标验证)
+7. 资源劣化测试(资源劣化验证)
+8. 混沌工程测试(故障注入验证)
+
+### 7.4 测试时间估算
+
+| 测试模块 | 预计时间 |
+|----------|---------|
+| 状态机测试 | 5-10 分钟 |
+| 配置约束测试 | 5-10 分钟 |
+| cgroup 测试 | 10-15 分钟 |
+| 错误边界测试 | 10-15 分钟 |
+| 可靠性测试 | 15-30 分钟 |
+| 性能测试 | 15-30 分钟 |
+| 资源劣化测试 | 30-60 分钟 |
+| 混沌工程测试 | 30-60 分钟 |
+| 文件传输测试 | 10-30 分钟 |
+| 并发创建测试 | 5-30 分钟 |
+| 长稳测试(30分钟) | 30 分钟 |
+| 长稳测试(1小时) | 60 分钟 |
+| **总计(不含长稳)** | **120-220 分钟** |
+| **总计(含长稳)** | **210-280 分钟** |
+
+## 八、故障排查
+
+### 8.1 常见问题
+
+| 问题 | 原因 | 解决方案 |
+|------|------|----------|
+| 连接拒绝 | 服务未启动或地址错误 | 检查 JIUWENBOX_SERVER 环境变量 |
+| 权限错误 | 测试需要 root 权限 | 使用 sudo 运行测试 |
+| stress-ng 未找到 | 未安装 stress-ng | 安装 stress-ng |
+| tc 未找到 | 未安装 iproute2 | 安装 iproute2 |
+| 测试超时 | 服务响应慢或资源不足 | 增加 TEST_TIMEOUT 环境变量 |
+| 网络测试失败 | 网络接口名称错误 | 设置 NETWORK_INTERFACE 环境变量 |
+
+### 8.2 调试技巧
+
+```bash
+# 启用详细日志
+python -m pytest tests/system_tests/ -v -s
+
+# 只运行失败的测试
+python -m pytest tests/system_tests/ -v --last-failed
+
+# 运行单个测试并启用调试
+python -m pytest tests/system_tests/test_performance.py::TestPerformanceMetrics::test_perf_001_qps_single_sandbox -v -s
+```
+
+## 九、CI/CD 集成
+
+### 9.1 GitHub Actions 示例
+
+```yaml
+name: System Tests
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.10'
+ - name: Install dependencies
+ run: |
+ pip install pytest httpx
+ sudo apt-get install -y stress-ng iproute2
+ sudo modprobe sch_netem
+ - name: Start jiuwenbox server
+ run: |
+ # 启动沙箱服务
+ nohup python -m jiuwenbox.server --host 0.0.0.0 --port 8080 &
+ sleep 10
+ - name: Run system tests
+ run: |
+ export JIUWENBOX_SERVER=http://localhost:8080
+ python -m pytest tests/system_tests/ -v --junitxml=test_results.xml
+ - name: Upload test results
+ uses: actions/upload-artifact@v4
+ with:
+ name: test-results
+ path: test_results.xml
+```
+
+### 9.2 GitLab CI 示例
+
+```yaml
+system_tests:
+ stage: test
+ image: python:3.10
+ before_script:
+ - pip install pytest httpx
+ - apt-get update && apt-get install -y stress-ng iproute2
+ - modprobe sch_netem
+ - # 启动沙箱服务
+ - python -m jiuwenbox.server --host 0.0.0.0 --port 8080 &
+ - sleep 10
+ script:
+ - export JIUWENBOX_SERVER=http://localhost:8080
+ - python -m pytest tests/system_tests/ -v --junitxml=test_results.xml
+ artifacts:
+ reports:
+ junit: test_results.xml
+```
+
+## 十、扩展指南
+
+### 10.1 添加新测试用例
+
+1. 在 `test_cases.md` 中定义测试用例
+2. 在对应的测试文件中实现测试函数
+3. 使用 pytest 标记(`@pytest.mark.system` 等)
+
+### 10.2 添加新配置参数
+
+1. 在 `test_config.py` 的 `TestConfig` 类中添加新参数
+2. 在测试中引用该参数
+3. 在指导书中添加环境变量说明
+
+### 10.3 添加新工具类
+
+1. 在 `test_utils.py` 中添加新类或方法
+2. 在测试中导入并使用
+
+---
+
+**文档版本**: v1.0
+**创建日期**: 2026-07-01
+**适用框架**: pytest + Python 3.10+
diff --git a/jiuwenbox/tests/system_tests/conftest.py b/jiuwenbox/tests/system_tests/conftest.py
new file mode 100644
index 0000000000..e52010e65d
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/conftest.py
@@ -0,0 +1,266 @@
+"""Shared fixtures for system reliability and performance tests."""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+
+import httpx
+import pytest
+
+from tests.system_tests.test_config import EnvironmentDetector, TestConfig
+
+logger = logging.getLogger(__name__)
+
+
+def pytest_configure(config):
+ config.addinivalue_line(
+ "markers",
+ "chaos: chaos engineering tests requiring Linux, stress-ng, and iproute2",
+ )
+ config.addinivalue_line(
+ "markers",
+ "resource_degradation: tests requiring Linux and stress-ng",
+ )
+ config.addinivalue_line(
+ "markers",
+ "network_degradation: tests requiring Linux and tc",
+ )
+
+
+def pytest_collection_modifyitems(config, items):
+ """Skip environment-specific tests when required tools are unavailable."""
+ if not EnvironmentDetector.can_run_chaos_tests():
+ skip_chaos = pytest.mark.skip(
+ reason="Chaos tests require Linux + stress-ng + iproute2"
+ )
+ for item in items:
+ if item.get_closest_marker("chaos"):
+ item.add_marker(skip_chaos)
+
+ if not EnvironmentDetector.can_run_resource_tests():
+ skip_resource = pytest.mark.skip(
+ reason="Resource degradation tests require Linux + stress-ng"
+ )
+ for item in items:
+ if item.get_closest_marker("resource_degradation"):
+ item.add_marker(skip_resource)
+
+ if not EnvironmentDetector.can_run_network_tests():
+ skip_network = pytest.mark.skip(
+ reason="Network tests require Linux + tc"
+ )
+ for item in items:
+ if item.get_closest_marker("network_degradation"):
+ item.add_marker(skip_network)
+
+
+_UDS_SCHEME = "unix://"
+_UDS_PLACEHOLDER_BASE_URL = "http://jiuwenbox"
+
+
+def _normalize_endpoint(endpoint: str) -> str:
+ return endpoint if "://" in endpoint else f"http://{endpoint}"
+
+
+def _build_httpx_client(endpoint: str, *, timeout: float = 30.0) -> httpx.Client:
+ if endpoint.startswith(_UDS_SCHEME):
+ uds_path = endpoint[len(_UDS_SCHEME):]
+ if not uds_path.startswith("/"):
+ raise ValueError(f"unix endpoint requires absolute path: {endpoint!r}")
+ return httpx.Client(
+ transport=httpx.HTTPTransport(uds=uds_path),
+ base_url=_UDS_PLACEHOLDER_BASE_URL,
+ timeout=timeout,
+ )
+ return httpx.Client(base_url=_normalize_endpoint(endpoint), timeout=timeout)
+
+
+class SandboxTrackingClient:
+ """Track sandboxes created during a test and clean them up afterwards."""
+
+ def __init__(self, endpoint: str, *, timeout: float = 30.0):
+ self._endpoint = endpoint
+ self._timeout = timeout
+ self._local = threading.local()
+ self._clients: list[httpx.Client] = []
+ self._clients_lock = threading.Lock()
+ self._created_ids: list[str] = []
+ self._created_ids_lock = threading.Lock()
+
+ def _get_client(self) -> httpx.Client:
+ client = getattr(self._local, "client", None)
+ if client is None:
+ client = _build_httpx_client(self._endpoint, timeout=self._timeout)
+ self._local.client = client
+ with self._clients_lock:
+ self._clients.append(client)
+ return client
+
+ def __getattr__(self, name: str):
+ return getattr(self._get_client(), name)
+
+ def post(self, url, *args, **kwargs):
+ response = self._get_client().post(url, *args, **kwargs)
+ if str(url).rstrip("/") == "/api/v1/sandboxes" and response.status_code == 201:
+ try:
+ sandbox_id = response.json().get("id")
+ except Exception as exc:
+ logger.debug("Failed to parse sandbox create response: %s", exc)
+ sandbox_id = None
+ if sandbox_id:
+ with self._created_ids_lock:
+ self._created_ids.append(sandbox_id)
+ return response
+
+ def delete(self, url, *args, **kwargs):
+ response = self._get_client().delete(url, *args, **kwargs)
+ sandbox_id = self._sandbox_id_from_delete_url(url)
+ if sandbox_id and response.status_code in (200, 202, 204, 404):
+ with self._created_ids_lock:
+ self._created_ids = [item for item in self._created_ids if item != sandbox_id]
+ return response
+
+ def track_sandbox(self, sandbox_id: str) -> None:
+ with self._created_ids_lock:
+ self._created_ids.append(sandbox_id)
+
+ def cleanup_sandboxes(self) -> None:
+ with self._created_ids_lock:
+ ids = list(reversed(self._created_ids))
+ self._created_ids.clear()
+ if not ids:
+ return
+ with _build_httpx_client(self._endpoint, timeout=self._timeout) as cleanup_client:
+ for sandbox_id in ids:
+ try:
+ cleanup_client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ except Exception as exc:
+ logger.warning("Failed to cleanup sandbox %s: %s", sandbox_id, exc)
+
+ def close(self) -> None:
+ with self._clients_lock:
+ clients = self._clients
+ self._clients = []
+ for client in clients:
+ try:
+ client.close()
+ except Exception as exc:
+ logger.debug("Failed to close httpx client: %s", exc)
+ self._local.client = None
+
+ @staticmethod
+ def _sandbox_id_from_delete_url(url) -> str | None:
+ path = str(url).split("?", 1)[0].rstrip("/")
+ prefix = "/api/v1/sandboxes/"
+ if not path.startswith(prefix):
+ return None
+ suffix = path[len(prefix):]
+ if "/" in suffix:
+ return None
+ return suffix or None
+
+
[email protected](scope="session")
+def server_endpoint(pytestconfig):
+ return pytestconfig.getoption("server_endpoint") or TestConfig.SERVER_ENDPOINT
+
+
+def client(server_endpoint):
+ tracking = SandboxTrackingClient(server_endpoint, timeout=TestConfig.DEFAULT_TIMEOUT)
+ try:
+ yield tracking
+ finally:
+ tracking.cleanup_sandboxes()
+ tracking.close()
+
+
+def restore_timeout(client):
+ try:
+ snapshot_resp = client.get("/api/v1/timeout")
+ if snapshot_resp.status_code != 200:
+ pytest.skip("Timeout API not available")
+ snapshot = snapshot_resp.json()
+ except Exception:
+ pytest.skip("Timeout API not available")
+ try:
+ yield snapshot
+ finally:
+ restore_payload = {
+ "idle_timeout": snapshot["idle_timeout"],
+ "idle_check_interval": snapshot["idle_check_interval"],
+ }
+ if "exec_timeout" in snapshot:
+ restore_payload["exec_timeout"] = snapshot["exec_timeout"]
+ try:
+ client.put("/api/v1/timeout", json=restore_payload)
+ except Exception as exc:
+ logger.warning("Failed to restore timeout config: %s", exc)
+
+
+def create_sandbox(client):
+ def factory(**kwargs):
+ resp = client.post("/api/v1/sandboxes", json=kwargs)
+ if resp.status_code != 201:
+ raise RuntimeError(
+ f"Failed to create sandbox: {resp.status_code} {resp.text}"
+ )
+ sandbox = resp.json()
+ return sandbox
+
+ return factory
+
+
+def wait_for_sandbox_ready(client):
+ def waiter(sandbox_id, timeout=TestConfig.SANDBOX_READY_TIMEOUT):
+ for _ in range(timeout * 2):
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ phase = status.json().get("phase")
+ if phase == "ready":
+ return True
+ if phase == "error":
+ raise RuntimeError(f"Sandbox failed: {status.json()}")
+ time.sleep(0.5)
+ raise TimeoutError(f"Sandbox {sandbox_id} did not become ready")
+
+ return waiter
+
+
+def exec_command(client):
+ def executor(sandbox_id, command, timeout_seconds=TestConfig.EXEC_TIMEOUT):
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": command, "timeout_seconds": timeout_seconds},
+ )
+ return resp
+
+ return executor
+
+
+def resource_degradation_cleanup():
+ processes = []
+ try:
+ yield processes
+ finally:
+ for proc in processes:
+ try:
+ proc.terminate()
+ proc.wait(timeout=5)
+ except Exception as exc:
+ logger.debug(
+ "Failed to terminate process during cleanup: %s", exc
+ )
+ try:
+ proc.kill()
+ proc.wait(timeout=5)
+ except Exception as kill_exc:
+ logger.warning(
+ "Failed to kill process during cleanup: %s", kill_exc
+ )
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_cgroup_limits.py b/jiuwenbox/tests/system_tests/test_cgroup_limits.py
new file mode 100644
index 0000000000..0c6f336ca3
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_cgroup_limits.py
@@ -0,0 +1,223 @@
+"""cgroup resource limits tests."""
+
+from __future__ import annotations
+
+import textwrap
+
+import pytest
+
+
+def _get_base_policy(*, cgroup: dict | None = None):
+ policy = {
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
+ "read_write": ["/tmp"],
+ "bind_mounts": [
+ {"host_path": "/bin", "sandbox_path": "/bin", "mode": "ro"},
+ {"host_path": "/usr", "sandbox_path": "/usr", "mode": "ro"},
+ {"host_path": "/lib", "sandbox_path": "/lib", "mode": "ro"},
+ {"host_path": "/lib64", "sandbox_path": "/lib64", "mode": "ro"},
+ {"host_path": "/opt/python3.11", "sandbox_path": "/opt/python3.11", "mode": "ro"},
+ ],
+ },
+ "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"},
+ "namespace": {"user": True, "pid": True, "ipc": True, "cgroup": True, "uts": True},
+ "network": {"mode": "isolated"},
+ "environment": {"PATH": "/opt/python3.11/bin:/usr/local/bin:/usr/bin:/bin"},
+ }
+ if cgroup is not None:
+ policy["cgroup"] = cgroup
+ return policy
+
+
+_CGROUP_PROBE_POLICY = _get_base_policy(cgroup={"pids_max": 1024})
+_cgroup_probe_cached: bool | None = None
+_cgroup_probe_skip_reason: str | None = None
+
+
+def cgroup_supported(client):
+ """Probe whether the server can apply per-sandbox cgroup limits."""
+ global _cgroup_probe_cached, _cgroup_probe_skip_reason
+ if _cgroup_probe_cached is False:
+ pytest.skip(_cgroup_probe_skip_reason or "cgroup not writable")
+ if _cgroup_probe_cached is None:
+ resp = client.post("/api/v1/sandboxes", json={"policy": _CGROUP_PROBE_POLICY})
+ if resp.status_code == 201:
+ sandbox_id = resp.json()["id"]
+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ _cgroup_probe_cached = True
+ else:
+ _cgroup_probe_cached = False
+ _cgroup_probe_skip_reason = (
+ f"cgroup probe sandbox failed (status={resp.status_code}): {resp.text}"
+ )
+ pytest.skip(_cgroup_probe_skip_reason)
+ return True
+
+
+def _cpu_ratio_script() -> str:
+ return textwrap.dedent(
+ """
+ import time
+
+ target_wall = 2.0
+ start_wall = time.monotonic()
+ start_cpu = time.process_time()
+ while time.monotonic() - start_wall < target_wall:
+ pass
+ wall = time.monotonic() - start_wall
+ cpu = time.process_time() - start_cpu
+ print('ratio=', cpu / wall if wall > 0 else 0)
+ """
+ ).strip()
+
+
+def _parse_cpu_ratio(stdout: str) -> float:
+ ratio_line = next(
+ (line for line in stdout.splitlines() if line.startswith("ratio=")),
+ "",
+ )
+ assert ratio_line, f"Missing ratio= line in stdout: {stdout!r}"
+ return float(ratio_line.split("=", 1)[1].strip())
+
+
+class TestCgroupCPULimits:
+ """CPU cgroup limits tests."""
+
+ @staticmethod
+ def test_cg_001_cpu_limit_half_core(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"cpu_max": "0.5"})
+ policy["name"] = "cpu-limit-test"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", _cpu_ratio_script()],
+ timeout_seconds=30,
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["exit_code"] == 0, data
+ assert _parse_cpu_ratio(data.get("stdout") or "") < 0.75
+
+ @staticmethod
+ def test_cg_002_cpu_limit_low(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"cpu_max": "0.1"})
+ policy["name"] = "cpu-limit-low"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", _cpu_ratio_script()],
+ timeout_seconds=30,
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["exit_code"] == 0, data
+ assert _parse_cpu_ratio(data.get("stdout") or "") < 0.3
+
+ @staticmethod
+ def test_cg_003_cpu_limit_full(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"cpu_max": "4"})
+ policy["name"] = "cpu-limit-full"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", _cpu_ratio_script()],
+ timeout_seconds=30,
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["exit_code"] == 0, data
+ assert _parse_cpu_ratio(data.get("stdout") or "") > 0.3
+
+
+class TestCgroupMemoryLimits:
+ """Memory cgroup limits tests."""
+
+ @staticmethod
+ def test_cg_004_memory_limit_1g(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"memory_max": "1G"})
+ policy["name"] = "memory-limit-1g"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", "data = b'x' * 500 * 1024 * 1024; print(len(data))"],
+ timeout_seconds=30,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+
+ @staticmethod
+ def test_cg_005_memory_limit_128m(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"memory_max": "128M"})
+ policy["name"] = "memory-limit-128m"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ [
+ "python3",
+ "-c",
+ (
+ "buf = bytearray(256 * 1024 * 1024); "
+ "buf[::4096] = b'x' * (len(buf) // 4096); "
+ "print('survived')"
+ ),
+ ],
+ timeout_seconds=30,
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["exit_code"] != 0, data
+ combined = ((data.get("stdout") or "") + (data.get("stderr") or "")).lower()
+ assert "survived" not in combined, data
+
+ @staticmethod
+ def test_cg_006_memory_limit_full(
+ client, wait_for_sandbox_ready, exec_command, cgroup_supported
+ ):
+ policy = _get_base_policy(cgroup={"memory_max": "4G"})
+ policy["name"] = "memory-limit-full"
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", "data = b'x' * 2 * 1024 * 1024 * 1024; print(len(data))"],
+ timeout_seconds=60,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
diff --git a/jiuwenbox/tests/system_tests/test_chaos_engineering.py b/jiuwenbox/tests/system_tests/test_chaos_engineering.py
new file mode 100644
index 0000000000..8f00408d84
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_chaos_engineering.py
@@ -0,0 +1,168 @@
+"""Chaos engineering tests for resilience testing."""
+
+from __future__ import annotations
+
+import subprocess
+import time
+
+import pytest
+
+from tests.system_tests.test_config import TestConfig
+from tests.system_tests.test_utils import ChaosInjector, PerformanceCollector
+
+
+class TestChaosEngineering:
+ """Chaos engineering injection tests."""
+
+ @staticmethod
+ def test_ce_001_kill_daemon_during_ipc(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.kill_sandbox_daemon(sandbox_id)
+
+ time.sleep(5)
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.json()["phase"] == "ready"
+
+ @staticmethod
+ def test_ce_002_network_disconnect_during_command(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.disconnect_network()
+
+ try:
+ resp = exec_command(sandbox_id, ["echo", "test"], timeout_seconds=10)
+ assert resp.status_code in (200, 408)
+ finally:
+ chaos.reconnect_network()
+
+ time.sleep(5)
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.json()["phase"] == "ready"
+
+ @staticmethod
+ def test_ce_003_cpu_exhaustion_during_exec(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=12, duration=60)
+ resp = exec_command(sandbox_id, ["sleep", "5"], timeout_seconds=120)
+ assert resp.status_code == 200
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_ce_004_disk_full_during_upload(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="10G", duration=60)
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/files",
+ files={"file": ("test.txt", b"test content", "text/plain")},
+ )
+ assert resp.status_code in (200, 400, 500)
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_ce_005_oom_during_concurrent_exec(client, wait_for_sandbox_ready, exec_command):
+ sandboxes = []
+ for _ in range(3):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandboxes.append(resp.json()["id"])
+
+ for sb_id in sandboxes:
+ wait_for_sandbox_ready(sb_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ chaos = ChaosInjector(client)
+ try:
+ rdm.degrade_memory(vm_bytes="22G", duration=60)
+ for sb_id in sandboxes:
+ chaos.trigger_oom(sb_id, memory_gb=22)
+
+ for sb_id in sandboxes:
+ resp = exec_command(sb_id, ["echo", "oom-test"], timeout_seconds=60)
+ assert resp.status_code in (200, 500)
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_ce_006_memory_pagetable_pollution(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_memory(vm_bytes="18G", duration=60)
+ resp = exec_command(sandbox_id, ["echo", "pagetable-test"], timeout_seconds=60)
+ assert resp.status_code == 200
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_ce_007_circuit_breaker_healing(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ for _ in range(3):
+ chaos.kill_sandbox_daemon(sandbox_id)
+ time.sleep(2)
+
+ time.sleep(10)
+ resp = exec_command(sandbox_id, ["echo", "healing-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+
+ @staticmethod
+ def test_ce_008_p999_latency_spike(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ collector = PerformanceCollector()
+ chaos = ChaosInjector(client)
+
+ for _ in range(10):
+ start = time.time()
+ exec_command(sandbox_id, ["echo", "normal"], timeout_seconds=10)
+ collector.record_latency(time.time() - start)
+
+ chaos.kill_sandbox_daemon(sandbox_id)
+ time.sleep(2)
+
+ for _ in range(5):
+ start = time.time()
+ exec_command(sandbox_id, ["echo", "recovery"], timeout_seconds=30)
+ collector.record_latency(time.time() - start)
+
+ metrics = collector.get_metrics()
+ assert metrics.p999 < TestConfig.P999_SPIKE_THRESHOLD
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_concurrent_create.py b/jiuwenbox/tests/system_tests/test_concurrent_create.py
new file mode 100644
index 0000000000..52c78bfd20
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_concurrent_create.py
@@ -0,0 +1,113 @@
+"""Concurrent sandbox creation tests."""
+
+from __future__ import annotations
+
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+import httpx
+import pytest
+
+from tests.system_tests.test_config import TestConfig
+
+
+class TestConcurrentCreate:
+ """Concurrent sandbox creation test cases."""
+
+ @staticmethod
+ def _normalize_endpoint(endpoint: str) -> str:
+ return endpoint if "://" in endpoint else f"http://{endpoint}"
+
+ @staticmethod
+ def _create_sandbox(endpoint: str, tracker) -> str:
+ with httpx.Client(
+ base_url=TestConcurrentCreate._normalize_endpoint(endpoint),
+ timeout=TestConfig.DEFAULT_TIMEOUT,
+ ) as http:
+ resp = http.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json().get("id")
+ assert sandbox_id, f"Missing sandbox id in response: {resp.text}"
+ tracker.track_sandbox(sandbox_id)
+ return sandbox_id
+
+ @staticmethod
+ def _wait_all_ready(client, sandbox_ids: list, timeout: int) -> bool:
+ start = time.time()
+ while time.time() - start < timeout:
+ all_ready = True
+ for sb_id in sandbox_ids:
+ status = client.get(f"/api/v1/sandboxes/{sb_id}")
+ if status.status_code != 200:
+ all_ready = False
+ break
+ phase = status.json().get("phase")
+ if phase == "error":
+ return False
+ if phase != "ready":
+ all_ready = False
+ break
+ if all_ready:
+ return True
+ time.sleep(0.5)
+ return False
+
+ @staticmethod
+ def test_cc_001_concurrent_create_5(client, server_endpoint):
+ start_time = time.time()
+ sandbox_ids = []
+
+ with ThreadPoolExecutor(max_workers=5) as pool:
+ futures = [
+ pool.submit(TestConcurrentCreate._create_sandbox, server_endpoint, client)
+ for _ in range(5)
+ ]
+ for future in as_completed(futures):
+ sandbox_ids.append(future.result())
+
+ assert len(sandbox_ids) == 5
+ assert TestConcurrentCreate._wait_all_ready(client, sandbox_ids, TestConfig.CONCURRENT_CREATE_TIMEOUT_5)
+
+ total_time = time.time() - start_time
+ assert total_time < TestConfig.CONCURRENT_CREATE_TIMEOUT_5
+
+ @staticmethod
+ def test_cc_002_concurrent_create_10(client, server_endpoint):
+ start_time = time.time()
+ sandbox_ids = []
+
+ with ThreadPoolExecutor(max_workers=10) as pool:
+ futures = [
+ pool.submit(TestConcurrentCreate._create_sandbox, server_endpoint, client)
+ for _ in range(10)
+ ]
+ for future in as_completed(futures):
+ sandbox_ids.append(future.result())
+
+ assert len(sandbox_ids) == 10
+ assert TestConcurrentCreate._wait_all_ready(client, sandbox_ids, TestConfig.CONCURRENT_CREATE_TIMEOUT_10)
+
+ total_time = time.time() - start_time
+ assert total_time < TestConfig.CONCURRENT_CREATE_TIMEOUT_10
+
+ @staticmethod
+ def test_cc_003_concurrent_create_20(client, server_endpoint):
+ start_time = time.time()
+ sandbox_ids = []
+
+ with ThreadPoolExecutor(max_workers=20) as pool:
+ futures = [
+ pool.submit(TestConcurrentCreate._create_sandbox, server_endpoint, client)
+ for _ in range(20)
+ ]
+ for future in as_completed(futures):
+ sandbox_ids.append(future.result())
+
+ assert len(sandbox_ids) == 20
+ assert TestConcurrentCreate._wait_all_ready(client, sandbox_ids, TestConfig.CONCURRENT_CREATE_TIMEOUT_20)
+
+ total_time = time.time() - start_time
+ assert total_time < TestConfig.CONCURRENT_CREATE_TIMEOUT_20
diff --git a/jiuwenbox/tests/system_tests/test_config.py b/jiuwenbox/tests/system_tests/test_config.py
new file mode 100644
index 0000000000..67a5783eef
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_config.py
@@ -0,0 +1,158 @@
+"""Test configuration and environment detection utilities."""
+
+from __future__ import annotations
+
+import logging
+import os
+import platform
+import shutil
+import subprocess
+from typing import Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+
+class TestConfig:
+ """Test configuration parameters."""
+
+ # API Endpoint
+ SERVER_ENDPOINT = os.environ.get("JIUWENBOX_SERVER", "http://localhost:8080")
+
+ # Timeouts (seconds)
+ DEFAULT_TIMEOUT = int(os.environ.get("TEST_TIMEOUT", "120"))
+ SANDBOX_READY_TIMEOUT = int(os.environ.get("SANDBOX_READY_TIMEOUT", "30"))
+ EXEC_TIMEOUT = int(os.environ.get("EXEC_TIMEOUT", "60"))
+
+ # Performance thresholds
+ QPS_SINGLE_THRESHOLD = int(os.environ.get("QPS_SINGLE_THRESHOLD", "50"))
+ QPS_MULTI_THRESHOLD = int(os.environ.get("QPS_MULTI_THRESHOLD", "100"))
+ LATENCY_COMMAND_THRESHOLD = float(os.environ.get("LATENCY_COMMAND_THRESHOLD", "0.05"))
+ LATENCY_STARTUP_THRESHOLD = float(os.environ.get("LATENCY_STARTUP_THRESHOLD", "0.1"))
+ LATENCY_SERVICE_THRESHOLD = float(os.environ.get("LATENCY_SERVICE_THRESHOLD", "1.0"))
+ P999_SPIKE_THRESHOLD = float(os.environ.get("P999_SPIKE_THRESHOLD", "0.5"))
+
+ # Resource degradation parameters
+ CPU_CORES_MILD = int(os.environ.get("CPU_CORES_MILD", "4"))
+ CPU_CORES_MODERATE = int(os.environ.get("CPU_CORES_MODERATE", "8"))
+ CPU_CORES_SEVERE = int(os.environ.get("CPU_CORES_SEVERE", "12"))
+ MEMORY_MILD = os.environ.get("MEMORY_MILD", "8G")
+ MEMORY_MODERATE = os.environ.get("MEMORY_MODERATE", "16G")
+ MEMORY_SEVERE = os.environ.get("MEMORY_SEVERE", "20G")
+
+ # Network interface
+ NETWORK_INTERFACE = os.environ.get("NETWORK_INTERFACE", "eth0")
+
+ # File transfer parameters
+ FILE_UPLOAD_SPEED_THRESHOLD = float(os.environ.get("FILE_UPLOAD_SPEED_THRESHOLD", "10"))
+ FILE_DOWNLOAD_SPEED_THRESHOLD = float(os.environ.get("FILE_DOWNLOAD_SPEED_THRESHOLD", "20"))
+ FILE_TRANSFER_TIMEOUT = int(os.environ.get("FILE_TRANSFER_TIMEOUT", "300"))
+
+ # Concurrent creation parameters
+ CONCURRENT_CREATE_TIMEOUT_5 = int(os.environ.get("CONCURRENT_CREATE_TIMEOUT_5", "10"))
+ CONCURRENT_CREATE_TIMEOUT_10 = int(os.environ.get("CONCURRENT_CREATE_TIMEOUT_10", "20"))
+ CONCURRENT_CREATE_TIMEOUT_20 = int(os.environ.get("CONCURRENT_CREATE_TIMEOUT_20", "40"))
+
+ # Long stability test parameters
+ LONG_STABILITY_DURATION_30MIN = int(os.environ.get("LONG_STABILITY_DURATION_30MIN", "1800"))
+ LONG_STABILITY_DURATION_1HOUR = int(os.environ.get("LONG_STABILITY_DURATION_1HOUR", "3600"))
+ LONG_STABILITY_SANDBOX_COUNT = int(os.environ.get("LONG_STABILITY_SANDBOX_COUNT", "5"))
+ LONG_STABILITY_REQUEST_INTERVAL_MS = int(os.environ.get("LONG_STABILITY_REQUEST_INTERVAL_MS", "100"))
+ LONG_STABILITY_SUCCESS_RATE_THRESHOLD = float(os.environ.get("LONG_STABILITY_SUCCESS_RATE_THRESHOLD", "0.999"))
+ LONG_STABILITY_AVG_LATENCY_THRESHOLD = float(os.environ.get("LONG_STABILITY_AVG_LATENCY_THRESHOLD", "0.1"))
+ LONG_STABILITY_P99_LATENCY_THRESHOLD = float(os.environ.get("LONG_STABILITY_P99_LATENCY_THRESHOLD", "0.3"))
+ LONG_STABILITY_CPU_THRESHOLD = float(os.environ.get("LONG_STABILITY_CPU_THRESHOLD", "80"))
+ LONG_STABILITY_MEMORY_THRESHOLD = float(os.environ.get("LONG_STABILITY_MEMORY_THRESHOLD", "80"))
+
+
+class EnvironmentDetector:
+ """Detect test environment capabilities."""
+
+ @staticmethod
+ def is_linux() -> bool:
+ """Check if running on Linux."""
+ return platform.system().lower() == "linux"
+
+ @staticmethod
+ def is_windows() -> bool:
+ """Check if running on Windows."""
+ return platform.system().lower() == "windows"
+
+ @staticmethod
+ def is_macos() -> bool:
+ """Check if running on macOS."""
+ return platform.system().lower() == "darwin"
+
+ @staticmethod
+ def has_stress_ng() -> bool:
+ """Check if stress-ng is available."""
+ return shutil.which("stress-ng") is not None
+
+ @staticmethod
+ def has_tc() -> bool:
+ """Check if tc (traffic control) is available."""
+ return shutil.which("tc") is not None
+
+ @staticmethod
+ def has_iproute2() -> bool:
+ """Check if iproute2 is available."""
+ return shutil.which("ip") is not None
+
+ @staticmethod
+ def has_docker() -> bool:
+ """Check if Docker is available."""
+ docker = shutil.which("docker")
+ if docker is None:
+ return False
+ try:
+ result = subprocess.run([docker, "ps"], capture_output=True, text=True)
+ return result.returncode == 0
+ except Exception as exc:
+ logger.debug("docker check failed: %s", exc)
+ return False
+
+ @staticmethod
+ def can_run_resource_tests() -> bool:
+ """Check if resource degradation tests can run."""
+ return EnvironmentDetector.is_linux() and EnvironmentDetector.has_stress_ng()
+
+ @staticmethod
+ def can_run_network_tests() -> bool:
+ """Check if network degradation tests can run."""
+ return EnvironmentDetector.is_linux() and EnvironmentDetector.has_tc()
+
+ @staticmethod
+ def can_run_chaos_tests() -> bool:
+ """Check if chaos engineering tests can run."""
+ return (
+ EnvironmentDetector.is_linux()
+ and EnvironmentDetector.has_stress_ng()
+ and EnvironmentDetector.has_iproute2()
+ )
+
+ @staticmethod
+ def get_capabilities() -> Dict[str, bool]:
+ """Get all environment capabilities."""
+ return {
+ "linux": EnvironmentDetector.is_linux(),
+ "windows": EnvironmentDetector.is_windows(),
+ "macos": EnvironmentDetector.is_macos(),
+ "stress_ng": EnvironmentDetector.has_stress_ng(),
+ "tc": EnvironmentDetector.has_tc(),
+ "iproute2": EnvironmentDetector.has_iproute2(),
+ "docker": EnvironmentDetector.has_docker(),
+ "resource_tests": EnvironmentDetector.can_run_resource_tests(),
+ "network_tests": EnvironmentDetector.can_run_network_tests(),
+ "chaos_tests": EnvironmentDetector.can_run_chaos_tests(),
+ }
+
+ @staticmethod
+ def print_capabilities() -> None:
+ """Print environment capabilities."""
+ capabilities = EnvironmentDetector.get_capabilities()
+ logger.info("=" * 50)
+ logger.info("Environment Capabilities")
+ logger.info("=" * 50)
+ for key, value in capabilities.items():
+ status = "available" if value else "unavailable"
+ logger.info(" %s: %s", key, status)
+ logger.info("=" * 50)
diff --git a/jiuwenbox/tests/system_tests/test_config_constraints.py b/jiuwenbox/tests/system_tests/test_config_constraints.py
new file mode 100644
index 0000000000..164e0047e4
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_config_constraints.py
@@ -0,0 +1,145 @@
+"""Configuration parameter constraint space tests."""
+
+from __future__ import annotations
+
+import logging
+import time
+
+import pytest
+
+logger = logging.getLogger(__name__)
+
+
+class TestValidParameterCombinations:
+ """Test valid parameter combinations."""
+
+ @staticmethod
+ def test_pc_001_idle_timeout_less_than_exec_timeout(client, wait_for_sandbox_ready, restore_timeout):
+ timeout_resp = client.put("/api/v1/timeout", json={"idle_timeout": 30, "exec_timeout": 60})
+ assert timeout_resp.status_code == 200, f"Failed to set timeout config: {timeout_resp.text}"
+
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+
+ @staticmethod
+ def test_pc_002_memory_limit_greater_than_daemon_rss(client, wait_for_sandbox_ready):
+ policy = {
+ "name": "memory-test",
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
+ "read_write": ["/tmp"],
+ "bind_mounts": [
+ {"host_path": "/bin", "sandbox_path": "/bin", "mode": "ro"},
+ {"host_path": "/usr", "sandbox_path": "/usr", "mode": "ro"},
+ {"host_path": "/lib", "sandbox_path": "/lib", "mode": "ro"},
+ {"host_path": "/lib64", "sandbox_path": "/lib64", "mode": "ro"},
+ {"host_path": "/opt/python3.11", "sandbox_path": "/opt/python3.11", "mode": "ro"},
+ ],
+ },
+ "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"},
+ "namespace": {"user": True, "pid": True, "ipc": True, "cgroup": True, "uts": True},
+ "network": {"mode": "isolated"},
+ "environment": {"PATH": "/opt/python3.11/bin:/usr/local/bin:/usr/bin:/bin"},
+ }
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "memory-test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+
+ @staticmethod
+ def test_pc_003_max_sandboxes_memory_combo(client, wait_for_sandbox_ready):
+ sandboxes = []
+ for i in range(3):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandboxes.append(resp.json()["id"])
+
+ for sb_id in sandboxes:
+ wait_for_sandbox_ready(sb_id)
+
+ for sb_id in sandboxes:
+ resp = client.post(
+ f"/api/v1/sandboxes/{sb_id}/exec",
+ json={"command": ["echo", "combo-test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+
+
+class TestInvalidParameterCombinations:
+ """Test invalid parameter combinations."""
+
+ @staticmethod
+ def test_pc_004_idle_timeout_greater_than_exec_timeout(client, restore_timeout):
+ resp = client.put("/api/v1/timeout", json={"idle_timeout": 120, "exec_timeout": 60})
+ assert resp.status_code in (400, 422), (
+ f"Expected rejection of invalid timeout combo: {resp.status_code} {resp.text}"
+ )
+
+ @staticmethod
+ def test_pc_005_memory_limit_less_than_daemon_rss(client):
+ policy = {
+ "name": "memory-too-small",
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc"],
+ "read_write": ["/tmp"],
+ },
+ "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"},
+ "namespace": {"user": True, "pid": True, "ipc": True, "cgroup": True, "uts": True},
+ "network": {"mode": "isolated"},
+ }
+
+ resp = client.post("/api/v1/sandboxes", json={"policy": policy})
+ assert resp.status_code == 201
+
+ sandbox_id = resp.json()["id"]
+ try:
+ for _ in range(60):
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ phase = status.json().get("phase")
+ if phase == "error":
+ break
+ if phase == "ready":
+ pytest.skip("Sandbox became ready with insufficient memory")
+ time.sleep(0.5)
+ else:
+ pytest.skip("Timeout waiting for error state")
+ finally:
+ try:
+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ except Exception as exc:
+ logger.debug("Failed to delete sandbox %s: %s", sandbox_id, exc)
+
+ @staticmethod
+ def test_pc_006_max_sandboxes_exceeds_memory(client):
+ sandboxes = []
+ try:
+ for i in range(20):
+ resp = client.post("/api/v1/sandboxes", json={})
+ if resp.status_code == 201:
+ sandboxes.append(resp.json()["id"])
+ else:
+ break
+ finally:
+ for sb_id in sandboxes:
+ try:
+ client.delete(f"/api/v1/sandboxes/{sb_id}")
+ except Exception as exc:
+ logger.debug("Failed to delete sandbox %s: %s", sb_id, exc)
diff --git a/jiuwenbox/tests/system_tests/test_error_boundaries.py b/jiuwenbox/tests/system_tests/test_error_boundaries.py
new file mode 100644
index 0000000000..db48f0eeab
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_error_boundaries.py
@@ -0,0 +1,115 @@
+"""Error boundary tests."""
+
+from __future__ import annotations
+
+import subprocess
+import time
+
+import pytest
+
+
+class TestErrorBoundaries:
+ """Error boundary tests."""
+
+ @staticmethod
+ def test_eb_001_permission_denied_in_sandbox(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["touch", "/etc/passwd.new"],
+ timeout_seconds=10,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] != 0
+
+ @staticmethod
+ def test_eb_002_permission_denied_on_host(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["sh", "-c", "mkdir -p /root/test 2>&1 || echo 'permission-denied'"],
+ timeout_seconds=10,
+ )
+ assert resp.status_code == 200
+
+ @staticmethod
+ def test_eb_003_disk_full_during_upload(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="20G", duration=60)
+ large_content = b"x" * (100 * 1024 * 1024)
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/files",
+ files={"file": ("large_file.bin", large_content, "application/octet-stream")},
+ )
+ assert resp.status_code in (400, 413, 500, 507)
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_eb_004_disk_full_during_create(client):
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="20G", duration=60)
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code in (500, 507)
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_eb_005_ipc_timeout(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=12, duration=30)
+ resp = exec_command(
+ sandbox_id,
+ ["sleep", "3"],
+ timeout_seconds=5,
+ )
+ assert resp.status_code == 200
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_eb_006_network_timeout(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_network(loss=50, delay=500)
+ resp = exec_command(
+ sandbox_id,
+ ["curl", "--connect-timeout", "5", "http://www.baidu.com"],
+ timeout_seconds=30,
+ )
+ assert resp.status_code in (200, 408)
+ finally:
+ rdm.restore_network()
+ rdm.cleanup()
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_file_transfer.py b/jiuwenbox/tests/system_tests/test_file_transfer.py
new file mode 100644
index 0000000000..46dc8433a6
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_file_transfer.py
@@ -0,0 +1,122 @@
+"""File transfer tests - upload performance and integrity."""
+
+from __future__ import annotations
+
+import hashlib
+import random
+import time
+
+import pytest
+
+from tests.system_tests.test_config import TestConfig
+
+
+class TestFileTransfer:
+ """File transfer test cases."""
+
+ @staticmethod
+ def _generate_test_data(size_mb: int) -> bytes:
+ return random.randbytes(size_mb * 1024 * 1024)
+
+ @staticmethod
+ def _calculate_md5(data: bytes) -> str:
+ return hashlib.md5(data).hexdigest()
+
+ @staticmethod
+ def test_ft_001_file_transfer_1m(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ file_data = TestFileTransfer._generate_test_data(1)
+ original_md5 = TestFileTransfer._calculate_md5(file_data)
+
+ upload_start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/upload?sandbox_path=/tmp/test_1m.bin",
+ files={"file": ("test_1m.bin", file_data, "application/octet-stream")},
+ timeout=TestConfig.FILE_TRANSFER_TIMEOUT,
+ )
+ upload_time = time.time() - upload_start
+ assert resp.status_code == 204
+ upload_speed = 1 / upload_time
+ assert upload_speed >= TestConfig.FILE_UPLOAD_SPEED_THRESHOLD
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["md5sum", "/tmp/test_1m.bin"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ output = (resp.json().get("stdout") or "").strip()
+ parts = output.split()
+ assert parts, "md5sum returned empty output"
+ downloaded_md5 = parts[0]
+ assert downloaded_md5 == original_md5
+
+ @staticmethod
+ def test_ft_002_file_transfer_10m(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ file_data = TestFileTransfer._generate_test_data(10)
+ original_md5 = TestFileTransfer._calculate_md5(file_data)
+
+ upload_start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/upload?sandbox_path=/tmp/test_10m.bin",
+ files={"file": ("test_10m.bin", file_data, "application/octet-stream")},
+ timeout=TestConfig.FILE_TRANSFER_TIMEOUT,
+ )
+ upload_time = time.time() - upload_start
+ assert resp.status_code == 204
+ upload_speed = 10 / upload_time
+ assert upload_speed >= TestConfig.FILE_UPLOAD_SPEED_THRESHOLD
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["md5sum", "/tmp/test_10m.bin"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ output = (resp.json().get("stdout") or "").strip()
+ parts = output.split()
+ assert parts, "md5sum returned empty output"
+ downloaded_md5 = parts[0]
+ assert downloaded_md5 == original_md5
+
+ @staticmethod
+ def test_ft_003_file_transfer_50m(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ file_data = TestFileTransfer._generate_test_data(50)
+ original_md5 = TestFileTransfer._calculate_md5(file_data)
+
+ upload_start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/upload?sandbox_path=/tmp/test_50m.bin",
+ files={"file": ("test_50m.bin", file_data, "application/octet-stream")},
+ timeout=TestConfig.FILE_TRANSFER_TIMEOUT,
+ )
+ upload_time = time.time() - upload_start
+ assert resp.status_code == 204
+ upload_speed = 50 / upload_time
+ assert upload_speed >= TestConfig.FILE_UPLOAD_SPEED_THRESHOLD
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["md5sum", "/tmp/test_50m.bin"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ output = (resp.json().get("stdout") or "").strip()
+ parts = output.split()
+ assert parts, "md5sum returned empty output"
+ downloaded_md5 = parts[0]
+ assert downloaded_md5 == original_md5
diff --git a/jiuwenbox/tests/system_tests/test_long_stability.py b/jiuwenbox/tests/system_tests/test_long_stability.py
new file mode 100644
index 0000000000..80825a7887
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_long_stability.py
@@ -0,0 +1,160 @@
+"""Long stability tests with load."""
+
+from __future__ import annotations
+
+import logging
+import statistics
+import subprocess
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from typing import List
+
+import pytest
+
+from tests.system_tests.test_config import TestConfig
+
+logger = logging.getLogger(__name__)
+
+
+class TestLongStability:
+ """Long stability test cases."""
+
+ @staticmethod
+ def _get_system_metrics() -> dict:
+ try:
+ result = subprocess.run(
+ ["/bin/ps", "-aux", "--sort=-%mem"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ lines = result.stdout.strip().split("\n")
+ if len(lines) > 1:
+ header = lines[0].split()
+ data = lines[1].split(None, len(header) - 1)
+ if len(data) >= len(header):
+ return {
+ "cpu": float(data[2]),
+ "memory": float(data[3]),
+ }
+ except Exception as exc:
+ logger.debug("Failed to get system metrics: %s", exc)
+ return {"cpu": 0.0, "memory": 0.0}
+
+ @staticmethod
+ def _run_load_on_sandbox(client, sandbox_id: str, duration: int, results: List[dict]):
+ start_time = time.time()
+ interval = TestConfig.LONG_STABILITY_REQUEST_INTERVAL_MS / 1000.0
+
+ while time.time() - start_time < duration:
+ req_start = time.time()
+ try:
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "hello"], "timeout_seconds": 10},
+ )
+ latency = time.time() - req_start
+ results.append({
+ "success": resp.status_code == 200,
+ "latency": latency,
+ "timestamp": time.time(),
+ })
+ except Exception as e:
+ results.append({
+ "success": False,
+ "latency": time.time() - req_start,
+ "timestamp": time.time(),
+ "error": str(e),
+ })
+
+ elapsed = time.time() - req_start
+ if elapsed < interval:
+ time.sleep(interval - elapsed)
+
+ @staticmethod
+ def test_ls_001_long_stability_30min(client, wait_for_sandbox_ready):
+ sandboxes = []
+ for _ in range(TestConfig.LONG_STABILITY_SANDBOX_COUNT):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ sandboxes.append(sandbox_id)
+
+ results = []
+ threads = []
+
+ for sb_id in sandboxes:
+ thread = threading.Thread(
+ target=TestLongStability._run_load_on_sandbox,
+ args=(client, sb_id, TestConfig.LONG_STABILITY_DURATION_30MIN, results),
+ daemon=True,
+ )
+ threads.append(thread)
+ thread.start()
+
+ for thread in threads:
+ thread.join()
+
+ success_count = sum(1 for r in results if r["success"])
+ success_rate = success_count / len(results) if results else 0
+ assert success_rate >= TestConfig.LONG_STABILITY_SUCCESS_RATE_THRESHOLD
+
+ latencies = [r["latency"] for r in results if r["success"]]
+ if latencies:
+ avg_latency = sum(latencies) / len(latencies)
+ assert avg_latency < TestConfig.LONG_STABILITY_AVG_LATENCY_THRESHOLD
+
+ sorted_latencies = sorted(latencies)
+ p99_index = int(len(sorted_latencies) * 0.99) - 1
+ p99_latency = sorted_latencies[p99_index] if p99_index >= 0 else 0
+ assert p99_latency < TestConfig.LONG_STABILITY_P99_LATENCY_THRESHOLD
+
+ for sb_id in sandboxes:
+ status = client.get(f"/api/v1/sandboxes/{sb_id}")
+ assert status.json().get("phase") == "ready"
+
+ @staticmethod
+ def test_ls_002_long_stability_1hour(client, wait_for_sandbox_ready):
+ sandboxes = []
+ for _ in range(TestConfig.LONG_STABILITY_SANDBOX_COUNT):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ sandboxes.append(sandbox_id)
+
+ results = []
+ threads = []
+
+ for sb_id in sandboxes:
+ thread = threading.Thread(
+ target=TestLongStability._run_load_on_sandbox,
+ args=(client, sb_id, TestConfig.LONG_STABILITY_DURATION_1HOUR, results),
+ daemon=True,
+ )
+ threads.append(thread)
+ thread.start()
+
+ for thread in threads:
+ thread.join()
+
+ success_count = sum(1 for r in results if r["success"])
+ success_rate = success_count / len(results) if results else 0
+ assert success_rate >= TestConfig.LONG_STABILITY_SUCCESS_RATE_THRESHOLD
+
+ latencies = [r["latency"] for r in results if r["success"]]
+ if latencies:
+ avg_latency = sum(latencies) / len(latencies)
+ assert avg_latency < TestConfig.LONG_STABILITY_AVG_LATENCY_THRESHOLD
+
+ sorted_latencies = sorted(latencies)
+ p99_index = int(len(sorted_latencies) * 0.99) - 1
+ p99_latency = sorted_latencies[p99_index] if p99_index >= 0 else 0
+ assert p99_latency < TestConfig.LONG_STABILITY_P99_LATENCY_THRESHOLD
+
+ for sb_id in sandboxes:
+ status = client.get(f"/api/v1/sandboxes/{sb_id}")
+ assert status.json().get("phase") == "ready"
diff --git a/jiuwenbox/tests/system_tests/test_performance.py b/jiuwenbox/tests/system_tests/test_performance.py
new file mode 100644
index 0000000000..e4fc76f1e4
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_performance.py
@@ -0,0 +1,176 @@
+"""Performance metrics tests."""
+
+from __future__ import annotations
+
+import logging
+import subprocess
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+import pytest
+
+from tests.system_tests.test_config import TestConfig
+from tests.system_tests.test_utils import PerformanceCollector
+
+logger = logging.getLogger(__name__)
+
+
+class TestPerformanceMetrics:
+ """Performance metrics tests."""
+
+ @staticmethod
+ def test_perf_001_qps_single_sandbox(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ collector = PerformanceCollector()
+ collector.start()
+
+ for _ in range(100):
+ start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ collector.record_latency(time.time() - start)
+
+ collector.stop()
+ metrics = collector.get_metrics()
+ assert metrics.qps >= TestConfig.QPS_SINGLE_THRESHOLD
+
+ @staticmethod
+ def test_perf_002_qps_multi_sandbox(client, wait_for_sandbox_ready):
+ sandboxes = []
+ for _ in range(3):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandboxes.append(resp.json()["id"])
+
+ for sb_id in sandboxes:
+ wait_for_sandbox_ready(sb_id)
+
+ collector = PerformanceCollector()
+ collector.start()
+
+ def run_command(sb_id):
+ start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sb_id}/exec",
+ json={"command": ["echo", "test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ return time.time() - start
+
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ for _ in range(30):
+ futures = [pool.submit(run_command, sb_id) for sb_id in sandboxes]
+ for future in as_completed(futures):
+ collector.record_latency(future.result())
+
+ collector.stop()
+ metrics = collector.get_metrics()
+ assert metrics.qps >= TestConfig.QPS_MULTI_THRESHOLD
+
+ @staticmethod
+ def test_perf_003_command_execution_latency(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ latencies = []
+ for _ in range(50):
+ start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "latency-test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ latencies.append(time.time() - start)
+
+ avg_latency = sum(latencies) / len(latencies)
+ assert avg_latency < TestConfig.LATENCY_COMMAND_THRESHOLD
+
+ @staticmethod
+ def test_perf_004_sandbox_startup_latency(client):
+ latencies = []
+ for _ in range(10):
+ start = time.time()
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201
+ sandbox_id = resp.json()["id"]
+
+ for _ in range(20):
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ if status.json()["phase"] == "ready":
+ break
+ time.sleep(0.05)
+
+ latencies.append(time.time() - start)
+
+ avg_latency = sum(latencies) / len(latencies)
+ assert avg_latency < TestConfig.LATENCY_STARTUP_THRESHOLD
+
+ @staticmethod
+ def test_perf_005_service_startup_latency(client):
+ health_start = time.time()
+ for _ in range(20):
+ try:
+ resp = client.get("/health")
+ if resp.status_code == 200:
+ break
+ except Exception as exc:
+ logger.debug("Health check failed: %s", exc)
+ time.sleep(0.1)
+ else:
+ pytest.fail("Service did not become healthy")
+
+ service_latency = time.time() - health_start
+ assert service_latency < TestConfig.LATENCY_SERVICE_THRESHOLD
+
+ @staticmethod
+ def test_perf_006_file_upload_download_latency(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ test_content = b"test" * (10 * 1024)
+
+ upload_start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/upload?sandbox_path=/tmp/test.txt",
+ files={"file": ("test.txt", test_content, "text/plain")},
+ )
+ assert resp.status_code == 204
+ upload_latency = time.time() - upload_start
+
+ download_start = time.time()
+ resp = client.get(f"/api/v1/sandboxes/{sandbox_id}/download?sandbox_path=/tmp/test.txt")
+ assert resp.status_code == 200
+ download_latency = time.time() - download_start
+
+ assert upload_latency < 0.5
+ assert download_latency < 0.5
+
+ @staticmethod
+ def test_perf_007_p999_latency_spike(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ collector = PerformanceCollector()
+
+ for _ in range(100):
+ start = time.time()
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "spike-test"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ collector.record_latency(time.time() - start)
+
+ metrics = collector.get_metrics()
+ assert metrics.p999 < TestConfig.P999_SPIKE_THRESHOLD
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_reliability.py b/jiuwenbox/tests/system_tests/test_reliability.py
new file mode 100644
index 0000000000..9d76a90587
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_reliability.py
@@ -0,0 +1,240 @@
+"""Reliability tests for sandbox service."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import time
+
+import pytest
+
+from tests.system_tests.test_utils import ChaosInjector
+
+
+def _docker_restart_policy(container_name: str) -> str | None:
+ docker = shutil.which("docker")
+ if docker is None:
+ return None
+ result = subprocess.run(
+ [docker, "inspect", "--format", "{{.HostConfig.RestartPolicy.Name}}", container_name],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ return None
+ return result.stdout.strip()
+
+
+class TestReliability:
+ """Reliability tests."""
+
+ @staticmethod
+ def test_rel_001_sandbox_process_auto_restart(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.kill_sandbox_daemon(sandbox_id)
+
+ time.sleep(10)
+ resp = exec_command(sandbox_id, ["echo", "restarted"], timeout_seconds=30)
+ assert resp.status_code == 200
+ data = resp.json()
+ assert "exit_code" in data, f"Missing exit_code in response: {data}"
+ assert data["exit_code"] == 0
+
+ @staticmethod
+ def test_rel_002_container_process_auto_restart(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ restart_policy = _docker_restart_policy("jiuwenbox-server")
+ if restart_policy is None:
+ pytest.skip("Docker or jiuwenbox-server container not available")
+ if restart_policy not in ("always", "unless-stopped"):
+ pytest.skip(
+ f"jiuwenbox-server restart policy is {restart_policy!r}; "
+ "need 'always' or 'unless-stopped' for this test"
+ )
+
+ docker = shutil.which("docker")
+ try:
+ subprocess.run([docker, "kill", "jiuwenbox-server"], check=True)
+ except subprocess.CalledProcessError:
+ pytest.skip("Docker container not running")
+
+ time.sleep(30)
+
+ health_resp = client.get("/health")
+ assert health_resp.status_code == 200
+
+ @staticmethod
+ def test_rel_003_exec_timeout_kill(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["sleep", "120"], "timeout_seconds": 10},
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert "exit_code" in data, f"Missing exit_code in response: {data}"
+ assert data["exit_code"] != 0
+
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.status_code == 200, f"Failed to get sandbox status: {status.text}"
+ status_data = status.json()
+ assert "phase" in status_data, f"Missing phase in response: {status_data}"
+ assert status_data["phase"] == "ready"
+
+ @staticmethod
+ def test_rel_004_scenario1_url_valid_instance_invalid(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ for _ in range(3):
+ chaos.kill_sandbox_daemon(sandbox_id)
+ time.sleep(2)
+
+ time.sleep(10)
+ resp = exec_command(sandbox_id, ["echo", "retry-success"], timeout_seconds=30)
+ assert resp.status_code == 200
+ data = resp.json()
+ assert "exit_code" in data, f"Missing exit_code in response: {data}"
+ assert data["exit_code"] == 0
+
+ @staticmethod
+ def test_rel_005_scenario2_url_valid_instance_abnormal(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.stop_sandbox_daemon(sandbox_id)
+
+ time.sleep(5)
+ resp = exec_command(sandbox_id, ["echo", "fallback-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+
+ chaos.restart_sandbox_daemon(sandbox_id)
+
+ @staticmethod
+ def test_rel_006_scenario3_url_unreachable(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.disconnect_network()
+
+ try:
+ resp = exec_command(sandbox_id, ["echo", "unreachable-test"], timeout_seconds=30)
+ assert resp.status_code in (200, 408, 503)
+ finally:
+ chaos.reconnect_network()
+
+ time.sleep(5)
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.status_code == 200, f"Failed to get sandbox status: {status.text}"
+ status_data = status.json()
+ assert "phase" in status_data, f"Missing phase in response: {status_data}"
+ assert status_data["phase"] == "ready"
+
+ @staticmethod
+ def test_rel_007_scenario4_container_service_crash(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ from tests.system_tests.test_utils import ResourceDegradationManager
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_memory(vm_bytes="22G", duration=60)
+ chaos = ChaosInjector(client)
+ chaos.trigger_oom(sandbox_id, memory_gb=22)
+ finally:
+ rdm.cleanup()
+
+ time.sleep(30)
+ health_resp = client.get("/health")
+ assert health_resp.status_code == 200
+
+ @staticmethod
+ def test_rel_008_resource_cleanup_on_stop(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ stop_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")
+ assert stop_resp.status_code == 200, f"Failed to stop sandbox: {stop_resp.text}"
+ stop_data = stop_resp.json()
+ assert "phase" in stop_data, f"Missing phase in response: {stop_data}"
+ assert stop_data["phase"] == "stopped"
+
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 200, f"Failed to get sandbox status: {get_resp.text}"
+ get_data = get_resp.json()
+ assert "phase" in get_data, f"Missing phase in response: {get_data}"
+ assert get_data["phase"] == "stopped"
+
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+ @staticmethod
+ def test_rel_009_idle_reaper_auto_cleanup(client, restore_timeout):
+ client.put("/api/v1/timeout", json={"idle_timeout": 10, "idle_check_interval": 5})
+
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+
+ time.sleep(15)
+
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+ @staticmethod
+ def test_rel_010_zombie_reaper_cleanup(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = exec_command(
+ sandbox_id,
+ ["python3", "-c", "import os; os.fork(); os._exit(0)"],
+ timeout_seconds=10,
+ )
+ assert resp.status_code == 200
+
+ time.sleep(5)
+ resp = exec_command(
+ sandbox_id,
+ ["sh", "-c", "ps aux | grep -E '[Z].*<defunct>' | wc -l"],
+ timeout_seconds=10,
+ )
+ assert resp.status_code == 200
+ raw = (resp.json().get("stdout") or "").strip()
+ assert raw.isdigit(), f"Unexpected stdout: {raw!r}"
+ zombie_count = int(raw)
+ assert zombie_count == 0
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_resource_degradation.py b/jiuwenbox/tests/system_tests/test_resource_degradation.py
new file mode 100644
index 0000000000..dc5364caf5
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_resource_degradation.py
@@ -0,0 +1,281 @@
+"""Resource degradation matrix tests."""
+
+from __future__ import annotations
+
+import subprocess
+import time
+
+import pytest
+
+from tests.system_tests.test_utils import ResourceDegradationManager
+
+
[email protected]_degradation
+class TestResourceDegradationCPU:
+ """CPU resource degradation tests."""
+
+ @staticmethod
+ def test_rd_001_cpu_mild_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=4, duration=30)
+ resp = exec_command(sandbox_id, ["echo", "cpu-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_002_cpu_moderate_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=8, duration=30)
+ resp = exec_command(sandbox_id, ["echo", "cpu-test"], timeout_seconds=60)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_003_cpu_severe_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=12, duration=30)
+ resp = exec_command(sandbox_id, ["echo", "cpu-test"], timeout_seconds=120)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+
[email protected]_degradation
+class TestResourceDegradationMemory:
+ """Memory resource degradation tests."""
+
+ @staticmethod
+ def test_rd_004_memory_mild_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_memory(vm_bytes="8G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "memory-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_005_memory_moderate_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_memory(vm_bytes="16G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "memory-test"], timeout_seconds=60)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_006_memory_severe_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_memory(vm_bytes="20G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "memory-test"], timeout_seconds=120)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
+
+
[email protected]_degradation
+class TestResourceDegradationNetwork:
+ """Network resource degradation tests."""
+
+ @staticmethod
+ def test_rd_007_network_mild_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_network(loss=1, delay=50)
+ resp = exec_command(sandbox_id, ["echo", "network-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_network()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_008_network_moderate_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_network(loss=5, delay=100)
+ resp = exec_command(sandbox_id, ["echo", "network-test"], timeout_seconds=60)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_network()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_009_network_severe_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_network(loss=10, delay=200)
+ resp = exec_command(sandbox_id, ["echo", "network-test"], timeout_seconds=120)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_network()
+ rdm.cleanup()
+
+
[email protected]_degradation
+class TestResourceDegradationDisk:
+ """Disk resource degradation tests."""
+
+ @staticmethod
+ def test_rd_010_disk_mild_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="1G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "disk-test"], timeout_seconds=30)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_011_disk_moderate_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="3G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "disk-test"], timeout_seconds=60)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_012_disk_severe_degradation(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_disk(path="/tmp", size="5G", duration=30)
+ resp = exec_command(sandbox_id, ["echo", "disk-test"], timeout_seconds=120)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_disk()
+ rdm.cleanup()
+
+
[email protected]_degradation
[email protected]_degradation
+class TestResourceDegradationCombined:
+ """Combined resource degradation tests."""
+
+ @staticmethod
+ def test_rd_013_degradation_business_flow(client, wait_for_sandbox_ready, exec_command):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=8, duration=60)
+ rdm.degrade_memory(vm_bytes="16G", duration=60)
+ rdm.degrade_network(loss=5, delay=100)
+
+ for i in range(5):
+ resp = exec_command(sandbox_id, ["echo", f"test-{i}"], timeout_seconds=60)
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.restore_network()
+ rdm.restore_disk()
+ rdm.cleanup()
+
+ @staticmethod
+ def test_rd_014_degradation_concurrent(client, wait_for_sandbox_ready, exec_command):
+ sandboxes = []
+ for _ in range(3):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandboxes.append(resp.json()["id"])
+
+ for sb_id in sandboxes:
+ wait_for_sandbox_ready(sb_id)
+
+ rdm = ResourceDegradationManager()
+ try:
+ rdm.degrade_cpu(cores=10, duration=30)
+
+ from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ def run_test(sb_id):
+ return exec_command(sb_id, ["echo", "concurrent-test"], timeout_seconds=60)
+
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ futures = [pool.submit(run_test, sb_id) for sb_id in sandboxes]
+ for future in as_completed(futures):
+ resp = future.result()
+ assert resp.status_code == 200
+ assert resp.json()["exit_code"] == 0
+ finally:
+ rdm.cleanup()
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_state_machine.py b/jiuwenbox/tests/system_tests/test_state_machine.py
new file mode 100644
index 0000000000..57347e2dd2
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_state_machine.py
@@ -0,0 +1,291 @@
+"""State machine tests for sandbox lifecycle transitions."""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from tests.system_tests.test_utils import StateMachineValidator, ChaosInjector
+
+
+_PROVISIONING_ERROR_POLICY = {
+ "name": "provisioning-error-test",
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
+ "read_write": ["/tmp"],
+ },
+ "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"},
+ "namespace": {"user": True, "pid": True, "ipc": True, "cgroup": True, "uts": True},
+ "network": {
+ "mode": "isolated",
+ "egress": {"default": "allow"},
+ "uplink": {"subnet": "169.254.0.0/24"},
+ },
+ "environment": {"PATH": "/opt/python3.11/bin:/usr/local/bin:/usr/bin:/bin"},
+}
+
+
+def _wait_for_sandbox_phase(
+ client,
+ sandbox_id: str,
+ expected_phase: str,
+ timeout: int = 30,
+ *,
+ reject_phases: tuple[str, ...] = (),
+) -> None:
+ for _ in range(timeout * 2):
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.status_code == 200, f"Failed to get sandbox status: {status.text}"
+ phase = status.json().get("phase")
+ if phase in reject_phases:
+ pytest.fail(
+ f"Sandbox {sandbox_id} reached unexpected phase {phase!r}; "
+ f"expected {expected_phase!r}"
+ )
+ if phase == expected_phase:
+ return
+ time.sleep(0.5)
+ pytest.fail(
+ f"Timeout waiting for sandbox {sandbox_id} to reach phase {expected_phase!r}"
+ )
+
+
+class TestStateMachineValidTransitions:
+ """Test valid sandbox state transitions."""
+
+ @staticmethod
+ def test_sm_001_provisioning_to_ready(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201
+ sandbox = resp.json()
+ wait_for_sandbox_ready(sandbox['id'])
+ status = client.get(f"/api/v1/sandboxes/{sandbox['id']}")
+ assert status.json()["phase"] == "ready"
+
+ @staticmethod
+ def test_sm_002_ready_to_stopped(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ stop_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")
+ assert stop_resp.json()["phase"] == "stopped"
+
+ @staticmethod
+ def test_sm_003_stopped_to_ready(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")
+ start_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/start")
+ assert start_resp.json()["phase"] == "ready"
+
+ @staticmethod
+ def test_sm_004_ready_to_deleting(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+ @staticmethod
+ def test_sm_005_stopped_to_deleting(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+ @staticmethod
+ def test_sm_006_error_to_ready(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["invalid-command-that-does-not-exist"], "timeout_seconds": 5},
+ )
+ assert resp.status_code == 200
+ _wait_for_sandbox_phase(client, sandbox_id, "error")
+
+ restart_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/restart")
+ assert restart_resp.status_code == 200, restart_resp.text
+ assert restart_resp.json()["phase"] == "ready"
+
+ @staticmethod
+ def test_sm_007_error_to_deleting(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["invalid-command-that-does-not-exist"], "timeout_seconds": 5},
+ )
+ assert resp.status_code == 200
+ _wait_for_sandbox_phase(client, sandbox_id, "error")
+
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+
+ @staticmethod
+ def test_sm_008_provisioning_to_error(client):
+ # Use an isolated uplink pool whose /30 blocks all overlap the reserved
+ # link-local range, so network setup fails during provisioning.
+ resp = client.post("/api/v1/sandboxes", json={"policy": _PROVISIONING_ERROR_POLICY})
+ assert resp.status_code == 201
+ sandbox_id = resp.json()["id"]
+
+ phase = None
+ try:
+ _wait_for_sandbox_phase(
+ client, sandbox_id, "error", reject_phases=("ready",)
+ )
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ phase = status.json().get("phase")
+ assert phase == "error"
+ finally:
+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+
+ @staticmethod
+ def test_sm_009_error_to_ready_auto_recovery(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.kill_sandbox_daemon(sandbox_id)
+
+ for _ in range(30):
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ if status.json()["phase"] == "ready":
+ break
+ time.sleep(1)
+ else:
+ pytest.fail("Sandbox did not recover from error")
+
+ @staticmethod
+ def test_sm_010_error_to_deleting(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ chaos = ChaosInjector(client)
+ chaos.kill_sandbox_daemon(sandbox_id)
+
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+ @staticmethod
+ def test_sm_011_deleting_to_terminal(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+
+ get_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert get_resp.status_code == 404
+
+
+class TestStateMachineValidatorDefinition:
+ """Validate the local state machine definition (not server API behavior)."""
+
+ @staticmethod
+ def test_validator_ready_to_provisioning_is_invalid():
+ assert not StateMachineValidator.is_valid_transition("ready", "provisioning")
+
+ @staticmethod
+ def test_validator_stopped_to_provisioning_is_invalid():
+ assert not StateMachineValidator.is_valid_transition("stopped", "provisioning")
+
+ @staticmethod
+ def test_validator_deleting_has_no_outgoing_transitions():
+ assert not StateMachineValidator.is_valid_transition("deleting", "ready")
+ assert not StateMachineValidator.is_valid_transition("deleting", "stopped")
+ assert not StateMachineValidator.is_valid_transition("deleting", "error")
+
+ @staticmethod
+ def test_validator_provisioning_to_stopped_is_invalid():
+ assert not StateMachineValidator.is_valid_transition("provisioning", "stopped")
+
+ @staticmethod
+ def test_validator_provisioning_to_deleting_is_invalid():
+ assert not StateMachineValidator.is_valid_transition("provisioning", "deleting")
+
+
+class TestStateMachineInvalidTransitions:
+ """Verify the server rejects or blocks invalid transition attempts via API."""
+
+ @staticmethod
+ def test_sm_014_start_after_delete_returns_not_found(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ delete_resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")
+ assert delete_resp.status_code == 204
+
+ start_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/start")
+ assert start_resp.status_code == 404, start_resp.text
+
+ @staticmethod
+ def test_sm_015_exec_during_provisioning_returns_conflict(client):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+
+ exec_resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "too-early"], "timeout_seconds": 5},
+ )
+ assert exec_resp.status_code == 409, exec_resp.text
+
+ @staticmethod
+ def test_sm_016_exec_on_stopped_sandbox_returns_conflict(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+
+ stop_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")
+ assert stop_resp.status_code == 200, stop_resp.text
+ assert stop_resp.json()["phase"] == "stopped"
+
+ exec_resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["echo", "stopped"], "timeout_seconds": 5},
+ )
+ assert exec_resp.status_code == 409, exec_resp.text
+
+ @staticmethod
+ def test_sm_017_state_tampering_detection(client, wait_for_sandbox_ready):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
+ sandbox_id = resp.json()["id"]
+ wait_for_sandbox_ready(sandbox_id)
+ resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={
+ "command": ["python3", "-c", "import os; os._exit(0)"],
+ "timeout_seconds": 5,
+ },
+ )
+ assert resp.status_code == 200
+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status.json()["phase"] == "ready"
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_utils.py b/jiuwenbox/tests/system_tests/test_utils.py
new file mode 100644
index 0000000000..3bbbefd0c1
--- /dev/null
+++ b/jiuwenbox/tests/system_tests/test_utils.py
@@ -0,0 +1,330 @@
+"""Test utility functions for system reliability and performance tests."""
+
+from __future__ import annotations
+
+import logging
+import subprocess
+import time
+from collections import deque
+from dataclasses import dataclass
+from typing import List, Optional
+
+from tests.system_tests.test_config import EnvironmentDetector, TestConfig
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class PerformanceMetrics:
+ """Performance metrics collected during tests."""
+
+ latencies: List[float]
+ qps: float = 0.0
+ p99: float = 0.0
+ p999: float = 0.0
+ avg_latency: float = 0.0
+
+
+class ResourceDegradationManager:
+ """Manage resource degradation for testing."""
+
+ def __init__(self):
+ self._processes = []
+ self._network_degraded = False
+
+ def degrade_cpu(self, cores: int = TestConfig.CPU_CORES_SEVERE, duration: int = 30):
+ """Degrade CPU by running stress-ng."""
+ if not EnvironmentDetector.has_stress_ng():
+ raise RuntimeError("stress-ng not available, cannot degrade CPU")
+
+ proc = subprocess.Popen(
+ ["/usr/bin/stress-ng", f"--cpu={cores}", f"--timeout={duration}s"],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ self._processes.append(proc)
+ time.sleep(2)
+ return proc
+
+ def degrade_memory(self, vm_bytes: str = TestConfig.MEMORY_SEVERE, duration: int = 30):
+ """Degrade memory by running stress-ng."""
+ if not EnvironmentDetector.has_stress_ng():
+ raise RuntimeError("stress-ng not available, cannot degrade memory")
+
+ proc = subprocess.Popen(
+ ["/usr/bin/stress-ng", f"--vm-bytes={vm_bytes}", "--vm=4", f"--timeout={duration}s"],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ self._processes.append(proc)
+ time.sleep(2)
+ return proc
+
+ def degrade_network(self, loss: int = 10, delay: int = 100, interface: str = TestConfig.NETWORK_INTERFACE):
+ """Degrade network using tc."""
+ if not EnvironmentDetector.has_tc():
+ raise RuntimeError("tc not available, cannot degrade network")
+
+ subprocess.run(
+ ["/sbin/tc", "qdisc", "add", "dev", interface, "root",
+ "netem", "loss", "random", f"{loss}%", "delay", f"{delay}ms"],
+ check=True,
+ )
+ self._network_degraded = True
+ return interface
+
+ def restore_network(self, interface: str = TestConfig.NETWORK_INTERFACE):
+ """Restore network quality."""
+ if self._network_degraded and EnvironmentDetector.has_tc():
+ try:
+ subprocess.run(
+ ["/sbin/tc", "qdisc", "del", "dev", interface, "root"],
+ check=True,
+ )
+ except subprocess.CalledProcessError as exc:
+ logger.warning("Failed to restore network on %s: %s", interface, exc)
+ self._network_degraded = False
+
+ def degrade_disk(self, path: str = "/tmp", size: str = "5G", duration: int = 30):
+ """Degrade disk by filling it."""
+ count = size[:-1]
+ proc = subprocess.Popen(
+ [
+ "/usr/bin/timeout",
+ f"{duration}s",
+ "/bin/dd",
+ "if=/dev/urandom",
+ f"of={path}/stress_file",
+ "bs=1G",
+ f"count={count}",
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ self._processes.append(proc)
+ time.sleep(2)
+ return proc
+
+ @staticmethod
+ def restore_disk(path: str = "/tmp"):
+ """Clean up disk stress file."""
+ subprocess.run(["/bin/rm", "-f", f"{path}/stress_file"], check=True)
+
+ def cleanup(self):
+ """Clean up all degradation processes."""
+ self.restore_network()
+ for proc in self._processes:
+ try:
+ proc.terminate()
+ proc.wait(timeout=5)
+ except Exception as exc:
+ logger.debug("Failed to terminate process: %s", exc)
+ try:
+ proc.kill()
+ proc.wait(timeout=5)
+ except Exception as kill_exc:
+ logger.warning("Failed to kill process: %s", kill_exc)
+ self._processes.clear()
+
+
+class ChaosInjector:
+ """Inject chaos into the system for resilience testing."""
+
+ def __init__(self, client):
+ self._client = client
+
+ def _resolve_daemon_pid(self, sandbox_id: str) -> str:
+ """Discover the sandbox daemon PID inside the sandbox."""
+ resp = self._client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={
+ "command": [
+ "sh",
+ "-c",
+ "pid=$(pgrep -f 'sandbox-daemon\\.py' | head -1); "
+ "if [ -z \"$pid\" ]; then pid=$(pgrep -f 'sandbox-daemon' | head -1); fi; "
+ "if [ -z \"$pid\" ]; then exit 1; fi; echo \"$pid\"",
+ ],
+ "timeout_seconds": 10,
+ },
+ )
+ if resp.status_code != 200:
+ raise RuntimeError(
+ f"Failed to discover daemon PID: {resp.status_code} {resp.text}"
+ )
+ raw = (resp.json().get("stdout") or "").strip()
+ if not raw.isdigit():
+ raise RuntimeError(
+ f"Could not find sandbox daemon PID in sandbox {sandbox_id}: {raw!r}"
+ )
+ return raw
+
+ def kill_sandbox_daemon(self, sandbox_id: str):
+ """Kill the sandbox daemon process."""
+ pid = self._resolve_daemon_pid(sandbox_id)
+ resp = self._client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["kill", "-9", pid], "timeout_seconds": 5},
+ )
+ return resp
+
+ def stop_sandbox_daemon(self, sandbox_id: str):
+ """Stop the sandbox daemon process (SIGSTOP)."""
+ pid = self._resolve_daemon_pid(sandbox_id)
+ resp = self._client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["kill", "-STOP", pid], "timeout_seconds": 5},
+ )
+ return resp
+
+ def restart_sandbox_daemon(self, sandbox_id: str):
+ """Restart the sandbox daemon process (SIGCONT)."""
+ pid = self._resolve_daemon_pid(sandbox_id)
+ resp = self._client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={"command": ["kill", "-CONT", pid], "timeout_seconds": 5},
+ )
+ return resp
+
+ @staticmethod
+ def disconnect_network():
+ """Disconnect network by bringing down interface."""
+ if not EnvironmentDetector.has_iproute2():
+ raise RuntimeError("iproute2 not available, cannot disconnect network")
+
+ try:
+ subprocess.run(
+ ["/sbin/ip", "link", "set", TestConfig.NETWORK_INTERFACE, "down"],
+ check=True,
+ )
+ return True
+ except subprocess.CalledProcessError as exc:
+ logger.warning("Failed to disconnect network: %s", exc)
+ return False
+
+ @staticmethod
+ def reconnect_network():
+ """Reconnect network by bringing up interface."""
+ if EnvironmentDetector.has_iproute2():
+ subprocess.run(
+ ["/sbin/ip", "link", "set", TestConfig.NETWORK_INTERFACE, "up"],
+ check=True,
+ )
+
+ def trigger_oom(self, sandbox_id: str, memory_gb: int = 22):
+ """Trigger OOM inside sandbox."""
+ resp = self._client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={
+ "command": ["/usr/bin/stress-ng", f"--vm-bytes={memory_gb}G", "--vm=1", "--timeout=60s"],
+ "timeout_seconds": 120,
+ },
+ )
+ return resp
+
+
+class StateMachineValidator:
+ """Validate sandbox state transitions."""
+
+ VALID_TRANSITIONS = {
+ "provisioning": ["ready", "error"],
+ "ready": ["stopped", "error", "deleting"],
+ "stopped": ["ready", "deleting"],
+ "error": ["ready", "deleting"],
+ "deleting": [],
+ }
+
+ @classmethod
+ def is_valid_transition(cls, from_state: str, to_state: str) -> bool:
+ """Check if a state transition is valid."""
+ from_state_lower = from_state.lower()
+ to_state_lower = to_state.lower()
+ return to_state_lower in cls.VALID_TRANSITIONS.get(from_state_lower, [])
+
+ @classmethod
+ def validate_transition(cls, from_state: str, to_state: str):
+ """Validate a state transition and raise if invalid."""
+ if not cls.is_valid_transition(from_state, to_state):
+ raise ValueError(
+ f"Invalid state transition: {from_state} -> {to_state}. "
+ f"Valid transitions from {from_state}: {cls.VALID_TRANSITIONS.get(from_state.lower(), [])}"
+ )
+
+
+class PerformanceCollector:
+ """Collect and analyze performance metrics."""
+
+ def __init__(self):
+ self._latencies = []
+ self._start_time = None
+ self._end_time = None
+
+ def start(self):
+ """Start timing."""
+ self._start_time = time.time()
+
+ def stop(self):
+ """Stop timing."""
+ self._end_time = time.time()
+
+ def record_latency(self, latency: float):
+ """Record a latency measurement."""
+ self._latencies.append(latency)
+
+ def get_metrics(self) -> PerformanceMetrics:
+ """Calculate and return performance metrics."""
+ if not self._latencies:
+ return PerformanceMetrics(latencies=[])
+
+ latencies = sorted(self._latencies)
+ total_time = self._end_time - self._start_time if self._start_time and self._end_time else 1
+ qps = len(latencies) / total_time if total_time > 0 else 0
+
+ n = len(latencies)
+ p99_idx = int(n * 0.99) - 1
+ p999_idx = int(n * 0.999) - 1
+
+ return PerformanceMetrics(
+ latencies=latencies,
+ qps=qps,
+ p99=latencies[p99_idx] if p99_idx >= 0 else latencies[-1],
+ p999=latencies[p999_idx] if p999_idx >= 0 else latencies[-1],
+ avg_latency=sum(latencies) / n,
+ )
+
+
+class RollingWindowStats:
+ """Calculate statistics over a rolling window."""
+
+ def __init__(self, window_size: int = 100):
+ self._window = deque(maxlen=window_size)
+
+ def add(self, value: float):
+ """Add a value to the window."""
+ self._window.append(value)
+
+ def avg(self) -> float:
+ """Calculate average."""
+ if not self._window:
+ return 0.0
+ return sum(self._window) / len(self._window)
+
+ def p99(self) -> float:
+ """Calculate P99."""
+ if not self._window:
+ return 0.0
+ sorted_vals = sorted(self._window)
+ idx = int(len(sorted_vals) * 0.99) - 1
+ return sorted_vals[idx] if idx >= 0 else sorted_vals[-1]
+
+ def p999(self) -> float:
+ """Calculate P999."""
+ if not self._window:
+ return 0.0
+ sorted_vals = sorted(self._window)
+ idx = int(len(sorted_vals) * 0.999) - 1
+ return sorted_vals[idx] if idx >= 0 else sorted_vals[-1]
+
+ def count(self) -> int:
+ """Get count of values in window."""
+ return len(self._window)