Skip to content

Transient sandbox-API errors before the entrypoint starts fail the run without a retry #796

Todo

Description

@neubig

This issue was created by an AI agent (OpenHands) on behalf of @neubig.

Summary

In cloud mode, if the sandbox API returns a 5xx, or the connection fails, while the dispatcher creates or polls a run's sandbox, the run is marked FAILED at once. The run never retries. The status_detail the dispatcher writes says transient: true, but the run is still terminal. No automation code has run at this point, so a retry is safe. The dispatcher already retries one error type in this phase (SandboxProvisioningError). It does not retry these other transient errors.

Impact

  • A short outage of the sandbox API costs every run that is dispatched during it. The run shows FAILED with the error Failed to get execution context and has no conversation.
  • An event-triggered run loses its event. Webhook providers do not redeliver an event that was accepted, and no API can rerun a terminal run with its original payload.
  • A cron run misses its whole interval.
  • The failure counts toward the unhealthy-automation check (maybe_disable_unhealthy_automation_after_run in _fail), so repeated outages can pause a healthy automation.
  • The same happens when the per-user API-key mint fails with a network error or a 5xx. The dispatcher classifies that error as transient too, but it still fails the run.

Root cause

  1. CloudSandboxBackend retries only HTTP 429 when it creates or polls a sandbox (cloud.py#L242-L251):

    self._retry = retry(
        retry=retry_if_exception(_is_rate_limit_error),   # 429 only
        ...

    A 5xx from POST /api/v1/sandboxes raises httpx.HTTPStatusError from resp.raise_for_status() (cloud.py#L697). A transport failure raises httpx.TransportError. A 5xx while polling (GET /api/v1/sandboxes?id=, cloud.py#L714) makes _create_and_wait delete the new sandbox and raise again (cloud.py#L600-L604).

  2. _acquire_execution_context retries only SandboxProvisioningError (dispatcher.py#L741-L771):

    try:
        ctx = await backend.get_execution_context(client)
        break
    except SandboxProvisioningError as exc:
        ...  # retry with backoff

    All other exceptions go straight to the caller.

  3. In _execute_run, the catch-all handler marks the run terminal FAILED (dispatcher.py#L1240-L1251):

    except Exception as exc:
        logger.exception("Failed to get execution context", extra=_log_ctx())
        source = "agent_server" if backend.is_local_mode else "sandbox_api"
        await _fail(
            "Failed to get execution context",
            status_detail=run_status_detail_from_exception(exc, ...),
        )
        return

    run_status_detail_from_exception uses classify_httpx_transient_error (transient.py#L46-L89). That function labels 5xx, 408, timeouts and transport errors as transient. So the service knows the error is transient, but it uses that only as a label on a terminal row.

    The APIKeyError handler (dispatcher.py#L1225-L1239) does the same with _api_key_error_status_detail: a 5xx, 408, 429 or network error is labeled transient=True and then failed. The existing test test_run_as_key_mint_network_error_is_transient asserts this FAILED result, and test_other_errors_are_not_retried (tests/test_dispatcher.py#L3550) asserts the no-retry rule.

Reproduction

This test runs the real _execute_run, _acquire_execution_context and CloudSandboxBackend against the repository's PostgreSQL test fixture. Only two external boundaries are stubbed:

  • The OpenHands sandbox API, with an httpx.MockTransport. The first create or poll call fails once, and later calls succeed.
  • The service-key API-key mint, which is a separate HTTP call to the OpenHands server.

Save the file as tests/test_rca_dispatch_transient.py, then run:

uv sync --frozen
uv run python -m pytest tests/test_rca_dispatch_transient.py -s -q
tests/test_rca_dispatch_transient.py
"""Repro: a transient sandbox-API error before the entrypoint starts fails the run.

Real code: dispatcher._execute_run, _acquire_execution_context and
CloudSandboxBackend. Stubbed boundaries: the OpenHands sandbox API (an
httpx.MockTransport) and the service-key API-key mint.
"""

import uuid
from datetime import timedelta
from unittest.mock import patch

import httpx
import pytest
from sqlalchemy import select
from sqlalchemy.orm import selectinload

from openhands.automation.backends import CloudSandboxBackend
from openhands.automation.config import get_config
from openhands.automation.dispatcher import _execute_run
from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus
from openhands.automation.utils import utcnow


USER_ID = uuid.uuid4()
ORG_ID = uuid.uuid4()


@pytest.fixture(autouse=True)
def _fast_retries(monkeypatch):
    cfg = get_config().sandbox
    monkeypatch.setattr(cfg, "sandbox_provision_retry_delay", 0)
    monkeypatch.setattr(cfg, "sandbox_provision_max_attempts", 3)
    monkeypatch.setattr(cfg, "sandbox_poll_interval", 0)


async def _running_run(factory) -> uuid.UUID:
    async with factory() as session:
        automation = Automation(
            user_id=USER_ID,
            org_id=ORG_ID,
            name="nightly",
            trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"},
            tarball_path="https://example.com/code.tar.gz",
            entrypoint="python3 main.py",
            enabled=True,
        )
        session.add(automation)
        await session.commit()
        run = AutomationRun(
            automation_id=automation.id,
            status=AutomationRunStatus.RUNNING,
            started_at=utcnow(),
            timeout_at=utcnow() + timedelta(seconds=600),
        )
        session.add(run)
        await session.commit()
        return run.id


async def _load(factory, run_id) -> AutomationRun:
    async with factory() as session:
        return (
            await session.execute(
                select(AutomationRun)
                .options(selectinload(AutomationRun.automation))
                .where(AutomationRun.id == run_id)
            )
        ).scalar_one()


RUNNING_SANDBOX = [
    {
        "id": "sb-ok",
        "status": "RUNNING",
        "session_api_key": "sess",
        "exposed_urls": [{"name": "AGENT_SERVER", "url": "http://agent.test"}],
    }
]


@pytest.mark.parametrize("fault", ["create_503", "create_connect_error", "poll_502"])
async def test_transient_sandbox_api_error_is_retried(
    fault, async_session_factory, mock_settings, monkeypatch
):
    calls: list[str] = []

    def handler(request: httpx.Request) -> httpx.Response:
        calls.append(f"{request.method} {request.url.path}")
        path = request.url.path
        if request.method == "POST" and path == "/api/v1/sandboxes":
            n = sum(c == "POST /api/v1/sandboxes" for c in calls)
            if n == 1 and fault == "create_503":
                return httpx.Response(503, text="upstream unavailable")
            if n == 1 and fault == "create_connect_error":
                raise httpx.ConnectError("connection reset", request=request)
            return httpx.Response(200, json={"id": "sb-ok"})
        if request.method == "GET" and path == "/api/v1/sandboxes":
            n = sum(c == "GET /api/v1/sandboxes" for c in calls)
            if n == 1 and fault == "poll_502":
                return httpx.Response(502, text="bad gateway")
            return httpx.Response(200, json=RUNNING_SANDBOX)
        if request.method == "DELETE":
            return httpx.Response(200, json={})
        # Anything past provisioning (agent server) is out of scope here.
        return httpx.Response(404)

    async def fake_mint(_run):
        return "sk-user"

    monkeypatch.setattr(
        "openhands.automation.backends.cloud.get_api_key_for_automation_run",
        fake_mint,
    )

    run_id = await _running_run(async_session_factory)
    run = await _load(async_session_factory, run_id)
    backend = CloudSandboxBackend(api_url="https://api.test", run=run)

    async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
        with patch("openhands.automation.dispatcher.get_backend", return_value=backend):
            await _execute_run(run, mock_settings, async_session_factory, client)

    updated = await _load(async_session_factory, run_id)
    print(f"\n[{fault}] sandbox API calls: {calls}")
    print(f"[{fault}] status={updated.status.value} error={updated.error_detail!r}")
    print(f"[{fault}] status_detail={updated.status_detail}")

    creates = calls.count("POST /api/v1/sandboxes")
    assert creates >= 2, (
        f"transient {fault} was not retried: {creates} sandbox create(s), "
        f"run is {updated.status.value}"
    )

Observed output on main at 19c4ea687d5ab89c6fea5357d11cd1644b7391bd (trimmed):

[create_503] sandbox API calls: ['POST /api/v1/sandboxes']
[create_503] status=FAILED error='Failed to get execution context'
[create_503] status_detail={'phase': 'dispatch', 'kind': 'server_error', 'detail': 'sandbox_api get_execution_context returned HTTP 503', 'transient': True, ... 'status_code': 503}
[create_connect_error] sandbox API calls: ['POST /api/v1/sandboxes']
[create_connect_error] status=FAILED error='Failed to get execution context'
[create_connect_error] status_detail={'phase': 'dispatch', 'kind': 'transport', 'detail': 'sandbox_api get_execution_context transport error: connection reset', 'transient': True, ...}
[poll_502] sandbox API calls: ['POST /api/v1/sandboxes', 'GET /api/v1/sandboxes', 'DELETE /api/v1/sandboxes/sb-ok']
[poll_502] status=FAILED error='Failed to get execution context'
[poll_502] status_detail={'phase': 'dispatch', 'kind': 'server_error', 'detail': 'sandbox_api get_execution_context returned HTTP 502', 'transient': True, ... 'status_code': 502}
E   AssertionError: transient create_503 was not retried: 1 sandbox create(s), run is FAILED
E   AssertionError: transient create_connect_error was not retried: 1 sandbox create(s), run is FAILED
E   AssertionError: transient poll_502 was not retried: 1 sandbox create(s), run is FAILED
3 failed

In all three cases, one transient failure is enough to make the run terminal. The next sandbox API call would have succeeded.

Expected behavior

A failure that the service itself classifies as transient, and that happens before the entrypoint starts, should not end the run on the first attempt. The run should either get a new sandbox within its provisioning budget, or go back to the queue with backoff. Only after the retry budget is used up should it be marked FAILED. That final FAILED should still carry transient: true.

Suggested fix

Smallest change: in _acquire_execution_context, apply the existing retry loop to more errors than SandboxProvisioningError. Also retry:

  • an exception for which classify_httpx_transient_error(exc, source="sandbox_api", operation="get_execution_context") returns a result (5xx, 408, timeout, transport), and
  • an APIKeyError that _api_key_error_status_detail would label transient=True.

Keep the current guards. Before each retry, call update_run_timeout_at guarded on RUNNING, and stop if the run was cancelled or reaped. Keep sandbox_provision_max_attempts as the bound. Keep the FAILED path for the last attempt.

Other option: send these errors to _defer_or_skip_blocked_run (with a new kind or the classified kind). The run then goes back to PENDING with bounded backoff, the same way a concurrency-limit block does. This helps more during a longer outage.

Caveat: a 5xx or a dropped connection on POST /api/v1/sandboxes can come after the server has already created the sandbox. A retry can then leave one orphan sandbox until the runtime TTL removes it. That costs less than losing the run, but the retry for the create call should have a low attempt count. If the API supports an idempotency key, the retry should send one.

Acceptance criteria

  • One 5xx, one transport error, or one timeout from POST /api/v1/sandboxes or GET /api/v1/sandboxes before the entrypoint starts does not mark the run FAILED. The run gets a sandbox on a later attempt and starts its entrypoint once (the test above passes).
  • A transient API-key mint failure (network error, 5xx, 408, 429) gets the same retry.
  • After the retry budget is used up, the run is FAILED with phase=dispatch, transient=true and an attempt count.
  • A non-transient error (4xx other than 408 and 429, or RuntimeError) still fails at once. Concurrency-limit, daily-limit and license-limit handling does not change.
  • A run that is cancelled or reaped during a retry is not resurrected, and any sandbox it got is released.

OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

Verified against main at 19c4ea687d5ab89c6fea5357d11cd1644b7391bd (current HEAD): CloudSandboxBackend._retry only retries HTTP 429 (openhands/automation/backends/cloud.py), _acquire_execution_context retries only SandboxProvisioningError (openhands/automation/dispatcher.py), and the APIKeyError and catch-all handlers in _execute_run _fail the run even when classify_httpx_transient_error / _api_key_error_status_detail label the error transient=True. Existing tests test_run_as_key_mint_network_error_is_transient and test_other_errors_are_not_retried pin the no-retry behavior, and the issue's repro runs the real _execute_run and CloudSandboxBackend against the PostgreSQL test fixture with only the two external HTTP boundaries stubbed, so the failure is reproduced in the actual dispatch path.

Scope: extend the existing _acquire_execution_context retry loop to the errors the service already classifies as transient (5xx, 408, 429, timeouts, transport errors from the sandbox API, and a transient APIKeyError), keeping the current guarded update_run_timeout_at pre-retry check, sandbox_provision_max_attempts as the bound, and the final FAILED with transient: true. Non-goals: no change to the retry semantics inside CloudSandboxBackend itself, to the concurrency/daily/license-limit defer-or-skip handling, to PermanentDispatchError / non-transient 4xx handling, to the local-mode path, or to the run-deferral queue (_defer_or_skip_blocked_run); no idempotency-key or dedupe change for sandbox create retries (the sandbox API contract lives in OpenHands/software-agent-sdk, cross-repo), accepting that a create retry may orphan one sandbox until its runtime TTL reclaims it — the bounded-attempt and deferred-runs-past-age guards stay.

Acceptance Criteria

  • Given a run in RUNNING, one HTTP 5xx, one HTTP 408, one timeout, or one transport error from POST /api/v1/sandboxes or GET /api/v1/sandboxes before the entrypoint starts does not mark the run FAILED: the dispatcher calls the same sandbox API operation again within the existing provisioning budget, the run gets a sandbox, and the run proceeds exactly once to execution (the repro in this issue then passes, creating the sandbox on attempt 2+).
  • A transient per-run API-key mint failure (network error, 5xx, 408 or 429) during _acquire_execution_context is retried the same way, and the run is not FAILED on the first mint attempt.
  • When sandbox_provision_max_attempts is exhausted, the run is FAILED with error_detail Failed to get execution context and a status_detail whose phase is dispatch and whose transient is true.
  • A non-transient failure (any 4xx other than 408/429 from the sandbox API, or a RuntimeError) still marks the run FAILED on the first attempt with no retry call, and test_other_errors_are_not_retried passes unchanged.
  • Concurrency-limit (ConcurrencyLimitReachedError), daily-limit (DailySandboxLimitReachedError) and license-limit (LicenseLimitReachedError) runs keep their current defer/skip outcomes and statuses.
  • A run that is cancelled or reaped while provisioning is not retried or resurrected: _acquire_execution_context returns without launching, any sandbox it obtained is released, and the run keeps its terminal status.
  • The repro test from this issue (tests/test_rca_dispatch_transient.py) passes under uv run python -m pytest tests/test_rca_dispatch_transient.py -s -q with the PostgreSQL fixture, and the existing dispatcher suite passes unchanged except for the tests that pinned the no-retry behavior for transient errors.

Activity

  1. added
    bug
    on Nov 24, 2026
  2. added
    priority:medium
    ready-for-dev
    on Nov 24, 2026
  3. self-assigned this
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugpriority:mediumready-for-dev

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions