Repository navigation
fix(agent-server): survive webhook rate limiting and reap stale run tasks - #3991
shanemort1982 wants to merge 1 commit into
Conversation
|
[Automatic Post]: It has been a while since there was any activity on this PR. @shanemort1982, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
1 similar comment
|
[Automatic Post]: It has been a while since there was any activity on this PR. @shanemort1982, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
…asks Fixes OpenHands#3842. Two defects compounded into permanently wedged conversations: 1. WebhookSubscriber._post_events retried on a fixed delay with no backoff, ignored Retry-After, ran overlapping volleys, and after exhausting retries only tried again when a NEW event arrived - so against a rate-limited downstream (the OpenHands app server rate-limits /api/v1/webhooks/events/* like any other route) delivery stalled forever and the queue trim dropped events permanently. 2. EventService.run() raised conversation_already_running whenever _run_task was alive, even with execution_status reporting non-RUNNING; a run task that never completes therefore blocked the conversation forever - the self-heal from OpenHands#3364 never fires because the task never reaches its cleanup tail. Webhook poster: serialise flushes; exponential backoff honouring Retry-After; exponentially growing cooldown (1s floor, 60s cap) instead of hammering; re-arm the flush timer on failure so delivery resumes without new events; prepend re-queued events to preserve delivery order; enforce the queue bound on enqueue as well as on failed-flush trim. EventService.run(): when a live _run_task coexists with non-RUNNING status, start a staleness clock; reap the same task if still lingering past STALE_RUN_TASK_REAP_SECONDS (120s, well beyond the 30s-bounded wait_for_pending tail) and start the requested run. The task finally block now only clears its own task reference so a reaped task cannot clobber its replacement. Rebased onto main and reconciled with the webhook_subscriber refactor.
e7abdf6 to
0f66d33
Compare
|
@VascoSch92 rebased onto current main and reconciled with the Green locally against main: Since you already reproduced #3842, could you give this a review? It's biting a self-hosted fleet daily: a run task that never reaches its cleanup tail leaves the conversation permanently answering 409 with no self-heal, and the webhook poster stalls forever against the app server's per-IP rate limit on |
|
[Automatic Post]: I have assigned @enyst as a reviewer based on the repository MAINTAINERS file. Thanks in advance for the help! This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
[Automatic Post]: This PR seems to be currently waiting for review. @enyst, could you please take a look when you have a chance? This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
Field update: this has been live in production across our self-hosted fleet for several days now (6 hosts on SDK 1.36.0 + this agent-server build) and the #3842 wedge has not reoccurred. We're now removing the watchdog shim we'd built to auto-POST The webhook backoff + cooldown circuit has also held up under real sustained-429 load that previously orphaned run tasks. Still showing |
enyst
left a comment
There was a problem hiding this comment.
👋 I'm an AI agent (Opus 5) reviewing this PR on behalf of Engel Nyst (@enyst).
🔴 Needs improvement - the webhook backoff work is sensible, but the stale-run recovery can permit two runs to mutate one conversation concurrently.
[CRITICAL ISSUES]
- [
openhands-agent-server/openhands/agent_server/event_service.py, Line 953] Concurrency / Data Ownership:_maybe_reap_stale_run_task()cancels the asyncio wrapper, drops_run_task, and immediately lets a replacement run start. For the synchronous fallback at line 1033, cancellation does not stopconversation.run()already executing inThreadPoolExecutor; it only stops awaiting that worker. The old worker can therefore continue mutating conversation state and persistence while the replacement run starts against the sameConversation. Do not make the conversation runnable again until the underlying worker has actually exited, or discard/recreate the old conversation instance before starting a replacement.
[TESTING GAPS]
- [
tests/agent_server/test_event_service.py, Line 3424] The Test Models the Wrong Thing: the reaper test cancels a plainasyncio.Event().wait()task, which is cooperatively cancellable and does not exercise therun_in_executorpath. Add a blocking synchronousconversation.run()regression test and prove a second run cannot start until that worker exits.
KEY INSIGHT:
An asyncio task reference is not ownership of the executor worker it awaits; clearing one does not terminate the other.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🔴 HIGH
This changes core conversation execution and recovery behavior, with a realistic overlapping-run path that can corrupt state or duplicate actions. Recommendation: Do not auto-merge. Request review from a human concurrency/agent-runtime maintainer to validate worker lifetime and replacement semantics.
VERDICT:
❌ Needs rework: stale-run recovery must not overlap an uncancelled synchronous run with its replacement.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.Was this review helpful? React with 👍 or 👎 to give feedback.
|
[Automatic Post]: It has been a while since there was any activity on this PR. @shanemort1982, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
VascoSch92
left a comment
There was a problem hiding this comment.
Left a couple of comments.
Could you also trim the comments and not reference the issue :-) ?
Thanks
|
|
||
| # Cap for the exponential retry/cooldown backoff so a long outage retries at a | ||
| # steady cadence instead of growing unboundedly. | ||
| _WEBHOOK_MAX_BACKOFF_SECONDS = 60.0 |
| if retry_after: | ||
| # TypeError guards non-string values (e.g. mocked responses). | ||
| with suppress(TypeError, ValueError): | ||
| wait = max(wait, float(retry_after)) |
There was a problem hiding this comment.
_retry_wait does wait = min(..., _WEBHOOK_MAX_BACKOFF_SECONDS) then wait = max(wait, float(retry_after)) the header value overrides the 60s cap with no ceiling.
That sleep runs at line 1753 inside _post_events_locked, which holds _post_lock.
A numeric Retry-After: 3600 stalls all delivery for an hour.
Real, highest-impact (misconfig/attacker-triggerable). Note: an HTTP-date Retry-After is harmless (float() raises → suppressed), so only numeric-seconds values trigger it — still a real bug.
| # reports non-RUNNING before run() reaps it and starts fresh (#3842). Must | ||
| # comfortably exceed the legitimate wrap-up tail (wait_for_pending is bounded | ||
| # at 30s) so a normal finishing run is never cancelled. | ||
| STALE_RUN_TASK_REAP_SECONDS = 120.0 |
| default_factory=lambda: PubSub[Event](max_subscribers=50), init=False | ||
| ) | ||
| _run_task: asyncio.Task | None = field(default=None, init=False) | ||
| # Stale run-task detection (#3842): a _run_task that never completes while |
There was a problem hiding this comment.
| # Stale run-task detection (#3842): a _run_task that never completes while | |
| # Stale run-task detection: a _run_task that never completes while |
| # may reach this finally after a replacement run has | ||
| # already been started, and must not clobber it. | ||
| if self._run_task is asyncio.current_task(): | ||
| self._run_task = None |
There was a problem hiding this comment.
Both guards are literally if (self._run_task is not None and not self._run_task.done()) or (...): raise ValueError("conversation_already_running") with no _maybe_reap_stale_run_task() call.
Only run() self-heals.
This can confirmed with the goal command. In fact, /goal start/resume stay permanently 409 on a wedged task.
| self.stored.id, | ||
| now - self._stale_run_first_seen, | ||
| ) | ||
| task.cancel() |
There was a problem hiding this comment.
Sync path is await loop.run_in_executor(self._run_executor, conversation.run); reaper does only task.cancel(); _run_task = None, then run() starts a fresh task. cancel() cannot stop the running thread → two runs on one conversation.
Real for the sync-executor wedge (which is exactly the #3842 scenario; the async path can't wedge without freezing the loop that runs the reaper).
|
This PR is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days. |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Scope gate: this is agent-server behaviour (webhook delivery + run-task lifecycle) inside OpenHands/software-agent-sdk, so it belongs here and no product/architecture decision is needed. I reviewed the current head 0f66d33, the current PR body/labels, the existing unresolved review threads (VascoSch92, enyst - both still open on this same head), and issue #3842 (now closed, labels bug/Stale). CI for this head is green (agent-server-tests, sdk-tests, coverage-report, etc. all success), and the focused suites pass locally: uv run pytest tests/agent_server/test_webhook_subscriber.py tests/agent_server/test_event_service.py -> 152 passed.
The webhook half of this change is well-constructed: serialising flushes behind _post_lock, exponential in-volley backoff, the cooldown circuit, re-arming the flush timer on failure, and prepending re-queued events all fix real defects, and the added tests cover the 429-storm / order-preservation / cooldown paths. The stale-run-task reaper addresses a genuine wedge.
However, two previously-raised issues that materially affect the reaper's safety are still present unchanged on this head, plus one bounded-input gap in the webhook poster:
-
The reaper can start a second run over a still-executing sync run.
_maybe_reap_stale_run_task()doestask.cancel()then immediately clears_run_task, andrun()then starts a replacement. On the sync path the work runs in a thread viarun_in_executor(self._run_executor, conversation.run); cancelling the awaiting asyncio task does not stop that thread, so the originalconversation.run()can still be mutating conversation state when_run_and_publish()launches a new one. This is exactly the #3842 scenario (sync-config conversations), so the fix can convert a permanent 409 into concurrent mutation of one conversation. -
The reaper is only wired into
run().start_goal_loop()(line ~1163) andresume_goal_loop()(line ~1353) still raiseconversation_already_runningon a live_run_taskwithout consulting the reaper, so/goal startand/goal resumeremain permanently 409 on a wedged task even though plain/runnow self-heals. -
Retry-Afterbypasses the advertised 60s cap._retry_wait()computesmin(..., _WEBHOOK_MAX_BACKOFF_SECONDS)and then doesmax(wait, float(retry_after)), so a numericRetry-After: 3600produces an hour-long sleep inside_post_events_locked, which holds_post_lock- stalling all delivery for that conversation.
Full findings with suggested fixes are inline. None of these are style nits; 1 and 2 change whether the reaper is safe/complete, and 3 is a bounded-input gap in the new backoff. Please address (or explicitly justify) before merge.
🔄 CHANGES REQUESTED
| self.stored.id, | ||
| now - self._stale_run_first_seen, | ||
| ) | ||
| task.cancel() |
There was a problem hiding this comment.
Reaper can run two executions of one conversation concurrently (sync path).
task.cancel() only cancels the asyncio task; the actual work for sync-config conversations runs in a worker thread started at loop.run_in_executor(self._run_executor, conversation.run) (line ~1033). Cancelling the awaiting task does not interrupt that thread, yet this block immediately sets self._run_task = None and returns True, after which run() calls asyncio.create_task(_run_and_publish()) and a second conversation.run() is dispatched to the executor. The original thread can still be mutating ConversationState (and holding self._state) at that point - the exact sync path involved in #3842.
If the wedge is truly a non-cooperating sync run, cancel() cannot be the recovery primitive. Consider: (a) not clearing _run_task until the task actually finishes, and gating the replacement run on task.done(); or (b) for the executor path, only reaping when the thread can be shown to have exited (e.g. an explicit completion/timeout event the thread sets), and otherwise surfacing an error rather than silently double-running. At minimum, document why double-dispatch is safe for the sync path - the PR description's 30s-tail argument does not cover a thread that never returns.
| # permanently answering 409 with no self-heal. Reap the latter. | ||
| if self._run_task is not None and not self._run_task.done(): | ||
| raise ValueError("conversation_already_running") | ||
| if not self._maybe_reap_stale_run_task(): |
There was a problem hiding this comment.
Self-heal only covers run(); the goal guards still hard-409 on a wedged task.
This is the only call site of _maybe_reap_stale_run_task(). start_goal_loop() (line ~1163) and resume_goal_loop() (line ~1353) still use the bare guard:
if (self._run_task is not None and not self._run_task.done()) or (
await self._get_execution_status() == ConversationExecutionStatus.RUNNING
):
raise ValueError("conversation_already_running")with no reaper consultation. So on a conversation wedged by #3842, /run self-heals but /goal start and /goal resume stay permanently 409 - the same class of stuck conversation the PR aims to fix. Please route those two guards through the reaper as well (they already hold _run_lock), or explicitly note the out-of-scope boundary.
| if retry_after: | ||
| # TypeError guards non-string values (e.g. mocked responses). | ||
| with suppress(TypeError, ValueError): | ||
| wait = max(wait, float(retry_after)) |
There was a problem hiding this comment.
Retry-After overrides the 60s cap with no ceiling, while holding _post_lock.
wait = min(self.spec.retry_delay * (2**attempt), _WEBHOOK_MAX_BACKOFF_SECONDS) is then followed by wait = max(wait, float(retry_after)), so a numeric Retry-After: 3600 yields a 3600s wait. That wait happens at await self._sleep(self._retry_wait(e, attempt)) inside _post_events_locked, which is guarded by _post_lock - so a single misconfigured or hostile downstream stalls all delivery for that conversation for the full header duration, and close()/buffer-triggered flushes block behind it. (An HTTP-date form is harmless since float() raises and is suppressed; only numeric-seconds values trigger it.)
Cap the honoured value, e.g.:
wait = max(wait, min(float(retry_after), _WEBHOOK_MAX_BACKOFF_SECONDS))and consider applying the same ceiling to the post-exhaustion cooldown path.
HUMAN:
Follow-up to my report in #3842, which VascoSch92 reproduced. We caught the trigger in the wild on our fleet: the app server rate-limits its own sandbox's webhook posts (429), the stock poster gives up, the app-side transcript freezes, and the lingering run task answers 409 forever with no self-heal. Fix validated end to end on a self-hosted box (evidence below) on top of the unit suites.
AGENT:
Why
Fixes #3842.
Two defects compound into the wedge:
WebhookSubscriber._post_eventsretries on a fixed delay with no backoff, does not honourRetry-After, fires overlapping volleys (each buffer-full flush posts concurrently), and after exhausting retries only tries again when a NEW event arrives. Against a rate-limited downstream (the OpenHands app server appliesInMemoryRateLimiter(requests=10, seconds=1)per client IP to ALL routes, including/api/v1/webhooks/events/...) the concurrent volleys trip the limiter, keep it tripped, and delivery stalls; the queue trim then drops events permanently. Production signature: hundreds ofWebhook post attempt 4 failed: 429/Failed to post events ... after 4 attemptsper second for 90+ minutes while the app-side transcript sat frozen (the agent's local store reached 8,622 events; the app side had 270).EventService.run()raisesconversation_already_runningwhenever_run_taskis alive, even whileexecution_statusreports non-RUNNING. A run task that never completes therefore wedges the conversation forever - the self-heal added in fix(agent-server): re-run input stranded in a finished run's cleanup tail #3364 never fires because the task never reaches its cleanup tail.Summary
Retry-After; after a failed volley enter an exponentially growing cooldown (1s floor, 60s cap) instead of hammering; re-arm the flush timer on failure so delivery resumes WITHOUT requiring a new event; preserve delivery order by prepending re-queued events.EventService.run(): when a live_run_taskcoexists with non-RUNNINGexecution_status, start a staleness clock; if the SAME task is still lingering on a later attempt pastSTALE_RUN_TASK_REAP_SECONDS(120s, comfortably beyond the 30s-boundedwait_for_pendingtail), cancel and reap it, then start the requested run. The task'sfinallynow only clears its own task reference so a reaped task cannot clobber a replacement run.How to Test
Commands run in a clean checkout with the patch applied:
uv run pytest tests/agent_server/test_webhook_subscriber.py tests/agent_server/test_event_service.py-> 150 passed. 5 new tests cover Retry-After/backoff with zero event loss and order preservation, cooldown queueing without posts, and the stale-run-task reaper (first observation never reaps; same lingering task past the grace period is cancelled and cleared; a different task restarts the clock). 5 existing assertions updated where the fixed-delay retry cadence intentionally changed to exponential.uv run ruff check/uv run ruff formaton the four touched files: clean.End to end on a self-hosted deployment (agent-server image built from this branch's changes applied to v1.30.0,
--target source; OpenHands app at current main). The app's global rate limit was tightened torequests=1/secondto force the storm, then a long multi-step streaming conversation was driven through the full app -> sandbox -> webhook path:Failed to post events to webhook ... after 4 attempts); the app-side transcript stalls until unrelated later events happen to re-trigger a flush - or forever when the storm persists (the production case above).Jev-Fast-Audit
⚡ Jev fast audit · estimates · 0.36s · commit 0f66d33⚠️ reduced context — partial coverage; 24/24 hunks, 4/4 files (context budget: 21).
Strongest signal: Data loss · 27% estimated likelihood.
Evidence: F001H004 · openhands-agent-server/openhands/agent_server/conversation_service.py:1632–1651.
Coverage:
All estimates and evidence