Repository navigation
Description
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:
- 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://...). - Run a one-shot CLI command, e.g.:
basic-memory project list - 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_SYNCis nottrue). - In-process file watcher (
BASIC_MEMORY_SYNC_CHANGES=true), whenwatchfiles.awatchrunsSyncServiceagainst 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=trueBASIC_MEMORY_SYNC_CHANGES=false- Manual
basic-memory syncinvoked 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.
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.- Optionally support
uvloopas 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. - 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
MakksSh commentedon May 18, 2026
Same problem!
Windows 10. WSL and base windows. Installed from uv tool add.
Version 0.21.1
SW4T400 commentedon Jun 5, 2026
@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
/home/stefa/pythoncode/github_clones/systematic_data/scr/systematic_data/basic_memory/SETUP_LOG_2026_05_15.md→ section "Upgrade attempts log → 2026-06-05"docker-compose.yml(reverted to0.21.1+ workaround flags)notes/infra/basic-memory/basic-memory-v0.21.6-upgrade-tested-reverted...0.21.1 → 0.21.6, dropped both workaround flags, observed crash, reverted. Notes + Postgres volume untouched.Bug Description
The
IndexError: pop from an empty dequestartup/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.6container 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.6image now ships Python 3.13 (cpython-3.13.13appears 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
ghcr.io/basicmachines-co/basic-memory:0.21.6against PostgreSQL 17 with pgvector (pgvector/pgvector:pg17).basic-memory mcp --transport streamable-http --host 0.0.0.0 --port 8000docker compose up -d, then watch the server logs.unhealthyand begins restarting; logs show the traceback below on each boot.The crash is timing-dependent (the asyncio
_readydeque 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 fromasyncio._run_once.Actual Behavior
Server enters a restart loop. Representative trailing frames (Python 3.13.13, from the v0.21.6 image):
This matches #831's signature (SQLAlchemy async pool dispose →
greenlet_spawn→asyncio._run_once→popleft()on an empty_readydeque), confirming #838 did not close this path.Environment
ghcr.io/basicmachines-co/basic-memory:0.21.6(ships Python 3.13.13)pgvector/pgvector:pg17)postgresql+asyncpg://…Workaround currently in effect (not satisfactory)
This keeps the server up (per-request MCP
write_note/searchstill 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)
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.self._ready.popleft()path, so this class of crash structurally cannot fire.engine.dispose()from cancellation on shutdown (cf. Async connections not returned to pool if task is cancelled sqlalchemy/sqlalchemy#8145).Happy to test a patched image / specific branch against our live Postgres + pgvector stack and report back.
Related
CancelledErrortraceback on CLI exit — same asyncpg teardown family)phernandez commentedon Jun 5, 2026
lets reopen this and make sure the postgres side is fixed
bengreeno commentedon Jun 5, 2026
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.
fix(core): run local Postgres startup migrations under uvloop
fix(core): install uvloop on the hook path before async work (PR #1070 …