Skip to content

[BUG] IndexError: pop from an empty deque during async engine dispose on Postgres / asyncpg (CLI commands, lifespan init, watcher) #831

Closed

Description

@SW4T400

DURING MY SELF HOSTING JOURNEY of basic-memory I, or lets be honest - Claude Code came accross this:

Issue draft 2 — Bug report

Template to choose: Bug report

Suggested title:
IndexError: pop from an empty deque during async engine dispose on Postgres / asyncpg (CLI commands, lifespan init, watcher)


Issue body (copy-paste below this line)

Bug Description

On the Postgres backend (postgresql+asyncpg://...), several code paths that follow the shape "open an async engine -> do work -> await engine.dispose()" can crash with IndexError: pop from an empty deque from asyncio/base_events.py:_run_once. The traceback originates inside SQLAlchemy's async dispose machinery (sqlalchemy/pool/base.py:_close_connection -> connectors/asyncio.py:close -> _concurrency_py3k.py:greenlet_spawn).

This is not a duplicate of #462 / PR #471 ("prevent CLI commands from hanging on exit", merged 2025-12-24). That fix addresses a different symptom — the process hangs forever waiting on outstanding async connections. The bug reported here is a hard exception thrown from asyncio._run_once; the process exits with a non-zero code rather than hanging. The fix from #471 is present in the version I am running (0.20.3) but does not cover this failure mode.

Steps To Reproduce

The crash is timing-dependent, not load-dependent — it hits even single-engine, single-query CLI commands. Easiest path to reproduce:

  1. Install Basic Memory 0.20.3 against a PostgreSQL 17 instance with pgvector enabled (BASIC_MEMORY_DATABASE_BACKEND=postgres, BASIC_MEMORY_DATABASE_URL=postgresql+asyncpg://...).
  2. Run a one-shot CLI command, e.g.:
    basic-memory project list
    
  3. Observe the traceback (does not fire on every invocation — repeat a handful of times).

The same failure also fires in two other paths during normal operation:

  • Lifespan initialization sync at MCP server startup (when BASIC_MEMORY_SKIP_INITIALIZATION_SYNC is not true).
  • In-process file watcher (BASIC_MEMORY_SYNC_CHANGES=true), when watchfiles.awatch runs SyncService against the shared async pool inside the FastMCP lifespan loop.

I do not have a minimal standalone reproducer to attach. The closest upstream reproducer with the same traceback signature is pola-rs/polars#25209, which demonstrates the same crash on multiple async drivers (asyncpg, aiosqlite, oracle+oracledb) — i.e. the root cause is in the CPython / SQLAlchemy async-dispose orchestration, not in any one driver.

Expected Behavior

CLI commands, lifespan startup, and the watcher loop should each open an async engine, do their work, dispose the engine, and return a zero exit status (or, for the watcher, continue running) without raising from asyncio._run_once.

Actual Behavior

The process raises:

File "asyncio/base_events.py", line 2035, in _run_once
    handle = self._ready.popleft()
IndexError: pop from an empty deque

with the originating frames inside SQLAlchemy's async dispose path:

sqlalchemy/pool/base.py:_close_connection
  -> connectors/asyncio.py:close
    -> _concurrency_py3k.py:greenlet_spawn
      -> asyncio/base_events.py:_run_once
        -> IndexError: pop from an empty deque

For one-shot CLI commands the process exits non-zero. For the in-process watcher and lifespan-init path, the surrounding server process dies as well.

Environment

  • OS: Linux (Docker container, Ubuntu-based image)
  • Python version: 3.12.13
  • Basic Memory version: 0.20.3
  • Installation method: pip (inside Docker image)
  • Database backend: PostgreSQL 17 with pgvector
  • Driver: postgresql+asyncpg://...
  • Claude Desktop version: n/a (MCP server, not Desktop client)

Additional Context

Workarounds currently in place to keep the server stable:

  • BASIC_MEMORY_SKIP_INITIALIZATION_SYNC=true
  • BASIC_MEMORY_SYNC_CHANGES=false
  • Manual basic-memory sync invoked on demand instead of relying on the watcher.

These turn off real features, so they are not satisfactory long-term.

Adjacent upstream tracking that helped narrow this down:

  • pola-rs/polars#25209 — canonical reproducer of the same traceback signature across multiple async drivers (asyncpg, aiosqlite, oracle+oracledb). Closed-as-completed on the polars side but the underlying CPython/SQLAlchemy interaction is unchanged for other consumers.
  • jlowin/fastmcp#1311 — adjacent FastMCP + asyncpg cleanup hang. This is referenced verbatim by basic-memory's own justfile:
    # Note: Uses timeout due to FastMCP Client + asyncpg cleanup hang
    # (tests pass, process hangs on exit)
    # See: https://github.com/jlowin/fastmcp/issues/1311
    
  • sqlalchemy/sqlalchemy#8145 — long-standing async pool / cancel-during-close discussion in SQLAlchemy.

Possible Solution

Three knobs worth trying on the basic-memory side, ranked by how likely they are to help vs. effort. None of these are patches I have tested against a live reproducer yet — I am happy to test if a maintainer prefers a specific approach.

  1. poolclass=NullPool + connect_args={"statement_cache_size": 0} on the async engine. SQLAlchemy's documented mitigation for "async engine reused across event loops"; removes the pool-dispose scheduling entirely, which is the surface that races with loop teardown.
  2. Optionally support uvloop as the event loop policy (e.g. via an opt-in env var). uvloop's C-level scheduler does not have the _ready.popleft() codepath at all, so this whole class of crash structurally cannot fire there.
  3. Shield the engine-dispose call from cancellation on shutdown, along the lines discussed in sqlalchemy#8145.

A driver swap from asyncpg to psycopg3 is unlikely to help — the polars reproducer fires on aiosqlite and oracle+oracledb as well, so the root cause is upstream of the driver.

Activity

  1. added
    bug
    on May 16, 2026
  2. MakksSh commented on May 18, 2026

    @MakksSh

    Same problem!
    Windows 10. WSL and base windows. Installed from uv tool add.
    Version 0.21.1

    Image
  3. SW4T400 commented on Jun 5, 2026

    @SW4T400
    Author

    @phernandez @groksrc
    This did not fix my issue. I had claude attempt to upgradeto 0.21.6 but it failed:

    basic-memory GitHub issue draft — asyncpg deque crash NOT fixed by #838 (postgres path, v0.21.6)

    Source


    Everything below this line is the copy-paste issue body for basicmachines-co/basic-memory.
    Template to choose: Bug report
    Suggested title: [BUG] asyncpg "IndexError: pop from an empty deque" still crashes Postgres backend on v0.21.6 — #838 fixed only the local/sqlite path


    Bug Description

    The IndexError: pop from an empty deque startup/teardown crash reported in #831 is still present on the Postgres (postgresql+asyncpg) backend in v0.21.6.

    #831 was closed as completed by #838 ("fix(mcp): preinitialize local ASGI database", v0.21.5). That PR addresses the local / SQLite ASGI initialization path. It does not cover the postgres + asyncpg async-engine-dispose race, which is the failure mode #831 actually documented (its traceback originates in SQLAlchemy's async dispose() → connectors/asyncio.py:close → greenlet_spawn → asyncio._run_once).

    On a fresh v0.21.6 container against Postgres 17 + pgvector, with the initialization sync and file watcher enabled (i.e. BASIC_MEMORY_SKIP_INITIALIZATION_SYNC=false, BASIC_MEMORY_SYNC_CHANGES=true), the server crashes on startup and enters a Docker restart loop. The only way to keep the server up is to re-disable both features via the env-var workarounds — which means the watcher / auto-indexing remain unusable on the Postgres backend.

    Additionally, the published v0.21.6 image now ships Python 3.13 (cpython-3.13.13 appears in the traceback). The asyncio _run_once → popleft() race is more readily triggered on 3.13; several of us had previously pinned a locally-rebuilt Python 3.12 image specifically to reduce this. Shipping 3.13 makes the regression easier to hit.

    Steps To Reproduce

    1. Run ghcr.io/basicmachines-co/basic-memory:0.21.6 against PostgreSQL 17 with pgvector (pgvector/pgvector:pg17).
    2. Set:
      BASIC_MEMORY_DATABASE_BACKEND: postgres
      BASIC_MEMORY_DATABASE_URL: postgresql+asyncpg://USER:PASS@postgres:5432/basic_memory
      BASIC_MEMORY_SKIP_INITIALIZATION_SYNC: "false"   # default
      BASIC_MEMORY_SYNC_CHANGES: "true"                # default — file watcher on
      Launch: basic-memory mcp --transport streamable-http --host 0.0.0.0 --port 8000
    3. docker compose up -d, then watch the server logs.
    4. Within seconds the container goes unhealthy and begins restarting; logs show the traceback below on each boot.

    The crash is timing-dependent (the asyncio _ready deque races with loop teardown), so it may take a couple of restarts to print, but the container does not stay healthy.

    Expected Behavior

    With the default flags (init-sync + watcher enabled), the Postgres-backed server should complete lifespan startup, open/dispose its asyncpg engine cleanly, run the file watcher, and stay healthy — without raising from asyncio._run_once.

    Actual Behavior

    Server enters a restart loop. Representative trailing frames (Python 3.13.13, from the v0.21.6 image):

    asyncio.exceptions.CancelledError
    
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      ...
      File ".../asyncio/base_events.py", line 2046, in _run_once
        handle = self._ready.popleft()
    IndexError: pop from an empty deque
    

    This matches #831's signature (SQLAlchemy async pool dispose → greenlet_spawn → asyncio._run_once → popleft() on an empty _ready deque), confirming #838 did not close this path.

    Environment

    • basic-memory: 0.21.6 (also reproduced on 0.21.1 with flags enabled)
    • Image: ghcr.io/basicmachines-co/basic-memory:0.21.6 (ships Python 3.13.13)
    • OS: Linux (Ubuntu 24.04 host), Docker
    • Database backend: PostgreSQL 17 + pgvector 0.8.2 (pgvector/pgvector:pg17)
    • Driver: postgresql+asyncpg://…
    • Transport: streamable-http
    • Deploy: Docker Compose, two containers (server + postgres)

    Workaround currently in effect (not satisfactory)

    BASIC_MEMORY_SKIP_INITIALIZATION_SYNC: "true"
    BASIC_MEMORY_SYNC_CHANGES: "false"

    This keeps the server up (per-request MCP write_note/search still index synchronously through Postgres + pgvector successfully), but permanently disables the file watcher — files written directly to the markdown store (e.g. via SMB/Obsidian) are never auto-indexed. We are pinned to 0.21.1 with these flags as the last known-good config; dropping the flags on any 0.21.x release we have tried re-introduces the crash.

    Why #838 doesn't cover this

    #838 ("preinitialize local ASGI database") targets the local/sqlite ASGI startup. The Postgres failure is in the asyncpg engine dispose orchestration during lifespan/watcher teardown — a different code path. Closing #831 against #838 left the postgres backend unfixed.

    Suggested fixes (from #831, none yet applied to the postgres engine)

    1. poolclass=NullPool + connect_args={"statement_cache_size": 0} on the async engine — SQLAlchemy's documented mitigation for an async engine whose dispose races with loop teardown; removes the pool-dispose scheduling that races with _run_once.
    2. Optional uvloop event-loop policy (opt-in env var) — uvloop's C scheduler has no self._ready.popleft() path, so this class of crash structurally cannot fire.
    3. Shield engine.dispose() from cancellation on shutdown (cf. Async connections not returned to pool if task is cancelled sqlalchemy/sqlalchemy#8145).
    4. Publish a Python 3.12 image variant (or revert the base to 3.12) for the Postgres backend until the dispose race is fixed — 3.13 makes it materially easier to hit.

    Happy to test a patched image / specific branch against our live Postgres + pgvector stack and report back.

    Related

  4. phernandez commented on Jun 5, 2026

    @phernandez
    Member

    lets reopen this and make sure the postgres side is fixed

  5. bengreeno commented on Jun 5, 2026

    @bengreeno

    This one is impacting me as well. I ended up resetting my DB and switching back to SQLite temporarily. Ultimately, I'd prefer Postgres long-term. I created #877 which may be related.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions