AsyncpgEventBroker: asyncpg sync NOTIFY callback breaks anyio >= 4.14 (NoEventLoopError)

Author: zealccCreated Sep 21, 2026Updated Sep 26, 2026

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

  1. listen_callback in eventbrokers/asyncpg.py:113 is a plain synchronous function.
  2. 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).
  3. anyio >= 4.14 changed TaskGroup.start_soon() to return a TaskHandle, and TaskHandle.__init__ eagerly constructs a CancelScope() → get_async_backend() → sniffio → raises NoEventLoopError because there is no task context. (anyio 4.13 and earlier spawned a plain asyncio.Task, which did not hit this path; 4.13 also renamed the private NoCurrentAsyncBackend to the public NoEventLoopError.)

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

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