Repository navigation
Description
This issue was created by an AI agent (OpenHands) on behalf of @neubig.
Summary
A run that is deferred because of the organization concurrency limit never gets its last dispatch attempt. When the next exponential backoff is longer than the time left before AUTOMATION_DEFER_MAX_AGE_SECONDS, _defer_or_skip_blocked_run sets deferred_until to exactly the deadline. On the next poll, expire_aged_deferred_runs runs before the dispatcher claims runs. It matches that row and marks it SKIPPED / defer_expired, without another sandbox attempt. The backoff also has no upper limit except the deadline, so the waits before that grow long. A run can go hours without a try while capacity is free, and then expire without running.
Impact
- A deferred cron or event run can be skipped as
defer_expiredeven when capacity came back well before its deadline. The run history shows "Deferred past the maximum deferral age" and no conversation, but the run did not try during the last part of its window. - For an event-triggered run, the event is lost. Nothing can rerun a
SKIPPEDrun with its original payload, and a manualPOST /v1/{id}/dispatchcreates a new run with no event. - Each cron automation adds one deferred run per tick while the cap is full, because no overlap guard exists (Add a minimal per-automation overlap guard (skip when a run is already in-flight) #218). So each blocked automation produces many of these skips.
Root cause
-
The deferral backoff doubles on each attempt. It is limited only by the time left before the deadline (dispatcher.py#L808-L815):
remaining = max_age - age_seconds backoff = config.defer_backoff_base_seconds * (2**attempts) delay = min(backoff * random.uniform(0.5, 1.5), remaining) deferred_until = now + timedelta(seconds=max(1, delay))
When the cap applies,
deferred_until = now + (max_age - (now - created_at)) = created_at + max_age. The existing testtest_backoff_bounded_by_remaining_ageexpects this, so the intent is a final attempt at the deadline. -
On every poll,
dispatch_pending_runsruns the expiry sweep before it claims runs (dispatcher.py#L1742-L1756). The sweep selects (utils/run.py#L575-L583):AutomationRun.status == AutomationRunStatus.PENDING, AutomationRun.deferred_until.is_not(None), AutomationRun.deferred_until <= now, AutomationRun.created_at <= deadline, # deadline = now - max_age
For the capped row,
deferred_until <= nowandcreated_at <= now - max_ageare the same condition. So the row becomes eligible for the sweep at the same moment it becomes eligible for dispatch, and the sweep runs first. The final attempt never happens. Every run that stays blocked until its backoff passes the deadline ends this way. The only exception is the rare case where an uncapped retry lands on or after the deadline. -
With the defaults (
defer_max_age_seconds=21600,defer_backoff_base_seconds=60, config.py#L684-L695) and no jitter, a run that stays blocked is tried at 0, 1, 3, 7, 15, 31, 63, 127 and 255 minutes. Then it waits about 105 minutes and is skipped without a try. In a simulation of the same formula with the ±50% jitter, a run gets about 9 attempts. The median last attempt is about 4.3 h after creation, and the final wait that ends in the skip is about 40 to 160 minutes (10th to 90th percentile). The gap before the last attempt can also be more than 2 hours, so a shorter period of free capacity is missed.
Reproduction
This test runs the real dispatch_pending_runs, _execute_run, _defer_or_skip_blocked_run, expire_aged_deferred_runs and CloudSandboxBackend against the repository's PostgreSQL test fixture. It uses the production backoff formula. The test only scales AUTOMATION_DEFER_MAX_AGE_SECONDS down to 4 s through the real config, so it runs fast. It also creates the run with deferral_count=3, so the next backoff is already longer than the time left, as it is for every long-blocked run. Two external boundaries are stubbed:
- The OpenHands sandbox API, with an
httpx.MockTransport. It first answers429 CONCURRENCY_LIMIT_REACHED. Then capacity comes back and it answers200. - The service-key API-key mint.
Save the file as tests/test_rca_defer_expired.py, then run:
uv sync --frozen
uv run python -m pytest tests/test_rca_defer_expired.py -s -qtests/test_rca_defer_expired.py
"""Repro: a deferred run's last backoff ends in defer_expired with no final attempt.
Real code: dispatcher.dispatch_pending_runs, _execute_run,
_defer_or_skip_blocked_run, utils.run.expire_aged_deferred_runs and
CloudSandboxBackend. Stubbed boundaries: the OpenHands sandbox API (an
httpx.MockTransport that answers the concurrency-limit 429, then capacity
returns) and the service-key API-key mint.
"""
import asyncio
import uuid
from datetime import timedelta
from unittest.mock import patch
import httpx
from openhands.automation.backends import CloudSandboxBackend
from openhands.automation.config import clear_config_cache, get_config
from openhands.automation.dispatcher import dispatch_pending_runs
from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus
from openhands.automation.utils import utcnow
async def _dispatch_once(factory, settings, client):
await dispatch_pending_runs(factory, settings, client)
tasks = [
t
for t in asyncio.all_tasks()
if t.get_name().startswith("execute-run-") and not t.done()
]
await asyncio.gather(*tasks)
async def test_capacity_back_before_deadline_but_run_is_skipped_untried(
async_session_factory, mock_settings, monkeypatch
):
# Same backoff shape as production (base * 2**n, capped by the time left),
# scaled down so the test runs in seconds: 4s max age instead of 6h.
monkeypatch.setenv("AUTOMATION_DEFER_MAX_AGE_SECONDS", "4")
monkeypatch.setenv("AUTOMATION_DEFER_BACKOFF_BASE_SECONDS", "60")
clear_config_cache()
assert get_config().service.defer_max_age_seconds == 4
capacity = {"free": False}
creates: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "POST" and request.url.path == "/api/v1/sandboxes":
creates.append("free" if capacity["free"] else "full")
if not capacity["free"]:
return httpx.Response(
429,
json={
"detail": {
"error": "CONCURRENCY_LIMIT_REACHED",
"message": "Concurrency limit reached",
}
},
)
return httpx.Response(200, json={"id": "sb-1"})
if request.method == "GET" and request.url.path == "/api/v1/sandboxes":
return httpx.Response(200, json=[{"id": "sb-1", "status": "STARTING"}])
return httpx.Response(200, json={})
async def fake_mint(_run):
return "sk-user"
monkeypatch.setattr(
"openhands.automation.backends.cloud.get_api_key_for_automation_run",
fake_mint,
)
async with async_session_factory() as session:
automation = Automation(
user_id=uuid.uuid4(),
org_id=uuid.uuid4(),
name="every 15 minutes",
trigger={"type": "cron", "schedule": "*/15 * * * *", "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.PENDING,
created_at=utcnow() - timedelta(seconds=1),
# Already deferred a few times: the next backoff (60 * 2**3 = 480s)
# is longer than the 3s left, so it is capped at the deadline.
deferral_count=3,
)
session.add(run)
await session.commit()
run_id = run.id
async def load():
async with async_session_factory() as session:
return await session.get(AutomationRun, run_id)
def backend_for(r):
return CloudSandboxBackend(api_url="https://api.test", run=r)
try:
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
with patch(
"openhands.automation.dispatcher.get_backend", side_effect=backend_for
):
# Pass 1: capacity is full, so the run is deferred to the deadline.
await _dispatch_once(async_session_factory, mock_settings, client)
r = await load()
print(
f"\npass 1: status={r.status.value} "
f"deferred_until-created_at="
f"{(r.deferred_until - r.created_at).total_seconds():.3f}s "
f"kind={r.status_detail['kind']}"
)
# Capacity comes back well before the deferral deadline.
capacity["free"] = True
await asyncio.sleep(
max(0.0, (r.deferred_until - utcnow()).total_seconds()) + 0.2
)
# Pass 2: the run is due and capacity is free.
await _dispatch_once(async_session_factory, mock_settings, client)
r = await load()
print(
f"pass 2: status={r.status.value} "
f"kind={(r.status_detail or {}).get('kind')}"
)
finally:
clear_config_cache()
print(f"sandbox create attempts: {creates}")
assert "free" in creates, (
"capacity was back when the run became due, but the run was skipped "
f"as {r.status_detail.get('kind')} without another sandbox attempt"
)Observed output on main at 19c4ea687d5ab89c6fea5357d11cd1644b7391bd:
pass 1: status=PENDING deferred_until-created_at=4.000s kind=concurrency_limit
pass 2: status=SKIPPED kind=defer_expired
sandbox create attempts: ['full']
E AssertionError: capacity was back when the run became due, but the run was skipped as defer_expired without another sandbox attempt
E assert 'free' in ['full']
1 failed
In pass 1, the run is deferred to exactly created_at + max_age. Capacity comes back before that time. Pass 2 is the first poll after the run is due, and it skips the run with no POST /api/v1/sandboxes call.
Expected behavior
A deferred run gets one dispatch attempt at, or just before, the end of its deferral window. It expires only if that attempt is still blocked. Retries during the window are frequent enough that a run starts soon after capacity returns. The quota is not bypassed: a still-blocked attempt stays blocked.
Suggested fix
-
Make the final attempt happen. Either:
- cap the delay so the last retry lands before the deadline (for example
min(backoff, remaining - margin)with a margin of at least one dispatcher poll interval), or - have
expire_aged_deferred_runsskip a row whosedeferred_untilis the capped deadline until one poll interval has passed, so the dispatch claim can take it first.
Either way,
_defer_or_skip_blocked_runstill marks the rundefer_expiredafter the final attempt is blocked. The sweep is still needed for a poll that is at theAUTOMATION_MAX_CONCURRENT_RUNScap. - cap the delay so the last retry lands before the deadline (for example
-
Add an upper limit to the backoff (for example
AUTOMATION_DEFER_BACKOFF_MAX_SECONDS, a few minutes by default). Then a run is tried often during its whole window, not 9 times with gaps that grow to hours. The jitter that fix(dispatcher): add jitter to the deferral backoff #773 added still spreads the retries. -
Optional, separate change: overlap protection for cron (Add a minimal per-automation overlap guard (skip when a run is already in-flight) #218), so a blocked cron automation keeps at most one deferred run and does not create one per tick.
Keeping expired runs for an explicit, idempotent retry (with the original event payload) would be a feature on top of this. It is not needed to fix the lost final attempt.
Acceptance criteria
- A run that stays blocked gets a dispatch attempt within one poll interval of its deferral deadline. It is marked
defer_expiredonly after that attempt is still blocked. - If capacity comes back before the deadline, the run starts once on its next due poll and is not skipped (the test above passes).
- With the default settings, no two dispatch attempts of a deferred run are further apart than the configured maximum backoff.
- A poll at the
AUTOMATION_MAX_CONCURRENT_RUNScap still expires runs that are past their deadline, and a run is never dispatched twice.
OpenHands AI triage
The following comments and acceptance criteria were added by the OpenHands AI agent.
Triage
Verified against main at 19c4ea68 and the referenced code: _defer_or_skip_blocked_run caps the deferral delay at the exact remaining age before AUTOMATION_DEFER_MAX_AGE_SECONDS, expire_aged_deferred_runs selects any deferred PENDING row with deferred_until <= now and created_at <= now - max_age, and dispatch_pending_runs runs that sweep before claiming runs. A run whose backoff was capped to the deadline therefore matches the sweep at the same instant it becomes claimable, and the sweep wins: the run is marked SKIPPED/defer_expired without a final dispatch attempt. The existing test test_backoff_bounded_by_remaining_age fixes this capped-to-deadline behavior, so the intent was a final attempt at the deadline. An independent simulation of the documented backoff formula reproduces the issue's numbers (about 9 attempts, median last attempt ~360 min, final capped wait ~41–158 min p10–p90).
The issue records reproduced failure in the actual product workflow, so it is prioritized high. The request has a defined outcome and the repository already provides the levers needed; no author input is missing.
Bounded scope: (1) ensure a deferred run gets one dispatch attempt at or just before its deferral deadline, and mark defer_expired only when that final attempt is still blocked — the final-attempt guarantee must not depend on poll timing; (2) add an upper bound to the deferral backoff (an AUTOMATION_DEFER_BACKOFF_MAX_SECONDS service setting with a few-minute default, documented like the other AUTOMATION_ settings), so no two consecutive dispatch attempts are farther apart than that bound; (3) keep the sweep so a poll that runs at the AUTOMATION_MAX_CONCURRENT_RUNS cap still expires runs past their deadline, and keep the cap itself enforceable — a still-blocked final attempt must stay blocked, and a run must never dispatch twice. Existing consumers of the defer_expired status kind and skip_reason stay compatible. Existing tests that pin the capped-to-deadline deferral (e.g. test_backoff_bounded_by_remaining_age) are updated to the new final-attempt behavior.
Non-goals: no overlap guard for cron automations (#218); no retry or re-dispatch of expired runs with their original event payload; no change to deferral when AUTOMATION_DEFER_MAX_AGE_SECONDS == 0; no change to the dispatcher claim model, the watchdog, or the concurrency cap itself.
Steps to Reproduce
Run the reproducer in the issue body: uv sync --frozen && uv run python -m pytest tests/test_rca_defer_expired.py -s -q. On main at 19c4ea68, pass 1 defers the run to exactly created_at + max_age (deferred_until-created_at=4.000s), and pass 2 marks it SKIPPED/defer_expired with sandbox create attempts ["full"] — no second attempt even though capacity returned.
Desired Behavior
A deferred run gets one dispatch attempt at, or just before, the end of its deferral window; it is marked defer_expired only if that attempt is still blocked. If capacity returns before the deadline, the run starts on its next due poll instead of being skipped. Retries are bounded so a run is tried regularly during its whole window.
Acceptance Criteria
- A run that stays blocked through its deferral window is marked
SKIPPED/defer_expiredonly after a dispatch attempt made at or within oneAUTOMATION_DISPATCHER_INTERVAL_SECONDSof the run's deferral deadline was itself blocked by the limit; an added regression test covers this with the realdispatch_pending_runsordering. - A run blocked by the organization concurrency limit starts when capacity returns before its deferral deadline, with no
defer_expiredskip; the reproducer from this issue passes without modification. - With default settings, no two consecutive dispatch attempts of a deferred run are farther apart than the configured maximum backoff, enforced by an added test of the delay computation; the new setting is documented with the other
AUTOMATION_env vars inconfig.py. - With
AUTOMATION_MAX_CONCURRENT_RUNSat its cap, a poll still expires deferred runs past their deadline, and a single run is never dispatched twice concurrently.
Activity