deer-flow/backend/app/composition.py
rayhpeng 34ce7c259b refactor(schedule): make the run-completion hook an inbound adapter
`run_outcome_mapping.py` called itself "not a port implementation" and sat in
a package of secondary adapters, while the half that actually invoked the use
case lived as a closure in the composition root. It is one thing, and it is a
primary adapter: the run runtime calls it the way HTTP calls the router and
the clock calls the poller.

`ScheduleRunCompletionListener` now holds the whole responsibility -- decide
whether a finished run is ours, translate it, invoke the use case. Those are
not two jobs: "ignore this run" is only meaningful as "do not call the
service", so splitting them is what left the second half in a place where
behaviour is not asserted.

`build_run_completion_hook` drops to `return
ScheduleRunCompletionListener(service)`. The composition root's own docstring
says no adapter logic lives there; that is now true of it as well as of the
routers it was written about.

Placement
---------
Kept in `app/adapters/schedule/` rather than moved beside the other two
primary adapters. The context stays in one package; direction is stated by
the class name and each module's first line, and the package `__init__` --
previously empty -- now lists which of its modules point which way, so a file
added without that line is visibly a file whose direction nobody decided.
A subdirectory for a single inbound module would have made the other four
look like they had been sorted into something.

Tests
-----
This is the part that was not a rename. The conversion had 24 cases; the
invocation had none, because the composition root is not where behaviour is
asserted, so nothing covered "an ordinary chat run must not reach the
service" as opposed to "produces no outcome object".

The cases now drive `__call__` against a recording service, which asserts the
same mappings plus what was done with them, and adds the two that were
unreachable before: the service left entirely alone for a filtered run, and
the completion stamped with a tz-aware current instant.

`test_composition.py` gains `TestRunCompletionHook` for the assembly decision
that remains -- including that the hook is bound to the service it was given,
which a wrong wiring would type-check past. Confirmed by mutation that this
case fails when the binding is broken.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 20:14:27 +08:00

130 lines
5.5 KiB
Python

"""Composition root -- the one place adapters are instantiated and wired.
Every application service is assembled here and nowhere else. Ports are
declared by the domain, implemented under ``app/adapters/``, and the two are
introduced to each other in this file; no router, middleware, or lifespan hook
constructs an adapter of its own.
**Why this is a pure function rather than part of the lifespan.** Wiring used
to live inside ``deps.py::langgraph_runtime``, tangled with engine startup,
orphan recovery, and graceful shutdown -- so the one rule that actually
governs it ("no SQL backend means no service, and the routes answer 503")
could not be tested without driving a full application startup, and was held
up by a single comment. ``build_domain_services`` takes what it needs and
returns what it built, so that rule is an assertion in
``tests/test_composition.py`` instead.
**What "no SQL backend" means.** ``session_factory is None`` is how a
``database.backend: memory`` deployment presents itself. Both contexts own
tables, so neither can run on it; each service is ``None`` and the dependency
providers translate that into 503. This is deliberately not a silent
degradation to an in-memory implementation -- scheduled work that vanishes on
restart is worse than scheduled work that is refused.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from deerflow.domain.feedback.service import FeedbackService
from deerflow.domain.schedule.model import SchedulePolicy
from deerflow.domain.schedule.service import ScheduleService
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from deerflow.config.scheduler_config import SchedulerConfig
from deerflow.persistence.thread_meta.base import ThreadMetaStore
from deerflow.runtime.runs.store import RunStore
@dataclass(frozen=True)
class DomainServices:
"""Every application service the Gateway serves, or ``None`` where the
configured backend cannot support one."""
feedback: FeedbackService | None
schedule: ScheduleService | None
def build_domain_services(
*,
session_factory: async_sessionmaker[AsyncSession] | None,
run_store: RunStore,
thread_store: ThreadMetaStore,
launch_run: Callable[..., Awaitable[Mapping[str, Any]]],
scheduler_config: SchedulerConfig,
) -> DomainServices:
"""Wire the domain services from already-built infrastructure.
Takes infrastructure rather than building it: engines, stores and the run
launcher have lifecycles (startup, recovery, shutdown) that belong to the
lifespan, while deciding *what is assembled from them* is this function's
only job. That split is what makes it callable from a test.
"""
if session_factory is None:
return DomainServices(feedback=None, schedule=None)
# Imported here, not at module scope: these pull in SQLAlchemy and the
# Gateway run path, and the composition root is imported by tests that
# only want the memory-backend branch.
from app.adapters.feedback.feedback_repository import SqlFeedbackRepository
from app.adapters.feedback.run_lookup import RunStoreRunLookup
from app.adapters.schedule.run_launcher import GatewayRunLauncher
from app.adapters.schedule.scheduled_run_repository import SqlScheduledRunRepository
from app.adapters.schedule.scheduled_task_repository import SqlScheduledTaskRepository
from app.adapters.schedule.thread_lookup import ThreadStoreThreadLookup
return DomainServices(
feedback=FeedbackService(
repository=SqlFeedbackRepository(session_factory),
runs=RunStoreRunLookup(run_store),
),
schedule=ScheduleService(
tasks=SqlScheduledTaskRepository(session_factory),
runs=SqlScheduledRunRepository(session_factory),
launcher=GatewayRunLauncher(launch_run),
threads=ThreadStoreThreadLookup(thread_store),
policy=build_schedule_policy(scheduler_config),
),
)
def build_run_completion_hook(
schedule_service: ScheduleService | None,
) -> Callable[[Any], Awaitable[None]] | None:
"""Install the schedule context on the run runtime's completion callback.
The inbound half of the wiring, and nothing more: which runs the context
cares about and what it does with them belongs to the adapter, not here.
This function's only decision is the same one the rest of this module
makes -- what to assemble, and what to leave unassembled.
Returns ``None`` when there is no service, so the runtime installs no hook
at all rather than one that always declines.
"""
if schedule_service is None:
return None
from app.adapters.schedule.run_completion import ScheduleRunCompletionListener
return ScheduleRunCompletionListener(schedule_service)
def build_schedule_policy(scheduler_config: SchedulerConfig) -> SchedulePolicy:
"""Project the operator's scheduler config onto the domain's policy.
Separate from the wiring above because it is the whole of the
configuration-to-domain translation: the domain declares which thresholds
it needs, and this names where each one comes from. `poll_interval_seconds`
is deliberately absent -- how often to look is the poller's business, not a
rule any task is subject to.
"""
return SchedulePolicy(
min_once_delay_seconds=scheduler_config.min_once_delay_seconds,
max_concurrent_runs=scheduler_config.max_concurrent_runs,
lease_seconds=scheduler_config.lease_seconds,
)