feat(maf-roundtable): add Phase-1 multi-agent roundtable infrastructure

Ship an independent, feature-flag-gated MAF roundtable skeleton with six
isolated tables, atomic single-transaction run launch/cancel, owner-scoped
read/write split, shared config enums, and HTTP/concurrency regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-01 01:07:05 +08:00
1 parent a0a75a9964
commit e690475e6e
27 files changed
+5369 -101

No files matched your search

@@ -0,0 +1,206 @@
"""P1 admin write-boundary + P2 config-default tests for the MAF roundtable.
P1 — admin diagnostic access is **read-only**:
- An admin with ``admin_diagnostic_access=True`` can *read* another user's
session / run / action / approval (cross-user diagnostics).
- The same admin **cannot** *write* another user's resources: update / delete
session, start / cancel run, append event, decide approval all raise
``MafForbiddenError`` (→ HTTP 403), never silently succeeding.
- Normal users remain fully isolated from each other.
P2 — config-driven create defaults:
- Omitted ``mode`` / ``write_policy`` / ``max_rounds`` fall back to the deployed
``MafRoundtableConfig`` values.
- An explicit request value overrides the config default.
"""
from __future__ import annotations
import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.maf_roundtable.service import (
MafForbiddenError,
MafNotFoundError,
MafRoundtableService,
)
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
from deerflow.persistence.base import Base
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
@pytest_asyncio.fixture
async def store(tmp_path):
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf_adm.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
yield make_maf_roundtable_store(sf)
await engine.dispose()
def _svc(store, *, enabled=True, admin_diagnostic_access=True, config=None):
return MafRoundtableService(
store,
enabled=enabled,
admin_diagnostic_access=admin_diagnostic_access,
config=config,
)
# ── P1: admin can READ cross-user ─────────────────────────────────────────
@pytest.mark.asyncio
async def test_admin_can_read_other_user_session(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
fetched = await svc.get_session(session_id=s["id"], user_id="admin-1", is_admin=True)
assert fetched["id"] == s["id"]
assert fetched["user_id"] == "alice"
@pytest.mark.asyncio
async def test_admin_can_read_other_user_run_and_action(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="alice")
action = await store.actions.create_action(
{"session_id": s["id"], "run_id": run["id"], "tool_name": "t", "idempotency_key": "k", "status": "pending"}
)
# Admin reads run + action cross-user without error.
assert (await svc.get_run(run_id=run["id"], user_id="admin-1", is_admin=True))["id"] == run["id"]
assert (await svc.get_action(action_id=action["id"], user_id="admin-1", is_admin=True))["id"] == action["id"]
assert len(await svc.list_runs(session_id=s["id"], user_id="admin-1", is_admin=True)) == 1
# ── P1: admin CANNOT WRITE cross-user ─────────────────────────────────────
@pytest.mark.asyncio
async def test_admin_cannot_update_other_user_session(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
with pytest.raises(MafForbiddenError):
await svc.update_session(session_id=s["id"], user_id="admin-1", fields={"title": "hijack"}, is_admin=True)
# Unchanged.
assert (await svc.get_session(session_id=s["id"], user_id="alice"))["title"] == ""
@pytest.mark.asyncio
async def test_admin_cannot_delete_other_user_session(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
with pytest.raises(MafForbiddenError):
await svc.delete_session(session_id=s["id"], user_id="admin-1", is_admin=True)
# Still present.
assert (await svc.get_session(session_id=s["id"], user_id="alice"))["id"] == s["id"]
@pytest.mark.asyncio
async def test_admin_cannot_start_run_on_other_user_session(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
with pytest.raises(MafForbiddenError):
await svc.create_run(session_id=s["id"], user_id="admin-1", is_admin=True)
# No run was created.
assert await svc.list_runs(session_id=s["id"], user_id="alice") == []
@pytest.mark.asyncio
async def test_admin_cannot_cancel_other_user_run(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="alice")
with pytest.raises(MafForbiddenError):
await svc.cancel_run(run_id=run["id"], user_id="admin-1", is_admin=True)
assert (await svc.get_run(run_id=run["id"], user_id="alice"))["status"] == "pending"
@pytest.mark.asyncio
async def test_non_owner_cannot_cancel_run_gets_not_found(store):
"""A non-admin user cancelling another user's run gets 404 (not 403)."""
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="alice")
with pytest.raises(MafNotFoundError):
await svc.cancel_run(run_id=run["id"], user_id="bob")
assert (await svc.get_run(run_id=run["id"], user_id="alice"))["status"] == "pending"
@pytest.mark.asyncio
async def test_admin_cannot_append_event_to_other_user_run(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="alice")
with pytest.raises(MafForbiddenError):
await svc.append_event(run_id=run["id"], user_id="admin-1", event_type="run.started", is_admin=True)
@pytest.mark.asyncio
async def test_admin_cannot_decide_other_user_approval(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="alice")
appr = await store.approvals.create_approval(
{"session_id": s["id"], "run_id": run["id"], "summary": "x", "status": "pending"}
)
with pytest.raises(MafForbiddenError):
await svc.decide_approval(approval_id=appr["id"], decision="approved", user_id="admin-1", is_admin=True)
assert (await store.approvals.get_approval(appr["id"]))["status"] == "pending"
@pytest.mark.asyncio
async def test_admin_diagnostic_off_cannot_even_read_cross_user(store):
svc = _svc(store, admin_diagnostic_access=False)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
with pytest.raises(MafNotFoundError):
await svc.get_session(session_id=s["id"], user_id="admin-1", is_admin=True)
@pytest.mark.asyncio
async def test_normal_users_remain_fully_isolated(store):
svc = _svc(store, admin_diagnostic_access=True)
s = await svc.create_session(user_id="alice", body={"task_text": "t"})
# bob is a non-admin → isolated on both read and write.
with pytest.raises(MafNotFoundError):
await svc.get_session(session_id=s["id"], user_id="bob")
with pytest.raises(MafNotFoundError):
await svc.update_session(session_id=s["id"], user_id="bob", fields={"title": "x"})
# ── P2: config-driven create defaults ─────────────────────────────────────
@pytest.mark.asyncio
async def test_create_session_uses_config_defaults_when_omitted(store):
cfg = MafRoundtableConfig(
default_mode="group_chat",
default_write_policy="confirm_all_writes",
default_max_rounds=12,
)
svc = _svc(store, config=cfg)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
assert s["mode"] == "group_chat"
assert s["write_policy"] == "confirm_all_writes"
assert s["max_rounds"] == 12
@pytest.mark.asyncio
async def test_create_session_explicit_values_override_config(store):
cfg = MafRoundtableConfig(
default_mode="group_chat",
default_write_policy="confirm_all_writes",
default_max_rounds=12,
)
svc = _svc(store, config=cfg)
s = await svc.create_session(
user_id="u1",
body={"task_text": "t", "mode": "structured", "write_policy": "auto", "max_rounds": 3},
)
assert s["mode"] == "structured"
assert s["write_policy"] == "auto"
assert s["max_rounds"] == 3
@@ -0,0 +1,282 @@
"""Tests for the MAF roundtable persistence + service layer (阶段一骨架).
Covers the Phase 1 exit criteria:
- Session CRUD with participants + capability snapshot.
- Run lifecycle (create / get / list / cancel).
- Monotonic per-run event seq under concurrent appends (MAF-01-06).
- Event 断线补拉 (list_events after_seq=N).
- Action idempotency-key uniqueness.
- Approval decision transition + "already decided" guard.
- User isolation (MAF-01-07) — non-owner gets None / 404, not 403.
- Admin diagnostic access bypass.
- Feature flag (MAF-01-04) — writes raise MafDisabledError when off; reads open.
- Run gating — running session rejects config edits.
- capability_snapshot frozen at creation.
- MAF tables have no FK to legacy roundtable_* tables.
"""
from __future__ import annotations
import asyncio
import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.maf_roundtable.service import (
MafConflictError,
MafNotFoundError,
MafRoundtableService,
)
from deerflow.persistence.base import Base
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
@pytest_asyncio.fixture
async def store(tmp_path):
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
yield make_maf_roundtable_store(sf)
await engine.dispose()
def _svc(store, *, enabled=True, admin_diagnostic_access=True):
return MafRoundtableService(store, enabled=enabled, admin_diagnostic_access=admin_diagnostic_access)
@pytest.mark.asyncio
async def test_create_and_get_session_round_trips(store):
svc = _svc(store)
created = await svc.create_session(
user_id="u1",
body={
"title": "舆情会商",
"task_text": "分析暑期文旅舆情",
"mode": "structured",
"model_name": "glm-5",
"max_rounds": 5,
"write_policy": "confirm_high_risk",
"capability_snapshot": {"agents": ["a1"]},
"participants": [
{"agent_id": "mgr", "display_name": "主持人", "role": "manager", "sort_order": 0},
{"agent_id": "seat-a", "display_name": "席A", "role": "seat", "sort_order": 1},
],
},
)
assert created["user_id"] == "u1"
assert created["status"] == "draft"
assert created["mode"] == "structured"
assert created["capability_snapshot"] == {"agents": ["a1"]}
assert len(created["participants"]) == 2
assert created["participants"][0]["agent_id"] == "mgr"
fetched = await svc.get_session(session_id=created["id"], user_id="u1")
assert fetched["id"] == created["id"]
assert len(fetched["participants"]) == 2
@pytest.mark.asyncio
async def test_list_sessions_owner_scoped(store):
svc = _svc(store)
await svc.create_session(user_id="u1", body={"task_text": "t1"})
await svc.create_session(user_id="u2", body={"task_text": "t2"})
rows_u1, total_u1 = await svc.list_sessions(user_id="u1")
assert total_u1 == 1
assert rows_u1[0]["user_id"] == "u1"
rows_u2, total_u2 = await svc.list_sessions(user_id="u2")
assert total_u2 == 1
assert rows_u2[0]["user_id"] == "u2"
@pytest.mark.asyncio
async def test_update_session_partial_and_participants_replace(store):
svc = _svc(store)
s = await svc.create_session(
user_id="u1",
body={"task_text": "orig", "participants": [{"agent_id": "a1", "role": "seat"}]},
)
updated = await svc.update_session(
session_id=s["id"],
user_id="u1",
fields={"title": "新标题", "participants": [{"agent_id": "a2", "role": "seat"}]},
)
assert updated["title"] == "新标题"
assert updated["task_text"] == "orig"
assert {p["agent_id"] for p in updated["participants"]} == {"a2"}
@pytest.mark.asyncio
async def test_update_session_freezes_capability_snapshot(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t", "capability_snapshot": {"v": 1}})
updated = await svc.update_session(
session_id=s["id"], user_id="u1", fields={"capability_snapshot": {"v": 999}}
)
assert updated["capability_snapshot"] == {"v": 1}
@pytest.mark.asyncio
async def test_delete_session_owner_scoped(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
with pytest.raises(MafNotFoundError):
await svc.delete_session(session_id=s["id"], user_id="u2")
await svc.delete_session(session_id=s["id"], user_id="u1")
with pytest.raises(MafNotFoundError):
await svc.get_session(session_id=s["id"], user_id="u1")
# ── run lifecycle ──────────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_create_run_sets_session_running(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
# No real MAF executor exists yet (Phase 2+): the run is parked in
# ``pending`` (a clearly reserved, not-yet-executing state) rather than
# pretending to be ``running``; the session is occupied (``running``).
assert run["status"] == "pending"
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "running"
@pytest.mark.asyncio
async def test_create_run_rejects_second_active_run(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
await svc.create_run(session_id=s["id"], user_id="u1")
with pytest.raises(MafConflictError):
await svc.create_run(session_id=s["id"], user_id="u1")
@pytest.mark.asyncio
async def test_update_session_rejected_while_running(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
await svc.create_run(session_id=s["id"], user_id="u1")
with pytest.raises(MafConflictError):
await svc.update_session(session_id=s["id"], user_id="u1", fields={"title": "x"})
@pytest.mark.asyncio
async def test_cancel_run_marks_session_cancelled(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
cancelled = await svc.cancel_run(run_id=run["id"], user_id="u1")
assert cancelled["status"] == "cancelled"
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "cancelled"
# ── events: monotonic seq + concurrent appends (MAF-01-06) ────────────────
@pytest.mark.asyncio
async def test_append_event_monotonic_seq(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
e1 = await svc.append_event(run_id=run["id"], user_id="u1", event_type="run.started")
e2 = await svc.append_event(run_id=run["id"], user_id="u1", event_type="agent.message.completed")
e3 = await svc.append_event(run_id=run["id"], user_id="u1", event_type="run.completed")
assert [e1["seq"], e2["seq"], e3["seq"]] == [1, 2, 3]
refreshed_run = await svc.get_run(run_id=run["id"], user_id="u1")
assert refreshed_run["last_event_seq"] == 3
@pytest.mark.asyncio
async def test_concurrent_appends_produce_dense_seq_set(store):
"""Many parallel appends must produce a dense 1..N seq set — no gaps, no
collisions — exercising the MAX+1 retry on the (run_id, seq) unique
constraint (MAF-01-06)."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
n = 40
results = await asyncio.gather(
*[
svc.append_event(
run_id=run["id"],
user_id="u1",
event_type="agent.message.delta",
payload={"i": i},
)
for i in range(n)
]
)
seqs = sorted(r["seq"] for r in results)
assert seqs == list(range(1, n + 1))
@pytest.mark.asyncio
async def test_list_events_after_seq_pull(store):
"""断线补拉: events with seq > after_seq in ascending order."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
for i in range(5):
await svc.append_event(run_id=run["id"], user_id="u1", event_type="tool.progress", payload={"i": i})
events, latest = await svc.list_events(run_id=run["id"], user_id="u1", after_seq=2)
assert [e["seq"] for e in events] == [3, 4, 5]
assert latest == 5
# ── actions: idempotency key ──────────────────────────────────────────────
@pytest.mark.asyncio
async def test_action_idempotency_key_unique(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
from sqlalchemy.exc import IntegrityError
await store.actions.create_action(
{
"session_id": s["id"],
"run_id": run["id"],
"tool_name": "update_task",
"idempotency_key": "sess1+run1+seat-a+update_task+act1",
"risk_level": "R2",
"status": "pending",
}
)
with pytest.raises(IntegrityError):
await store.actions.create_action(
{
"session_id": s["id"],
"run_id": run["id"],
"tool_name": "update_task",
"idempotency_key": "sess1+run1+seat-a+update_task+act1",
"status": "pending",
}
)
found = await store.actions.get_by_idempotency_key("sess1+run1+seat-a+update_task+act1")
assert found is not None
assert found["tool_name"] == "update_task"
# ── approvals: decision transition ────────────────────────────────────────
@pytest.mark.asyncio
async def test_approval_decision_and_already_decided_guard(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
appr = await store.approvals.create_approval(
{"session_id": s["id"], "run_id": run["id"], "summary": "高风险写入", "status": "pending"}
)
decided = await svc.decide_approval(approval_id=appr["id"], decision="approved", user_id="u1")
assert decided["status"] == "approved"
assert decided["decided_by"] == "u1"
with pytest.raises(MafConflictError):
await svc.decide_approval(approval_id=appr["id"], decision="rejected", user_id="u1")
@@ -0,0 +1,319 @@
"""P1 concurrency + single-transaction launch tests for MAF roundtable.
Covers:
- **Concurrent run launch**: ``asyncio.gather`` of ≥8 ``create_run`` calls must
yield exactly one active run; the rest get ``MafConflictError``.
- **Single-transaction atomicity**: flush / pre-commit failures roll back fully —
session stays at its prior status, no orphan run, no residual ``starting``.
- **Success shape**: session ``running``, unique run ``pending``.
- **Cancel then re-launch** works.
- **Concurrent approval decision**: parallel approve + reject → exactly one winner.
"""
from __future__ import annotations
import asyncio
from unittest.mock import patch
import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.maf_roundtable.service import (
MafConflictError,
MafRoundtableService,
)
from deerflow.persistence.base import Base
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
@pytest_asyncio.fixture
async def store(tmp_path):
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf_conc.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
yield make_maf_roundtable_store(sf)
await engine.dispose()
def _svc(store, *, enabled=True, admin_diagnostic_access=True):
return MafRoundtableService(store, enabled=enabled, admin_diagnostic_access=admin_diagnostic_access)
# ── P1: concurrent run launch (single-tx CAS) ─────────────────────────────
@pytest.mark.asyncio
async def test_concurrent_create_run_only_one_wins(store):
"""8 parallel ``create_run`` calls → exactly one active run, 7 conflicts."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
async def _attempt() -> tuple[str, object]:
try:
run = await svc.create_run(session_id=s["id"], user_id="u1")
return ("ok", run)
except MafConflictError as exc:
return ("conflict", exc)
results = await asyncio.gather(*[_attempt() for _ in range(8)])
oks = [r for r in results if r[0] == "ok"]
conflicts = [r for r in results if r[0] == "conflict"]
assert len(oks) == 1, f"expected exactly one winner, got {len(oks)}"
assert len(conflicts) == 7
runs = await svc.list_runs(session_id=s["id"], user_id="u1")
active = [r for r in runs if r["status"] in ("pending", "running", "waiting_approval", "waiting_input")]
assert len(active) == 1
assert active[0]["id"] == oks[0][1]["id"]
assert active[0]["status"] == "pending"
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "running"
@pytest.mark.asyncio
async def test_create_run_success_session_running_run_pending(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
assert run["status"] == "pending"
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "running"
assert len(await svc.list_runs(session_id=s["id"], user_id="u1")) == 1
@pytest.mark.asyncio
async def test_concurrent_create_run_second_launch_after_cancel(store):
"""After the winning run is cancelled, a fresh launch succeeds."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
results = await asyncio.gather(
*[svc.create_run(session_id=s["id"], user_id="u1") for _ in range(3)],
return_exceptions=True,
)
winners = [r for r in results if not isinstance(r, Exception)]
assert len(winners) == 1
await svc.cancel_run(run_id=winners[0]["id"], user_id="u1")
run2 = await svc.create_run(session_id=s["id"], user_id="u1")
assert run2["status"] == "pending"
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "running"
@pytest.mark.asyncio
async def test_flush_failure_rolls_back_session_and_no_run(store):
"""If flush() fails after the claim UPDATE, the whole transaction rolls back:
session stays at its prior status and no run row is persisted.
"""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
prior_status = s["status"]
assert prior_status == "draft"
async def boom_flush(self, *args, **kwargs):
raise RuntimeError("simulated flush failure")
with patch.object(AsyncSession, "flush", boom_flush):
with pytest.raises(RuntimeError, match="simulated flush failure"):
await svc.create_run(session_id=s["id"], user_id="u1")
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == prior_status
assert refreshed["status"] != "starting"
assert await svc.list_runs(session_id=s["id"], user_id="u1") == []
# A subsequent healthy launch still works.
run = await svc.create_run(session_id=s["id"], user_id="u1")
assert run["status"] == "pending"
@pytest.mark.asyncio
async def test_pre_commit_failure_leaves_no_starting_residue(store):
"""If an error occurs after flush but before commit, the transaction rolls
back: session must not residual ``starting`` / ``running``, and no run row.
"""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
real_flush = AsyncSession.flush
async def flush_then_boom(self, *args, **kwargs):
await real_flush(self, *args, **kwargs)
raise RuntimeError("simulated post-flush pre-commit failure")
with patch.object(AsyncSession, "flush", flush_then_boom):
with pytest.raises(RuntimeError, match="simulated post-flush pre-commit failure"):
await svc.create_run(session_id=s["id"], user_id="u1")
refreshed = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed["status"] == "draft"
assert refreshed["status"] != "starting"
assert await svc.list_runs(session_id=s["id"], user_id="u1") == []
# ── P1: concurrent approval decision ──────────────────────────────────────
@pytest.mark.asyncio
async def test_concurrent_approval_decision_only_one_wins(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
appr = await store.approvals.create_approval(
{"session_id": s["id"], "run_id": run["id"], "summary": "高风险写入", "status": "pending"}
)
async def _decide(decision: str, who: str) -> tuple[str, object]:
try:
decided = await svc.decide_approval(approval_id=appr["id"], decision=decision, user_id=who)
return ("ok", decided)
except MafConflictError as exc:
return ("conflict", exc)
results = await asyncio.gather(
*[_decide("approved", "u1") for _ in range(4)],
*[_decide("rejected", "u1") for _ in range(4)],
)
oks = [r for r in results if r[0] == "ok"]
conflicts = [r for r in results if r[0] == "conflict"]
assert len(oks) == 1, f"expected exactly one winning decision, got {len(oks)}"
assert len(conflicts) == 7
winner = oks[0][1]
final = await store.approvals.get_approval(appr["id"])
assert final["status"] == winner["status"]
assert final["decided_by"] == winner["decided_by"] == "u1"
assert final["decided_at"] == winner["decided_at"]
assert final["decided_at"] is not None
@pytest.mark.asyncio
async def test_approval_decision_cannot_be_overwritten(store):
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
appr = await store.approvals.create_approval(
{"session_id": s["id"], "run_id": run["id"], "summary": "x", "status": "pending"}
)
first = await svc.decide_approval(approval_id=appr["id"], decision="approved", user_id="u1")
with pytest.raises(MafConflictError):
await svc.decide_approval(approval_id=appr["id"], decision="rejected", user_id="u1")
final = await store.approvals.get_approval(appr["id"])
assert final["status"] == first["status"] == "approved"
assert final["decided_by"] == "u1"
# ── P1: cancel_run single-transaction atomicity ───────────────────────────
@pytest.mark.asyncio
async def test_cancel_run_flush_failure_rolls_back_run_and_session(store):
"""If the cancel transaction's flush fails, run stays pending and session
stays running — nothing is half-committed."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
assert run["status"] == "pending"
async def boom_flush(self, *args, **kwargs):
raise RuntimeError("simulated cancel flush failure")
with patch.object(AsyncSession, "flush", boom_flush):
with pytest.raises(RuntimeError, match="simulated cancel flush failure"):
await svc.cancel_run(run_id=run["id"], user_id="u1")
refreshed_run = await svc.get_run(run_id=run["id"], user_id="u1")
assert refreshed_run["status"] == "pending"
assert refreshed_run["finished_at"] is None
refreshed_session = await svc.get_session(session_id=s["id"], user_id="u1")
assert refreshed_session["status"] == "running"
# A healthy cancel afterwards succeeds.
cancelled = await svc.cancel_run(run_id=run["id"], user_id="u1")
assert cancelled["status"] == "cancelled"
@pytest.mark.asyncio
async def test_cancel_repairs_historical_inconsistent_session(store):
"""Historical half-completed data: run=cancelled but session still running.
Re-cancelling returns the cancelled run and repairs the session."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
# Manufacture the inconsistency: run cancelled, session left running.
await store.runs.set_status(run["id"], "cancelled")
await store.sessions.set_status(s["id"], "running")
assert (await svc.get_session(session_id=s["id"], user_id="u1"))["status"] == "running"
result = await svc.cancel_run(run_id=run["id"], user_id="u1")
assert result["status"] == "cancelled"
assert (await svc.get_session(session_id=s["id"], user_id="u1"))["status"] == "cancelled"
@pytest.mark.asyncio
async def test_cancel_terminal_run_does_not_change_run(store):
"""A completed/failed run is not re-cancelled; its status is returned as-is."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
await store.runs.set_status(run["id"], "completed")
await store.sessions.set_status(s["id"], "completed")
result = await svc.cancel_run(run_id=run["id"], user_id="u1")
assert result["status"] == "completed"
assert (await svc.get_run(run_id=run["id"], user_id="u1"))["status"] == "completed"
@pytest.mark.asyncio
async def test_concurrent_cancel_same_run_consistent(store):
"""Two concurrent cancels of the same run → run and session both cancelled,
no exceptions, no inconsistent state."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
results = await asyncio.gather(
*[svc.cancel_run(run_id=run["id"], user_id="u1") for _ in range(2)],
return_exceptions=True,
)
assert not any(isinstance(r, Exception) for r in results), results
assert all(r["status"] == "cancelled" for r in results)
assert (await svc.get_run(run_id=run["id"], user_id="u1"))["status"] == "cancelled"
assert (await svc.get_session(session_id=s["id"], user_id="u1"))["status"] == "cancelled"
# ── P2: pending run time semantics ────────────────────────────────────────
@pytest.mark.asyncio
async def test_pending_run_has_no_started_at(store):
"""A freshly-created pending run is queued, not started: started_at is None."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
assert run["status"] == "pending"
assert run["started_at"] is None
@pytest.mark.asyncio
async def test_cancel_pending_run_sets_finished_at(store):
"""Cancelling a pending run sets finished_at (terminal) while started_at
stays None (it never actually ran)."""
svc = _svc(store)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
cancelled = await svc.cancel_run(run_id=run["id"], user_id="u1")
assert cancelled["status"] == "cancelled"
assert cancelled["finished_at"] is not None
assert cancelled["started_at"] is None
@@ -0,0 +1,59 @@
"""P2 deployment-config enum / range validation for MafRoundtableConfig.
Config and API schemas share ``MafMode`` / ``MafWritePolicy`` from
``deerflow.config.maf_roundtable_config`` — invalid deployment values must fail
at load time, not silently become runtime bugs.
"""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
def test_valid_config_loads():
cfg = MafRoundtableConfig(
enabled=True,
default_mode="group_chat",
default_write_policy="auto",
default_max_rounds=16,
admin_diagnostic_access=False,
)
assert cfg.default_mode == "group_chat"
assert cfg.default_write_policy == "auto"
assert cfg.default_max_rounds == 16
def test_default_config_loads():
cfg = MafRoundtableConfig()
assert cfg.enabled is False
assert cfg.default_mode == "structured"
assert cfg.default_write_policy == "confirm_high_risk"
assert cfg.default_max_rounds == 8
def test_invalid_default_mode_rejected():
with pytest.raises(ValidationError):
MafRoundtableConfig(default_mode="wrong")
def test_invalid_default_write_policy_rejected():
with pytest.raises(ValidationError):
MafRoundtableConfig(default_write_policy="wrong")
def test_default_max_rounds_zero_rejected():
with pytest.raises(ValidationError):
MafRoundtableConfig(default_max_rounds=0)
def test_default_max_rounds_above_cap_rejected():
with pytest.raises(ValidationError):
MafRoundtableConfig(default_max_rounds=65)
def test_allow_mock_events_field_removed():
"""allow_mock_events must not be a config field anymore."""
assert "allow_mock_events" not in MafRoundtableConfig.model_fields
@@ -0,0 +1,474 @@
"""P2 HTTP route tests for the MAF roundtable API.
Covers the full HTTP status code matrix:
- **401 Unauthorized**: missing / invalid auth
- **403 Forbidden**: admin trying to write another user's resource
- **404 Not Found**: non-existent session / run / action / approval
- **409 Conflict**: concurrent run launch, already-decided approval
- **422 Unprocessable Entity**: invalid enum values (mode, write_policy, role)
- **503 Service Unavailable**: feature disabled, mock events disabled
Also verifies that identity comes from ``request.state.user`` (stamped by auth
middleware), not from body parameters — a client cannot forge ``user_id`` in the
request body to impersonate another user.
"""
from __future__ import annotations
import pytest
import pytest_asyncio
from fastapi import FastAPI, Request
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.gateway.routers.maf_roundtable import router as maf_router
from app.maf_roundtable import MafRoundtableService
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
from deerflow.persistence.base import Base
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
class FakeUser:
"""Minimal user object for testing (mimics the real User model's shape)."""
def __init__(self, user_id: str, is_admin: bool = False):
self.id = user_id
self.system_role = "admin" if is_admin else "user"
@pytest_asyncio.fixture
async def app_and_client(tmp_path):
"""Build a minimal FastAPI app with the MAF router + a fake auth middleware."""
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf_http.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
store = make_maf_roundtable_store(sf)
cfg = MafRoundtableConfig(enabled=True, admin_diagnostic_access=True)
svc = MafRoundtableService(store, enabled=True, admin_diagnostic_access=True, config=cfg)
app = FastAPI()
app.state.maf_roundtable_service = svc
app.include_router(maf_router)
# Fake auth middleware: reads X-Test-User / X-Test-Role headers and stamps
# request.state.user. No header → 401 (unauthenticated).
@app.middleware("http")
async def fake_auth(request: Request, call_next):
user_id = request.headers.get("X-Test-User")
if user_id is None:
from starlette.responses import JSONResponse
return JSONResponse(status_code=401, content={"detail": "Authentication required"})
is_admin = request.headers.get("X-Test-Role") == "admin"
request.state.user = FakeUser(user_id, is_admin)
return await call_next(request)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield app, client, store
await engine.dispose()
# ── 401 Unauthorized ──────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_401_missing_auth(app_and_client):
_, client, _ = app_and_client
resp = await client.get("/api/maf-roundtable/sessions")
assert resp.status_code == 401
# ── 403 Forbidden (admin write cross-user) ────────────────────────────────
@pytest.mark.asyncio
async def test_403_admin_cannot_update_other_user_session(app_and_client):
_, client, _ = app_and_client
# alice creates a session
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
session_id = resp.json()["id"]
# admin tries to update it → 403
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"title": "hijack"},
headers={"X-Test-User": "admin-1", "X-Test-Role": "admin"},
)
assert resp.status_code == 403
@pytest.mark.asyncio
async def test_403_admin_cannot_delete_other_user_session(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.delete(
f"/api/maf-roundtable/sessions/{session_id}",
headers={"X-Test-User": "admin-1", "X-Test-Role": "admin"},
)
assert resp.status_code == 403
# ── 404 Not Found ─────────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_404_nonexistent_session(app_and_client):
_, client, _ = app_and_client
resp = await client.get(
"/api/maf-roundtable/sessions/nonexistent-id",
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_404_other_user_session_not_leaked(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
# bob (non-admin) tries to read alice's session → 404 (not 403, so existence is not leaked)
resp = await client.get(
f"/api/maf-roundtable/sessions/{session_id}",
headers={"X-Test-User": "bob"},
)
assert resp.status_code == 404
# ── 409 Conflict ──────────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_409_second_run_launch_conflicts(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
# First run launch succeeds
resp = await client.post(
f"/api/maf-roundtable/sessions/{session_id}/runs",
json={},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
# Second run launch → 409
resp = await client.post(
f"/api/maf-roundtable/sessions/{session_id}/runs",
json={},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 409
@pytest.mark.asyncio
async def test_409_approval_already_decided(app_and_client):
_, client, store = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.post(
f"/api/maf-roundtable/sessions/{session_id}/runs",
json={},
headers={"X-Test-User": "alice"},
)
run_id = resp.json()["id"]
# Create an approval directly via the store
appr = await store.approvals.create_approval(
{"session_id": session_id, "run_id": run_id, "summary": "x", "status": "pending"}
)
# First decision succeeds
resp = await client.post(
f"/api/maf-roundtable/approvals/{appr['id']}/decision",
json={"decision": "approved"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
# Second decision → 409
resp = await client.post(
f"/api/maf-roundtable/approvals/{appr['id']}/decision",
json={"decision": "rejected"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 409
# ── 422 Unprocessable Entity (invalid enums) ──────────────────────────────
@pytest.mark.asyncio
async def test_422_invalid_mode(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "mode": "invalid_mode"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_422_invalid_write_policy(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "write_policy": "invalid_policy"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_422_invalid_participant_role(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "participants": [{"agent_id": "a1", "role": "invalid_role"}]},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
# ── 503 Service Unavailable ───────────────────────────────────────────────
@pytest.mark.asyncio
async def test_503_feature_disabled(tmp_path):
"""When the feature flag is off, write paths return 503."""
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf_disabled.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
store = make_maf_roundtable_store(sf)
cfg = MafRoundtableConfig(enabled=False)
svc = MafRoundtableService(store, enabled=False, admin_diagnostic_access=True, config=cfg)
app = FastAPI()
app.state.maf_roundtable_service = svc
app.include_router(maf_router)
@app.middleware("http")
async def fake_auth(request: Request, call_next):
request.state.user = FakeUser("alice", False)
return await call_next(request)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
resp = await client.post("/api/maf-roundtable/sessions", json={"task_text": "t"})
assert resp.status_code == 503
await engine.dispose()
@pytest.mark.asyncio
async def test_404_post_events_endpoint_removed(app_and_client):
"""POST /runs/{id}/events is deliberately absent — no public mock write path."""
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.post(
f"/api/maf-roundtable/sessions/{session_id}/runs",
json={},
headers={"X-Test-User": "alice"},
)
run_id = resp.json()["id"]
resp = await client.post(
f"/api/maf-roundtable/runs/{run_id}/events",
json={"event_type": "manager.decision"},
headers={"X-Test-User": "alice"},
)
# FastAPI returns 405 when GET exists on the same path but POST is not
# registered; either 404 or 405 means no public write surface.
assert resp.status_code in (404, 405)
@pytest.mark.asyncio
async def test_internal_append_event_still_writes(app_and_client):
"""service.append_event remains available for the future MAF executor."""
app, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.post(
f"/api/maf-roundtable/sessions/{session_id}/runs",
json={},
headers={"X-Test-User": "alice"},
)
run_id = resp.json()["id"]
svc = app.state.maf_roundtable_service
event = await svc.append_event(run_id=run_id, user_id="alice", event_type="run.started")
assert event["seq"] == 1
assert event["event_type"] == "run.started"
# Public GET still works for the written event.
resp = await client.get(
f"/api/maf-roundtable/runs/{run_id}/events",
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
assert len(resp.json()["events"]) == 1
# ── PUT explicit-null rejection ───────────────────────────────────────────
@pytest.mark.asyncio
async def test_422_put_mode_null(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"mode": None},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_422_put_title_null(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "title": "keep"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"title": None},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_422_put_max_rounds_null(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"max_rounds": None},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_200_put_task_payload_null_clears(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "task_payload": {"k": 1}},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
assert resp.json()["task_payload"] == {"k": 1}
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"task_payload": None},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
assert resp.json()["task_payload"] is None
@pytest.mark.asyncio
async def test_200_put_model_name_null_clears(app_and_client):
_, client, _ = app_and_client
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "model_name": "glm-5"},
headers={"X-Test-User": "alice"},
)
session_id = resp.json()["id"]
assert resp.json()["model_name"] == "glm-5"
resp = await client.put(
f"/api/maf-roundtable/sessions/{session_id}",
json={"model_name": None},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
assert resp.json()["model_name"] is None
# ── Identity forgery prevention ───────────────────────────────────────────
@pytest.mark.asyncio
async def test_identity_from_request_state_not_body(app_and_client):
"""A client cannot forge user_id in the request body to impersonate another user.
The service reads user_id from request.state.user (stamped by auth middleware),
not from the request body. Even if a malicious client includes a user_id field
in the JSON body, it is ignored.
"""
_, client, _ = app_and_client
# alice creates a session
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t"},
headers={"X-Test-User": "alice"},
)
assert resp.status_code == 200
session_id = resp.json()["id"]
assert resp.json()["user_id"] == "alice"
# bob tries to create a session with a forged user_id in the body
resp = await client.post(
"/api/maf-roundtable/sessions",
json={"task_text": "t", "user_id": "alice"}, # forged field
headers={"X-Test-User": "bob"},
)
assert resp.status_code == 200
# The session is owned by bob (from request.state.user), not alice (from body)
assert resp.json()["user_id"] == "bob"
# bob cannot read alice's session
resp = await client.get(
f"/api/maf-roundtable/sessions/{session_id}",
headers={"X-Test-User": "bob"},
)
assert resp.status_code == 404
@@ -0,0 +1,205 @@
"""User-isolation + table-isolation tests for the MAF roundtable experiment (MAF-01-07).
These tests focus on the security boundary: a non-owner cannot read or mutate
another user's session / run / action / approval, and the six MAF tables have
no foreign-key relationship to the legacy ``roundtable_*`` tables (the
experiment is fully isolated — see implementation plan §2.3 "不改原有的工程定义").
"""
from __future__ import annotations
import pytest
import pytest_asyncio
from sqlalchemy import inspect
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.maf_roundtable.service import MafNotFoundError, MafRoundtableService
from deerflow.persistence.base import Base
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
from deerflow.persistence.maf_roundtable.model import (
MafRoundtableActionRow,
MafRoundtableApprovalRow,
MafRoundtableEventRow,
MafRoundtableParticipantRow,
MafRoundtableRunRow,
MafRoundtableSessionRow,
)
@pytest_asyncio.fixture
async def store(tmp_path):
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'maf_iso.db'}")
async with engine.begin() as conn:
import deerflow.persistence.maf_roundtable.model # noqa: F401
await conn.run_sync(Base.metadata.create_all)
sf = async_sessionmaker(engine, expire_on_commit=False)
yield make_maf_roundtable_store(sf), engine
await engine.dispose()
def _svc(store, *, enabled=True, admin_diagnostic_access=True):
return MafRoundtableService(store, enabled=enabled, admin_diagnostic_access=admin_diagnostic_access)
# ── user isolation: non-owner cannot read ────────────────────────────────
@pytest.mark.asyncio
async def test_non_owner_cannot_read_session(store):
svc, _ = store
s = await svc.sessions.create_session({"user_id": "u1", "task_text": "secret"})
fetched = await svc.sessions.get_session(s["id"], user_id="u2")
assert fetched is None # owner scope returns None, not the row
@pytest.mark.asyncio
async def test_non_owner_cannot_update_session(store):
svc, _ = store
s = await svc.sessions.create_session({"user_id": "u1", "task_text": "t"})
updated = await svc.sessions.update_session(s["id"], user_id="u2", fields={"title": "hijack"})
assert updated is None
refreshed = await svc.sessions.get_session(s["id"], user_id="u1")
assert refreshed["title"] == "" # unchanged
@pytest.mark.asyncio
async def test_non_owner_cannot_delete_session(store):
svc, _ = store
s = await svc.sessions.create_session({"user_id": "u1", "task_text": "t"})
ok = await svc.sessions.delete_session(s["id"], user_id="u2")
assert ok is False
refreshed = await svc.sessions.get_session(s["id"], user_id="u1")
assert refreshed is not None # still there
@pytest.mark.asyncio
async def test_service_non_owner_get_raises_not_found(store):
"""At the service layer, an out-of-scope read surfaces as 404 (not 403) so
the existence of another user's session is not leaked (MAF-01-07)."""
svc = _svc(store[0])
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
with pytest.raises(MafNotFoundError):
await svc.get_session(session_id=s["id"], user_id="u2")
@pytest.mark.asyncio
async def test_non_owner_cannot_read_run_via_service(store):
svc = _svc(store[0])
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
with pytest.raises(MafNotFoundError):
await svc.get_run(run_id=run["id"], user_id="u2")
@pytest.mark.asyncio
async def test_non_owner_cannot_append_event(store):
svc = _svc(store[0])
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
with pytest.raises(MafNotFoundError):
await svc.append_event(run_id=run["id"], user_id="u2", event_type="run.started")
@pytest.mark.asyncio
async def test_non_owner_cannot_read_action(store):
svc = _svc(store[0])
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
run = await svc.create_run(session_id=s["id"], user_id="u1")
action = await store[0].actions.create_action(
{
"session_id": s["id"],
"run_id": run["id"],
"tool_name": "update_task",
"idempotency_key": "k1",
"status": "pending",
}
)
with pytest.raises(MafNotFoundError):
await svc.get_action(action_id=action["id"], user_id="u2")
# ── admin diagnostic access ───────────────────────────────────────────────
@pytest.mark.asyncio
async def test_admin_diagnostic_access_bypasses_owner_filter(store):
svc = _svc(store[0], admin_diagnostic_access=True)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
fetched = await svc.get_session(session_id=s["id"], user_id="admin-1", is_admin=True)
assert fetched["id"] == s["id"]
rows, total = await svc.list_sessions(user_id="admin-1", is_admin=True)
assert total >= 1
@pytest.mark.asyncio
async def test_admin_diagnostic_access_off_keeps_owner_scope(store):
svc = _svc(store[0], admin_diagnostic_access=False)
s = await svc.create_session(user_id="u1", body={"task_text": "t"})
with pytest.raises(MafNotFoundError):
await svc.get_session(session_id=s["id"], user_id="admin-1", is_admin=True)
# ── table isolation: no FK to legacy roundtable_* ─────────────────────────
@pytest.mark.asyncio
async def test_maf_tables_isolated_from_legacy_roundtable(store):
"""The six MAF tables must exist and none of their FKs may target a legacy
roundtable_* table (MAF-01-02 / 退出标准: MAF 表和旧 roundtable 表完全无关联外键)."""
_, engine = store
async with engine.connect() as conn:
table_names = await conn.run_sync(lambda sync_conn: set(inspect(sync_conn).get_table_names()))
maf_tables = {n for n in table_names if n.startswith("maf_roundtable_")}
assert maf_tables == {
"maf_roundtable_sessions",
"maf_roundtable_participants",
"maf_roundtable_runs",
"maf_roundtable_events",
"maf_roundtable_actions",
"maf_roundtable_approvals",
}
# Every FK defined on an MAF model must reference another maf_roundtable_* table.
maf_models = [
MafRoundtableSessionRow,
MafRoundtableParticipantRow,
MafRoundtableRunRow,
MafRoundtableEventRow,
MafRoundtableActionRow,
MafRoundtableApprovalRow,
]
for model in maf_models:
for fk in model.__table__.foreign_keys:
target_table = fk.column.table.name
assert target_table.startswith("maf_roundtable_"), (
f"{model.__tablename__} FK targets non-MAF table {target_table}"
)
# ── feature flag (MAF-01-04) ──────────────────────────────────────────────
@pytest.mark.asyncio
async def test_disabled_feature_rejects_writes(store):
from app.maf_roundtable.service import MafDisabledError
svc = _svc(store[0], enabled=False)
with pytest.raises(MafDisabledError):
await svc.create_session(user_id="u1", body={"task_text": "t"})
@pytest.mark.asyncio
async def test_disabled_feature_keeps_reads_open(store):
from app.maf_roundtable.service import MafDisabledError
svc_on = _svc(store[0], enabled=True)
s = await svc_on.create_session(user_id="u1", body={"task_text": "t"})
svc_off = _svc(store[0], enabled=False)
# Reads do not raise — admin can review history while the feature is off.
fetched = await svc_off.get_session(session_id=s["id"], user_id="u1")
assert fetched["id"] == s["id"]
# But a write through the disabled service still raises.
with pytest.raises(MafDisabledError):
await svc_off.update_session(session_id=s["id"], user_id="u1", fields={"title": "x"})