Skip to content

feat: Phase 1b — real sandbox dispatch with per-user API keys - #4

Merged
xingyaoww merged 50 commits into
mainfrom
dispatch-phase1b
Mar 25, 2026
Merged

xingyaoww merged 50 commits into
mainfrom
dispatch-phase1b

Conversation

@xingyaoww

Copy link
Copy Markdown
Contributor

Summary

Migrates the dispatch-phase1b branch from the deploy repo to the standalone automation service 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 support
  • automation/utils/api_key.py — Service-key based API key minting for automation runs (per-user keys via get_api_key_for_automation_run())
  • tests/test_execution.py — Unit tests for tarball builder, shell_quote, AutomationResult
  • scripts/test_automation.py — E2E test suite against real staging sandboxes (echo, setup.sh, env vars, SDK import, callback)
  • integration/ — Integration test scaffolding

Modified Files

  • dispatcher.py — Rewritten with DispatchConfig dataclass, asyncio.create_task for non-blocking dispatch, per-user API keys, selectinload for eager relationship loading, structured error handling with error_detail
  • router.py — Added POST /runs/{run_id}/complete callback endpoint for sandbox completion notifications
  • schemas.py — RunCompleteRequest schema, RunStatus migrated to StrEnum
  • config.py — Added saas_api_url, automation_callback_base_url, service_key settings
  • app.py — DispatchConfig construction and wiring in lifespan
  • utils/run.py — mark_run_status() now accepts optional error_detail parameter

Testing

  • ✅ All unit tests pass (tests/test_execution.py — 9/9)
  • ✅ Ruff check + format clean
  • ✅ Pyright type check clean
  • ✅ E2E tests pass against staging (5/5: echo, setup-sh, env-vars, sdk-import, callback)

How to run e2e tests

export OPENHANDS_API_KEY="sk-oh-..."
python scripts/test_automation.py --api-url https://staging.all-hands.dev --test all

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>
@github-actions

github-actions Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report
FileStmtsMissCoverMissing
__init__.py10100% 
app.py793851%30, 33, 36–37, 39, 42, 45–47, 50–51, 54, 61–62, 65–66, 70, 78–79, 82, 89–90, 92, 95–96, 99, 104–112, 114–116
auth.py77692%59, 92, 149, 200, 208–209
config.py30196%58
constants.py120100% 
db.py382728%28–29, 31–32, 34, 42, 53–55, 59, 61–62, 66–67, 75, 77–78, 84, 96, 101, 104–110
dispatcher.py1286549%46, 59–60, 62, 65–67, 69, 71–72, 114–117, 120–121, 125, 130, 132, 136, 138–139, 142–144, 146–148, 155, 161, 166, 170–171, 173, 176, 187–188, 190–192, 198, 203, 207–209, 212–214, 241–242, 266–273, 294–295, 305–306, 313–314, 316
execution.py20515524%43–45, 52–57, 87–90, 98–100, 108, 113–117, 131, 133, 135–138, 140–145, 147, 149–156, 158–159, 161, 176, 181, 192, 198–200, 211, 217–219, 245, 253, 257, 259–260, 263, 309–315, 318–319, 321, 323–325, 328, 331, 334–337, 339, 342–343, 346–348, 352, 355, 359–362, 364, 372–373, 376, 382, 384–385, 387–389, 437–443, 446–447, 449, 451–453, 456, 459, 462–465, 467, 470–471, 474–476, 480, 483, 487–490, 492, 500–501, 505–507, 509–515, 519, 521, 530–532, 534–536
logger.py531866%25–26, 36, 46–47, 49–55, 68, 88, 90–93
models.py650100% 
router.py1035645%71–72, 92, 94, 97, 99, 113, 126, 128–129, 131–132, 135–137, 148–150, 168–171, 190, 193, 196, 203, 205, 234, 239–241, 244–246, 250–251, 256, 260–263, 265, 273, 275–276, 281–282, 285, 287, 289–290, 299, 320–322, 326
scheduler.py57984%124–125, 162–163, 178–179, 189–190, 192
schemas.py1441192%67–69, 71, 129, 153–154, 157, 162, 167, 173
uploads.py1106045%38, 144–147, 155–157, 163–164, 167, 176–177, 180–181, 189–190, 192–195, 198–201, 203, 205–207, 209–212, 214–215, 217, 232, 238–239, 242, 245, 248, 251, 253, 266–267, 281, 284–286, 288–289, 291, 297–298, 311, 319–321, 325
watchdog.py998118%38–43, 59–62, 65–67, 79–80, 83–87, 99–100, 103, 111, 113–114, 119, 131–136, 138, 143, 155–156, 160, 167–168, 175–176, 188–189, 204–205, 207, 209, 218, 220–222, 224, 231–233, 235–237, 239–240, 242, 252, 257–260, 262–267, 269–275, 277
storage
   __init__.py30100% 
   file_store.py14471%10, 19, 24, 29
   google_cloud.py72888%103–108, 193, 195
utils
   __init__.py40100% 
   api_key.py322425%40–41, 46–48, 50, 55, 60, 62–65, 67–68, 70–71, 73, 79, 81–82, 89, 91–92, 98
   cron.py45686%39, 45, 74, 80, 123, 140
   run.py582556%89–90, 111–113, 118–120, 143, 145–149, 151–153, 156–158, 164–165, 167, 173–174
   sandbox.py1088224%32–37, 51–52, 57–60, 62–64, 66–72, 84, 86, 96–97, 99–101, 103–104, 107–108, 114, 120–122, 132–133, 138–144, 167–168, 170–174, 176–180, 217–218, 220, 222–225, 230–231, 234, 236–237, 243–245, 250–252, 257–258, 266–268, 270
   tarball_validation.py480100% 
   time.py30100% 
TOTAL158867657% 

- 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>
@github-actions

github-actions Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Deploy Preview PR Created/Updated

A deploy preview has been created/updated for this PR.

Deploy PR: https://github.com/OpenHands/deploy/pull/3506
Automation SHA: dc6a1a10090498673a617ad45874f85f611044c2
Last updated: Mar 25, 2026, 01:05:39 PM ET

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>
@xingyaoww
xingyaoww requested a review from all-hands-bot March 23, 2026 12:22

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Comment thread automation/router.py Resolved
Comment thread automation/dispatcher.py Resolved
Comment thread automation/dispatcher.py Resolved
Comment thread automation/watchdog.py Resolved
Comment thread .pr/test_automation.log Resolved
Comment thread automation/execution.py Resolved
Comment thread tests/test_execution.py Resolved
Comment thread automation/utils/run.py Resolved
Comment thread automation/dispatcher.py Resolved
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>
@xingyaoww
xingyaoww requested a review from all-hands-bot March 23, 2026 12:38

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Acceptable — Core architecture is solid and previous critical issues are resolved. Two issues need attention: excessive nesting complexity and query parameter token exposure.

Comment thread automation/execution.py Resolved
Comment thread automation/router.py Resolved
Comment thread automation/dispatcher.py Resolved
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>
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>
Comment thread automation/utils/api_key.py Resolved
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>
Comment thread scripts/test_tarball/main.py Resolved
openhands-agent and others added 2 commits March 23, 2026 14:34
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>
Comment thread automation/config.py Resolved
Comment thread automation/execution.py Resolved
openhands-agent and others added 11 commits March 25, 2026 02:16
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>
@xingyaoww

Copy link
Copy Markdown
Contributor Author

@openhands-ai

openhands-ai Bot commented Mar 25, 2026

Copy link
Copy Markdown

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>
@openhands-ai

openhands-ai Bot commented Mar 25, 2026

Copy link
Copy Markdown

Summary

I fixed both CI failures linked in the PR #4 comment:

Changes Made (commit abeb139)

All three issues stem from PR #11 merging into main and renaming the Automation model field triggers → trigger, which the dispatch-phase1b branch hadn't caught up with.

  1. automation/dispatcher.py:162 — automation.triggers → automation.trigger (fixed pyright error + runtime bug)
  2. tests/test_dispatcher.py — triggers= → trigger= in both TestEffectiveTimeout test cases (fixed 2 unit test failures)
  3. scripts/test_tarball/main.py — Wrapped a long print() line across multiple lines (fixed ruff format violation)

Checklist

  • Fixed unit test failures (run 23550194152) — TestEffectiveTimeout tests now use correct trigger= kwarg
  • Fixed pre-commit failures (run 23550194255) — pyright type error resolved + ruff format clean
  • Changes are minimal — only the 3 affected files, no extraneous modifications
  • Committed and pushed to dispatch-phase1b branch to update PR feat: Phase 1b — real sandbox dispatch with per-user API keys #4

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Comment thread AGENTS.md Resolved

@malhotra5 malhotra5 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

- 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants