mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-05-22 00:23:38 +00:00
Finish Phase 2 of the config refactor: production code no longer calls AppConfig.current() anywhere. AppConfig now flows as an explicit parameter down every consumer lane. Call-site migrations -------------------- - Memory subsystem (queue/updater/storage): MemoryConfig captured at enqueue time so the Timer closure survives the ContextVar boundary. - Sandbox layer: tools.py, security.py, sandbox_provider.py, local_sandbox_provider, aio_sandbox_provider all take app_config explicitly. Module-level caching in tools.py's path helpers is removed — pure parameter flow. - Skills layer: manager.py + loader.py + lead_agent.prompt cache refresh all thread app_config; cache worker closes over it. - Community tools (tavily, jina, firecrawl, exa, ddg, image_search, infoquest, aio_sandbox): read runtime.context.app_config. - Subagents registry: get_subagent_config / list_subagents / get_available_subagent_names require app_config. - Runtime worker: requires RunContext.app_config; no fallback. - Gateway routers (uploads, skills): add Depends(get_config). - Channels feishu: uses AppConfig.from_file() (pure) at its sync boundary. - LangGraph Server bootstrap (make_lead_agent): falls back to AppConfig.from_file() — pure load, not ambient lookup. Context resolution ------------------ - resolve_context(runtime) now raises on non-DeerFlowContext runtime.context. Every entry point attaches typed context; dict/None shapes are rejected loudly instead of being papered over with an ambient AppConfig lookup. AppConfig lifecycle ------------------- - AppConfig.current() kept as a deprecated slot that raises RuntimeError, purely so legacy tests that still run `patch.object(AppConfig, "current")` don't trip AttributeError at teardown. Production never calls it. - conftest autouse fixture no longer monkey-patches `current` — it only stubs `from_file()` so tests don't need a real config.yaml. Design refs ----------- - docs/plans/2026-04-12-config-refactor-plan.md (Phase 2: P2-6..P2-10) - docs/plans/2026-04-12-config-refactor-design.md §8 All 2338 non-e2e tests pass. Zero AppConfig.current() call sites remain in backend/packages or backend/app (docstrings in deps.py excepted).
158 lines
5.2 KiB
Python
158 lines
5.2 KiB
Python
"""Async checkpointer factory.
|
|
|
|
Provides an **async context manager** for long-running async servers that need
|
|
proper resource cleanup.
|
|
|
|
Supported backends: memory, sqlite, postgres.
|
|
|
|
Usage (e.g. FastAPI lifespan)::
|
|
|
|
from deerflow.runtime.checkpointer.async_provider import make_checkpointer
|
|
|
|
async with make_checkpointer() as checkpointer:
|
|
app.state.checkpointer = checkpointer # InMemorySaver if not configured
|
|
|
|
For sync usage see :mod:`deerflow.runtime.checkpointer.provider`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import logging
|
|
from collections.abc import AsyncIterator
|
|
|
|
from langgraph.types import Checkpointer
|
|
|
|
from deerflow.config.app_config import AppConfig
|
|
from deerflow.runtime.checkpointer.provider import (
|
|
POSTGRES_CONN_REQUIRED,
|
|
POSTGRES_INSTALL,
|
|
SQLITE_INSTALL,
|
|
)
|
|
from deerflow.runtime.store._sqlite_utils import ensure_sqlite_parent_dir, resolve_sqlite_conn_str
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Async factory
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def _async_checkpointer(config) -> AsyncIterator[Checkpointer]:
|
|
"""Async context manager that constructs and tears down a checkpointer."""
|
|
if config.type == "memory":
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
yield InMemorySaver()
|
|
return
|
|
|
|
if config.type == "sqlite":
|
|
try:
|
|
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
|
except ImportError as exc:
|
|
raise ImportError(SQLITE_INSTALL) from exc
|
|
|
|
conn_str = resolve_sqlite_conn_str(config.connection_string or "store.db")
|
|
await asyncio.to_thread(ensure_sqlite_parent_dir, conn_str)
|
|
async with AsyncSqliteSaver.from_conn_string(conn_str) as saver:
|
|
await saver.setup()
|
|
yield saver
|
|
return
|
|
|
|
if config.type == "postgres":
|
|
try:
|
|
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
|
except ImportError as exc:
|
|
raise ImportError(POSTGRES_INSTALL) from exc
|
|
|
|
if not config.connection_string:
|
|
raise ValueError(POSTGRES_CONN_REQUIRED)
|
|
|
|
async with AsyncPostgresSaver.from_conn_string(config.connection_string) as saver:
|
|
await saver.setup()
|
|
yield saver
|
|
return
|
|
|
|
raise ValueError(f"Unknown checkpointer type: {config.type!r}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public async context manager
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def _async_checkpointer_from_database(db_config) -> AsyncIterator[Checkpointer]:
|
|
"""Async context manager that constructs a checkpointer from unified DatabaseConfig."""
|
|
if db_config.backend == "memory":
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
yield InMemorySaver()
|
|
return
|
|
|
|
if db_config.backend == "sqlite":
|
|
try:
|
|
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
|
except ImportError as exc:
|
|
raise ImportError(SQLITE_INSTALL) from exc
|
|
|
|
conn_str = db_config.checkpointer_sqlite_path
|
|
ensure_sqlite_parent_dir(conn_str)
|
|
async with AsyncSqliteSaver.from_conn_string(conn_str) as saver:
|
|
await saver.setup()
|
|
yield saver
|
|
return
|
|
|
|
if db_config.backend == "postgres":
|
|
try:
|
|
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
|
except ImportError as exc:
|
|
raise ImportError(POSTGRES_INSTALL) from exc
|
|
|
|
if not db_config.postgres_url:
|
|
raise ValueError("database.postgres_url is required for the postgres backend")
|
|
|
|
async with AsyncPostgresSaver.from_conn_string(db_config.postgres_url) as saver:
|
|
await saver.setup()
|
|
yield saver
|
|
return
|
|
|
|
raise ValueError(f"Unknown database backend: {db_config.backend!r}")
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def make_checkpointer(app_config: AppConfig) -> AsyncIterator[Checkpointer]:
|
|
"""Async context manager that yields a checkpointer for the caller's lifetime.
|
|
Resources are opened on enter and closed on exit -- no global state::
|
|
|
|
async with make_checkpointer(app_config) as checkpointer:
|
|
app.state.checkpointer = checkpointer
|
|
|
|
Yields an ``InMemorySaver`` when no checkpointer is configured in *config.yaml*.
|
|
|
|
Priority:
|
|
1. Legacy ``checkpointer:`` config section (backward compatible)
|
|
2. Unified ``database:`` config section
|
|
3. Default InMemorySaver
|
|
"""
|
|
|
|
# Legacy: standalone checkpointer config takes precedence
|
|
if app_config.checkpointer is not None:
|
|
async with _async_checkpointer(app_config.checkpointer) as saver:
|
|
yield saver
|
|
return
|
|
|
|
# Unified database config
|
|
db_config = getattr(app_config, "database", None)
|
|
if db_config is not None and db_config.backend != "memory":
|
|
async with _async_checkpointer_from_database(db_config) as saver:
|
|
yield saver
|
|
return
|
|
|
|
# Default: in-memory
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
yield InMemorySaver()
|