Wrapper gaps: shared/unbounded voice rate-limit state, PersistenceOrchestrator.close() leaks stores + no aclose, and compute-agent finalizer pins the event loop
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
# 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()# 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] = windowThe 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
- Unbounded memory.
client_ipsis adefaultdict(list); each new client IP creates an entry that never gets deleted (only the list values are pruned toRATE_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/64prefixes per session — grows this dict without bound until RSS OOMs. - Cross-tenant state. A SaaS host running two tenants via
build_call_app()under the same Uvicorn: tenant A's 5 concurrent calls exhaustMAX_CONCURRENT_CONNECTIONSand tenant B's callers are rejected with1013 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:
# 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 windowhandle_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
# 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:
- Unguarded sequential close. If
self.conversation.close()raises (typical when a network-backed backend has already been drained at shutdown),self.knowledgeandself.stateare never closed — their pooled DB / Qdrant / Redis connections leak. Fields are never reset toNone, so a re-close hits the same failing store first and skips the others again. - 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 noaclose().self._sync()(line 108) routes throughrun_sync_or_offload, which by design raisesRuntimeErrorwhen called from a running event loop unlessPRAISONAI_ALLOW_LOOP_BLOCKING=true(_async_bridge.py:422–438). A FastAPIlifespan/ 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
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
# 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:
- 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 longprovider.shutdown()takes — typically hundreds of ms to multiple seconds for E2B / Modal / Fly — which is exactly the "one stuck tenant stalls every other tenant" pathologyAsyncBridgewas written to prevent (_async_bridge.py:418–421). - Fresh loop per teardown, per thread.
asyncio.run(_shutdown())inside a one-shot executor builds a brand-newasyncio.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 raiseRuntimeError: attached to a different loopor leak its transport. The module already ships anAsyncBridge(single shared background loop; nevernew_event_loop()per call) — but_releasebypasses it. - Interpreter-shutdown reliability.
weakref.finalizealso runs at interpreter exit, when new threads can be refused withRuntimeError: can't start new threadandasyncio.runmay refuse to spin a loop. Every such failure is swallowed as alogger.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:
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;CallAppStatedocstring 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; noaclosepresent;_sync()at 108–125.src/praisonai/praisonai/_async_bridge.py— the "never block a running loop unlessPRAISONAI_ALLOW_LOOP_BLOCKING=true" contract at 418–438; shared-bridgesubmit()at 148–156;current_bridge()at 267.src/praisonai/praisonai/integrations/compute_managed_agent.py—_releaseat 251–282;weakref.finalizeregistration at 209–211; cloud-reaper comment at 205–208.
Generated with Claude Code
Source: MervinPraison/PraisonAI