deer-flow/backend/tests/blocking_io/test_persistence_engine_sqlite.py
AnoobFeng debb0fd161
Some checks are pending
Backend Blocking IO / backend-blocking-io (push) Waiting to run
Unit Tests / backend-unit-tests (push) Waiting to run
E2E Tests / e2e-tests (push) Waiting to run
Frontend Unit Tests / frontend-unit-tests (push) Waiting to run
Lint Check / lint-backend (push) Waiting to run
Lint Check / lint-frontend (push) Waiting to run
Replay E2E (front-back contract) / Layer 1 — backend golden (no API key) (push) Waiting to run
Replay E2E (front-back contract) / Layer 2 — full-stack render (no API key) (push) Waiting to run
feat(persistence): wire alembic migrations, bootstrap schema on startup (#3706)
* feat(persistence): wire alembic migrations + bootstrap schema on startup

Closes #3682. Pre-#3658 DBs lack the `runs.token_usage_by_model` column
because alembic was never wired up — startup only ran `create_all`,
which never ALTERs existing tables.

Adds a hybrid bootstrap in FastAPI lifespan (replaces bare `create_all`):
- empty DB     → create_all + stamp head
- legacy DB    → stamp 0001_baseline + upgrade head
- versioned DB → upgrade head

Concurrency: Postgres `pg_advisory_lock` (cross-process); SQLite
per-engine `asyncio.Lock` + 30s `PRAGMA busy_timeout` on both prod and
alembic engines. Column revisions use `safe_add_column` /
`safe_drop_column` idempotent helpers as fallback.

Other bits:
- 0001 baseline (chain root) + 0002 add `runs.token_usage_by_model`
- `include_object` filter so alembic ignores LangGraph checkpointer tables
- `make migrate-rev MSG="..."` for authoring new revisions
  (no migrate/stamp targets — startup is the only execution path)
- Tests: three-branch decision, concurrency, #3682 regression, env
  filter, blocking-IO gate anchor
- CLAUDE.md: new "Schema migrations" section

* fix(style): fix lint error

* perf(persistence): address review feedback on alembic bootstrap

Behavioural fixes
- _SQLITE_LOCKS now keyed via WeakKeyDictionary so id-reuse after GC
  cannot return a stale, loop-bound lock and the cache cannot leak one
  entry per disposed engine.
- safe_add_column compares nullable / server_default against the desired
  column when the name already exists and emits a warning on drift,
  surfacing manual-ALTER workarounds instead of silently no-op'ing.
- _postgres_lock issues SET LOCAL idle_in_transaction_session_timeout=0
  before pg_advisory_lock, so managed Postgres cannot kill the idle
  lock-holding session mid-upgrade and silently release the advisory
  lock.
- legacy branch now backfills missing baseline tables via a restricted
  create_all (Base.metadata.create_all scoped to _BASELINE_TABLE_NAMES).
  Restores pre-#1930 upgraders whose channel_* tables were never
  provisioned, without pre-empting future create_table revisions for
  newly-added models.

Schema parity
- runs.token_usage_by_model gains server_default=text("'{}'") in both
  the ORM model and the 0001_baseline create_table, matching what 0002
  adds via ALTER. create_all and alembic-upgrade paths now produce
  identical column definitions.
- New parity test compares Base.metadata.create_all output against a
  pure alembic upgrade base->head, asserting column-set, nullable, and
  server_default agree across all tables (normalized through the same
  helper safe_add_column's drift check uses).

Guards
- test_baseline_table_names_constant_matches_0001 pins
  _BASELINE_TABLE_NAMES to 0001_baseline.upgrade()'s actual output --
  the constant cannot drift silently when someone edits 0001.
- test_legacy_backfill_skips_non_baseline_tables verifies the restricted
  backfill does not create a phantom table on Base.metadata, modelling
  a future revision that would otherwise collide on op.create_table.

Doc residuals
- Three-branch decision table is now consistent across bootstrap.py
  top docstring, engine.py comment, test module docstring, and
  CLAUDE.md.
- Stale test anchor in blocking_io/test_persistence_engine_sqlite.py
  docstring now points at the real file.

* fix(style): fix lint error

* fix(persistence): close drift detection holes

- _check_column_drift compares column type via a family equivalence
  allowlist ({JSON, JSONB}). Catches the wrong-type workaround
  `TEXT NOT NULL DEFAULT '{}'` that previously slipped through silently,
  while keeping Postgres JSON/JSONB dialect reflection quiet. Reflected
  and desired type are also echoed in every drift warning's payload for
  operator triage.

- Extract _escape_url_for_alembic so bootstrap._alembic_safe_url and
  scripts/_autogen_revision share the ConfigParser % escape rule
  instead of duplicating it.

- backend/README.md: add `make migrate-rev MSG=...` to Commands and a
  Schema Migrations section per the repo's README/CLAUDE.md sync policy.

- test_base_to_dict.py: scope the test ORM class to an isolated MetaData
  so the create_all-vs-alembic parity test (added in the previous
  commit) is not polluted by the phantom table on the full pytest
  session.
2026-06-24 13:57:12 +08:00

77 lines
2.9 KiB
Python

"""Regression test: persistence-engine sqlite dir setup must run off the loop.
Anchors the production offload in `persistence/engine.py:init_engine`, where the
SQLite data directory is created with `os.makedirs`. `init_engine` runs on the
FastAPI lifespan event loop, so a sync `os.makedirs` (a stat + mkdir syscall)
there blocks startup — the same class of bug fixed for the checkpointer's
`ensure_sqlite_parent_dir` in #1912 (see `test_sqlite_lifespan.py`).
This invokes the production `init_engine(backend="sqlite", ...)` under the strict
Blockbuster context with a `sqlite_dir` that does not yet exist, so `os.makedirs`
actually runs. The async engine/session machinery is mocked out so the only host
filesystem operation under test is the directory creation; if it regresses to run
directly on the event loop, Blockbuster raises `BlockingError` and this fails.
We also stub ``bootstrap_schema`` so the alembic stamp/upgrade path -- which has
its own ``asyncio.to_thread`` regression anchor in
``test_persistence_bootstrap.py`` -- does not turn this test into a
double-coverage one. Keeping concerns separated means a regression in either
offload (makedirs vs alembic) points at the right place.
"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
# Pre-import so `init_engine`'s lazy ``import deerflow.persistence.models`` is a
# cached no-op rather than a file read under the strict gate.
import deerflow.persistence.models # noqa: E402,F401
from deerflow.persistence import engine as engine_mod # noqa: E402
pytestmark = pytest.mark.asyncio
def _noop_listens_for(*_args, **_kwargs):
"""Decorator factory that registers nothing (mock engine has no real events)."""
def _decorator(fn):
return fn
return _decorator
async def test_init_engine_sqlite_dir_setup_does_not_block_event_loop(tmp_path: Path) -> None:
data_dir = tmp_path / "newsubdir" # does not exist yet -> os.makedirs runs
db_file = data_dir / "app.db"
mock_conn = AsyncMock()
begin_ctx = AsyncMock()
begin_ctx.__aenter__.return_value = mock_conn
begin_ctx.__aexit__.return_value = False
mock_engine = MagicMock()
mock_engine.begin.return_value = begin_ctx
mock_engine.dispose = AsyncMock()
async def _noop_bootstrap(*_args, **_kwargs):
return None
with (
patch.object(engine_mod, "create_async_engine", return_value=mock_engine),
patch.object(engine_mod, "async_sessionmaker", return_value=MagicMock()),
patch("sqlalchemy.event.listens_for", _noop_listens_for),
patch(
"deerflow.persistence.bootstrap.bootstrap_schema",
new=_noop_bootstrap,
),
):
await engine_mod.init_engine(
backend="sqlite",
url=f"sqlite+aiosqlite:///{db_file}",
sqlite_dir=str(data_dir),
)
assert data_dir.exists()
await engine_mod.close_engine()