#5321·PraisonAI

src/praisonai wrapper: adapter registry only wired on Python entry point, CLI subcommands bypass AsyncBridge, and scheduler twins drift on delivery-counter lock discipline

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

In-depth review of src/praisonai/praisonai/ against the wrapper philosophy — "lightweight and powerful, protocol-driven, three-way surface (CLI + YAML + Python) must not fork, safe-by-default, no global singletons" — turned up three gaps that ship on main and violate the contract in real deployments. Each is anchored to file:line, validated against the current source, and small enough to land as one PR.

Scope: everything below is inside src/praisonai/praisonai/. No SDK (praisonaiagents) or praisonai-tools changes proposed. Findings here are distinct from — and do not overlap with — the still-open #5065 (private cli_config tool-timeout / capability asymmetry / env-var toggles), #5150 (chat_history bleed / passthrough per-loop pool / availability-cache pin), and #5259 (workflow-generator prompt-injection / pool resurrect after close / _sync_wrapped race).


1. YAML retriever: / reader: / reranker: silently no-op on praisonai <file.yaml>, praisonai serve, and praisonai eval — only praisonai.run() / arun() register the default adapters

The core-SDK retriever/reader/reranker registries (praisonaiagents.knowledge.retrieval.get_retriever_registry(), praisonaiagents.knowledge.rerankers.get_reranker_registry()) start empty except for what the core itself auto-registers (only the built-in simple reranker). Every wrapper-provided adapter (fusion, hybrid, recursive, auto_merge, and every wrapper-owned reader/reranker) has to be wired in explicitly via praisonai.adapters.register_default_adapters().

That wiring is called from exactly two places — both in the Python entry point.

Where

src/praisonai/praisonai/_entrypoint.py:106-127 — praisonai.run(...):

python
from .agents_generator import AgentsGenerator

# Wire the built-in readers/retrievers/rerankers into the core-SDK
# registries so YAML/CLI declarations (e.g. `retriever: fusion`,
# `reranker: llm`) resolve. Idempotent + thread-safe, and register-only-if-
# absent: a custom adapter already registered under a built-in name (e.g. a
# multi-tenant host's own `fusion`) is preserved, never overwritten.
from .adapters import register_default_adapters
register_default_adapters()

_entrypoint.py:150-151 — the arun() twin does the same via asyncio.to_thread.

That is the full call-site inventory:

$ grep -rn "register_default_adapters" src/praisonai/ src/praisonai-code/
src/praisonai/praisonai/_entrypoint.py:108:    from .adapters import register_default_adapters
src/praisonai/praisonai/_entrypoint.py:109:    register_default_adapters()
src/praisonai/praisonai/_entrypoint.py:150:    from .adapters import register_default_adapters
src/praisonai/praisonai/_entrypoint.py:151:    await asyncio.to_thread(register_default_adapters)
src/praisonai/praisonai/adapters/__init__.py:21:def register_default_adapters() -> None:

None of the three other launch surfaces call it. Each constructs AgentsGenerator directly and starts running.

src/praisonai-code/praisonai_code/cli/legacy/praison_ai.py:808-812 — the CLI dispatch behind praisonai <agents.yaml>:

python
AgentsGenerator = _get_agents_generator()
# Extract CLI configuration for YAML CLI parity
cli_config = self._extract_cli_config_for_yaml()
with AgentsGenerator(self.agent_file, self.framework, self.config_list, cli_config=cli_config) as agents_generator:
    result = agents_generator.generate_crew_and_kickoff()

The same pattern repeats at L849, L923, L2437 in that file. No register_default_adapters anywhere.

src/praisonai/praisonai/cli/features/serve.py:316-320 — the FastAPI-hosted request dispatch behind praisonai serve:

python
from praisonai.agents_generator import AgentsGenerator
...
gen = AgentsGenerator(
    ...
)

src/praisonai/praisonai/cli/features/eval.py:78-79, 133-139 — the eval harness:

python
from praisonai.agents_generator import AgentsGenerator
generator = AgentsGenerator(agent_file)

The wiring function itself is safe to call from every path — it is idempotent, thread-safe, and register-only-if-absent (src/praisonai/praisonai/adapters/__init__.py:21-46):

python
def register_default_adapters() -> None:
    global _defaults_registered
    if _defaults_registered:
        return
    with _REGISTRATION_LOCK:
        if _defaults_registered:
            return
        from praisonai.adapters.readers import register_default_readers
        from praisonai.adapters.retrievers import register_default_retrievers
        from praisonai.adapters.rerankers import register_default_rerankers

        register_default_readers()
        register_default_retrievers()
        register_default_rerankers()
        _defaults_registered = True

And the individual registrars preserve any prior binding — see src/praisonai/praisonai/adapters/retrievers.py:593-614:

python
def register_default_retrievers():
    """Register all default retrievers with the registry."""
    from praisonaiagents.knowledge.retrieval import get_retriever_registry

    registry = get_retriever_registry()

    # Preserve any existing entry: an application (or a multi-tenant host) may
    # have already registered a custom retriever under a built-in name. Wiring
    # the wrapper defaults must never silently replace it, so register only
    # names that are not already present.
    existing = set(registry.list_retrievers())
    for name, factory in (
        ("basic", BasicRetriever),
        ("fusion", FusionRetriever),
        ("recursive", RecursiveRetriever),
        ("auto_merge", AutoMergeRetriever),
        ("hybrid", HybridRetriever),
    ):
        if name not in existing:
            registry.register(name, factory)

Why this is a real bug

The stated philosophy is "every feature runs 3 ways: CLI, YAML, Python". retriever: / reader: / reranker: fields in an agents.yaml today do not: they resolve on the Python surface and silently fall back on the CLI, serve, and eval surfaces. There is no warning, no strict-mode gate, no config diff — the run produces different answers because a different retriever backed it.

The comment above the sole two call sites (_entrypoint.py:107) explicitly names YAML/CLI declarations (retriever: fusion, reranker: llm) as the reason for the wiring — but the CLI is exactly the surface that never fires it.

Concrete failure scenario

agents.yaml:

yaml
framework: praisonai
knowledge:
  retriever: fusion         # wrapper-owned; only exists once register_default_adapters ran
  reranker: llm
roles:
  researcher:
    role: Researcher
    tasks:
      research:
        description: "Summarise the corpus on {topic}"
  1. python -c "from praisonai import run; run('agents.yaml', topic='oncology')" — _entrypoint.run() calls register_default_adapters(); fusion resolves; retrieval produces reciprocal-rank-fusion results.
  2. Same file, run via praisonai agents.yaml (or POSTed to praisonai serve /agents/{name}/kickoff, or scored by praisonai eval) — AgentsGenerator is constructed directly; fusion is unknown to the core registry; retrieval falls back to whatever the core's default is (or raises deep inside praisonaiagents.knowledge.retrieval.build_retriever). Answers differ; the diff is completely invisible from the YAML.

The wrapper already fails fast on the analogous parity issue for cli_backend and tool_timeout (agents_generator.py:1587-1594, _validate_cli_backend_compatibility, agents_generator.py:1308-1330, _validate_adapter_cli_capabilities) — adapter-registry wiring is the same class of parity concern and should be enforced the same way.

Suggested fix

Move the call into AgentsGenerator so every launch path is covered by construction, and delete the now-redundant call sites in _entrypoint.py. The function is already idempotent + thread-safe, so the two current callers hit the fast path.

python
# src/praisonai/praisonai/agents_generator.py — at the top of __init__ (or
# at the start of generate_crew_and_kickoff / agenerate_crew_and_kickoff)
class AgentsGenerator:
    def __init__(self, agent_file, framework, config_list, ...):
        # Wire the built-in readers/retrievers/rerankers into the core-SDK
        # registries so YAML `retriever:` / `reader:` / `reranker:` declarations
        # resolve identically on every launch path (CLI, serve, eval, Python).
        # Idempotent + register-only-if-absent; safe to call more than once.
        from .adapters import register_default_adapters
        register_default_adapters()
        ...

Then delete _entrypoint.py:108-109 and _entrypoint.py:150-151 — the wiring is now single-sourced through AgentsGenerator, matching the pattern the tool-timeout executor and the framework-adapter resolution already follow.

Backward compat is preserved because the function is documented as idempotent (adapters/__init__.py:21-46); user code that pre-wires the registry before constructing a generator still works — the second call sees _defaults_registered=True and returns immediately.

Add a regression test that constructs an AgentsGenerator without going through praisonai.run() and asserts praisonai.adapters._defaults_registered is True afterwards (and, more usefully, that get_retriever_registry().list_retrievers() contains fusion).

Validation

  • Grep across src/praisonai/ and src/praisonai-code/ confirms register_default_adapters is called only from _entrypoint.py (two hits, run and arun).
  • Read of praisonai_code/cli/legacy/praison_ai.py:808-2437, cli/features/serve.py:316-320, and cli/features/eval.py:78-193 confirms every non-Python launch surface constructs AgentsGenerator directly.
  • Read of praisonai-agents/praisonaiagents/knowledge/retrieval.py:100-148 and .../rerankers.py:200 confirms the core-side registries start effectively empty for wrapper-owned entries.
  • register_default_adapters at adapters/__init__.py:21-46 is idempotent under a lock and register-only-if-absent, so the second call from the current _entrypoint.py sites is a no-op after the move.

2. Ten wrapper CLI subcommands call asyncio.run(...) per invocation and completely bypass the shared AsyncBridge — every call thrashes a fresh loop, defeats per-loop pool reuse, and skips any embedder-installed scoped_bridge() isolation

praisonai/_async_bridge.py:1-7 is explicit about its purpose:

python
"""
Async bridge module - single source of truth for running coroutines synchronously.

This module provides a safe way to run async functions from sync contexts,
handling nested event loop scenarios without creating a new event loop
on every call (which is expensive and breaks multi-agent workflows).
"""

And capabilities/passthrough.py:37-58 names the exact failure mode asyncio.run() produces on a wrapper-cached async client:

python
def _get_async_client() -> Any:
    """Return the shared async httpx client for the running event loop.

    ``httpx.AsyncClient`` binds its connection pool to the event loop that first
    used it, so a client cached across separate ``asyncio.run()`` lifecycles (or
    reused from a different loop) fails with a loop-closed error. We therefore
    key the cached client to its owning loop and rebuild it whenever the current
    loop differs from the one that created it.
    """

That per-loop rebuild is a symptom-level mitigation; the root cause — that the wrapper's own CLI subcommands spawn a fresh loop per invocation — is unfixed.

Where

$ grep -rn "asyncio.run(" src/praisonai/praisonai/ | grep -v "^\s*#" | grep -v capabilities/passthrough.py
src/praisonai/praisonai/cli/commands/managed.py:728
src/praisonai/praisonai/cli/commands/managed.py:842
src/praisonai/praisonai/cli/commands/standardise.py:512
src/praisonai/praisonai/cli/features/background.py:304
src/praisonai/praisonai/cli/features/background.py:307
src/praisonai/praisonai/cli/features/background.py:310
src/praisonai/praisonai/cli/features/background.py:313
src/praisonai/praisonai/cli/features/sandbox_cli.py:112
src/praisonai/praisonai/cli/features/sandbox_cli.py:189
src/praisonai/praisonai/cli/legacy/direct_prompt.py:876
src/praisonai/praisonai/cli/legacy/interactive_legacy.py:1618
src/praisonai/praisonai/cli/legacy/interactive_legacy.py:1625
src/praisonai/praisonai/cli/legacy/interactive_legacy.py:1627
src/praisonai/praisonai/acp/server.py:668
src/praisonai/praisonai/integrations/compute_managed_agent.py:272

Representative sites:

src/praisonai/praisonai/cli/features/background.py:300-313 — a single praisonai background <subcmd> invocation spawns a fresh loop per branch:

python
handler = BackgroundHandler(verbose=verbose)

try:
    if parsed.subcommand == "list":
        asyncio.run(handler.list_tasks(status=parsed.status))
    elif parsed.subcommand == "status":
        asyncio.run(handler.get_status(parsed.task_id))
    elif parsed.subcommand == "cancel":
        asyncio.run(handler.cancel_task(parsed.task_id))
    elif parsed.subcommand == "clear":
        asyncio.run(handler.clear_completed())

src/praisonai/praisonai/cli/legacy/interactive_legacy.py:1616-1627 — three separate asyncio.run() calls in the interactive /tasks slash-command handler alone:

python
if not args:
    asyncio.run(handler.list_tasks())
elif args.lower().startswith("cancel"):
    parts = args.split(maxsplit=1)
    ...
    asyncio.run(handler.cancel_task(task_id))
else:
    asyncio.run(handler.get_status(args))

src/praisonai/praisonai/cli/commands/managed.py:836-842 — one loop per row when shutting down N managed instances:

python
for name, info in rows:
    try:
        asyncio.run(resolve_compute(name).shutdown(info.instance_id))

For contrast, agents_generator.py:1420-1439 already does it right — the sync run path opens a scoped_bridge() and routes the adapter through the shared bridge so a stuck coroutine in one tenant does not park the shared loop for the rest:

python
from ._async_bridge import scoped_bridge
with observability_session(prep['adapter'].name):
    self._run_adapter_setup(prep['adapter'])
    # Isolate this sync run's sync→async work (adapter internals call
    # run_sync) onto its own loop+thread so a stuck coroutine in one
    # agent/tenant does not park the shared default loop for the rest.
    with scoped_bridge():
        return prep['adapter'].run(...)

run_sync_or_offload (_async_bridge.py:387-487) is the exact primitive the CLI subcommands should be using — sync context → shared background loop, async context → hard-fail unless the caller opted in via PRAISONAI_ALLOW_LOOP_BLOCKING. That's precisely the safety guarantee asyncio.run(...) at a CLI leaf skips.

Why this is a real bug

  1. Loop-closed HTTP client — praisonai background list inside a shell loop, or the /tasks REPL slash-command inside an already-running praisonai chat, tears down and rebuilds any per-loop async client (or SDK-owned pool). The passthrough._get_async_client mitigation only covers its own module; every other wrapper module that transitively holds a per-loop httpx.AsyncClient / aiohttp.ClientSession / cloud-SDK client is subject to RuntimeError: Event loop is closed on the next call.
  2. Per-loop resource leaks — praisonai managed stop over 20 rows creates 20 fresh event loops, 20 fresh SDK client instances, and 20 fresh connection pools. In an E2B / Modal / GCP-heavy backend, the SDK's own connection reuse is completely defeated.
  3. scoped_bridge() isolation is bypassed — an embedder / server host that wraps a request in scoped_bridge() (a multi-tenant praisonai serve deployment, or a gateway that isolates per-tenant loops) has no way to force the CLI's asyncio.run(...) sites to participate. The tenant isolation the bridge advertises is defeated at the CLI leaf.
  4. REPL loop churn — interactive_legacy.py:1618-1627 runs in the same process as a live praisonai chat. The bridge is already alive from the outer session; each /tasks slash-command stops and restarts a different loop instead of re-entering the shared one.

Concrete failure scenario

$ for i in $(seq 1 100); do praisonai background list; done   # a supervisor healthcheck

Any wrapper module that lazily caches an httpx.AsyncClient on first use — or any cloud SDK whose transport binds to the loop that first constructed it — sees the client's loop close underneath it on iteration N and raises RuntimeError: Event loop is closed on iteration N+1. The user files a "flaky background list" bug; nothing in the wrapper points at asyncio.run() as the cause.

Interactive variant: a user opens praisonai chat, runs /tasks list (fresh loop), then /tasks status <id> (another fresh loop) — the second call has no shared HTTP pool, no shared DB connection, no shared bridge state.

Suggested fix

Introduce a single wrapper in _async_bridge.py and mechanically migrate the 10 sites:

python
# src/praisonai/praisonai/_async_bridge.py
def run_cli_coro(coro, *, timeout: float | None = None) -> Any:
    """Preferred CLI-command entry point. Routes through the shared
    AsyncBridge so per-loop connection pools survive across calls, any
    embedder-installed scoped_bridge() is honoured, and a nested loop
    raises loudly instead of spawning a second one.

    Sync context  -> run_sync(coro, timeout=timeout) on the shared loop.
    Async context -> RuntimeError; caller must `await coro` directly.
    """
    import asyncio
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return run_sync(coro, timeout=timeout)
    raise RuntimeError(
        "run_cli_coro() cannot be called from within a running event loop; "
        "await the coroutine directly instead."
    )

Then migrate each site mechanically. For background.py:

python
# Before
if parsed.subcommand == "list":
    asyncio.run(handler.list_tasks(status=parsed.status))

# After
from praisonai._async_bridge import run_cli_coro
if parsed.subcommand == "list":
    run_cli_coro(handler.list_tasks(status=parsed.status))

interactive_legacy.py's three sites (L1618, L1625, L1627) get the same substitution — this is important because the outer praisonai chat already has a scoped_bridge() on the stack, so each slash-command run_cli_coro(...) re-enters the same bridge instead of restarting a fresh loop.

Migration path is drop-in: run_sync already has a 300s configurable timeout, closes cancelled futures, and preserves the shared background loop across calls. No public API surface changes; only internal call sites move.

Add a CI grep gate akin to the existing scripts/check_c7_imports.sh that fails on any new asyncio.run( under src/praisonai/praisonai/cli/, with an allow-list for the one intentional legacy CLI entrypoint (acp/server.py:668, if kept) marked with a comment.

Validation

  • Grep across src/praisonai/praisonai/ finds 15 uncommented asyncio.run( sites (10 under cli/, 3 under acp/integrations, 2 under capabilities/api where the second is a comment). api/agent_invoke.py:823 is the sole commented-out reference.
  • Read of _async_bridge.py:1-7,365-487 confirms the bridge is documented as the single source of truth and provides both run_sync and run_sync_or_offload.
  • Read of capabilities/passthrough.py:20-77 confirms the wrapper already documents the per-loop httpx.AsyncClient failure asyncio.run() produces, and that close_clients() at L61-77 explicitly accepts the async-client leak as a residual it cannot fix from a sync helper (which the CLI-leaf asyncio.run() pattern is).
  • Read of agents_generator.py:1420-1439 confirms the shape of the correct fix — scoped_bridge() + run_sync — is already established in the wrapper's own hot path.

3. AgentScheduler and AsyncAgentScheduler are twinned 720/825-line files with a 973-line dif