mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-23 21:16:17 +00:00
* feat(projects): project workspaces with scoped chats and thread membership
Backend:
- projects table model and migration; fail-closed ProjectRepository with
ownership checks, CRUD/archive/restore/delete router, and atomic thread
move between projects
- threads_meta.project_id column exposed as reserved deerflow_project_id
metadata; project-aware thread create/search with pagination bounds and
membership echoed in create responses
- first-run admission assigns the project only at genuine first run, seeded
at write time and dropped when invalid; serialized against project
deletion and thread assignment
- branch creation inherits the source thread's project membership (an
archived/deleted project degrades the branch to unassigned instead of
failing the request)
Frontend:
- projects data layer, thread move API, and sidebar projects section with
flat/grouped modes, archived-project threads, and stable virtual-list
offsets
- project detail page with project-scoped new chat
(/workspace/chats/new?project=) and paginated thread list
- move-to-project thread menu, new-project dialog, archived-project gates
- project-scoped new chats pre-create the thread with membership before the
first submit or /goal set, so runs never proceed outside the project
- goal-set preparation is fenced against conversation switches: a stale
continuation is dropped instead of saving the goal or launching the
abandoned submission on the newly opened conversation
- project thread lists join thread lifecycle invalidations (stop, pin) so
an open project page never keeps stale titles, recency, or pagination
* fix(chats): keep archive undo toast when the sidebar row unmounts
The archive success toast was fired from per-mutate callbacks passed to
mutation.mutate. React Query drops those handlers when the observer
component unmounts before the mutation settles; archiving the open chat
removes its sidebar row mid-flight, so the undo toast never appeared and
the e2e archive-undo test timed out waiting for it.
Move the success/error handlers to the mutation level (useArchiveThread
options, same pattern as useMoveThreadToProject) where callbacks are
delivered even after the originating row unmounts.
* fix(projects): pin project thread listing contract and exclude archived chats
GET /api/projects/{id}/threads returned the thread store row verbatim
(list[dict], no response_model): user_id/assistant_id leaked, any future
ThreadMetaRow column would auto-leak, and the OpenAPI schema was empty.
Return a narrow ProjectThreadResponse (the exact fields ProjectThread
declares) with the same metadata secret redaction the surrounding thread
endpoints get from _MetadataRedactingResponse.
The listing also ran search() without the archived filter, so a retired
chat rendered as a normal row on the project page while the sidebar hid
it. Search archived=False to mirror the sidebar's archived:false lists;
restore stays on the global Archived tab.
Both regressions pinned by new router tests: wire-shape allowlist and
archived-member exclusion.
* docs(migrations): record the 0019/0020 chain against the bootstrap reservation
The tree now chains 0018 -> 0019_projects -> 0020_threads_meta_project_id,
so migrations/AGENTS.md was stale twice over: the revision index stopped at
0018 and the rolling-forward section still claimed the tree 'deliberately
remains at 0018'.
Document the new head and record the intentional numeric-prefix reuse of
0019: 0019_projects is in-chain while 0019_thread_incarnations stays the
reserved, allowlisted out-of-tree rollout id. The owning rollout revision
must re-parent onto this tree's head when it merges so alembic never sees
two heads off 0018; bootstrap.py now cross-references that note next to
_FORWARD_COMPATIBLE_REVISION.
* fix(chats): invalidate project thread lists on archive/restore
useArchiveThread refreshed the infinite sidebar cache, threads/search and
the per-thread metadata cache but not the project-scoped list
([...PROJECTS_QUERY_KEY, 'threads', id]) this PR adds — the one thread
mutation not wired to that key, after usePinThread, useRenameThread,
useDeleteThread, useMoveThreadToProject and invalidateStoppedThreadCaches.
An archive from a sidebar row while a project page is open therefore left
the archived chat rendered as a normal row until remount (and undo left it
missing). Invalidate the prefix in the mutation-level success handler.
Regression test asserts the project-list prefix is invalidated on success.
* fix(projects): fetch project discovery only in grouped sidebar mode
RecentChatList mounted two useProjects queries per sidebar render, but
knownProjectIds is consumed only by the grouped-mode exclusion filter; in
the default flat mode every page load paid two GET /api/projects?status=
round trips for data nothing read. Gate both queries on grouped mode —
GroupedProjectList fetches the same keys when the toggle is on and
TanStack dedupes the observers.
Also set retry: false on useProject: a deleted or foreign project 404s
deterministically, and the page renders a dedicated not-found state for
it, so the default 1s/2s/4s retry backoff kept deep links in 'loading'
for ~7s before that state appeared. Matches useThreadMetadata /
useThreadTokenUsage.
* fix(threads): fail closed on project-scoped create in memory mode
MemoryThreadMetaStore.create accepted project_id and silently ignored it,
making memory mode the one membership path that fails open: POST
/api/threads with a project id returned 200 and the run started
unassigned, violating the invariant that a run never proceeds outside the
selected project (the SQL store raises ProjectNotAssignableError inside
the insert transaction for the same request).
Raise ProjectNotAssignableError whenever project_id is present so the
router's existing 404 mapping applies, the frontend keeps the composer
text for a retry, and memory mode behaves exactly like SQL mode.
set_project already reports rejection; create now matches it.
Store-level test (raises, nothing persisted, project filter stays empty,
unscoped creates still work) plus a router-level test asserting the 404
and that no row is left behind.
* fix(projects): window the project page thread list
ProjectThreadsSection rendered every loaded page as a plain Link row, so a
long-lived project accumulated unbounded DOM on the page's scroll surface:
each load-more appended another 100 rows and every formatTimeAgo tick
re-rendered the whole list.
Reuse VirtualThreadList (now generic over any row shape with a
thread_id), pointing its scroll parent at this page's ScrollArea viewport
via the shared [data-slot="scroll-area-viewport"] selector used by
/workspace/chats; under the 60-row threshold it falls back to the plain
render, so small projects are unchanged.
* fix(projects): restore row dividers and pin them with a render test
The row class template literal concatenated transition-colors directly
with the conditional border-b token, so non-final rows rendered the
invalid class 'transition-colorsborder-b' and lost both the divider and
the transition. Compose the row classes with cn() and a boolean guard
instead.
The section moved out of page.tsx into a testable component so the row
markup finally has coverage: a DOM test asserts every row except the
final data row carries border-b (index-based, not last: — correct under
virtualization where the last mounted row is not the last data row), and
the untitled fallback plus load-more button render for a partial page.
* fix(projects): validate forward schemas and fence membership reads
169 lines
7.2 KiB
Python
169 lines
7.2 KiB
Python
"""Regression test for migration ``0004_run_ownership`` dedupe pass.
|
|
|
|
End-to-end shape:
|
|
|
|
1. Hand-build a SQLite DB that mirrors a real pre-0004 deployment that ran
|
|
``GATEWAY_WORKERS>1`` before this PR and accumulated duplicate active rows
|
|
per thread (the exact dirty state the multi-worker ownership fix targets).
|
|
2. Stamp it at ``0003_scheduled_tasks`` so ``bootstrap_schema`` takes the
|
|
versioned branch and runs ``alembic upgrade head``.
|
|
3. Insert two+ pending/running rows for the same ``thread_id`` (only possible
|
|
because the partial unique index does not exist yet).
|
|
4. Run ``init_engine`` (the FastAPI lifespan entry point), which routes
|
|
through ``bootstrap_schema`` → ``upgrade head`` → ``0004.upgrade()``.
|
|
5. Verify the migration cancelled the superseded duplicates (set them to
|
|
``error`` with an explanatory message), kept the newest active row, and
|
|
successfully built the ``uq_runs_thread_active`` partial unique index.
|
|
|
|
Pre-fix codepath would have raised ``UNIQUE constraint failed`` (SQLite) /
|
|
``could not create unique index`` (Postgres) on step 5, aborting the alembic
|
|
upgrade and blocking gateway startup.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
from datetime import UTC, datetime, timedelta
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from sqlalchemy.orm import Session
|
|
|
|
import deerflow.persistence.models # noqa: F401 -- registers ORM models
|
|
from deerflow.persistence.base import Base
|
|
from deerflow.persistence.engine import close_engine, init_engine
|
|
from deerflow.persistence.run.model import RunRow
|
|
|
|
pytestmark = pytest.mark.asyncio
|
|
|
|
|
|
def _seed_pre_0004_with_duplicates(db_path: Path) -> None:
|
|
"""Build a DB at revision 0003 with duplicate active rows per thread.
|
|
|
|
Uses a synchronous engine so the seed is independent of the async engine
|
|
under test. ``Base.metadata.create_all`` produces the full current schema
|
|
(including the partial unique index), so we drop just the unique index to
|
|
land in the dirty state the migration's dedupe pass targets: a versioned
|
|
DB at 0003 where duplicate active rows per thread can coexist. We then
|
|
stamp at 0003 and insert the duplicates via the ORM (so Python-side
|
|
defaults populate).
|
|
"""
|
|
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)
|
|
with sync_engine.begin() as conn:
|
|
# Drop only the partial unique index — this is the invariant the
|
|
# migration rebuilds, and its absence is what permits duplicate
|
|
# active rows to exist in the first place.
|
|
conn.execute(sa.text("DROP INDEX IF EXISTS uq_runs_thread_active"))
|
|
# Stamp at 0003 so bootstrap takes the versioned branch and runs
|
|
# ``alembic upgrade head`` (which is what executes 0004.upgrade()).
|
|
conn.execute(sa.text("CREATE TABLE IF NOT EXISTS alembic_version (version_num VARCHAR(32) NOT NULL)"))
|
|
conn.execute(sa.text("DELETE FROM alembic_version"))
|
|
conn.execute(sa.text("INSERT INTO alembic_version (version_num) VALUES ('0003_scheduled_tasks')"))
|
|
|
|
base = datetime.now(UTC)
|
|
with Session(sync_engine) as session:
|
|
session.add_all(
|
|
[
|
|
RunRow(
|
|
run_id="run-old-a",
|
|
thread_id="thread-dup",
|
|
status="pending",
|
|
created_at=base,
|
|
updated_at=base,
|
|
),
|
|
RunRow(
|
|
run_id="run-old-b",
|
|
thread_id="thread-dup",
|
|
status="running",
|
|
created_at=base + timedelta(seconds=10),
|
|
updated_at=base + timedelta(seconds=10),
|
|
),
|
|
RunRow(
|
|
run_id="run-newest",
|
|
thread_id="thread-dup",
|
|
status="pending",
|
|
created_at=base + timedelta(seconds=60),
|
|
updated_at=base + timedelta(seconds=60),
|
|
),
|
|
RunRow(
|
|
run_id="run-solo",
|
|
thread_id="thread-solo",
|
|
status="running",
|
|
created_at=base,
|
|
updated_at=base,
|
|
),
|
|
RunRow(
|
|
run_id="run-success",
|
|
thread_id="thread-done",
|
|
status="success",
|
|
created_at=base,
|
|
updated_at=base,
|
|
),
|
|
]
|
|
)
|
|
session.commit()
|
|
finally:
|
|
sync_engine.dispose()
|
|
|
|
|
|
def _fetch_runs(db_path: Path) -> dict[str, tuple[str, str | None]]:
|
|
"""Map run_id -> (status, error) for assertions."""
|
|
with sqlite3.connect(db_path) as raw:
|
|
rows = raw.execute("SELECT run_id, status, error FROM runs").fetchall()
|
|
return {run_id: (status, error) for run_id, status, error in rows}
|
|
|
|
|
|
def _index_exists(db_path: Path, index_name: str) -> bool:
|
|
with sqlite3.connect(db_path) as raw:
|
|
row = raw.execute(
|
|
"SELECT 1 FROM sqlite_master WHERE type='index' AND name=?",
|
|
(index_name,),
|
|
).fetchone()
|
|
return row is not None
|
|
|
|
|
|
async def test_migration_dedupes_duplicate_active_rows_before_unique_index(tmp_path: Path) -> None:
|
|
db_path = tmp_path / "dirty.db"
|
|
_seed_pre_0004_with_duplicates(db_path)
|
|
|
|
url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
|
|
await init_engine(backend="sqlite", url=url, sqlite_dir=str(tmp_path))
|
|
|
|
try:
|
|
runs = _fetch_runs(db_path)
|
|
|
|
# Newest active row on the duplicated thread survives unchanged.
|
|
assert runs["run-newest"] == ("pending", None)
|
|
|
|
# Older duplicate active rows are cancelled with an explanatory error.
|
|
assert runs["run-old-a"][0] == "error"
|
|
assert "uq_runs_thread_active" in (runs["run-old-a"][1] or "")
|
|
assert runs["run-old-b"][0] == "error"
|
|
assert "uq_runs_thread_active" in (runs["run-old-b"][1] or "")
|
|
|
|
# Untouched threads: single active row stays active, terminal rows stay terminal.
|
|
assert runs["run-solo"] == ("running", None)
|
|
assert runs["run-success"] == ("success", None)
|
|
|
|
# The partial unique index was successfully created — the upgrade did
|
|
# not abort with ``UNIQUE constraint failed``.
|
|
assert _index_exists(db_path, "uq_runs_thread_active")
|
|
assert _index_exists(db_path, "ix_runs_lease")
|
|
|
|
with sqlite3.connect(db_path) as raw:
|
|
version_row = raw.execute("SELECT version_num FROM alembic_version").fetchone()
|
|
# Bootstrap upgrades through the later revisions after 0004.
|
|
assert version_row[0] == "0020_threads_meta_project_id"
|
|
|
|
# Sanity: the invariant the index enforces is now true — at most one
|
|
# active row per thread.
|
|
with sqlite3.connect(db_path) as raw:
|
|
dupes = raw.execute("SELECT thread_id, COUNT(*) FROM runs WHERE status IN ('pending', 'running') GROUP BY thread_id HAVING COUNT(*) > 1").fetchall()
|
|
assert dupes == []
|
|
finally:
|
|
await close_engine()
|