Skip to content

fix(agent-server): survive webhook rate limiting and reap stale run tasks - #3991

Closed
shanemort1982 wants to merge 1 commit into
OpenHands:mainfrom
shanemort1982:fix/3842-webhook-backoff-and-stale-run-reap
Closed

shanemort1982 wants to merge 1 commit into
OpenHands:mainfrom
shanemort1982:fix/3842-webhook-backoff-and-stale-run-reap

Conversation

@shanemort1982

@shanemort1982 shanemort1982 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. WebhookSubscriber._post_events retries on a fixed delay with no backoff, does not honour Retry-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 applies InMemoryRateLimiter(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 of Webhook post attempt 4 failed: 429 / Failed to post events ... after 4 attempts per 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).

  2. EventService.run() raises conversation_already_running whenever _run_task is alive, even while execution_status reports 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

  • Webhook poster: serialise flushes behind a lock; exponential backoff between attempts, honouring 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_task coexists with non-RUNNING execution_status, start a staleness clock; if the SAME task is still lingering on a later attempt past STALE_RUN_TASK_REAP_SECONDS (120s, comfortably beyond the 30s-bounded wait_for_pending tail), cancel and reap it, then start the requested run. The task's finally now 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 format on 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 to requests=1/second to force the storm, then a long multi-step streaming conversation was driven through the full app -> sandbox -> webhook path:

  • Stock agent-server (1.30.0): webhook volleys tripped repeated 429s and logged the permanent give-up (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).
  • Patched agent-server: the serialised, paced poster stayed under the SAME limiter - zero 429s - and the full transcript including the final assistant message reached the app store; the conversation completed normally. Under a separately induced sustained-failure scenario, the cooldown machinery held: re-arms progressed 10s -> 20s -> 40s -> 60s (capped), no hot loop, no drops within the queue bound.

Jev-Fast-Audit

⚡ Jev fast audit · estimates · 0.36s · commit 0f66d33
Strongest signal: Data loss · 27% estimated likelihood.
Evidence: F001H004 · openhands-agent-server/openhands/agent_server/conversation_service.py:1632–1651.
Coverage: ⚠️ reduced context — partial coverage; 24/24 hunks, 4/4 files (context budget: 21).

All estimates and evidence
Estimate Likelihood / value Direct evidence
SQL injection 3.0% No direct hunk selected
Command injection 3.0% No direct hunk selected
Weakened authentication 4.0% No direct hunk selected
Weakened authorization 7.0% No direct hunk selected
Contract regression 15.0% No direct hunk selected
Data loss 27.0% F001H004 · openhands-agent-server/openhands/agent_server/conversation_service.py:1632–1651
Sensitive data disclosure 5.0% No direct hunk selected
Unexpected data transfer 3.0% No direct hunk selected
Credential misuse 5.0% No direct hunk selected
Untrusted instruction authority 2.0% No direct hunk selected
Package source redirection 4.0% No direct hunk selected
Unverified remote execution 2.0% No direct hunk selected
Privileged environment access 3.0% No direct hunk selected
Security assessment bypass 4.0% No direct hunk selected
Prohibited workload 2.0% No direct hunk selected
Primary concern Data loss; confidence 48.0% F001H004 · openhands-agent-server/openhands/agent_server/conversation_service.py:1632–1651

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.
@shanemort1982
shanemort1982 force-pushed the fix/3842-webhook-backoff-and-stale-run-reap branch from e7abdf6 to 0f66d33 Compare July 16, 2026 18:47
@shanemort1982

Copy link
Copy Markdown
Contributor Author

@VascoSch92 rebased onto current main and reconciled with the webhook_subscriber refactor. The PR was showing mergeable: dirty purely because two files (conversation_service.py, test_webhook_subscriber.py) had been committed with CRLF line endings, so every line read as changed and the three-way merge blew up. Normalised to LF and re-applied; the real change is back to +369/-22 across 4 files and now merges clean.

Green locally against main: test_event_service.py + test_webhook_subscriber.py = 152 passed, ruff clean. CI on the new head is passing so far.

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 /api/v1/webhooks/events/*. The reaper half is the important one for the wedge.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@all-hands-bot
all-hands-bot requested a review from enyst July 18, 2026 12:39
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@shanemort1982

Copy link
Copy Markdown
Contributor Author

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 /run on idle+RUNNING conversations as a stopgap for #3842, because the reaper makes it redundant. That removal is the cleanest confirmation the fix is doing its job in practice: every conversation the shim was "recovering" turned out to be a fresh conversation waiting for its first user message, not a stale run task.

The webhook backoff + cooldown circuit has also held up under real sustained-429 load that previously orphaned run tasks.

Still showing mergeable: dirty. Happy to rebase onto current main and normalise line-endings on conversation_service.py / test_webhook_subscriber.py if that helps move it forward. @enyst, a review would be great when you have a moment.

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👋 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 stop conversation.run() already executing in ThreadPoolExecutor; it only stops awaiting that worker. The old worker can therefore continue mutating conversation state and persistence while the replacement run starts against the same Conversation. 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 plain asyncio.Event().wait() task, which is cooperatively cancellable and does not exercise the run_in_executor path. Add a blocking synchronous conversation.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:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger 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.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. 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 /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.

Was this review helpful? React with 👍 or 👎 to give feedback.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@neubig
neubig requested review from VascoSch92 and removed request for VascoSch92 August 5, 2026 14:51

@VascoSch92 VascoSch92 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use Final[float] from typing

if retry_after:
# TypeError guards non-string values (e.g. mocked responses).
with suppress(TypeError, ValueError):
wait = max(wait, float(retry_after))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as before

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@github-actions

Copy link
Copy Markdown
Contributor

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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The reaper can start a second run over a still-executing sync run. _maybe_reap_stale_run_task() does task.cancel() then immediately clears _run_task, and run() then starts a replacement. On the sync path the work runs in a thread via run_in_executor(self._run_executor, conversation.run); cancelling the awaiting asyncio task does not stop that thread, so the original conversation.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.

  2. The reaper is only wired into run(). start_goal_loop() (line ~1163) and resume_goal_loop() (line ~1353) still raise conversation_already_running on a live _run_task without consulting the reaper, so /goal start and /goal resume remain permanently 409 on a wedged task even though plain /run now self-heals.

  3. Retry-After bypasses the advertised 60s cap. _retry_wait() computes min(..., _WEBHOOK_MAX_BACKOFF_SECONDS) and then does max(wait, float(retry_after)), so a numeric Retry-After: 3600 produces 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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

agent-server: conversation wedges at execution_status=idle while /run returns 409 (stale _run_task never reaped, no self-heal)

4 participants