deer-flow/backend/tests/test_scheduled_task_models.py
rayhpeng 6f84a4094d refactor(schedule): fill the ports with adapters and delete the old path
The outer ring for the domain added in #4597: SQL repositories, the run
launcher, the thread lookup, and the run-completion listener implementing
the ports it declared, plus the HTTP router and the poller that drive
them. All of it is instantiated in one composition root, so no route or
lifespan hook builds an adapter of its own.

With the ports filled, the pre-hexagonal implementation is deleted rather
than left alongside: `app/scheduler/service.py` and its router mixed
policy, persistence, and HTTP into one class, which is why its rules were
only reachable through a live database. Keeping both would leave two
implementations of the same rules writing to the same table.

Three of the domain's contracts needed real work on this side rather than
a straight port of the pre-#4597 adapters:

- The launcher now distinguishes certain failure from doubt. Only a 4xx
  is certain enough to raise LaunchFailedError, which releases the task's
  single active slot; a 5xx, an arbitrary exception, or a reply whose
  identity will not decode all raise LaunchIndeterminateError and keep
  the slot held. Guessing "failed" after the launch request was sent is
  what re-opens #4452's duplicate execution.

- The task repository implements the optimistic token. `save` is a
  conditional UPDATE on `version` rather than read-check-write, because
  the latter lets two savers observe the same version and both commit;
  every other committed write increments it. This needs a column, so it
  ships with migration 0011 -- the only schema change in the slice, and
  the reason the alembic head pins move.

- The router builds commands with plain `None` for "not supplied", and
  maps ConcurrentUpdateError onto a retryable 409.

The concurrency invariants are pinned by contract suites that run each
port against both the in-memory double and real sqlite -- including a new
TestOptimisticConcurrency covering what invalidates an earlier read --
plus the dispatch-race tests against a real database.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 13:01:32 +08:00

59 lines
2.5 KiB
Python

import re
from sqlalchemy import Index
from deerflow.config.app_config import AppConfig
from deerflow.domain.schedule.model import ACTIVE_RUN_STATUSES
from deerflow.persistence.models import ScheduledTaskRow, ScheduledTaskRunRow
def test_app_config_exposes_scheduler_section():
config = AppConfig.model_validate(
{
"models": [],
"sandbox": {"use": "local"},
}
)
assert config.scheduler.enabled is False
assert config.scheduler.poll_interval_seconds == 5
assert config.scheduler.lease_seconds == 120
def test_scheduled_task_models_registered():
assert ScheduledTaskRow.__tablename__ == "scheduled_tasks"
assert ScheduledTaskRunRow.__tablename__ == "scheduled_task_runs"
def _active_run_index() -> Index:
return next(arg for arg in ScheduledTaskRunRow.__table_args__ if isinstance(arg, Index) and arg.name == "uq_scheduled_task_run_active")
def test_active_run_index_arbitrates_one_active_run_per_task():
"""The index is the atomic arbiter of the overlap rule, so its shape is a
contract, not a detail: unique, keyed on `task_id` alone."""
index = _active_run_index()
assert index.unique is True
assert [column.name for column in index.expressions] == ["task_id"]
def test_active_run_index_predicate_matches_the_domain_constant():
"""`ACTIVE_RUN_STATUSES` and this predicate must stay in lockstep.
The domain's fast path (`has_active`) and the index disagree the moment
they drift, which silently decouples the overlap check from its arbiter.
The domain tests cannot assert this -- they are deliberately
dependency-free and cannot import an ORM model -- so the assertion the
`ACTIVE_RUN_STATUSES` docstring promises lives here.
Both dialect predicates are checked: `create_all` renders the SQLite one
and production renders the Postgres one, so a drift in either is real.
"""
index = _active_run_index()
expected = {str(status) for status in ACTIVE_RUN_STATUSES}
assert expected == {"queued", "running"}, "domain constant changed -- update the ORM predicates below"
predicates = {key: str(value) for key, value in index.dialect_kwargs.items() if key.endswith("_where")}
assert set(predicates) == {"sqlite_where", "postgresql_where"}, "a dialect lost its partial-index predicate"
for dialect, predicate in predicates.items():
assert set(re.findall(r"'([^']+)'", predicate)) == expected, f"{dialect} predicate drifted from ACTIVE_RUN_STATUSES"