#5347·PraisonAI

Wrapper gaps: shared/unbounded voice rate-limit state, PersistenceOrchestrator.close() leaks stores + no aclose, and compute-agent finalizer pins the event loop

Author: MervinPraisonCreated Sep 28, 2026Updated Sep 28, 2026
Labelsbugdocumentationclaude

Three validated correctness/robustness gaps in src/praisonai/praisonai/ — all read against the current tree and cross-checked against sibling code in the same package. Each one has a concrete user-visible failure mode and a minimal fix.

Scope note: these are wrapper-tier issues (per ARCHITECTURE.md §2). None require API changes to the core SDK, and none add new dependencies.


1. Voice-call rate limiter uses process-wide module globals — unbounded memory + broken multi-tenant isolation

File: src/praisonai/praisonai/api/call.py Lines: 96–103 (module globals), 480–491 (rate-limit path), 493–499 & 572–574 (connection cap)

Current problematic code

python
# call.py:96–103 — module-level, shared across every app built in this process
active_connections = 0
client_ips = defaultdict(list)

_conn_lock = asyncio.Lock()
_ips_lock = asyncio.Lock()
python
# call.py:480–491 — inside handle_media_stream()
client_ip = websocket.client.host if websocket.client else "unknown"
now = time.time()
async with _ips_lock:
    window = [t for t in client_ips[client_ip] if now - t < RATE_LIMIT_WINDOW]
    if len(window) >= MAX_REQUESTS_PER_WINDOW:
        client_ips[client_ip] = window
        await websocket.close(code=4029, reason="Rate limit exceeded")
        return
    window.append(now)
    client_ips[client_ip] = window

The file already introduces CallAppState (line 111) specifically so "co-hosted / multi-tenant build_call_app() instances in one process never share a tool schema or cross-consume each other's stream tokens" (docstring at lines 115–118). But the four rate-limit / capacity primitives above never moved off the module, so tenant A's traffic keeps eating tenant B's budget.

Failure scenario

  1. Unbounded memory. client_ips is a defaultdict(list); each new client IP creates an entry that never gets deleted (only the list values are pruned to RATE_LIMIT_WINDOW=3600s; the key stays with an empty list). Worse, defaultdict.__getitem__ at line 485 creates an empty entry on any read. A caller behind rotating IPv6 addresses — mobile carriers commonly rotate /64 prefixes per session — grows this dict without bound until RSS OOMs.
  2. Cross-tenant state. A SaaS host running two tenants via build_call_app() under the same Uvicorn: tenant A's 5 concurrent calls exhaust MAX_CONCURRENT_CONNECTIONS and tenant B's callers are rejected with 1013 Server busy — exactly the isolation contract the file's docstring already claims.

Proposed fix

Move all four primitives onto CallAppState, sized/pruned by construction, and read them from websocket.app.state:

python
# api/call.py
from collections import OrderedDict

class CallAppState:
    __slots__ = ("tools", "pending_sessions", "_lock",
                 "active_connections", "conn_lock",
                 "client_ips", "ips_lock", "max_ips")

    def __init__(self, max_tracked_ips: int = 10_000):
        self.tools: list = []
        self.pending_sessions: "dict[str, float]" = {}
        self._lock = threading.Lock()
        self.active_connections = 0
        self.conn_lock = asyncio.Lock()
        self.client_ips: "OrderedDict[str, list[float]]" = OrderedDict()
        self.ips_lock = asyncio.Lock()
        self.max_ips = max_tracked_ips

    def touch_ip(self, ip: str, now: float) -> list[float]:
        # LRU-bounded; empty entries are dropped so the dict cannot grow forever.
        window = [t for t in self.client_ips.get(ip, ()) if now - t < RATE_LIMIT_WINDOW]
        if window:
            self.client_ips[ip] = window
            self.client_ips.move_to_end(ip)
        else:
            self.client_ips.pop(ip, None)
        while len(self.client_ips) > self.max_ips:
            self.client_ips.popitem(last=False)
        return window

handle_media_stream() then uses websocket.app.state.call_state.ips_lock / .client_ips / .conn_lock / .active_connections — the same app-owned pattern already used for state.tools and state.pending_sessions.

Aligns with the existing multi-tenant contract, puts a hard bound on rate-limiter memory, and adds no dependency or hot-path cost.


2. PersistenceOrchestrator.close() leaks sibling stores on first exception and has no async counterpart

File: src/praisonai/praisonai/persistence/orchestrator.py Lines: 736–747 (compare with db/adapter.py PraisonAIDB.aclose() / close() which isolates per-store errors)

Current problematic code

python
# persistence/orchestrator.py:736–747
def close(self) -> None:
    """Close all stores and release resources."""
    if self.conversation:
        self._sync(self.conversation.close())
    if self.knowledge:
        self._sync(self.knowledge.close())
    if self.state:
        self._sync(self.state.close())

    # Clear cache using thread-safe method
    self._cache_clear()
    logger.info("Persistence orchestrator closed")

Two real defects:

  1. Unguarded sequential close. If self.conversation.close() raises (typical when a network-backed backend has already been drained at shutdown), self.knowledge and self.state are never closed — their pooled DB / Qdrant / Redis connections leak. Fields are never reset to None, so a re-close hits the same failing store first and skips the others again.
  2. No async close. The orchestrator ships a full async surface (aon_agent_start, aon_message, aon_agent_end, aretrieve_knowledge, aadd_knowledge — lines 343, 436, 480, 570, 605) but no aclose(). self._sync() (line 108) routes through run_sync_or_offload, which by design raises RuntimeError when called from a running event loop unless PRAISONAI_ALLOW_LOOP_BLOCKING=true (_async_bridge.py:422–438). A FastAPI lifespan / async agent shutdown handler therefore has no clean way to close the orchestrator.

Failure scenario

An AgentOS / FastAPI deployment terminates. The Postgres conversation store's close() raises because its pool was already stopped by the LB drain; the orchestrator's close() propagates the exception and the Qdrant knowledge + Redis state stores keep their connections open. Repeated redeployments exhaust the DB pool / file descriptors. Separately, an async lifespan calling close() gets RuntimeError("run_sync_or_offload() would block the running event loop…") and nothing is closed.

Proposed fix

python
import asyncio, inspect

def close(self) -> None:
    """Close all stores; per-store errors are isolated so one bad store never
    strands the others' connections. Idempotent."""
    for attr in ("conversation", "knowledge", "state"):
        store = getattr(self, attr, None)
        if store is None:
            continue
        try:
            self._sync(store.close())
        except Exception:
            logger.exception("Error closing %s store", attr)
        finally:
            setattr(self, attr, None)
    self._cache_clear()
    logger.info("Persistence orchestrator closed")

async def aclose(self) -> None:
    """Async close for FastAPI lifespans / async agents — never blocks the loop."""
    for attr in ("conversation", "knowledge", "state"):
        store = getattr(self, attr, None)
        if store is None:
            continue
        try:
            close_fn = getattr(store, "aclose", None) or store.close
            if inspect.iscoroutinefunction(close_fn):
                await close_fn()
            else:
                await asyncio.to_thread(close_fn)
        except Exception:
            logger.exception("Error async-closing %s store", attr)
        finally:
            setattr(self, attr, None)
    self._cache_clear()

async def __aexit__(self, *exc):
    await self.aclose()

Restores the async-safe pillar (no store silently left open by a peer's error, no hidden RuntimeError at shutdown) and matches the pattern the sibling PraisonAIDB adapter already uses.


3. compute_managed_agent._release pins the event loop for the whole cloud-shutdown round-trip and spawns a fresh loop per teardown

File: src/praisonai/praisonai/integrations/compute_managed_agent.py Lines: 251–282 (registered via weakref.finalize(self, _release, …) at line 209)

Current problematic code

python
# integrations/compute_managed_agent.py:251–282
def _release(provider, instance_id: str, place: str) -> None:
    import asyncio
    async def _shutdown():
        await provider.shutdown(instance_id)
    try:
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            asyncio.run(_shutdown())
        else:
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
                pool.submit(asyncio.run, _shutdown()).result()
        logger.debug("[compute_managed] released %s on %s", instance_id, place)
    except Exception as exc:
        logger.warning("[compute_managed] could not release %s on %s: %s", instance_id, place, exc)

The docstring correctly identifies the "GC on the loop thread" hazard, but the fix reintroduces three regressions the wrapper explicitly forbids:

  1. Pins the event loop for a cloud round trip. pool.submit(asyncio.run, _shutdown()).result() is a synchronous .result() on the loop thread. Every GC-triggered release stalls the loop for however long provider.shutdown() takes — typically hundreds of ms to multiple seconds for E2B / Modal / Fly — which is exactly the "one stuck tenant stalls every other tenant" pathology AsyncBridge was written to prevent (_async_bridge.py:418–421).
  2. Fresh loop per teardown, per thread. asyncio.run(_shutdown()) inside a one-shot executor builds a brand-new asyncio.new_event_loop() and discards it, along with the thread. If the provider's client (httpx.AsyncClient, aiohttp.ClientSession, an async DB pool) was created on another loop, calling .shutdown() from this fresh loop can raise RuntimeError: attached to a different loop or leak its transport. The module already ships an AsyncBridge (single shared background loop; never new_event_loop() per call) — but _release bypasses it.
  3. Interpreter-shutdown reliability. weakref.finalize also runs at interpreter exit, when new threads can be refused with RuntimeError: can't start new thread and asyncio.run may refuse to spin a loop. Every such failure is swallowed as a logger.warning(...) — leaving a billable cloud instance running with no other reaper (comment at lines 205–208 confirms Docker/Fly have no idle reaper).

Failure scenario

A user runs an async workflow that constructs multiple ComputeManagedAgent backends (E2B + Modal + Fly). Backends fall out of reference during the run; GC on the loop thread fires _release, freezing every other in-flight tool call for the duration of each cloud shutdown. Separately, on SIGTERM during a rolling deploy, several finalizers fail to spawn threads → 3 billed cloud instances are silently left running, surfaced only as WARNING log lines lost with the process.

Proposed fix

Route through the module's existing shared bridge — which never allocates a fresh loop and never blocks a running one — and make the wait non-blocking:

python
def _release(provider, instance_id: str, place: str) -> None:
    """Reclaim an instance without pinning the caller's event loop or building
    a throwaway event loop per teardown."""
    from praisonai._async_bridge import current_bridge

    async def _shutdown():
        await provider.shutdown(instance_id)

    try:
        fut = current_bridge().submit(_shutdown())
    except RuntimeError:
        # Bridge poisoned / interpreter shutting down.
        logger.warning("[compute_managed] leaked %s on %s (bridge unavailable)",
                       instance_id, place)
        return

    # Fire-and-forget; never call .result() from the caller's thread — that is
    # what pins the loop for the whole cloud round trip.
    def _log_result(f):
        try:
            f.result()
            logger.debug("[compute_managed] released %s on %s", instance_id, place)
        except Exception as exc:
            logger.warning("[compute_managed] could not release %s on %s: %s",
                           instance_id, place, exc)
    fut.add_done_callback(_log_result)

AsyncBridge.submit() already exists (_async_bridge.py:148) and returns a concurrent.futures.Future that supports add_done_callback. If a blocking wait is truly needed at interpreter exit, atexit can wait once for all outstanding release futures instead of blocking on each GC.

Aligns compute-agent teardown with the wrapper's async-safety rule (one shared loop, never new_event_loop() per call), removes a per-GC "pin the loop for a cloud round trip" hazard, and preserves the reclaim guarantee for billed cloud places under interpreter shutdown.


Validation notes

All three findings were read against the current tree at:

  • src/praisonai/praisonai/api/call.py — module globals at 96–103; CallAppState docstring at 115–118 asserting the isolation contract; rate-limit path at 480–491; conn-cap at 493–499 & 572–574.
  • src/praisonai/praisonai/persistence/orchestrator.py — close() at 736–747; async surface at 343/436/480/570/605; no aclose present; _sync() at 108–125.
  • src/praisonai/praisonai/_async_bridge.py — the "never block a running loop unless PRAISONAI_ALLOW_LOOP_BLOCKING=true" contract at 418–438; shared-bridge submit() at 148–156; current_bridge() at 267.
  • src/praisonai/praisonai/integrations/compute_managed_agent.py — _release at 251–282; weakref.finalize registration at 209–211; cloud-reaper comment at 205–208.

Generated with Claude Code

https://claude.ai/code/session_01SP8YpB1FUELVHX1KDk5fRk