supermemoryai/supermemory · warning

Cannot wait for background tasks in sync context from async

Error message

Cannot wait for background tasks in sync context from async environment. Use async context manager or call wait_for_background_tasks() manually.

What it means

Logged when the sync context manager __exit__ tries asyncio.run(wait_for_background_tasks(...)) but an event loop is already running in the current thread (the standard 'asyncio.run() cannot be called from a running event loop' RuntimeError). The middleware cancels all background tasks as a safe fallback, meaning pending memory saves are discarded.

Source

Thrown at packages/openai-sdk-python/src/supermemory_openai/middleware.py:604

        try:
            await self.wait_for_background_tasks(timeout=5.0)
        except asyncio.TimeoutError:
            self._logger.warn("Some background memory tasks did not complete on exit")

    def __enter__(self):
        """Sync context manager entry."""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Sync context manager exit - attempt to wait for background tasks."""
        if self._background_tasks:
            try:
                # Try to wait for background tasks in sync context
                asyncio.run(self.wait_for_background_tasks(timeout=5.0))
            except RuntimeError as e:
                if "cannot be called from a running event loop" in str(e):
                    # In async context, just cancel the tasks
                    self._logger.warn(
                        "Cannot wait for background tasks in sync context from async environment. "
                        "Use async context manager or call wait_for_background_tasks() manually."
                    )
                    self.cancel_background_tasks()
                else:
                    raise
            except asyncio.TimeoutError:
                self._logger.warn(
                    "Some background memory tasks did not complete on exit"
                )
                self.cancel_background_tasks()

    def __getattr__(self, name: str) -> Any:
        """Delegate all other attributes to the wrapped client."""
        return getattr(self._client, name)


def with_supermemory(

View on GitHub (pinned to d436792e77)

Solutions

  1. Use the async client (AsyncOpenAI) with 'async with' in async environments
  2. Avoid the sync context manager under a running loop; call wait_for_background_tasks() manually from async code and skip __exit__ draining
  3. Drain tasks yourself before exit: run 'await client.wait_for_background_tasks(timeout=5)' inside the loop, then exit the context
  4. If you must nest loops, use nest_asyncio.apply() — but prefer the async client

Example fix

# before
with SupermemoryOpenAI(OpenAI()) as client:  # inside Jupyter/async env
    client.chat.completions.create_with_memory(...)

# after
client = SupermemoryOpenAI(AsyncOpenAI())
async with client:
    await client.chat.completions.create_with_memory(...)
Defensive patterns

Strategy: validation

Validate before calling

import asyncio
try:
    asyncio.get_running_loop()
    # use async client + 'async with'
except RuntimeError:
    pass  # sync 'with' is safe here

Type guard

def in_async_context() -> bool:
    try:
        asyncio.get_running_loop()
        return True
    except RuntimeError:
        return False

Prevention

When it happens

Trigger: Using 'with wrapped_sync_client:' inside an async environment — Jupyter notebooks, IPython, or sync code invoked from an async framework (FastAPI runs sync handlers in a thread, but libraries like nest_asyncio or direct calls from coroutines trigger it). __exit__ calls asyncio.run, which is illegal with a live loop.

Common situations: Notebook usage of the sync client with a context manager; sync SDK calls made from async application code; nest_asyncio environments. The workaround is to manage draining manually or use the async client.

Related errors


AI-assisted analysis of supermemoryai/supermemory@d436792e77 (2026-08-28). Data as JSON: /api/errors/1f080fe960db0063. Report an issue: GitHub.