Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
40f9370
feat: phase 1b dispatch — real sandbox execution with per-user API keys
openhands-agent Mar 20, 2026
35b812f
fix: remove integration tests, fix pre-commit (pyright, ruff)
openhands-agent Mar 20, 2026
afd32c2
rewrite test_automation.py to simulate dispatcher lifecycle
openhands-agent Mar 20, 2026
1a220ba
rewrite test_automation.py as single streaming lifecycle test
openhands-agent Mar 20, 2026
3d9be66
fix output markers + add .pr/test_automation.log
openhands-agent Mar 20, 2026
49d1629
add .pr/test_automation.log (force-add past .gitignore)
openhands-agent Mar 20, 2026
b15b229
extract tarball contents to scripts/test_tarball/
openhands-agent Mar 20, 2026
236f983
test_tarball: realistic SDK automation script (ADR pattern)
openhands-agent Mar 20, 2026
6f0e3a8
Merge remote-tracking branch 'origin/main' into dispatch-phase1b
openhands-agent Mar 23, 2026
38fb133
feat: Phase 1b dispatch — timeout_at, conversation_id, watchdog, oh-i…
openhands-agent Mar 23, 2026
3aa993f
fix: add --no-cache-dir to setup.sh to avoid stale SDK installs
openhands-agent Mar 23, 2026
2540046
fix: address PR review — callback auth, race conditions, cleanup
openhands-agent Mar 23, 2026
505b92b
feat: pass SANDBOX_ID/SESSION_API_KEY env vars for SDK saas_runtime_mode
openhands-agent Mar 23, 2026
f01493b
docs: add AGENTS.md with repo knowledge
openhands-agent Mar 23, 2026
b490435
Simplify dispatch: on-demand API key fetch, standard callback auth
openhands-agent Mar 23, 2026
282c0a5
fix: use "key" field name matching OpenHands API response
openhands-agent Mar 23, 2026
c75f3dc
Squash migrations: merge 003+004, drop callback_token entirely
openhands-agent Mar 23, 2026
a97d65c
test: add conversation creation to sandbox test script
openhands-agent Mar 23, 2026
36acab2
Delete tests/integration/test_automation_e2e.py
xingyaoww Mar 23, 2026
afbdc0a
Add test_automation.py run log against staging
openhands-agent Mar 23, 2026
ec80299
refactor: rename callback_base_url to base_url across the repo
openhands-agent Mar 23, 2026
f2c3c8f
Add exc_info=True to logger.error calls for stack trace logging
openhands-agent Mar 23, 2026
1af3e83
refactor: remove DispatchConfig, use Settings directly
openhands-agent Mar 23, 2026
7886473
Update test log: workspace+llm+secrets pass, conversation 401
openhands-agent Mar 23, 2026
e7df60a
fix: ruff format and lint issues in scripts
openhands-agent Mar 23, 2026
b83b33d
Update test log: full E2E pass including Conversation
openhands-agent Mar 23, 2026
3bd1e90
Update test log: full E2E pass (SDK lint fix @ 13a4aa65)
openhands-agent Mar 23, 2026
5f9ddcb
refactor: extract _find_agent_server_url to reduce nesting in _create…
openhands-agent Mar 23, 2026
28c4e06
feat: download external tarballs directly inside sandbox
openhands-agent Mar 24, 2026
b30a602
fix: show last 1000 chars of stderr in error detail
openhands-agent Mar 24, 2026
c338b97
feat: log full stdout/stderr on run failure
openhands-agent Mar 24, 2026
1873e84
fix: propagate setup.sh failures and include stdout in error
openhands-agent Mar 24, 2026
8a94d46
feat: add run_id and automation_id to all structured logs
openhands-agent Mar 24, 2026
9813217
fix: mark run as COMPLETED when entrypoint succeeds
openhands-agent Mar 24, 2026
b159e9d
fix: add rate limit retry for sandbox API calls
openhands-agent Mar 24, 2026
a699f75
refactor(dispatcher): make settings non-optional in dispatch functions
openhands-agent Mar 25, 2026
2f45269
feat: fire-and-forget dispatch with sandbox verification
openhands-agent Mar 25, 2026
5df2be8
fix: include error_code and error_message in sandbox failure logs
openhands-agent Mar 25, 2026
673b220
fix: delete sandbox on dispatch failure
openhands-agent Mar 25, 2026
48fd69b
refactor: deduplicate delete_sandbox function
openhands-agent Mar 25, 2026
437b67e
Add timeout parameter to automation creation
openhands-agent Mar 25, 2026
f7e1c81
Fix lint: add missing blank line in constants.py
openhands-agent Mar 25, 2026
263f11d
Replace dataclasses with pydantic dataclasses
openhands-agent Mar 25, 2026
06ffe48
Move _mark_run_terminal to utils/run.py
openhands-agent Mar 25, 2026
d2c7697
refactor: align with SDK rename saas_runtime_mode -> local_agent_serv…
openhands-agent Mar 25, 2026
98b8e39
Merge branch 'main' into dispatch-phase1b
malhotra5 Mar 25, 2026
abeb139
fix: rename triggers→trigger to match model after #11 merge, fix ruff…
openhands-agent Mar 25, 2026
37d94b6
fix: rename remaining triggers→trigger in test_router.py
openhands-agent Mar 25, 2026
a2b9dd8
chore: remove empty tests/integration/ scaffolding
openhands-agent Mar 25, 2026
dc6a1a1
docs: update AGENTS.md to match actual codebase
openhands-agent Mar 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ yarn-error.log*

logs

# PR artifacts / logs
.pr/*.log

# agent
.envrc
cache
Expand Down
554 changes: 554 additions & 0 deletions .pr/test_automation_run1.log

Large diffs are not rendered by default.

126 changes: 126 additions & 0 deletions AGENTS.md
Comment thread
xingyaoww marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Automations Service

Self-contained microservice that schedules and dispatches automation runs inside OpenHands Cloud sandboxes.

## Repository Structure

```
automation/
├── automation/ # Main application package
│ ├── app.py # FastAPI app, lifespan, background tasks
│ ├── auth.py # API key auth via OpenHands /api/keys/current
│ ├── config.py # Pydantic settings (Settings, env prefix AUTOMATION_)
│ ├── constants.py # Timeouts, polling intervals, sandbox constants
│ ├── db.py # Database engine and session factory (asyncpg / Cloud SQL)
│ ├── dispatcher.py # Polls PENDING runs, dispatches to sandbox (fire-and-forget)
│ ├── execution.py # Sandbox lifecycle: create → upload → execute → delete
│ ├── logger.py # JSON structured logging configuration
│ ├── models.py # SQLAlchemy models (Automation, AutomationRun, TarballUpload)
│ ├── router.py # API routes (CRUD, trigger, callback, runs list)
│ ├── scheduler.py # Cron scheduler — polls automations, creates PENDING runs
│ ├── schemas.py # Pydantic request/response schemas
│ ├── uploads.py # Tarball upload router
│ ├── watchdog.py # Staleness watchdog — marks hung runs as FAILED
│ ├── storage/ # File storage abstraction
│ │ ├── file_store.py # Abstract base class for file storage
│ │ └── google_cloud.py # GCS implementation
│ └── utils/ # Utility modules
│ ├── api_key.py # Per-user API key minting via service key
│ ├── cron.py # Cron schedule utilities (next/prev fire time)
│ ├── run.py # Run status transitions (create, mark, update)
│ ├── sandbox.py # Sandbox verification and cleanup
│ ├── tarball_validation.py # Tarball path validation (internal/external)
│ └── time.py # UTC time helpers
├── containers/
│ └── Dockerfile # Container image definition
├── migrations/ # Alembic migrations
├── scripts/
│ ├── test_automation.py # E2E test (sandbox lifecycle with live streaming)
│ └── test_tarball/ # Tarball contents uploaded to sandbox during test
│ ├── main.py # Test script run inside sandbox (SDK workspace test)
│ └── setup.sh # Installs SDK inside sandbox
├── tests/ # Unit tests (flat structure, no external deps)
│ ├── integration/ # Integration tests (require OPENHANDS_API_KEY)
│ ├── test_auth.py
│ ├── test_dispatcher.py
│ ├── test_execution.py
│ ├── test_router.py
│ ├── test_scheduler.py
│ └── ...
└── pyproject.toml
```

## Cross-Repo Coordination

Three repos work together:

| Repo | Branch | Purpose |
|------|--------|---------|
| `OpenHands/automation` | `dispatch-phase1b` | Automation service (this repo) |
| `OpenHands/deploy` (aka `All-Hands-AI/deploy`) | `dispatch-phase1b` | Deploys automation as a sidecar |
| `OpenHands/software-agent-sdk` | `feat/saas-runtime-mode` | SDK changes for in-sandbox execution |

**AUTOMATION_SHA linking**: The deploy repo references a specific automation commit in two workflow files:
- `.github/workflows/deploy.yaml` → `AUTOMATION_SHA: "<full-sha>"`
- `.github/workflows/deploy-automation.yaml` → `AUTOMATION_SHA: "<full-sha>"`

After pushing to the automation repo, update both files in the deploy repo.

## Build & Test Commands

```bash
# Pre-commit (run from repo root)
pre-commit run --files automation/**/*.py scripts/**/*.py tests/**/*.py --show-diff-on-failure

# Unit tests (no external deps, skips Docker-dependent tests)
uv run pytest tests/ -v --ignore=tests/integration

# Integration test (requires OPENHANDS_API_KEY)
OPENHANDS_API_KEY=sk-oh-... uv run pytest tests/integration/ -v

# E2E test script (live sandbox, ~80s)
OPENHANDS_API_KEY=sk-oh-... uv run python scripts/test_automation.py --api-url https://staging.all-hands.dev
```

## Dispatch Pipeline

The dispatcher uses a **fire-and-forget** model. For each PENDING run:

1. **Fetch per-user API key** — `get_api_key_for_automation_run()` mints a key via the service key
2. **Resolve tarball** — Internal (`oh-internal://`) downloads from GCS; external (HTTP) URLs are downloaded inside the sandbox
3. **Create sandbox** — `POST /api/v1/sandboxes` (Cloud API, Bearer token auth)
4. **Wait for RUNNING** — Poll `GET /api/v1/sandboxes?id=<id>` until status=RUNNING
5. **Upload/download tarball** — `POST /api/file/upload/<path>` (agent-server) or `curl` inside sandbox
6. **Start entrypoint** — `POST /api/bash/start_bash_command` (agent-server)
- Extracts tarball, runs setup.sh (if present), exports env vars, runs entrypoint
7. **Return immediately** — Dispatcher does not wait for completion

Completion is handled asynchronously:
- **Happy path**: SDK inside sandbox POSTs to `POST /api/v1/automations/runs/{id}/complete`
- **Fallback**: Watchdog scans for runs past their `timeout_at` deadline, verifies status via sandbox bash history, and marks as COMPLETED or FAILED

### Env Vars Injected Into Sandbox

| Variable | Source | Purpose |
|----------|--------|---------|
| `OPENHANDS_API_KEY` | Per-user key issued via service key | SDK auth for get_llm()/get_secrets() |
| `OPENHANDS_CLOUD_API_URL` | Config (`openhands_api_base_url`) | Cloud API base URL |
| `SANDBOX_ID` | From sandbox creation response | SDK reads for settings API calls |
| `SESSION_API_KEY` | From sandbox creation response | SDK reads for settings API auth |
| `AUTOMATION_CALLBACK_URL` | Constructed by dispatcher | SDK posts completion status here |
| `AUTOMATION_RUN_ID` | Run ID | Included in callback payload |
| `AUTOMATION_EVENT_PAYLOAD` | Trigger context JSON | Available to user's script |

The SDK's `OpenHandsCloudWorkspace(local_agent_server_mode=True)` reads `SANDBOX_ID`, `SESSION_API_KEY`, and `AGENT_SERVER_PORT` from env vars automatically.

## Callback & Race Condition Handling

- **Callback auth**: The completion endpoint (`/runs/{id}/complete`) uses standard API key auth — the per-user `OPENHANDS_API_KEY` passed into the sandbox is validated via `authenticate_request`, and ownership is verified against the run's parent automation.
- **Optimistic locking**: Both callback endpoint and watchdog use `UPDATE ... WHERE status = 'RUNNING'` and check `CursorResult.rowcount` to handle races. Returns 409 on conflict.
- **Sandbox cleanup**: On callback, sandbox is deleted in a fire-and-forget background task (unless `keep_alive=True`). On dispatch failure, the dispatcher deletes the sandbox immediately.

## Database

- **Engine**: SQLAlchemy async with asyncpg; supports direct PostgreSQL (`AUTOMATION_DB_HOST`, `AUTOMATION_DB_PORT`, etc.) or GCP Cloud SQL connector (`AUTOMATION_GCP_DB_INSTANCE`)
- **Migrations**: Alembic in `migrations/` directory
- **Locking patterns**: `FOR UPDATE SKIP LOCKED` in scheduler/dispatcher polling, optimistic `UPDATE WHERE status=X` for callback/watchdog
23 changes: 21 additions & 2 deletions automation/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from automation.router import router
from automation.scheduler import scheduler_loop
from automation.uploads import router as uploads_router
from automation.watchdog import watchdog_loop


logger = logging.getLogger("automation.app")
Expand Down Expand Up @@ -61,26 +62,44 @@ async def lifespan(app: FastAPI):
logger.info("Background scheduler started")

# Dispatcher: picks up PENDING runs and dispatches them
if not settings.base_url:
logger.warning(
"AUTOMATION_BASE_URL not set — using localhost. "
"Sandboxes in the cloud won't be able to reach this URL."
)
dispatcher_task = asyncio.create_task(
dispatcher_loop(
app.state.session_factory,
settings=settings,
interval_seconds=settings.dispatcher_interval_seconds,
shutdown_event=shutdown_event,
)
)
app.state.dispatcher_task = dispatcher_task
logger.info("Background dispatcher started")

# Watchdog: marks stale RUNNING runs as FAILED
watchdog_task = asyncio.create_task(
watchdog_loop(
app.state.session_factory,
settings=settings,
shutdown_event=shutdown_event,
)
)
app.state.watchdog_task = watchdog_task
logger.info("Background watchdog started")

yield

# Shutdown
logger.info("Shutting down background tasks...")
shutdown_event.set()

# Wait for both tasks to exit gracefully
# Wait for all tasks to exit gracefully
for task_name, task in [
("scheduler", scheduler_task),
("dispatcher", dispatcher_task),
("watchdog", watchdog_task),
]:
try:
await asyncio.wait_for(task, timeout=5.0)
Expand Down Expand Up @@ -141,7 +160,7 @@ async def readiness():
await conn.execute(text("SELECT 1"))
return {"status": "ready"}
except Exception as e:
logger.error("Readiness check failed: %s", e)
logger.error("Readiness check failed: %s", e, exc_info=True)
return JSONResponse(
status_code=503,
content={"status": "not_ready", "error": "database unavailable"},
Expand Down
2 changes: 1 addition & 1 deletion automation/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@

import logging
import uuid
from dataclasses import dataclass

import httpx
from cachetools import TTLCache
from fastapi import Depends, HTTPException, Request, status
from pydantic.dataclasses import dataclass
from tenacity import (
RetryCallState,
before_sleep_log,
Expand Down
15 changes: 13 additions & 2 deletions automation/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ class Settings(BaseSettings):
# Dispatcher (polls automation_runs table for pending jobs)
dispatcher_interval_seconds: int = 10

# Admin API key for issuing per-user automation API keys via SaaS
admin_api_key: str = ""
# Service key for authenticating with the SaaS API to fetch per-user
# API keys (called by the dispatcher before each automation run).
service_key: str = ""

# Public URL for the automation service (used for sandbox callbacks).
# In production, this is the ingress URL (e.g., https://automation.all-hands.dev).
# If empty, falls back to http://localhost:{server_port} (dev only).
base_url: str = ""

# Service
host: str = "0.0.0.0"
Expand All @@ -46,6 +52,11 @@ class Settings(BaseSettings):

model_config = {"env_prefix": "AUTOMATION_"}

@property
def resolved_base_url(self) -> str:
"""Public base URL with localhost fallback for dev."""
return self.base_url or f"http://localhost:{self.server_port}"


# Hardcoded internal URL scheme for uploaded tarballs.
# This is not configurable - changing it would require a database migration
Expand Down
27 changes: 27 additions & 0 deletions automation/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Constants for the automation service."""

from datetime import timedelta


# Maximum allowed timeout for automation runs (10 minutes)
# Used for:
# - Validation in API requests (timeout field)
# - Default timeout passed to sandbox execution
# - Watchdog staleness detection
MAX_RUN_DURATION = timedelta(minutes=10)
MAX_RUN_DURATION_SECONDS = int(MAX_RUN_DURATION.total_seconds())

# Sandbox execution constants
SANDBOX_POLL_INTERVAL = 5 # seconds between status checks
SANDBOX_READY_TIMEOUT = 300 # max wait for sandbox to become ready
WORK_DIR = "/workspace/automation"
TARBALL_PATH = "/tmp/automation.tar.gz"

# Limits for external tarball downloads (in sandbox)
EXTERNAL_DOWNLOAD_TIMEOUT = 120 # seconds
EXTERNAL_MAX_FILESIZE = 100 * 1024 * 1024 # 100 MB

# Rate limit retry settings
RATE_LIMIT_MIN_WAIT = 10 # initial wait after a 429
RATE_LIMIT_MAX_WAIT = 60 # max wait between retries
RATE_LIMIT_MAX_RETRIES = 5
Loading
Loading