Skip to content

Bug: asyncio.run() in __del__ causes RuntimeError crash in production #154

@bleedblack1

Description

@bleedblack1

The AgentGraph.__del__ method in src/agent/graph.py uses asyncio.run() to clean up the PostgreSQL connection pool. This crashes every time in Chainlit/uvicorn because asyncio.run() cannot be called when an event loop is already running.

Bug Location

File: src/agent/graph.py
Lines: 28-30

def __del__(self) -> None:
    if self.pool:
        asyncio.run(self.close_pool())  #  CRASH

Error Message

RuntimeError: asyncio.run() cannot be called from a running event loop

Why This Happens

  1. asyncio.run() creates a new event loop — but it fails if one is already running
  2. Chainlit/uvicorn always have an active event loop — so this always crashes
  3. __del__ is unreliable — Python doesn't guarantee when or if it runs
  4. During interpreter shutdown — the event loop may already be closed

Impact

Impact Severity
Production crashes on server shutdown Critical
Connection pool leaks if cleanup fails High
Affects all deployments using PostgreSQL checkpointing Critical

Secondary Issue

The LANGGRAPH_DB_URI is constructed at module import time even when environment variables are None:

LANGGRAPH_DB_URI = f"postgresql://{os.getenv('POSTGRES_USER')}:{os.getenv('POSTGRES_PASSWORD')}@postgres:5432/{os.getenv('POSTGRES_LANGGRAPH_DB')}?sslmode=disable"

This creates a malformed URI like postgresql://None:None@postgres:5432/None?sslmode=disable.

Proposed Solution

  1. Remove __del__ — eliminates the crash entirely
  2. Add async context manager__aenter__/__aexit__ for proper cleanup
  3. Add explicit close() method — idempotent, safe to call multiple times
  4. Lazy URI construction — build URI only when needed, with validation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions