AsyncpgEventBroker: asyncpg sync NOTIFY callback breaks anyio >= 4.14 (NoEventLoopError)
AsyncpgEventBroker: asyncpg sync NOTIFY callback breaks anyio >= 4.14 (NoEventLoopError)
Things to check first
- I have checked that my issue does not already have a solution in the FAQ
- I have searched the existing issues and didn't find my bug already reported there
- I have checked that my bug is still present in the latest release
Version
4.0.0a6 · anyio 4.14.2 · asyncpg 0.31.0 · Python 3.14
What happened?
AsyncScheduler + AsyncpgEventBroker + anyio 4.14.x raises NoEventLoopError on every NOTIFY that arrives (including its own published events on the same connection), so the event is dropped and cross-worker coordination silently breaks.
Exception in callback AsyncpgEventBroker._listen_notifications.<locals>.listen_callback()
Traceback (most recent call last):
File ".../asyncio/events.py", line 94, in _run
self._context.run(self._callback, *self._args)
File ".../apscheduler/eventbrokers/asyncpg.py", line 118, in listen_callback
self._task_group.start_soon(self.publish_local, event)
File ".../anyio/abc/_tasks.py", line 144, in start_soon
return self.create_task(call_for_coroutine(func, args), name=final_name)
File ".../anyio/_backends/_asyncio.py", line 932, in create_task
return self._spawn(coro, name=name)
File ".../anyio/_backends/_asyncio.py", line 888, in _spawn
handle = TaskHandle(coro, name)
File ".../anyio/_core/_tasks.py", line 259, in __init__
self._cancel_scope = CancelScope()
File ".../anyio/_core/_tasks.py", line 60, in __new__
return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline)
File ".../anyio/_core/_eventloop.py", line 195, in get_async_backend
raise NoEventLoopError(...)
anyio.NoEventLoopError: Not currently running on any asynchronous event loop.Root cause
listen_callbackineventbrokers/asyncpg.py:113is a plain synchronous function.- asyncpg detects a sync callable and dispatches it via
loop.call_soon()(asyncpg/connection.py:1719), so it runs as a bare callback with no running asyncio task (current_task()is None). - anyio >= 4.14 changed
TaskGroup.start_soon()to return aTaskHandle, andTaskHandle.__init__eagerly constructs aCancelScope()→get_async_backend()→ sniffio → raisesNoEventLoopErrorbecause there is no task context. (anyio 4.13 and earlier spawned a plainasyncio.Task, which did not hit this path; 4.13 also renamed the privateNoCurrentAsyncBackendto the publicNoEventLoopError.)
How can we reproduce the bug?
Two workers on the same Postgres (or strictly, one worker plus any publisher is enough — the broker also echoes its own pg_notify back to its listening connection):
import asyncio
from apscheduler import Scheduler
from apscheduler.datastores.sqlalchemy import SQLAlchemyDataStore
from apscheduler.eventbrokers.asyncpg import AsyncpgEventBroker
from apscheduler.triggers.interval import IntervalTrigger
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("postgresql+asyncpg://user:pass@host/db")
async def job():
print("job ran")
async def main():
async with Scheduler(
data_store=SQLAlchemyDataStore(engine),
event_broker=AsyncpgEventBroker.from_async_sqla_engine(engine),
) as scheduler:
await scheduler.add_job(job, IntervalTrigger(seconds=5), id="job1")
await scheduler.run_until_stopped()
asyncio.run(main())Expected: events are dispatched to local schedulers via publish_local.
Actual: NoEventLoopError on every notification; events never dispatched.
A minimal note: pinning anyio to < 4.14 avoids the crash but leaves the sync callback fragile.
Suggested fix
Make listen_callback an async def. asyncpg will then wrap it via loop.create_task() (asyncpg/connection.py:1717), giving it a real task context where start_soon works. remove_listener takes the same callable, so no other change is needed.
Source: agronholm/apscheduler