Repository navigation
feat: Phase 1b — real sandbox dispatch with per-user API keys - #4
Conversation
Migrates dispatch-phase1b branch from deploy repo to standalone
automation service repo.
Key changes:
- execution.py: sandbox lifecycle (create, upload tarball, execute, delete)
via SaaS API with env var injection and callback support
- dispatcher.py: rewritten with DispatchConfig, per-user API keys via
get_api_key_for_automation_run(), asyncio.create_task for non-blocking
dispatch, error handling with error_detail
- utils/api_key.py: service-key based API key minting for automation runs
- router.py: POST /runs/{run_id}/complete callback endpoint
- schemas.py: RunCompleteRequest schema, RunStatus uses StrEnum
- config.py: saas_api_url, automation_callback_base_url, service_key
- app.py: DispatchConfig construction and wiring
- utils/run.py: mark_run_status() accepts error_detail
- tests/test_execution.py: unit tests for tarball builder, shell_quote
- scripts/test_automation.py: e2e test against real staging sandbox
- integration/: integration test scaffolding
Co-authored-by: openhands <openhands@all-hands.dev>
- Remove integration/ dir (kept in deploy repo) - Fix pyright: add None checks for tarfile.extractfile() - Fix ruff: StrEnum, line length, import sorting Co-authored-by: openhands <openhands@all-hands.dev>
Each test mirrors a specific dispatcher._execute_run() path: - dispatch-basic: minimal tarball, no setup.sh - dispatch-with-setup: setup.sh installs deps before entrypoint - dispatch-env-injection: env vars exported to sandbox - dispatch-callback-env: AUTOMATION_CALLBACK_URL + RUN_ID injected - dispatch-sdk-workspace: OpenHandsCloudWorkspace importable - dispatch-failure: non-zero exit handled correctly - dispatch-full-lifecycle: all steps combined in one run Co-authored-by: openhands <openhands@all-hands.dev>
One function (run_test) that mirrors dispatcher._execute_run(): 1. Create sandbox via SaaS API 2. Wait until RUNNING 3. Upload tarball to sandbox 4. start_bash_command (non-blocking) — extract, setup.sh, entrypoint 5. Poll search_bash_events — stream stdout/stderr to local terminal 6. Verify ALL_OK marker + exit_code == 0 7. Delete sandbox Uses start_bash_command + search_bash_events instead of the blocking execute_bash_command so output appears in real-time. Co-authored-by: openhands <openhands@all-hands.dev>
Run log from app.all-hands.dev — full lifecycle in 3.5s: create sandbox → upload tarball → setup.sh → main.py → stream → delete Co-authored-by: openhands <openhands@all-hands.dev>
Full lifecycle pass against app.all-hands.dev in 3.5s. Co-authored-by: openhands <openhands@all-hands.dev>
setup.sh and main.py now live as real files in version control. test_automation.py packs the directory into a tarball at runtime. Co-authored-by: openhands <openhands@all-hands.dev>
main.py now mirrors the automations ADR (architecture PR #11) and SDK example 10_cloud_workspace_share_credentials.py: - OpenHandsCloudWorkspace creates an inner sandbox - get_llm() fetches LLM config from SaaS account - get_secrets() fetches lazy LookupSecret refs - Conversation runs a task inside the inner sandbox setup.sh installs openhands-{workspace,sdk,tools} from SDK main. TODO: switch to saas_runtime_mode=True once SDK PR #2490 merges. Test run log shows full lifecycle working: - LLM configured (claude-opus-4-5-20251101) - Inner sandbox created + conversation triggered - ConversationRunError from bot account LLM config (not code issue) Co-authored-by: openhands <openhands@all-hands.dev>
…nternal downloads - Add timeout_at column to automation_runs (pre-computed deadline for efficient indexed watchdog queries, set at dispatch time) - Add conversation_id column to automation_runs (set by completion callback when SDK script creates a conversation) - Add staleness watchdog (periodic scan, marks stale RUNNING runs FAILED) - Dispatcher downloads oh-internal:// tarballs via GCS storage - Dispatcher injects OPENHANDS_API_KEY, OPENHANDS_CLOUD_API_URL, and AUTOMATION_EVENT_PAYLOAD env vars into sandbox - Add FileStore.read() + GoogleCloudFileStore.read() for GCS download - Add Alembic migration 003 for new columns - Update test_tarball/main.py for saas_runtime_mode=True - Update test_tarball/setup.sh to install from SDK PR #2490 branch Co-authored-by: openhands <openhands@all-hands.dev>
|
🚀 Deploy Preview PR Created/Updated A deploy preview has been created/updated for this PR. Deploy PR: https://github.com/OpenHands/deploy/pull/3506 Once the deploy PR's CI passes, the automation service will be deployed to the feature environment. |
Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
🔴 Needs improvement - Core architecture is sound, but several critical issues must be fixed before merge: unauthenticated callback endpoint, localhost callback URLs that sandboxes can't reach, missing error handling for background tasks, and race conditions in status updates.
Address all review comments from PR #4 review: 🔴 Critical fixes: - Callback endpoint now requires one-time token (generated at dispatch, validated with hmac.compare_digest, invalidated after use) - Callback URL uses configurable callback_base_url instead of localhost (AUTOMATION_CALLBACK_BASE_URL env var, warns if unset) - Background tasks wrapped in _execute_run_safe() to prevent silent exception swallowing from asyncio.create_task() 🟠 Important fixes: - Watchdog and callback use optimistic locking (WHERE status = RUNNING) to prevent race conditions — concurrent updates are safe - Removed .pr/test_automation.log from VCS, added .pr/*.log to .gitignore 🟡 Improvements: - Sandbox cleanup on partial creation failure in execution.py - Integration test wrapper at tests/integration/test_automation_e2e.py (pytest-discoverable, skipped without OPENHANDS_API_KEY) - Migration 003 updated to include callback_token column Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Acceptable — Core architecture is solid and previous critical issues are resolved. Two issues need attention: excessive nesting complexity and query parameter token exposure.
Update test script to inject SANDBOX_ID and SESSION_API_KEY as env vars into the sandbox command. These are read by the SDK's fixed _init_saas_runtime_mode() (sdk commit 3f81ef3) so that get_llm() and get_secrets() work inside the sandbox. Verified E2E: sandbox created -> SDK workspace -> get_llm() returns litellm_proxy model -> get_secrets() returns ['github_token'] -> ALL_OK Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
a5c31f7 to
6cad670
Compare
Changes: - Dispatcher fetches per-user API key on demand via get_api_key_for_automation_run (service_key → SaaS), never stored - Callback endpoint uses authenticate_request (same OPENHANDS_API_KEY the sandbox already has) instead of bespoke callback_token - Drop callback_token from AutomationRun model (migration 004) - Remove unused admin_api_key from config - execution.py: auto-inject SANDBOX_ID + SESSION_API_KEY env vars; add keep_sandbox param - Refactor scripts/test_automation.py to call run_automation() directly Co-authored-by: openhands <openhands@all-hands.dev>
6cad670 to
b490435
Compare
The CreateUserApiKeyResponse in OpenHands/OpenHands uses "key" (not "api_key") as the field name. Remove the fallback to keep a single consistent field name. Co-authored-by: openhands <openhands@all-hands.dev>
callback_token was introduced in 003 and immediately removed in 004. Since neither migration has been applied to production, squash them into a single migration that only adds conversation_id + timeout_at. Co-authored-by: openhands <openhands@all-hands.dev>
Update scripts/test_tarball/main.py to create a Conversation using the LLM config and secrets fetched from the workspace, following the pattern from the SDK example (10_cloud_workspace_share_credentials.py). - Create agent via get_default_agent(llm=llm, cli_mode=True) - Create RemoteConversation with event callbacks - Inject SaaS secrets via conversation.update_secrets() - Send a prompt exercising secrets (or a simple file-write fallback) - Wait for stream to settle and report cost/events Co-authored-by: openhands <openhands@all-hands.dev>
3b38331 to
b159e9d
Compare
The dispatch_pending_runs() and dispatcher_loop() functions require settings to actually execute runs in sandboxes. Making settings optional was misleading because without it, runs would be marked as RUNNING but never actually dispatched to sandboxes. Changes: - Make settings parameter non-optional in dispatch_pending_runs() - Make settings parameter non-optional in dispatcher_loop() - Remove conditional check for settings before creating background tasks - Update tests to use mock_settings fixture and mock _execute_run_safe Co-authored-by: openhands <openhands@all-hands.dev>
- Add dispatch_automation() for async fire-and-forget execution - Keep run_automation() for blocking execution (testing) - Add keep_alive and sandbox_id columns to AutomationRun - Add sandbox verification utility (utils/sandbox.py) - Update watchdog to verify run status before marking as failed - Update /complete endpoint to cleanup sandbox when keep_alive=False - Add update_sandbox_id() utility function - Update tests for new DispatchResult type The dispatcher now starts the bash command and disconnects immediately. Completion status is determined by: 1. SDK callback to /complete endpoint (primary) 2. Watchdog verification via sandbox (fallback) Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Delete the sandbox immediately if dispatch fails after sandbox creation (e.g., tarball upload fails) to avoid orphaned sandboxes. Co-authored-by: openhands <openhands@all-hands.dev>
- Rename _delete_sandbox_impl to delete_sandbox (public) in utils/sandbox.py - Remove duplicate _delete_sandbox from execution.py - Update all callers to use shared delete_sandbox from utils Co-authored-by: openhands <openhands@all-hands.dev>
- Add automation/constants.py with centralized constants (MAX_RUN_DURATION_SECONDS, sandbox settings, rate limit settings) - Add timeout field to Automation model and migration - Add timeout validation in CreateAutomationRequest and UpdateAutomationRequest (positive, <= 600s) - Add timeout to AutomationResponse schema - Update dispatcher to calculate effective timeout: min(automation.timeout, MAX_RUN_DURATION_SECONDS) - Update execution.py to import constants from constants.py - Update utils/run.py to use MAX_RUN_DURATION from constants - Add unit tests for timeout validation and effective timeout calculation Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
- auth.py: AuthenticatedUser - execution.py: DispatchResult, AutomationResult (frozen) - utils/sandbox.py: BashCommandResult, VerificationResult (frozen) Pydantic dataclasses provide better validation and serialization while maintaining the same frozen=True behavior. Co-authored-by: openhands <openhands@all-hands.dev>
- Add mark_run_terminal() as public function in automation/utils/run.py - Remove local _mark_run_terminal from dispatcher.py - Update dispatcher.py to import and use mark_run_terminal from utils The function safely marks a run with a terminal status (COMPLETED/FAILED) only if the run is still in RUNNING state, avoiding race conditions. Co-authored-by: openhands <openhands@all-hands.dev>
…er_mode - Update test_tarball/main.py to use local_agent_server_mode and remove explicit automation_callback_url/automation_run_id args (now read from env vars by the SDK) - Update execution.py docstrings - Update AGENTS.md Co-authored-by: openhands <openhands@all-hands.dev>
|
I'm on it! xingyaoww can track my progress at all-hands.dev |
… format - dispatcher.py: automation.triggers → automation.trigger - test_dispatcher.py: triggers= kwarg → trigger= in TestEffectiveTimeout - test_tarball/main.py: break long line for ruff format Co-authored-by: openhands <openhands@all-hands.dev>
SummaryI fixed both CI failures linked in the PR #4 comment: Changes Made (commit
|
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
- Fix repo structure: add missing files (auth.py, constants.py, db.py, logger.py, uploads.py, storage/, utils/ subpackage, containers/) - Fix Settings class name (was AutomationSettings) - Fix execution.py description (no SandboxExecutor class) - Fix test directory structure (flat, not tests/unit/) - Fix pre-commit config path (root, not dev_config/) - Rewrite dispatch pipeline to reflect fire-and-forget model - Add async completion flow (callback + watchdog fallback) - Fix callback auth docs (standard API key auth, not callback_token) - Fix database config docs (AUTOMATION_DB_* env vars, not DATABASE_URL) - Add sandbox cleanup behavior docs Co-authored-by: openhands <openhands@all-hands.dev>
Summary
Migrates the
dispatch-phase1bbranch from thedeployrepo to the standaloneautomationservice repo, bringing real sandbox execution with per-user API keys.Coordinates with SDK changes in OpenHands/software-agent-sdk#2490.
Key Changes
New Files
automation/execution.py— Sandbox lifecycle: create → upload tarball → execute → delete via SaaS API, with env var injection and completion callback supportautomation/utils/api_key.py— Service-key based API key minting for automation runs (per-user keys viaget_api_key_for_automation_run())tests/test_execution.py— Unit tests for tarball builder,shell_quote,AutomationResultscripts/test_automation.py— E2E test suite against real staging sandboxes (echo, setup.sh, env vars, SDK import, callback)integration/— Integration test scaffoldingModified Files
dispatcher.py— Rewritten withDispatchConfigdataclass,asyncio.create_taskfor non-blocking dispatch, per-user API keys,selectinloadfor eager relationship loading, structured error handling witherror_detailrouter.py— AddedPOST /runs/{run_id}/completecallback endpoint for sandbox completion notificationsschemas.py—RunCompleteRequestschema,RunStatusmigrated toStrEnumconfig.py— Addedsaas_api_url,automation_callback_base_url,service_keysettingsapp.py—DispatchConfigconstruction and wiring in lifespanutils/run.py—mark_run_status()now accepts optionalerror_detailparameterTesting
tests/test_execution.py— 9/9)How to run e2e tests