DEV Community

Cover image for Silent Failure #22: The Webhook Fired Into a Task Nobody Held
Renhua Wei
Renhua Wei

Posted on

Silent Failure #22: The Webhook Fired Into a Task Nobody Held

The webhook test went green on the first run — 10 runs in a loop, 10 passes, 50ms of sleep between the send and the assert. That green is what cost me the afternoon: the task it was supposed to launch had already been collected before the assertion ran.

I was in OpenHands/software-agent-sdk, on the conversation service, chasing a report that webhook notifications sometimes never arrive. The service sends a message, schedules asyncio.create_task(self._notify_webhook(...)), returns 200 to the client, and the receiver on the other end sits there with an empty inbox. No exception. No log line. The endpoint that had been "working for weeks" simply didn't.

My first repro looked fine, which is exactly the problem: one send, one 50ms sleep, one assertion that the receiver got the payload. It passed every time I ran it, so I wrote "cannot reproduce" in the PR description and went to lunch. That test was measuring the scheduler, not the reference — 50ms is plenty of time for a task to finish, and a task that finishes is never collected. I had 100% coverage of the happy path and 0% of the failure mode. It passed for the wrong reason.

The docstring I should have read months ago is three lines under asyncio.create_task: "Save a reference to the result of this function, to avoid a task disappearing mid-execution." The event loop keeps only a weak reference to a task. The task keeps itself alive while it's running only as long as something else holds it, and a bare create_task(...) throws that handle on the floor. Under normal load the task finishes before the garbage collector ever looks at it, which is why this bug hides for weeks and then eats one specific shutdown.

To see it, I had to stop being polite to the code:

t = asyncio.create_task(slow_notify())  # handle discarded, like production
del t
gc.collect()                            # what the shutdown path does for free
await asyncio.sleep(0)
Enter fullscreen mode Exit fullscreen mode

That prints Task was destroyed but it is pending! if you're lucky enough to have __del__ run, and nothing at all if the interpreter exits first — which is the shutdown case. So the failure has two faces: a scary log line in staging, and complete silence in production.

I assumed the fix was one line: keep the handle in a set. It is one line, plus the two lines everyone forgets, plus the drain, plus the bug I introduced in the drain.

def _spawn_background(self, coro) -> asyncio.Task:
    task = asyncio.create_task(coro)
    self._background_tasks.add(task)
    task.add_done_callback(self._background_tasks.discard)
    return task
Enter fullscreen mode Exit fullscreen mode

Then the redirect: fire the webhook through _spawn_background instead of create_task. Then __aexit__ has to actually wait for them, or the fix just moves the loss a few milliseconds later.

Here is where I got cocky. I wrote:

while self._background_tasks:
    await asyncio.gather(*self._background_tasks)
Enter fullscreen mode Exit fullscreen mode

The test hung. Not failed, hung — the process pinned a core and sat there until the CI timeout. Mortifying, and the cause is a nice piece of trivia: gather() on tasks that are already done returns immediately without suspending, so the loop never yields, so the done_callback that discards from the set never runs, so the set is never empty. A busy loop inside an async exit.

The fix is to drain a snapshot instead of a condition:

pending, self._background_tasks = self._background_tasks, set()
if pending:
    await asyncio.gather(*pending, return_exceptions=True)
Enter fullscreen mode Exit fullscreen mode

Swap first, then await. return_exceptions=True because one failed webhook should not turn a clean shutdown into a raised exception — the send is already best-effort, and the drain exists to let it finish, not to re-litigate it.

Numbers, since I don't trust a fix I can't count: 4 new tests (task survives GC inside the await window, drain waits for a slow notifier, a raising notifier doesn't break exit, and no busy-spin when everything is already done). tests/test_conversation_service.py - 157 passed, 92 warnings in 8.61s. The webhook and config subset - 70 passed. pyright - 0 errors, 0 warnings. The first version of the drain test passed against the busy-loop code for 30 seconds and then timed out at 60, which is how I found it — a timeout is not a pass, and I had to stop treating "no assertion error" as "correct".

What I'd test first

  • Create the task, drop the handle, call gc.collect() inside the await window, then assert the side effect happened. If this passes with the bare create_task, your test isn't reaching the GC.
  • Close the service while a notifier sleeps for 2s, and assert the receiver got the payload after the exit returns. A test that only awaits the task directly proves nothing about __aexit__.
  • Make the notifier raise, and assert __aexit__ still returns. Exceptions in a done callback are swallowed by the loop; exceptions in a drain are not.
  • Point the same drain at an already-empty set and assert the call returns in under 50ms. That's the cheap version of the busy-loop regression.

My take, and I'll take the argument: an asyncio.create_task you cannot point at the set that owns it, together with the __aexit__ that drains it, is a webhook that will be lost exactly when it matters — on the shutdown path, under load, in the one process that had something to flush.

I've only measured this on Python 3.11.18, asyncio's default task factory, one service, 4 tests. That's a small sample and I know it.

What does your shutdown do with a task that is already done but whose done_callback hasn't run yet — do you drain the set, or do you drain a snapshot of it, and how many seconds do you give it before you stop waiting?

Top comments (0)