Skip to content

feat: Implement pluggable multi-provider sandbox architecture - #12820

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:sandbox_saas
Jan 28, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:sandbox_saas

Conversation

@yuzhichang

@yuzhichang yuzhichang commented Jan 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Implement a flexible sandbox provider system supporting both self-managed (Docker) and SaaS (Aliyun Code Interpreter) backends for secure code execution in agent workflows.

Key Changes:

  • ✅ Aliyun Code Interpreter provider using official agentrun-sdk>=0.0.16
  • ✅ Self-managed provider with gVisor (runsc) security
  • ✅ Arguments parameter support for dynamic code execution
  • ✅ Database-only configuration (removed fallback logic)
  • ✅ Configuration scripts for quick setup

Issue #12479

Features

🔌 Provider Abstraction Layer

1. Self-Managed Provider (agent/sandbox/providers/self_managed.py)

  • Wraps existing executor_manager HTTP API
  • gVisor (runsc) for secure container isolation
  • Configurable pool size, timeout, retry logic
  • Languages: Python, Node.js, JavaScript
  • ⚠️ Requires: gVisor installation, Docker, base images

2. Aliyun Code Interpreter (agent/sandbox/providers/aliyun_codeinterpreter.py)

  • SaaS integration using official agentrun-sdk
  • Serverless microVM execution with auto-authentication
  • Hard timeout: 30 seconds max
  • Credentials: AGENTRUN_ACCESS_KEY_ID, AGENTRUN_ACCESS_KEY_SECRET, AGENTRUN_ACCOUNT_ID, AGENTRUN_REGION
  • Automatically wraps code to call main() function

3. E2B Provider (agent/sandbox/providers/e2b.py)

  • Placeholder for future integration

⚙️ Configuration System

  • conf/system_settings.json: Default provider = aliyun_codeinterpreter
  • agent/sandbox/client.py: Enforces database-only configuration
  • Admin UI: /admin/sandbox-settings
  • Configuration validation via validate_config() method
  • Health checks for all providers

🎯 Key Capabilities

Arguments Parameter Support:
All providers support passing arguments to main() function:

# User code
def main(name: str, count: int) -> dict:
    return {"message": f"Hello {name}!" * count}

# Executed with: arguments={"name": "World", "count": 3}
# Result: {"message": "Hello World!Hello World!Hello World!"}

Self-Describing Providers:
Each provider implements get_config_schema() returning form configuration for Admin UI

Error Handling:
Structured ExecutionResult with stdout, stderr, exit_code, execution_time

Configuration Scripts

Two scripts for quick Aliyun sandbox setup:

Shell Script (requires jq):

source scripts/configure_aliyun_sandbox.sh

Python Script (interactive):

python3 scripts/configure_aliyun_sandbox.py

Testing

# Unit tests
uv run pytest agent/sandbox/tests/test_providers.py -v

# Aliyun provider tests
uv run pytest agent/sandbox/tests/test_aliyun_codeinterpreter.py -v

# Integration tests (requires credentials)
uv run pytest agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py -v

# Quick SDK validation
python3 agent/sandbox/tests/verify_sdk.py

Test Coverage:

  • 30 unit tests for provider abstraction
  • Provider-specific tests for Aliyun
  • Integration tests with real API
  • Security tests for executor_manager

Documentation

  • docs/develop/sandbox_spec.md - Complete architecture specification
  • agent/sandbox/tests/MIGRATION_GUIDE.md - Migration from legacy sandbox
  • agent/sandbox/tests/QUICKSTART.md - Quick start guide
  • agent/sandbox/tests/README.md - Testing documentation

Breaking Changes

⚠️ Migration Required:

  1. Directory Move: sandbox/ → agent/sandbox/

    • Update imports: from sandbox. → from agent.sandbox.
  2. Mandatory Configuration:

    • SystemSettings must have sandbox.provider_type configured
    • Removed fallback default values
    • Configuration must exist in database (from conf/system_settings.json)
  3. Aliyun Credentials:

    • Requires AGENTRUN_* environment variables (not ALIYUN_*)
    • AGENTRUN_ACCOUNT_ID is now required (Aliyun primary account ID)
  4. Self-Managed Provider:

    • gVisor (runsc) must be installed for security
    • Install: go install gvisor.dev/gvisor/runsc@latest

Database Schema Changes

# SystemSettings.value: CharField → TextField
api/db/db_models.py: Changed for unlimited config length

# SystemSettingsService.get_by_name(): Fixed query precision
api/db/services/system_settings_service.py: startswith → exact match

Files Changed

Backend (Python)

  • agent/sandbox/providers/base.py - SandboxProvider ABC interface
  • agent/sandbox/providers/manager.py - ProviderManager
  • agent/sandbox/providers/self_managed.py - Self-managed provider
  • agent/sandbox/providers/aliyun_codeinterpreter.py - Aliyun provider
  • agent/sandbox/providers/e2b.py - E2B provider (placeholder)
  • agent/sandbox/client.py - Unified client (enforces DB-only config)
  • agent/tools/code_exec.py - Updated to use provider system
  • admin/server/services.py - SandboxMgr with registry & validation
  • admin/server/routes.py - 5 sandbox API endpoints
  • conf/system_settings.json - Default: aliyun_codeinterpreter
  • api/db/db_models.py - TextField for SystemSettings.value
  • api/db/services/system_settings_service.py - Exact match query

Frontend (TypeScript/React)

  • web/src/pages/admin/sandbox-settings.tsx - Settings UI
  • web/src/services/admin-service.ts - Sandbox service functions
  • web/src/services/admin.service.d.ts - Type definitions
  • web/src/utils/api.ts - Sandbox API endpoints

Documentation

  • docs/develop/sandbox_spec.md - Architecture spec
  • agent/sandbox/tests/MIGRATION_GUIDE.md - Migration guide
  • agent/sandbox/tests/QUICKSTART.md - Quick start
  • agent/sandbox/tests/README.md - Testing guide

Configuration Scripts

  • scripts/configure_aliyun_sandbox.sh - Shell script (jq)
  • scripts/configure_aliyun_sandbox.py - Python script

Tests

  • agent/sandbox/tests/test_providers.py - 30 unit tests
  • agent/sandbox/tests/test_aliyun_codeinterpreter.py - Provider tests
  • agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py - Integration tests
  • agent/sandbox/tests/verify_sdk.py - SDK validation

Architecture

Admin UI → Admin API → SandboxMgr → ProviderManager → [SelfManaged|Aliyun|E2B]
                                      ↓
                                  SystemSettings

Usage

1. Configure Provider

Via Admin UI:

  1. Navigate to /admin/sandbox-settings
  2. Select provider (Aliyun Code Interpreter / Self-Managed)
  3. Fill in configuration
  4. Click "Test Connection" to verify
  5. Click "Save" to apply

Via Configuration Scripts:

# Aliyun provider
export AGENTRUN_ACCESS_KEY_ID="xxx"
export AGENTRUN_ACCESS_KEY_SECRET="yyy"
export AGENTRUN_ACCOUNT_ID="zzz"
export AGENTRUN_REGION="cn-shanghai"
source scripts/configure_aliyun_sandbox.sh

2. Restart Service

cd docker
docker compose restart ragflow-server

3. Execute Code in Agent

from agent.sandbox.client import execute_code

result = execute_code(
    code='def main(name: str) -> dict: return {"message": f"Hello {name}!"}',
    language="python",
    timeout=30,
    arguments={"name": "World"}
)

print(result.stdout)  # {"message": "Hello World!"}

Troubleshooting

"Container pool is busy" (Self-Managed)

  • Cause: Pool exhausted (default: 1 container in .env)
  • Fix: Increase SANDBOX_EXECUTOR_MANAGER_POOL_SIZE to 5+

"Sandbox provider type not configured"

  • Cause: Database missing configuration
  • Fix: Run config script or set via Admin UI

"gVisor not found"

  • Cause: runsc not installed
  • Fix: go install gvisor.dev/gvisor/runsc@latest && sudo cp ~/go/bin/runsc /usr/local/bin/

Aliyun authentication errors

  • Cause: Wrong environment variable names
  • Fix: Use AGENTRUN_* prefix (not ALIYUN_*)

Checklist

  • All tests passing (30 unit tests + integration tests)
  • Documentation updated (spec, migration guide, quickstart)
  • Type definitions added (TypeScript)
  • Admin UI implemented
  • Configuration validation
  • Health checks implemented
  • Error handling with structured results
  • Breaking changes documented
  • Configuration scripts created
  • gVisor requirements documented

Co-Authored-By: Claude Sonnet 4.5 [email protected]

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. 🧰 typescript Pull requests that update Typescript code size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jan 26, 2026
@yuzhichang
yuzhichang marked this pull request as draft January 26, 2026 08:23
@yuzhichang
yuzhichang force-pushed the sandbox_saas branch 2 times, most recently from 7381936 to d4e8507 Compare January 27, 2026 09:24
@yuzhichang yuzhichang changed the title feat: Add multi-provider sandbox architecture with SaaS support feat: Implement pluggable multi-provider sandbox architecture Jan 27, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Jan 27, 2026
@yuzhichang
yuzhichang marked this pull request as ready for review January 27, 2026 09:28
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jan 27, 2026
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jan 27, 2026
- Remove unused imports and variables in provider implementations
  * Remove unused template_name assignment in aliyun_codeinterpreter.py
  * Remove unused time import in e2b.py
  * Remove unused MagicMock import in test_providers.py
  * Add noqa comments for SDK availability checks in verify_sdk.py
- Delete MIGRATION_GUIDE.md and QUICKSTART.md (consolidated into main README)
- Update agent/sandbox/tests/README.md with accurate information:
  * Correct environment variable names (AGENTRUN_* not ALIYUN_*)
  * Add SDK validation section
  * Add self-managed provider testing instructions
  * Add troubleshooting for common issues
  * Update provider-specific notes and references

Fixes CI ruff linting failures in PR infiniflow#12820
Add a flexible sandbox provider system supporting both self-managed and SaaS
backends for secure code execution in agent workflows.

- `agent/sandbox/providers/base.py`: SandboxProvider ABC interface with
  SandboxInstance and ExecutionResult dataclasses
- `agent/sandbox/providers/manager.py`: ProviderManager for active provider
  management
- `agent/sandbox/client.py`: Unified client with automatic provider loading
  from SystemSettings (enforces database-only configuration)
- `agent/tools/code_exec.py`: Updated to use provider system with backward
  compatibility fallback

1. **Self-Managed Provider** (`agent/sandbox/providers/self_managed.py`):
   - Wraps existing executor_manager HTTP API
   - Supports gVisor (runsc) for secure container isolation
   - Configurable pool size, timeout, and retry logic
   - Requires: gVisor installation, Docker, base images

2. **Aliyun Code Interpreter** (`agent/sandbox/providers/aliyun_codeinterpreter.py`):
   - SaaS integration using official agentrun-sdk>=0.0.16
   - Serverless microVM execution with automatic authentication
   - Code wrapping to call main() function with arguments support
   - Required: AGENTRUN_ACCESS_KEY_ID, AGENTRUN_ACCESS_KEY_SECRET,
     AGENTRUN_ACCOUNT_ID, AGENTRUN_REGION

3. **E2B Provider** (`agent/sandbox/providers/e2b.py`):
   - Placeholder for future E2B integration

- `conf/system_settings.json`: Default provider configuration
  (provider_type: aliyun_codeinterpreter)
- `api/db/services/system_settings_service.py`: Fixed exact match query
  (startswith → exact match for setting name lookup)
- `api/db/db_models.py`: Changed SystemSettings.value to TextField
  for unlimited config length
- `admin/server/services.py`: SandboxMgr with provider registry,
  config validation, and connection testing
- `admin/server/routes.py`: 5 admin API endpoints for sandbox management
- `web/src/pages/admin/sandbox-settings.tsx`: Comprehensive settings UI
  with provider selection, dynamic forms, and testing

- `agent/sandbox/tests/test_providers.py`: 30 unit tests
- `agent/sandbox/tests/test_aliyun_codeinterpreter.py`: Provider-specific tests
- `agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py`: Integration tests
- `agent/sandbox/tests/verify_sdk.py`: Quick SDK validation script

- `docs/develop/sandbox_spec.md`: Complete architecture specification
  with provider details, configuration format, and troubleshooting
- `agent/sandbox/tests/MIGRATION_GUIDE.md`: Migration from legacy sandbox
- `agent/sandbox/tests/QUICKSTART.md`: Quick start guide
- `agent/sandbox/tests/README.md`: Testing documentation

- **Arguments Parameter**: All providers support passing arguments to main()
  function for dynamic code execution
- **Self-Describing Providers**: get_config_schema() returns form configuration
- **Config Validation**: validate_config() method for provider-specific checks
- **Health Checks**: All providers implement health_check() method
- **Error Handling**: Structured ExecutionResult with stdout, stderr, exit_code

- `scripts/configure_aliyun_sandbox.sh`: Shell script (jq) for quick setup
- `scripts/configure_aliyun_sandbox.py`: Python script for interactive setup

- `agent/sandbox/` directory moved from `sandbox/`
- SystemSettings must have `sandbox.provider_type` configured (removed fallback)
- Aliyun credentials require AGENTRUN_* environment variables
- Self-managed provider requires gVisor (runsc) for security

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
- Remove unused variable `template_name` in aliyun_codeinterpreter.py
- Remove unused variables `normalized_lang`, `execution_time`, and `start_time` in e2b.py
- Remove unused `time` import in e2b.py
- Remove unused `MagicMock` import in test_providers.py
- Fix unused imports in verify_sdk.py by using importlib.util.find_spec

This fixes CI ruff check failures:
- F841: Local variables assigned but never used
- F401: Imports unused

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@yuzhichang

Copy link
Copy Markdown
Member Author

CI Fix

Just pushed a commit to fix the ruff linting errors:

  • Remove unused variables in and
  • Remove unused imports in test files
  • Use for SDK availability checks in

All ruff checks should now pass ✅

@yuzhichang
yuzhichang merged commit fd11aca into infiniflow:main Jan 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XXL This PR changes 1000+ lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant