Skip to content

Watchdog marks a run FAILED when the API-key mint for verification fails once #797

Todo

Description

@neubig

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

Summary

When a cloud run misses its completion callback, the watchdog checks the run's sandbox to learn the real outcome. To do that, it first mints a new per-user API key. If that one HTTP call fails (a network error or a 5xx from the key endpoint), _verify_and_mark_run marks the run FAILED at once with Timed out: verification failed: .... A run that finished with exit code 0 is then recorded as failed. The watchdog does not try again on its next tick.

Not every verification error does this. Since an earlier fix, transient errors from the sandbox lookup and from the agent server come back as VerificationOutcome.TRANSIENT_ERROR, and those leave the run RUNNING for the next tick. The gap is the exceptions that backend.verify_run() raises. In practice that is APIKeyError from the key mint, which happens before the sandbox lookup.

Impact

  • A run that completed (or is still running) is shown as FAILED, with the error Timed out: verification failed: Request failed: ... and no conversation link. Its real result is never read.
  • Each watchdog verification of a cloud run mints a key. So one short outage of the key endpoint fails every stale run that the watchdog checks during that outage.
  • The FAILED row counts toward the unhealthy-automation check: mark_stale_runs calls maybe_disable_unhealthy_automation_after_run after a terminal result.
  • The status detail does not mark the error as transient (kind: unknown, transient: false), so operators cannot tell it apart from a real failure.

Root cause

  1. The watchdog builds a new backend for each stale run and calls verify_run (watchdog.py#L243-L249). CloudSandboxBackend.verify_run calls self._ensure_api_key() before it reaches the sandbox (cloud.py#L554-L563). That call mints a new key through get_api_key_for_automation_run (cloud.py#L264-L271). On a network error or an HTTP error, the mint raises APIKeyError (api_key.py#L87-L107).

  2. APIKeyError is not caught inside verify_run_status. Only sandbox-lookup and agent-server errors are turned into TRANSIENT_ERROR. So the exception reaches the catch-all in _verify_and_mark_run, which marks the run terminal FAILED (watchdog.py#L246-L290):

    try:
        verification = await backend.verify_run(run_id)
    except Exception as e:
        error_detail = f"Timed out: verification failed: {e}"
        stmt = (
            update(AutomationRun)
            .where(AutomationRun.id == run.id,
                   AutomationRun.status == AutomationRunStatus.RUNNING)
            .values(status=AutomationRunStatus.FAILED, ...,
                    status_detail=run_status_detail_from_exception(e, ...)),
        )
  3. run_status_detail_from_exception sees only httpx errors as transient (run_status_detail.py#L188-L220). An APIKeyError wrapping an httpx.ConnectError is therefore recorded as kind: unknown, transient: false.

The transient-outcome branch already exists and does the right thing for other errors (watchdog.py#L439-L468): it leaves the run RUNNING and records a transient status_detail. The exception path just never uses it.

Reproduction

This test runs the real mark_stale_runs, _verify_and_mark_run, CloudSandboxBackend, get_api_key_for_automation_run and verify_run_status against the repository's PostgreSQL test fixture. The only stub is outbound HTTP. An httpx.MockTransport is injected into httpx.AsyncClient. It serves the key-mint endpoint, the sandbox API and the agent server's bash-events endpoint. The first key mint raises httpx.ConnectError, and later mints succeed. The agent server reports that the run's command exited with code 0.

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

uv sync --frozen
uv run python -m pytest tests/test_rca_watchdog_verify.py -s -q
tests/test_rca_watchdog_verify.py
"""Repro: one failed API-key mint during watchdog verification fails the run.

Real code: watchdog.mark_stale_runs, _verify_and_mark_run, CloudSandboxBackend,
get_api_key_for_automation_run, verify_run_status. Stubbed boundary: every
outbound HTTP request (OpenHands key-mint API, sandbox API, agent server),
through an httpx.MockTransport injected into httpx.AsyncClient.
"""

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

import httpx

from openhands.automation.backends import CloudSandboxBackend
from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus
from openhands.automation.utils import utcnow
from openhands.automation.watchdog import mark_stale_runs


async def test_one_failed_key_mint_does_not_fail_a_finished_run(
    async_session_factory, mock_settings, monkeypatch
):
    calls: list[str] = []
    mint_attempts = 0

    def handler(request: httpx.Request) -> httpx.Response:
        nonlocal mint_attempts
        calls.append(f"{request.method} {request.url.host}{request.url.path}")
        if request.url.path.endswith("/api-keys"):
            mint_attempts += 1
            if mint_attempts == 1:
                raise httpx.ConnectError("connection reset by peer", request=request)
            return httpx.Response(200, json={"key": "sk-user"})
        if request.url.path == "/api/v1/sandboxes" and request.method == "GET":
            return httpx.Response(
                200,
                json=[
                    {
                        "id": "sb-1",
                        "status": "RUNNING",
                        "session_api_key": "sess",
                        "exposed_urls": [
                            {"name": "AGENT_SERVER", "url": "http://agent.test"}
                        ],
                    }
                ],
            )
        if request.url.host == "agent.test":
            # The run's entrypoint finished with exit code 0; only its
            # completion callback was lost.
            return httpx.Response(
                200, json={"items": [{"exit_code": 0, "stdout": "ok", "stderr": ""}]}
            )
        return httpx.Response(200, json={})

    transport = httpx.MockTransport(handler)
    real_client = httpx.AsyncClient

    class StubbedClient(real_client):
        def __init__(self, *args, **kwargs):
            kwargs["transport"] = transport
            super().__init__(*args, **kwargs)

    monkeypatch.setattr(httpx, "AsyncClient", StubbedClient)

    async with async_session_factory() as session:
        automation = Automation(
            user_id=uuid.uuid4(),
            org_id=uuid.uuid4(),
            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() - timedelta(minutes=10),
            timeout_at=utcnow() - timedelta(seconds=5),
            sandbox_id="sb-1",
            bash_command_id="cmd1",
        )
        session.add(run)
        await session.commit()
        run_id = run.id

    def backend_for(run):
        return CloudSandboxBackend(api_url="https://api.test", run=run)

    async def state():
        async with async_session_factory() as session:
            r = await session.get(AutomationRun, run_id)
            return r.status, r.error_detail, r.status_detail

    with patch("openhands.automation.watchdog.get_backend", side_effect=backend_for):
        await mark_stale_runs(async_session_factory, mock_settings)
        after_first = await state()
        print(f"\nafter tick 1: status={after_first[0].value} error={after_first[1]!r}")
        print(f"after tick 1: status_detail={after_first[2]}")
        await mark_stale_runs(async_session_factory, mock_settings)
        after_second = await state()
        print(f"after tick 2: status={after_second[0].value} error={after_second[1]!r}")
    print(f"HTTP calls: {calls}")

    assert after_first[0] == AutomationRunStatus.RUNNING, (
        "a single transient key-mint failure made the run terminal"
    )
    assert after_second[0] == AutomationRunStatus.COMPLETED

Observed output on main at 19c4ea687d5ab89c6fea5357d11cd1644b7391bd (trimmed):

after tick 1: status=FAILED error='Timed out: verification failed: Request failed: connection reset by peer'
after tick 1: status_detail={'phase': 'verification', 'kind': 'unknown', 'detail': 'Request failed: connection reset by peer', 'transient': False, ... 'source': 'automation_service', 'operation': 'verify_run', 'code': 'APIKeyError'}
after tick 2: status=FAILED error='Timed out: verification failed: Request failed: connection reset by peer'
HTTP calls: ['POST <api>/api/service/users/<user>/orgs/<org>/api-keys']
E   AssertionError: a single transient key-mint failure made the run terminal
1 failed

Control: I changed the stub so that the first mint also succeeds. The same run then becomes COMPLETED on tick 1, after the calls POST .../api-keys, GET /api/v1/sandboxes, GET /api/bash/bash_events/search and DELETE /api/v1/sandboxes/sb-1. So the only thing that changed the outcome from COMPLETED to FAILED is one failed key mint.

Expected behavior

If verification cannot run because of a transient error, the run should stay RUNNING with a transient status_detail, the same as for a transient sandbox-lookup error. The next watchdog tick should verify it again. The run becomes terminal only when verification gives a real answer, or when a bounded retry budget is used up.

Suggested fix

Smallest change: in _verify_and_mark_run, classify the exception before the FAILED write. If it is transient, take the existing TRANSIENT_ERROR branch: leave the run RUNNING and record status_detail with transient: true. Transient means one of these:

  • an httpx 5xx, 408 or 429 error, a timeout or a transport error (classify_httpx_transient_error), or
  • an APIKeyError whose status_code is None with an httpx.RequestError cause, or whose status_code is 5xx, 408 or 429. This is the same rule that _api_key_error_status_detail in dispatcher.py already uses.

Another option is to do this in CloudSandboxBackend.verify_run: catch a transient APIKeyError and return VerificationResult(outcome=TRANSIENT_ERROR, ...).

To keep a run from staying RUNNING forever during a long outage, bound the retry. Reuse the existing hard deadline (sandbox_ready_timeout + effective timeout + run_timeout_hard_grace, see _defer_still_running), or a count kept in status_detail. After that, fail with transient: true.

A 403 or 404 from the mint, or an auth error that still fails after the refresh, can stay terminal.

Acceptance criteria

  • One network error or 5xx from the key mint during watchdog verification leaves the run RUNNING, with a transient status_detail in phase verification (the test above passes).
  • On a later tick where the mint succeeds, the run gets its real outcome (COMPLETED for exit code 0, FAILED with the exit code otherwise).
  • Repeated transient failures end in FAILED with transient: true once a bounded deadline passes. The run does not stay RUNNING forever.
  • A non-transient mint failure (403/404) and the existing ENVIRONMENT_UNAVAILABLE and VERIFICATION_ERROR paths behave as before.

OpenHands AI triage

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

Triage

Verified on main: the catch-all in _verify_and_mark_run (openhands/automation/watchdog.py) turns any exception from backend.verify_run into a terminal FAILED write, and CloudSandboxBackend.verify_run reaches the sandbox only after minting a per-run key via get_api_key_for_automation_run, which raises APIKeyError on a transport error or a retryable HTTP status. run_status_detail_from_exception classifies only httpx errors, so an APIKeyError is recorded as kind: unknown, transient: false, and a run that actually finished is marked FAILED with no conversation link and no retry on the next tick. The existing TRANSIENT_ERROR branch already leaves runs RUNNING correctly for sandbox-lookup and agent-server transient outcomes; the key-mint exception path never reaches it.

Scope: classify a transient key-mint APIKeyError with the same transient-vs-terminal rule the dispatcher already applies to run-as key-mint failures (_api_key_error_status_detail in dispatcher.py: transport errors, timeouts, and 5xx/408/429 are transient; 403/404 and 401 are not), route it to the existing TRANSIENT_ERROR branch so the run stays RUNNING with a transient status_detail and is re-verified on the next tick, and bound the retries so a sustained outage still terminalizes the run. The fix may live in the watchdog's exception path or in CloudSandboxBackend.verify_run; reviewers judge only the observable behavior below.

Non-goals: no change to the dispatcher's dispatch-path key-mint handling; no key-mint caching or reduced mint frequency (a run is still re-verified each tick during an outage); no new status-detail schema, migration, or local-mode verification change; and no change to the STILL_RUNNING hard-deadline behavior beyond what the bounded retry budget needs.

Acceptance Criteria

  • A single transient key-mint failure during watchdog verification — a transport error, timeout, or 5xx/408/429 response — leaves the run RUNNING and persists a status_detail with phase: verification and transient: true; no terminal FAILED write, no cleanup_after_verification call, and no unhealthy-automation event for that tick.
  • On a later watchdog tick where the mint succeeds, verification completes and the run records its real outcome: COMPLETED when the command exited 0, or FAILED with the exit code/stderr otherwise.
  • When the mint fails transiently on every tick, the run becomes terminal FAILED with a transient: true status detail once a bounded retry budget passes (reusing the existing still-running hard deadline or an equivalently bounded mechanism), and it never stays RUNNING indefinitely.
  • When the run is terminalized after the bounded budget, the existing watchdog post-terminal behavior applies unchanged (sandbox/workspace cleanup, including the configurable cleanup delay and keep-alive handling).
  • Non-transient mint failures (403/404, and 401 per the existing classification) stay terminal as today, and the existing ENVIRONMENT_UNAVAILABLE, VERIFICATION_ERROR, and STILL_RUNNING watchdog paths are unchanged — current tests/test_watchdog.py cases keep passing.
  • The issue's reproduction scenario (first key mint fails with a connection error, later mints succeed, exit code 0) passes as an automated test in the repository suite.

Activity

  1. added
    bug
    on Nov 24, 2026
  2. added
    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:lowready-for-dev

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions