Skip to content

Automation completion callback is sent once with no retry; a transient 5xx leaves successful runs RUNNING until the watchdog #7099

Backlog

Description

@neubig

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

Summary

The automation completion callback that OpenHandsCloudWorkspace.__exit__ (and BaseWorkspace._send_completion_callback) sends is a single best-effort POST. It is not retried on a transport error or a 5xx/429, and a non-2xx response is not even treated as a failure. When that one POST is lost, a run that finished successfully stays RUNNING in the Automation Service until its watchdog deadline. The watchdog then marks it COMPLETED from the bash exit code, but without the conversation_id and cost the callback carried.

Impact

What a user sees when the single callback POST gets a transient 502/503/429 or a connection error:

  • The run shows Running for the rest of its timeout budget, even though the agent finished long ago. For a run with a long timeout this can be most of an hour.
  • When the watchdog finally closes it, the run is COMPLETED but has no conversation link and no cost. For prompt and plugin presets whose conversation was started by the app server, the conversation id is only in the sandbox env (AUTOMATION_CONVERSATION_ID); it is never written to the run at dispatch (dispatcher.py#L1578-L1580). So the run cannot be opened from the run list.
  • The finish-tool response (run_metadata.finish_tool_response) is not recorded, because only the callback route fetches it.
  • While it is stuck RUNNING it counts toward the service's concurrency cap (count_running_runs in dispatch_pending_runs).
  • The sandbox log only shows INFO Completion callback sent (COMPLETED): 502, which reads like success.

Root cause

All three stock runners in OpenHands/automation (prompt, plugin and plugin-spec presets) rely on the SDK to send the callback when the workspace context exits (prompt/sdk_main.py#L569-L577):

workspace_ctx = OpenHandsCloudWorkspace(local_agent_server_mode=True, ..., keep_alive=True)
with workspace_ctx as workspace:   # __exit__ sends the completion callback

The sender in the SDK makes one attempt and logs whatever comes back (openhands-workspace/.../cloud/workspace.py#L857-L902):

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
    self._send_completion_callback(exc_type, exc_val)
    self.cleanup()
...
        try:
            headers = {"Authorization": f"Bearer {self.cloud_api_key}"}
            with httpx.Client(timeout=10.0) as cb_client:
                resp = cb_client.post(callback_url, json=payload, headers=headers)
                logger.info(f"Completion callback sent ({status}): {resp.status_code}")
        except Exception as e:
            logger.warning(f"Completion callback failed: {e}")

The generic version in openhands-sdk has the same shape (openhands-sdk/.../workspace/base.py#L88-L156). RemoteWorkspace (local mode) and LocalWorkspace use it.

So:

  1. There is no retry on httpx.TransportError or on 5xx/429.
  2. resp.status_code is never checked. A 502 is logged at INFO as "sent".
  3. The process then exits. Nothing else in the sandbox reports the outcome.

The service returns transient errors on this route in normal operation. For example, authenticate_request maps an unreachable or non-200 /api/v1/users/me to 502, and an upstream rate limit to 429 (automation auth.py#L523-L556). Load-balancer 502/503 errors during deploys hit the route the same way.

On the service side, the only remaining path is the watchdog. After timeout_at it checks the bash command's exit code and, for exit code 0, writes only status, completed_at and status_detail (watchdog.py#L299-L318). It does not write conversation_id, cost or the finish-tool response.

Retrying is safe with the service as it is today. POST /runs/{id}/complete updates only WHERE status = 'RUNNING'. A replay after a committed callback (a lost acknowledgement) gets 409 Run is COMPLETED, expected RUNNING, and the route does not overwrite state or emit a second completion event (router.py#L1855-L1899). The second repro test below confirms this. The fix therefore does not need a server change: the client only has to treat 409 as final. Note that the route makes outbound calls before its UPDATE (auth, sandbox lookup, conversation event search with a 30 s timeout), so the 10 s client timeout can expire while the server still commits. A retry after a read timeout then gets 409, which is the correct result.

Reproduction

This test runs the real SDK OpenHandsCloudWorkspace exactly as the preset runner builds it, and the real Automation Service route and watchdog against PostgreSQL. Only two boundaries are stubbed:

  • A real local HTTP server stands in for the gateway in front of the service. It returns 502 to the first POST and 200 to any later POST.
  • backend.verify_run (the agent-server bash-history lookup) is stubbed to report exit code 0.

The SDK the service pins (openhands-sdk/openhands-workspace==1.63.1, installed into sandboxes through /sdk-version) has the same _send_completion_callback as main at af85e224 (diffed).

git clone https://github.com/OpenHands/automation && cd automation   # at 19c4ea687d5ab89c6fea5357d11cd1644b7391bd
uv sync --frozen
# save the file below as tests/test_repro_callback_no_retry.py (needs Docker for the Postgres fixture)
OPENHANDS_SUPPRESS_BANNER=1 uv run python -m pytest tests/test_repro_callback_no_retry.py -s -q -p no:cacheprovider
"""Repro: one transient 502 on the completion callback strands a successful run."""

import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import AsyncMock, MagicMock, patch

from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus
from openhands.automation.utils.agent_server import VerificationResult
from openhands.automation.watchdog import _verify_and_mark_run
from openhands.workspace import OpenHandsCloudWorkspace
from tests.test_router import TEST_ORG_ID, TEST_USER_ID


class FlakyGateway(BaseHTTPRequestHandler):
    """Stands in for the load balancer in front of the automation service."""

    received: list[dict] = []

    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        FlakyGateway.received.append(body)
        status = 502 if len(FlakyGateway.received) == 1 else 200
        self.send_response(status)
        self.end_headers()

    def log_message(self, *args):
        pass


async def test_transient_502_on_callback_is_not_retried(
    async_client, async_session, monkeypatch, mock_settings
):
    automation = Automation(
        user_id=TEST_USER_ID,
        org_id=TEST_ORG_ID,
        name="callback repro",
        trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"},
        tarball_path="s3://bucket/code.tar.gz",
        entrypoint="uv run main.py",
    )
    async_session.add(automation)
    await async_session.commit()
    run = AutomationRun(automation_id=automation.id, status=AutomationRunStatus.RUNNING)
    async_session.add(run)
    await async_session.commit()

    server = HTTPServer(("127.0.0.1", 0), FlakyGateway)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    monkeypatch.setenv(
        "AUTOMATION_CALLBACK_URL",
        f"http://127.0.0.1:{server.server_port}/api/automation/v1/runs/{run.id}/complete",
    )
    monkeypatch.setenv("AUTOMATION_RUN_ID", str(run.id))
    monkeypatch.setenv("SANDBOX_ID", "sbx")
    monkeypatch.setenv("SESSION_API_KEY", "sess")

    # Exactly what the prompt/plugin preset runner does in cloud mode.
    workspace = OpenHandsCloudWorkspace(
        local_agent_server_mode=True,
        cloud_api_url="http://127.0.0.1:1",
        cloud_api_key="user-key",
        keep_alive=True,
    )
    with workspace as ws:
        ws.register_conversation("conv-123")
        ws.register_cost(0.42)
    server.shutdown()

    print("\nSDK callback attempts:", len(FlakyGateway.received), FlakyGateway.received)
    assert len(FlakyGateway.received) == 1  # one attempt, no retry after the 502

    await async_session.refresh(run)
    print("run status after the SDK exited:", run.status.value)
    assert run.status == AutomationRunStatus.RUNNING

    # The watchdog is the only path left. It completes the run after timeout_at
    # with no conversation_id and no cost. Stub: the agent-server bash history.
    backend = MagicMock(is_local_mode=False)
    backend.verify_run = AsyncMock(
        return_value=VerificationResult(verified=True, success=True, exit_code=0)
    )
    backend.cleanup_after_verification = AsyncMock()
    with patch("openhands.automation.watchdog.get_backend", return_value=backend):
        await _verify_and_mark_run(async_session, run, mock_settings)
    await async_session.commit()
    await async_session.refresh(run)
    print(
        "after watchdog:",
        run.status.value,
        "conversation_id=",
        run.conversation_id,
        "cost=",
        run.cost,
    )
    assert run.status == AutomationRunStatus.COMPLETED
    assert run.conversation_id is None and run.cost is None

    # Had the SDK retried the identical payload once, the real route would have
    # recorded it. Instead it now gets 409, so the metadata is gone for good.
    replay = await async_client.post(
        f"/api/automation/v1/runs/{run.id}/complete", json=FlakyGateway.received[0]
    )
    print("late identical callback:", replay.status_code, replay.json())
    assert replay.status_code == 409


async def test_replay_after_committed_callback_is_rejected_without_overwrite(
    async_client, async_session
):
    """Lost acknowledgement: the service already rejects replays safely."""
    automation = Automation(
        user_id=TEST_USER_ID,
        org_id=TEST_ORG_ID,
        name="replay repro",
        trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"},
        tarball_path="s3://bucket/code.tar.gz",
        entrypoint="uv run main.py",
    )
    async_session.add(automation)
    await async_session.commit()
    run = AutomationRun(automation_id=automation.id, status=AutomationRunStatus.RUNNING)
    async_session.add(run)
    await async_session.commit()

    url = f"/api/automation/v1/runs/{run.id}/complete"
    body = {"status": "COMPLETED", "conversation_id": "conv-1", "cost": 0.5}
    with patch(
        "openhands.automation.router.capture_automation_event", new=AsyncMock()
    ) as capture:
        first = await async_client.post(url, json=body)
        same = await async_client.post(url, json=body)
        conflicting = await async_client.post(url, json={"status": "FAILED"})
    print("\nfirst:", first.status_code, "| identical replay:", same.status_code,
          same.json(), "| conflicting:", conflicting.status_code)
    await async_session.refresh(run)
    print("final:", run.status.value, run.conversation_id, run.cost,
          "completion events:", capture.await_count)
    assert first.status_code == 200
    assert same.status_code == 409 and conflicting.status_code == 409
    assert run.status == AutomationRunStatus.COMPLETED and run.cost == 0.5
    assert capture.await_count == 1

Observed output on automation 19c4ea687d5ab89c6fea5357d11cd1644b7391bd with openhands-workspace==1.63.1 (the same sender code as SDK main at af85e224c9c0698e2b34efac4c27d254c64b151b). Both tests pass, which means the current behavior is confirmed:

INFO     Completion callback sent (COMPLETED): 502                       workspace.py:900
SDK callback attempts: 1 [{'status': 'COMPLETED', 'run_id': '8d79cc30-...', 'conversation_id': 'conv-123', 'cost': 0.42}]
run status after the SDK exited: RUNNING
INFO     Verifying run status via backend                                watchdog.py:247
after watchdog: COMPLETED conversation_id= None cost= None
late identical callback: 409 {'detail': 'Run is COMPLETED, expected RUNNING'}
first: 200 | identical replay: 409 {'detail': 'Run is COMPLETED, expected RUNNING'} | conflicting: 409
final: COMPLETED conv-1 0.5 completion events: 1
2 passed

Expected behavior

A successful run whose callback gets a single transient failure is still marked COMPLETED promptly, with its conversation_id and cost. A non-2xx callback response is logged as a failure, not as "sent".

Suggested fix

In openhands-sdk/openhands/sdk/workspace/base.py::_send_completion_callback and openhands-workspace/openhands/workspace/cloud/workspace.py::_send_completion_callback, ideally with one shared helper so the two copies cannot drift:

  • Retry the same payload with a short, bounded budget: for example, up to 4 attempts with exponential backoff and jitter, about 30 s in total. Retry on httpx.TransportError (connect errors and read timeouts), 5xx and 429. Respect Retry-After when it is present.
  • Stop at once on any 2xx, and on 409. A 409 means the run is already terminal: either an earlier attempt committed, or the watchdog or a cancellation got there first. The service's WHERE status = 'RUNNING' guard already makes replays safe, so no server change is needed.
  • Do not retry other 4xx responses (401/403/404/422).
  • Log the final outcome at WARNING when it is not 2xx/409, so a lost callback is visible in the sandbox log.
  • Keep the method best-effort: it must never raise out of __exit__.

Acceptance criteria

  • With a callback endpoint that returns 502 (or drops the connection) once and then 200, the workspace sends the identical payload again and the run is recorded as COMPLETED with its conversation_id and cost.
  • 429 and other 5xx responses are retried within the bounded budget. 2xx and 409 stop retries at once. Other 4xx responses are not retried.
  • A replay after a committed callback (lost acknowledgement) does not create a second completion and does not overwrite a conflicting terminal state. This already holds on the service side; add a test that the client stops on 409.
  • A non-2xx final outcome is logged at WARNING, not as "sent".
  • Both BaseWorkspace and OpenHandsCloudWorkspace behave the same, and unit tests cover them with a real local HTTP server.

OpenHands AI triage

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

Triage

Verified against the SDK at main: both callback senders (openhands-sdk/openhands/sdk/workspace/base.py and openhands-workspace/openhands/workspace/cloud/workspace.py) make exactly one POST, never check resp.status_code, and swallow httpx exceptions without retry, matching the issue. The automation service's complete route guards updates with WHERE status = 'RUNNING' and answers replays with 409 without overwriting state, so bounded client-side retry needs no server change. openhands-workspace depends on openhands-sdk, so the two copies can share a helper if the implementer chooses. Regression tests belong under tests/workspace/ and tests/sdk/workspace/ per repository guidance.

Scope: retry/status-classification/logging behavior of the two completion-callback senders in this repository, including their regression tests.

Non-goals: no changes to the automation service (watchdog, complete route, or run schema); no callback when AUTOMATION_CALLBACK_URL is unset; no change to callback payload shape; no retry policy for LLM calls or other workspace HTTP calls; no migration or API-compatibility change (the method stays best-effort and never raises out of __exit__).

Acceptance Criteria

  • With a local HTTP test server that returns 502 once and then 200, both BaseWorkspace._send_completion_callback and OpenHandsCloudWorkspace._send_completion_callback send the identical payload again, the final POST returns 200, and the method does not raise.
  • With the endpoint returning 429, then 5xx responses, then 2xx, both senders retry within the bounded budget and stop on the first 2xx; total attempts stay within the configured budget (e.g. up to 4 attempts).
  • On a 409 response, both senders stop immediately without further attempts and do not raise or log a failure-level warning (409 means the run is already terminal, e.g. the watchdog or a prior committed attempt).
  • On a non-retryable 4xx response (e.g. 401, 403, 404, 422), both senders make exactly one POST attempt and stop without raising.
  • On httpx.TransportError (connection error or read timeout) followed by 2xx, both senders retry and succeed; on persistent transport error through the budget, they stop without raising.
  • When the final outcome is not 2xx or 409, the senders log a WARNING-level message stating the failure (the word "sent" is not used for a failed outcome); a 2xx outcome keeps its existing success log.
  • Existing behavior is preserved: no POST when AUTOMATION_CALLBACK_URL is unset, a single POST when the endpoint returns 2xx on the first attempt, and the __exit__ path never propagates an exception from the callback.
  • Regression tests for BaseWorkspace and OpenHandsCloudWorkspace use a real local HTTP server for the retry/status-classification cases (not only mocked httpx.Client), are placed under tests/sdk/workspace/ and tests/workspace/ respectively, and fail on the current main code.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    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