mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-09 16:08:31 +00:00
* feat: add scheduled tasks MVP
* fix: harden scheduled task execution semantics
* feat(scheduled-tasks): preset-driven schedule form with timezone and live preview
Replace the raw cron input with a preset Select (hourly/daily/weekly/monthly/custom)
plus structured inputs (time picker, weekday toggles, day-of-month), datetime-local
for one-time tasks, a timezone selector defaulting to the browser timezone, and a
live human-readable preview. Reuses one ScheduledTaskScheduleInput for create and
edit; backend contract unchanged; zero new deps (pure Intl + DST-safe offset helpers).
* feat(scheduled-tasks): full-page i18n + recipe templates + E2E locale pin
Localize the rest of the scheduled-tasks page (filters, detail pane, actions,
edit form, run list, enum values) via t.scheduledTasks.* in en/zh. Add four
built-in recipe templates (GitHub Trending, news digest, issue triage, weekly
report) exposed as a chip row that pre-fills title + prompt + schedule. Pin
Playwright locale to en-US so E2E selectors stay stable against i18n. No backend
change, no new deps.
* fix(scheduled-tasks): idempotent 0003 migration, update head constants, future-date once test
Merge with main surfaced three CI failures:
- 0003_scheduled_tasks create_table collided with legacy test seeds that
build from full metadata; guard with inspector.has_table so the revision
no-ops when the table already exists (0004/0005 are already idempotent via
_helpers.py).
- persistence bootstrap concurrency/regression tests pinned HEAD to main's
0002_runs_token_usage; bump to the new head 0005_scheduled_task_thread_nullable.
- once-task router test used a fixed past run_at and tripped the
must-be-in-the-future validation; use a future date.
* address review: ok-check, 502 for trigger failure, mock fields, migration filename, doc fences
- fetchThreadScheduledTasks now checks response.ok like the other fetchers.
- trigger endpoint returns 502 (not 409) when dispatch fails outright, so
clients can distinguish a real conflict from a server-side failure.
- E2E mock normalizes scheduled-task objects with context_mode/last_thread_id
and nullable thread_id, matching the backend contract the UI renders against.
- Rename 0002_scheduled_tasks.py -> 0003_scheduled_tasks.py to match its
revision id (file was renamed in spirit already; filename now follows).
- CONFIGURATION.md: close the Tool Groups yaml fence and drop the stray fence
after the Scheduler notes so the sections render correctly.
* fix(scheduled-tasks): harden lease, poller, config, and frontend UX after review
* fix(scheduled-tasks): harden run lifecycle, overlap skip, non_interactive gating, and DST conversion after review
- defer a once task's terminal status to the run-completion hook; the task
stays running until the real outcome, and a startup sweep cancels once
tasks orphaned by a crash (launch-time 'completed' could stick forever)
- record interrupted runs as a distinct 'interrupted' run status with a
readable message; an interrupted once task ends 'cancelled', not 'failed'
- enforce overlap_policy=skip for fresh_thread_per_run via an active-run
pre-check (same-thread ConflictError can never fire across fresh threads)
- protect terminal run statuses from the late launch-path 'running' write
- honor context.non_interactive only for internally-authenticated callers;
arbitrary clients can no longer strip ask_clarification
- fix DST-stale timezone offset in zonedLocalToUtcIso by re-deriving the
offset at the resolved instant (once tasks fired an hour late around
spring-forward and the create->edit round-trip diverged)
- drop dead ScheduledTaskRunRepository.update_by_run_id; share one Gateway
API error helper between channels and scheduled-tasks frontends
* fix(scheduled-tasks): close review round-3 gaps in guards, concurrency, and API ergonomics
- scrub internal-only context keys (non_interactive) from the assembled run
config for non-internal callers: gating body.context alone left the same
key smuggle-able through the free-form body.config copied verbatim by
build_run_config
- guard update_after_launch with protect_terminal so the launch bookkeeping
write cannot clobber a once task already finalized by a fast-failing run's
completion hook (parent-row sibling of the run-row guard)
- reject a manual trigger while the task has an active run (409) instead of
launching a duplicate concurrent run on fresh_thread_per_run
- re-arm a terminal once task to enabled when PATCH pushes run_at into the
future; previously the endpoint returned 200 with a next_run_at that could
never be claimed
- make max_concurrent_runs a real global cap: each poll claims only into the
remaining budget of active (queued/running) scheduled runs
- paginate GET /scheduled-tasks/{id}/runs (limit<=200, offset) and push the
thread filter of /threads/{id}/scheduled-tasks into SQL
- stamp context.user_id on scheduler-launched runs, matching IM channels, so
user-scoped guardrail providers see the owning user
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
121 lines
4.8 KiB
Python
121 lines
4.8 KiB
Python
"""Regression test for GitHub issue #3682.
|
|
|
|
End-to-end shape:
|
|
|
|
1. Hand-build a SQLite DB that mirrors a real pre-#3658 deployment -- the
|
|
``runs`` table is missing the ``token_usage_by_model`` column, mirroring
|
|
what every existing user's DB looked like after the upgrade that triggered
|
|
the issue.
|
|
2. Run ``init_engine`` (the entry point used by the FastAPI Gateway
|
|
lifespan), which now routes through ``bootstrap_schema``.
|
|
3. Confirm a real ``SELECT`` against the column succeeds, demonstrating the
|
|
500 from the original issue is gone.
|
|
|
|
The pre-fix codepath would have raised
|
|
``sqlalchemy.exc.OperationalError: no such column: runs.token_usage_by_model``
|
|
on step 3.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
|
|
import deerflow.persistence.models # noqa: F401 -- registers ORM models
|
|
from deerflow.persistence.base import Base
|
|
from deerflow.persistence.engine import close_engine, get_session_factory, init_engine
|
|
from deerflow.persistence.run import RunRepository
|
|
|
|
pytestmark = pytest.mark.asyncio
|
|
|
|
|
|
def _seed_pre_3658_database(db_path: Path) -> None:
|
|
"""Build a DB that looks like a pre-PR-#3658 deployment.
|
|
|
|
Uses the synchronous ``sqlite3`` driver so the seed is independent of the
|
|
async engine under test.
|
|
"""
|
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Easiest way to get the legacy shape exactly right: create_all then
|
|
# ALTER away the new column.
|
|
sync_url = f"sqlite:///{db_path.as_posix()}"
|
|
sync_engine = sa.create_engine(sync_url)
|
|
try:
|
|
Base.metadata.create_all(sync_engine)
|
|
with sync_engine.begin() as conn:
|
|
conn.execute(sa.text("ALTER TABLE runs DROP COLUMN token_usage_by_model"))
|
|
finally:
|
|
sync_engine.dispose()
|
|
|
|
|
|
async def test_legacy_database_recovers_token_usage_column(tmp_path: Path) -> None:
|
|
db_path = tmp_path / "legacy.db"
|
|
_seed_pre_3658_database(db_path)
|
|
|
|
# Sanity: confirm we did indeed land in the buggy pre-fix shape before
|
|
# init_engine touches the file.
|
|
with sqlite3.connect(db_path) as raw:
|
|
cols = {row[1] for row in raw.execute("PRAGMA table_info(runs)").fetchall()}
|
|
assert "run_id" in cols
|
|
assert "token_usage_by_model" not in cols
|
|
version_table_count = raw.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='alembic_version'").fetchone()[0]
|
|
assert version_table_count == 0
|
|
|
|
# Run the same init_engine path FastAPI lifespan uses on startup.
|
|
url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
|
|
await init_engine(backend="sqlite", url=url, sqlite_dir=str(tmp_path))
|
|
|
|
try:
|
|
# The column must now be present.
|
|
with sqlite3.connect(db_path) as raw:
|
|
cols = {row[1] for row in raw.execute("PRAGMA table_info(runs)").fetchall()}
|
|
assert "token_usage_by_model" in cols
|
|
version_row = raw.execute("SELECT version_num FROM alembic_version").fetchone()
|
|
assert version_row[0] == "0003_scheduled_tasks"
|
|
|
|
# And the read path that originally 500'd must now succeed.
|
|
sf = get_session_factory()
|
|
assert sf is not None
|
|
repo = RunRepository(sf)
|
|
# No rows yet -- the point is just that the SELECT does not raise
|
|
# ``no such column: runs.token_usage_by_model``.
|
|
result = await repo.aggregate_tokens_by_thread(thread_id=str(uuid4()))
|
|
assert result["total_tokens"] == 0
|
|
assert result["by_model"] == {}
|
|
finally:
|
|
await close_engine()
|
|
|
|
|
|
async def test_legacy_database_with_manual_alter_still_bootstraps(tmp_path: Path) -> None:
|
|
"""User-side workaround scenario: someone already applied the manual
|
|
``ALTER TABLE runs ADD COLUMN token_usage_by_model JSON`` from the issue
|
|
write-up. The hybrid bootstrap must just stamp head, not double-add the
|
|
column, and not error.
|
|
"""
|
|
db_path = tmp_path / "manual_altered.db"
|
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
sync_engine = sa.create_engine(f"sqlite:///{db_path.as_posix()}")
|
|
try:
|
|
Base.metadata.create_all(sync_engine)
|
|
# Don't strip the column -- this is the "user already ran the
|
|
# workaround" case where create_all already produced it.
|
|
finally:
|
|
sync_engine.dispose()
|
|
|
|
url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
|
|
await init_engine(backend="sqlite", url=url, sqlite_dir=str(tmp_path))
|
|
try:
|
|
with sqlite3.connect(db_path) as raw:
|
|
cols = [row[1] for row in raw.execute("PRAGMA table_info(runs)").fetchall()]
|
|
# No duplicate column -- list, not set, to catch dupes.
|
|
assert cols.count("token_usage_by_model") == 1
|
|
version_row = raw.execute("SELECT version_num FROM alembic_version").fetchone()
|
|
assert version_row[0] == "0003_scheduled_tasks"
|
|
finally:
|
|
await close_engine()
|