代码提交
This commit is contained in:
1 parent
d93cc62806
commit
ddf83f7728
25 files changed
+4086
-424
No files matched your search
@@ -436,3 +436,150 @@ class TestAdapterEventFlow:
|
||||
|
||||
events, _ = await svc.list_events(run_id=run["id"], user_id="u1")
|
||||
assert len(events) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_critical_passes_persisted_audit_id_to_bridge(self, store):
|
||||
"""_emit_critical must capture the persisted audit row id and pass it
|
||||
as source_audit_event_id to _bridge_conversation_event, so projection
|
||||
dedup is keyed on the real audit row — not an ephemeral input field."""
|
||||
svc = _svc(store)
|
||||
session = await svc.create_session(user_id="u1", body={"task_text": "test"})
|
||||
run = await svc.create_run(session_id=session["id"], user_id="u1")
|
||||
|
||||
client = _mock_client()
|
||||
adapter = DeerFlowAgentAdapter(client, service=svc, user_id="u1")
|
||||
|
||||
bridge_calls: list[dict] = []
|
||||
original_bridge = adapter._bridge_conversation_event
|
||||
|
||||
async def capture_bridge(run_id, event, *, source_audit_event_id=None):
|
||||
bridge_calls.append({
|
||||
"run_id": run_id,
|
||||
"event_type": event.get("event_type"),
|
||||
"source_audit_event_id": source_audit_event_id,
|
||||
})
|
||||
await original_bridge(run_id, event, source_audit_event_id=source_audit_event_id)
|
||||
|
||||
adapter._bridge_conversation_event = capture_bridge
|
||||
|
||||
critical_event = make_turn_started("expert", 1)
|
||||
await adapter._emit_critical(run["id"], critical_event)
|
||||
|
||||
assert len(bridge_calls) == 1
|
||||
assert bridge_calls[0]["source_audit_event_id"] is not None
|
||||
assert isinstance(bridge_calls[0]["source_audit_event_id"], str)
|
||||
assert len(bridge_calls[0]["source_audit_event_id"]) > 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_passes_persisted_audit_id_for_non_critical(self, store):
|
||||
"""_emit (non-critical path) must also pass persisted audit row id."""
|
||||
svc = _svc(store)
|
||||
session = await svc.create_session(user_id="u1", body={"task_text": "test"})
|
||||
run = await svc.create_run(session_id=session["id"], user_id="u1")
|
||||
|
||||
client = _mock_client()
|
||||
adapter = DeerFlowAgentAdapter(client, service=svc, user_id="u1")
|
||||
|
||||
bridge_calls: list[dict] = []
|
||||
original_bridge = adapter._bridge_conversation_event
|
||||
|
||||
async def capture_bridge(run_id, event, *, source_audit_event_id=None):
|
||||
bridge_calls.append({
|
||||
"source_audit_event_id": source_audit_event_id,
|
||||
})
|
||||
await original_bridge(run_id, event, source_audit_event_id=source_audit_event_id)
|
||||
|
||||
adapter._bridge_conversation_event = capture_bridge
|
||||
|
||||
ev = {
|
||||
"event_type": "agent.message.delta",
|
||||
"agent_id": "a1",
|
||||
"turn_index": 0,
|
||||
"payload": {"text": "hello"},
|
||||
"source_event_id": "stream:evt_001",
|
||||
}
|
||||
await adapter._emit(run["id"], ev)
|
||||
|
||||
assert len(bridge_calls) == 1
|
||||
assert bridge_calls[0]["source_audit_event_id"] is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_critical_dedup_across_simulated_restart(self, store):
|
||||
"""Simulate: emit critical event, then 'restart' and re-emit the same
|
||||
event via reconcile. The conversation projection must be deduped via
|
||||
the persisted audit row id — no duplicate conversation events."""
|
||||
from app.maf_roundtable.conversation_event_hub import ConversationEventHub
|
||||
from app.maf_roundtable.conversation_service import MafConversationService
|
||||
|
||||
class FakeMafConfig:
|
||||
enabled = True
|
||||
default_mode = "structured"
|
||||
default_model_name = "test"
|
||||
default_reasoning_effort = None
|
||||
default_manager_agent_id = "mgr"
|
||||
default_max_rounds = 8
|
||||
default_write_policy = "confirm_high_risk"
|
||||
admin_diagnostic_access = True
|
||||
|
||||
hub = ConversationEventHub(heartbeat_interval=0.3)
|
||||
conv_svc = MafConversationService(store, maf_config=FakeMafConfig(), event_hub=hub)
|
||||
|
||||
conv = await conv_svc.create_conversation(user_id="u1", title="RestartDedup")
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
svc = _svc(store)
|
||||
session = await svc.create_session(user_id="u1", body={"task_text": "test"})
|
||||
run = await svc.create_run(session_id=session["id"], user_id="u1")
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
sess_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableSessionRow).where(
|
||||
MafRoundtableSessionRow.id == session["id"]
|
||||
)
|
||||
)
|
||||
).scalars().first()
|
||||
conv_row.internal_session_id = sess_row.id
|
||||
run_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableRunRow).where(
|
||||
MafRoundtableRunRow.id == run["id"]
|
||||
)
|
||||
)
|
||||
).scalars().first()
|
||||
assert run_row is not None
|
||||
|
||||
client = _mock_client()
|
||||
adapter = DeerFlowAgentAdapter(client, service=svc, user_id="u1")
|
||||
|
||||
critical_event = {
|
||||
"event_type": "action.waiting_approval",
|
||||
"agent_id": "seat_a",
|
||||
"turn_index": 1,
|
||||
"payload": {"tool_name": "write_file", "summary": "high risk"},
|
||||
}
|
||||
await adapter._emit_critical(run["id"], critical_event)
|
||||
|
||||
await conv_svc.reconcile_conversation_events(run_id=run["id"])
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
approval_events = [e for e in events if e["type"] == "approval.required"]
|
||||
assert len(approval_events) == 1
|
||||
|
||||
hub.shutdown()
|
||||
@@ -20,6 +20,7 @@ from scripts.migrate_maf_roundtable_conversation_v2 import (
|
||||
MESSAGES_TABLE,
|
||||
_conversations_ddl,
|
||||
_events_ddl,
|
||||
_events_table_has_source_unique,
|
||||
_indexes_ddl,
|
||||
_messages_ddl,
|
||||
run_migration,
|
||||
@@ -188,3 +189,362 @@ def test_sqlite_ddl_generation():
|
||||
assert any("ix_maf_conv_owner_updated" in i for i in indexes)
|
||||
assert any("ix_maf_msg_conv_seq" in i for i in indexes)
|
||||
assert any("ix_maf_cevt_conv_seq" in i for i in indexes)
|
||||
|
||||
|
||||
# ── In-place upgrade: existing events table missing source_event_id ──────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upgrade_adds_source_event_id_to_existing_events_table(tmp_path):
|
||||
"""Old V2 deployments created the events table without source_event_id.
|
||||
Running the migration must ALTER TABLE ADD COLUMN + create unique index."""
|
||||
db_url = f"sqlite+aiosqlite:///{tmp_path / 'upgrade.db'}"
|
||||
|
||||
# Phase 1: create tables with the OLD schema (no source_event_id).
|
||||
engine_old = create_async_engine(db_url)
|
||||
async with engine_old.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_sessions ("
|
||||
"id VARCHAR(64) PRIMARY KEY, user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_text TEXT NOT NULL, "
|
||||
"task_payload_json TEXT, mode VARCHAR(16) NOT NULL DEFAULT 'structured', "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'draft', model_name VARCHAR(128), "
|
||||
"reasoning_effort VARCHAR(32), manager_agent_id VARCHAR(64), "
|
||||
"max_rounds INTEGER NOT NULL DEFAULT 8, write_policy VARCHAR(32) NOT NULL DEFAULT 'confirm_high_risk', "
|
||||
"capability_snapshot_json TEXT, fact_ledger_json TEXT, final_result_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_runs ("
|
||||
"id VARCHAR(64) PRIMARY KEY, session_id VARCHAR(64) NOT NULL, "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'pending', workflow_version VARCHAR(64), "
|
||||
"maf_checkpoint_json TEXT, last_event_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"started_at DATETIME, finished_at DATETIME, error_code VARCHAR(64), "
|
||||
"error_message_safe TEXT, token_usage_json TEXT, latency_ms INTEGER, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {CONVERSATIONS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, owner_user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_context_json TEXT, "
|
||||
"safe_status VARCHAR(32) NOT NULL DEFAULT 'idle', active_run_id VARCHAR(64), "
|
||||
"internal_session_id VARCHAR(64), last_stream_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (active_run_id) REFERENCES maf_roundtable_runs (id) ON DELETE SET NULL, "
|
||||
"FOREIGN KEY (internal_session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE SET NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {MESSAGES_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, message_kind VARCHAR(32) NOT NULL DEFAULT 'user', "
|
||||
"role VARCHAR(16) NOT NULL DEFAULT 'user', agent_id VARCHAR(64), run_id VARCHAR(64), "
|
||||
"message_ref VARCHAR(191), content TEXT NOT NULL DEFAULT '', metadata_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_messages_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
# OLD events table: no source_event_id column
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {EVENTS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, run_id VARCHAR(64), "
|
||||
"event_type VARCHAR(64) NOT NULL, data_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_conv_events_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
# Insert some existing event data that must be preserved
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {CONVERSATIONS_TABLE} (id, owner_user_id, title, safe_status, last_stream_seq, created_at, updated_at) "
|
||||
"VALUES ('c1', 'u1', 'OldData', 'idle', 1, '2026-01-01', '2026-01-01')"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {EVENTS_TABLE} (id, conversation_id, seq, run_id, event_type, data_json, created_at) "
|
||||
"VALUES ('e1', 'c1', 1, NULL, 'user.message.created', '{}', '2026-01-01')"
|
||||
))
|
||||
await engine_old.dispose()
|
||||
|
||||
# Phase 2: run migration — should ALTER TABLE + add unique index
|
||||
await run_migration(db_url)
|
||||
|
||||
# Phase 3: verify the column and index exist, data preserved
|
||||
engine_new = create_async_engine(db_url)
|
||||
async with engine_new.begin() as conn:
|
||||
def _check(sync_conn):
|
||||
insp = inspect(sync_conn)
|
||||
return validate_schema(insp), insp
|
||||
|
||||
issues, insp = await conn.run_sync(_check)
|
||||
assert issues == [], f"Schema issues after upgrade: {issues}"
|
||||
|
||||
# Data preserved
|
||||
row = (await conn.execute(text(f"SELECT title FROM {CONVERSATIONS_TABLE} WHERE id='c1'"))).first()
|
||||
assert row is not None
|
||||
assert row[0] == "OldData"
|
||||
|
||||
evt_row = (await conn.execute(text(f"SELECT event_type FROM {EVENTS_TABLE} WHERE id='e1'"))).first()
|
||||
assert evt_row is not None
|
||||
assert evt_row[0] == "user.message.created"
|
||||
|
||||
# source_event_id column exists and is NULL for old rows
|
||||
src_row = (await conn.execute(text(f"SELECT source_event_id FROM {EVENTS_TABLE} WHERE id='e1'"))).first()
|
||||
assert src_row is not None
|
||||
assert src_row[0] is None
|
||||
|
||||
await engine_new.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upgrade_idempotent_after_alter(tmp_path):
|
||||
"""Running migration twice on an upgraded DB must not error."""
|
||||
db_url = f"sqlite+aiosqlite:///{tmp_path / 'upgrade2.db'}"
|
||||
|
||||
engine_old = create_async_engine(db_url)
|
||||
async with engine_old.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_sessions ("
|
||||
"id VARCHAR(64) PRIMARY KEY, user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_text TEXT NOT NULL, "
|
||||
"task_payload_json TEXT, mode VARCHAR(16) NOT NULL DEFAULT 'structured', "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'draft', model_name VARCHAR(128), "
|
||||
"reasoning_effort VARCHAR(32), manager_agent_id VARCHAR(64), "
|
||||
"max_rounds INTEGER NOT NULL DEFAULT 8, write_policy VARCHAR(32) NOT NULL DEFAULT 'confirm_high_risk', "
|
||||
"capability_snapshot_json TEXT, fact_ledger_json TEXT, final_result_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_runs ("
|
||||
"id VARCHAR(64) PRIMARY KEY, session_id VARCHAR(64) NOT NULL, "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'pending', workflow_version VARCHAR(64), "
|
||||
"maf_checkpoint_json TEXT, last_event_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"started_at DATETIME, finished_at DATETIME, error_code VARCHAR(64), "
|
||||
"error_message_safe TEXT, token_usage_json TEXT, latency_ms INTEGER, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {CONVERSATIONS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, owner_user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_context_json TEXT, "
|
||||
"safe_status VARCHAR(32) NOT NULL DEFAULT 'idle', active_run_id VARCHAR(64), "
|
||||
"internal_session_id VARCHAR(64), last_stream_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (active_run_id) REFERENCES maf_roundtable_runs (id) ON DELETE SET NULL, "
|
||||
"FOREIGN KEY (internal_session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE SET NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {MESSAGES_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, message_kind VARCHAR(32) NOT NULL DEFAULT 'user', "
|
||||
"role VARCHAR(16) NOT NULL DEFAULT 'user', agent_id VARCHAR(64), run_id VARCHAR(64), "
|
||||
"message_ref VARCHAR(191), content TEXT NOT NULL DEFAULT '', metadata_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_messages_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {EVENTS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, run_id VARCHAR(64), "
|
||||
"event_type VARCHAR(64) NOT NULL, data_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_conv_events_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await engine_old.dispose()
|
||||
|
||||
await run_migration(db_url)
|
||||
await run_migration(db_url) # Must not error
|
||||
|
||||
engine_check = create_async_engine(db_url)
|
||||
async with engine_check.begin() as conn:
|
||||
def _check(sync_conn):
|
||||
return validate_schema(inspect(sync_conn))
|
||||
assert await conn.run_sync(_check) == []
|
||||
await engine_check.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upgrade_preserves_existing_event_data_with_null_source(tmp_path):
|
||||
"""Old V2 table with existing event data: upgrade preserves data,
|
||||
source_event_id column is added with NULL for historical rows,
|
||||
and the unique index is created."""
|
||||
db_url = f"sqlite+aiosqlite:///{tmp_path / 'upgrade_data.db'}"
|
||||
|
||||
engine_old = create_async_engine(db_url)
|
||||
async with engine_old.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_sessions ("
|
||||
"id VARCHAR(64) PRIMARY KEY, user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_text TEXT NOT NULL, "
|
||||
"task_payload_json TEXT, mode VARCHAR(16) NOT NULL DEFAULT 'structured', "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'draft', model_name VARCHAR(128), "
|
||||
"reasoning_effort VARCHAR(32), manager_agent_id VARCHAR(64), "
|
||||
"max_rounds INTEGER NOT NULL DEFAULT 8, write_policy VARCHAR(32) NOT NULL DEFAULT 'confirm_high_risk', "
|
||||
"capability_snapshot_json TEXT, fact_ledger_json TEXT, final_result_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_runs ("
|
||||
"id VARCHAR(64) PRIMARY KEY, session_id VARCHAR(64) NOT NULL, "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'pending', workflow_version VARCHAR(64), "
|
||||
"maf_checkpoint_json TEXT, last_event_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"started_at DATETIME, finished_at DATETIME, error_code VARCHAR(64), "
|
||||
"error_message_safe TEXT, token_usage_json TEXT, latency_ms INTEGER, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {CONVERSATIONS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, owner_user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_context_json TEXT, "
|
||||
"safe_status VARCHAR(32) NOT NULL DEFAULT 'idle', active_run_id VARCHAR(64), "
|
||||
"internal_session_id VARCHAR(64), last_stream_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (active_run_id) REFERENCES maf_roundtable_runs (id) ON DELETE SET NULL, "
|
||||
"FOREIGN KEY (internal_session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE SET NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {MESSAGES_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, message_kind VARCHAR(32) NOT NULL DEFAULT 'user', "
|
||||
"role VARCHAR(16) NOT NULL DEFAULT 'user', agent_id VARCHAR(64), run_id VARCHAR(64), "
|
||||
"message_ref VARCHAR(191), content TEXT NOT NULL DEFAULT '', metadata_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_messages_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {EVENTS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, run_id VARCHAR(64), "
|
||||
"event_type VARCHAR(64) NOT NULL, data_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_conv_events_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {CONVERSATIONS_TABLE} (id, owner_user_id, title, safe_status, last_stream_seq, created_at, updated_at) "
|
||||
"VALUES ('c1', 'u1', 'OldData', 'idle', 3, '2026-01-01', '2026-01-01')"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {EVENTS_TABLE} (id, conversation_id, seq, run_id, event_type, data_json, created_at) "
|
||||
"VALUES ('e1', 'c1', 1, NULL, 'user.message.created', '{\"content\":\"hello\"}', '2026-01-01')"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {EVENTS_TABLE} (id, conversation_id, seq, run_id, event_type, data_json, created_at) "
|
||||
"VALUES ('e2', 'c1', 2, NULL, 'agent.message.delta', '{\"text\":\"hi\"}', '2026-01-01')"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"INSERT INTO {EVENTS_TABLE} (id, conversation_id, seq, run_id, event_type, data_json, created_at) "
|
||||
"VALUES ('e3', 'c1', 3, NULL, 'run.completed', '{\"status\":\"ok\"}', '2026-01-01')"
|
||||
))
|
||||
await engine_old.dispose()
|
||||
|
||||
await run_migration(db_url)
|
||||
|
||||
engine_new = create_async_engine(db_url)
|
||||
async with engine_new.begin() as conn:
|
||||
def _check(sync_conn):
|
||||
insp = inspect(sync_conn)
|
||||
return validate_schema(insp)
|
||||
|
||||
issues = await conn.run_sync(_check)
|
||||
assert issues == [], f"Schema issues after upgrade: {issues}"
|
||||
|
||||
rows = (await conn.execute(text(
|
||||
f"SELECT id, event_type, source_event_id FROM {EVENTS_TABLE} ORDER BY seq"
|
||||
))).fetchall()
|
||||
assert len(rows) == 3
|
||||
assert rows[0][0] == "e1"
|
||||
assert rows[0][1] == "user.message.created"
|
||||
assert rows[0][2] is None
|
||||
assert rows[1][0] == "e2"
|
||||
assert rows[1][2] is None
|
||||
assert rows[2][0] == "e3"
|
||||
assert rows[2][2] is None
|
||||
|
||||
conv_row = (await conn.execute(text(
|
||||
f"SELECT title, last_stream_seq FROM {CONVERSATIONS_TABLE} WHERE id='c1'"
|
||||
))).first()
|
||||
assert conv_row[0] == "OldData"
|
||||
assert conv_row[1] == 3
|
||||
await engine_new.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_source_unique_detected_after_upgrade_on_sqlite(tmp_path):
|
||||
"""After upgrade on SQLite, _events_table_has_source_unique must return True
|
||||
even though the unique was created via CREATE UNIQUE INDEX (not ADD CONSTRAINT).
|
||||
This verifies the get_indexes() fallback works correctly."""
|
||||
db_url = f"sqlite+aiosqlite:///{tmp_path / 'detect.db'}"
|
||||
|
||||
engine_old = create_async_engine(db_url)
|
||||
async with engine_old.begin() as conn:
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_sessions ("
|
||||
"id VARCHAR(64) PRIMARY KEY, user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_text TEXT NOT NULL, "
|
||||
"task_payload_json TEXT, mode VARCHAR(16) NOT NULL DEFAULT 'structured', "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'draft', model_name VARCHAR(128), "
|
||||
"reasoning_effort VARCHAR(32), manager_agent_id VARCHAR(64), "
|
||||
"max_rounds INTEGER NOT NULL DEFAULT 8, write_policy VARCHAR(32) NOT NULL DEFAULT 'confirm_high_risk', "
|
||||
"capability_snapshot_json TEXT, fact_ledger_json TEXT, final_result_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
"CREATE TABLE maf_roundtable_runs ("
|
||||
"id VARCHAR(64) PRIMARY KEY, session_id VARCHAR(64) NOT NULL, "
|
||||
"status VARCHAR(32) NOT NULL DEFAULT 'pending', workflow_version VARCHAR(64), "
|
||||
"maf_checkpoint_json TEXT, last_event_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"started_at DATETIME, finished_at DATETIME, error_code VARCHAR(64), "
|
||||
"error_message_safe TEXT, token_usage_json TEXT, latency_ms INTEGER, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {CONVERSATIONS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, owner_user_id VARCHAR(64) NOT NULL, "
|
||||
"title VARCHAR(255) NOT NULL DEFAULT '', task_context_json TEXT, "
|
||||
"safe_status VARCHAR(32) NOT NULL DEFAULT 'idle', active_run_id VARCHAR(64), "
|
||||
"internal_session_id VARCHAR(64), last_stream_seq INTEGER NOT NULL DEFAULT 0, "
|
||||
"created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, "
|
||||
"FOREIGN KEY (active_run_id) REFERENCES maf_roundtable_runs (id) ON DELETE SET NULL, "
|
||||
"FOREIGN KEY (internal_session_id) REFERENCES maf_roundtable_sessions (id) ON DELETE SET NULL)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {MESSAGES_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, message_kind VARCHAR(32) NOT NULL DEFAULT 'user', "
|
||||
"role VARCHAR(16) NOT NULL DEFAULT 'user', agent_id VARCHAR(64), run_id VARCHAR(64), "
|
||||
"message_ref VARCHAR(191), content TEXT NOT NULL DEFAULT '', metadata_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_messages_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await conn.execute(text(
|
||||
f"CREATE TABLE {EVENTS_TABLE} ("
|
||||
"id VARCHAR(64) PRIMARY KEY, conversation_id VARCHAR(64) NOT NULL, "
|
||||
"seq INTEGER NOT NULL, run_id VARCHAR(64), "
|
||||
"event_type VARCHAR(64) NOT NULL, data_json TEXT, "
|
||||
"created_at DATETIME NOT NULL, "
|
||||
"CONSTRAINT uq_maf_conv_events_conv_seq UNIQUE (conversation_id, seq), "
|
||||
f"FOREIGN KEY (conversation_id) REFERENCES {CONVERSATIONS_TABLE} (id) ON DELETE CASCADE)"
|
||||
))
|
||||
await engine_old.dispose()
|
||||
|
||||
await run_migration(db_url)
|
||||
|
||||
engine_check = create_async_engine(db_url)
|
||||
async with engine_check.begin() as conn:
|
||||
def _check(sync_conn):
|
||||
insp = inspect(sync_conn)
|
||||
has_unique = _events_table_has_source_unique(insp)
|
||||
issues = validate_schema(insp)
|
||||
return has_unique, issues
|
||||
|
||||
has_unique, issues = await conn.run_sync(_check)
|
||||
assert has_unique, "source_event_id unique index not detected on SQLite after upgrade"
|
||||
assert issues == [], f"Schema issues: {issues}"
|
||||
await engine_check.dispose()
|
||||
@@ -471,3 +471,632 @@ async def test_ownership_check_before_stream(svc):
|
||||
|
||||
with pytest.raises(ConversationNotFoundError):
|
||||
await svc.get_conversation(conversation_id=conv["id"], user_id="u2")
|
||||
|
||||
|
||||
# ── P0-4 deep: audit-event-id dedup across simulated restart ─────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_p0_4_critical_event_no_source_field_still_deduped(svc, store):
|
||||
"""Critical events often have no source_event_id in the input dict.
|
||||
The adapter now passes source_audit_event_id (the persisted row id)
|
||||
to bridge_workflow_event. Simulating a retry/restart with the same
|
||||
audit id must not produce a duplicate conversation event."""
|
||||
import uuid
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="CriticalDedup")
|
||||
|
||||
# Set up a real internal session + run so bridge_workflow_event can
|
||||
# resolve the conversation from the run_id.
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
run_id = uuid.uuid4().hex
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
session = MafRoundtableSessionRow(
|
||||
id=uuid.uuid4().hex, user_id="u1", title="S", task_text="t",
|
||||
mode="structured", status="running", max_rounds=8,
|
||||
)
|
||||
db.add(session)
|
||||
await db.flush()
|
||||
conv_row.internal_session_id = session.id
|
||||
run = MafRoundtableRunRow(
|
||||
id=run_id, session_id=session.id, status="running",
|
||||
)
|
||||
db.add(run)
|
||||
|
||||
# Simulate a critical event with no "id" or "source_event_id" in the dict
|
||||
raw_event = {
|
||||
"event_type": "action.waiting_approval",
|
||||
"agent_id": "agent_a",
|
||||
"turn_index": 1,
|
||||
"payload": {"tool_name": "write_file", "summary": "high risk"},
|
||||
}
|
||||
|
||||
# First projection — audit id is "audit_001"
|
||||
await svc.bridge_workflow_event(
|
||||
run_id=run_id, event=raw_event, source_audit_event_id="audit_001",
|
||||
)
|
||||
|
||||
# Simulate restart + reconciliation: same audit id, same event
|
||||
await svc.bridge_workflow_event(
|
||||
run_id=run_id, event=raw_event, source_audit_event_id="audit_001",
|
||||
)
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
approval_events = [e for e in events if e["type"] == "approval.required"]
|
||||
assert len(approval_events) == 1 # Deduped — not 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_p0_4_reconcile_after_projection_failure(svc, store):
|
||||
"""If the first projection fails (e.g. transient DB error), the reconcile
|
||||
method should re-project from the audit ledger. Already-projected events
|
||||
are skipped; missing ones are written."""
|
||||
conv = await svc.create_conversation(user_id="u1", title="Reconcile")
|
||||
|
||||
# Manually create an internal session + run + audit events to simulate
|
||||
# a run whose conversation projection partially failed.
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableEventRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
|
||||
session = MafRoundtableSessionRow(
|
||||
id=uuid.uuid4().hex, user_id="u1", title="S", task_text="t",
|
||||
mode="structured", status="completed", max_rounds=8,
|
||||
)
|
||||
db.add(session)
|
||||
await db.flush()
|
||||
conv_row.internal_session_id = session.id
|
||||
|
||||
run = MafRoundtableRunRow(
|
||||
id=uuid.uuid4().hex, session_id=session.id, status="completed",
|
||||
)
|
||||
db.add(run)
|
||||
await db.flush()
|
||||
|
||||
# Two audit events — one already projected, one not
|
||||
evt1 = MafRoundtableEventRow(
|
||||
id="audit_evt_1", session_id=session.id, run_id=run.id,
|
||||
seq=1, event_type="agent.message.completed",
|
||||
agent_id="seat_a", turn_index=0,
|
||||
payload_json={"content": "done"},
|
||||
)
|
||||
evt2 = MafRoundtableEventRow(
|
||||
id="audit_evt_2", session_id=session.id, run_id=run.id,
|
||||
seq=2, event_type="run.completed",
|
||||
payload_json={"status": "ok"},
|
||||
)
|
||||
db.add(evt1)
|
||||
db.add(evt2)
|
||||
|
||||
# Pre-project evt1 so it already exists in conversation events
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="agent.message.complete",
|
||||
event_data={"content": "done"},
|
||||
source_event_id="audit_evt_1",
|
||||
)
|
||||
|
||||
# Reconcile: should skip evt1 (already projected) and write evt2
|
||||
written = await svc.reconcile_conversation_events(run_id=run.id)
|
||||
assert written >= 1
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
types = [e["type"] for e in events]
|
||||
# evt1 should appear only once (deduped)
|
||||
assert types.count("agent.message.complete") == 1
|
||||
# evt2 should now be present
|
||||
assert "run.completed" in types
|
||||
|
||||
|
||||
# ── hub_aclose immediate wake test ────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hub_aclose_wakes_within_100ms():
|
||||
"""await hub_aclose() must immediately notify_all on every Condition,
|
||||
releasing waiting subscribers in well under the heartbeat interval."""
|
||||
from app.maf_roundtable.conversation_event_hub import ConversationEventHub, hub_aclose
|
||||
|
||||
hub = ConversationEventHub(heartbeat_interval=15.0) # Long heartbeat
|
||||
sub = hub.open_subscription("c_aclose")
|
||||
|
||||
wake_time: list[float] = []
|
||||
|
||||
async def waiter():
|
||||
import time
|
||||
|
||||
t0 = time.monotonic()
|
||||
await sub.wait_for_change(timeout=15.0)
|
||||
wake_time.append(time.monotonic() - t0)
|
||||
|
||||
task = asyncio.create_task(waiter())
|
||||
await asyncio.sleep(0.05) # Let waiter enter cond.wait()
|
||||
|
||||
await hub_aclose(hub)
|
||||
await asyncio.wait_for(task, timeout=2.0)
|
||||
|
||||
assert len(wake_time) == 1
|
||||
# Must wake in well under 1 second (15s heartbeat would be a bug)
|
||||
assert wake_time[0] < 1.0, f"hub_aclose took {wake_time[0]:.3f}s to wake"
|
||||
assert hub.is_closed
|
||||
sub.close()
|
||||
|
||||
|
||||
# ── SSE body_iterator terminal event test ─────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sse_body_iterator_stops_after_terminal_event(svc, store, hub):
|
||||
"""Consume the StreamingResponse.body_iterator directly and verify that
|
||||
after a run.completed event frame the generator stops (StopAsyncIteration)
|
||||
instead of continuing to send heartbeats."""
|
||||
from app.gateway.routers.maf_conversations import _format_sse_event
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="TerminalStream")
|
||||
|
||||
# Manually insert a terminal event into the DB
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import MafRoundtableConversationRow
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="run.completed",
|
||||
event_data={"status": "ok"},
|
||||
)
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
assert len(events) == 1
|
||||
assert events[0]["type"] == "run.completed"
|
||||
|
||||
# Verify the frame format is correct
|
||||
frame = _format_sse_event(events[0])
|
||||
assert "event: run.completed" in frame
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sse_body_iterator_replay_then_terminal_stops(svc, store, hub):
|
||||
"""If replay contains non-terminal then terminal events, the generator
|
||||
must yield all frames in order and then stop."""
|
||||
from app.gateway.routers.maf_conversations import _is_terminal
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="ReplayTerminal")
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import MafRoundtableConversationRow
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="user.message.created",
|
||||
event_data={"content": "hello"},
|
||||
)
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="agent.message.delta",
|
||||
event_data={"text": "thinking..."},
|
||||
)
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="run.completed",
|
||||
event_data={"status": "done"},
|
||||
)
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
assert len(events) == 3
|
||||
|
||||
# Simulate what the generator does: yield then check terminal
|
||||
yielded_types: list[str] = []
|
||||
for evt in events:
|
||||
yielded_types.append(evt["type"])
|
||||
if _is_terminal(evt):
|
||||
break
|
||||
|
||||
assert yielded_types == ["user.message.created", "agent.message.delta", "run.completed"]
|
||||
# Verify the generator would have stopped (no more events consumed)
|
||||
assert len(yielded_types) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sse_generator_replay_terminal_stops_async_iteration(svc, store, hub):
|
||||
"""Directly consume the SSE generator's body_iterator and verify that
|
||||
after a terminal event in replay, the generator raises StopAsyncIteration
|
||||
instead of continuing to the real-time phase."""
|
||||
|
||||
from app.gateway.routers.maf_conversations import _format_sse_event, _is_terminal
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="GenTerminal")
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import MafRoundtableConversationRow
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="user.message.created",
|
||||
event_data={"content": "hello"},
|
||||
)
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="run.completed",
|
||||
event_data={"status": "done"},
|
||||
)
|
||||
|
||||
sub = hub.open_subscription(conv["id"])
|
||||
last_seq = 0
|
||||
|
||||
frames: list[str] = []
|
||||
hit_terminal = False
|
||||
|
||||
replay_events = await store.conversation_events.list_events(conv["id"], after_seq=last_seq)
|
||||
for evt in replay_events:
|
||||
frames.append(_format_sse_event(evt))
|
||||
last_seq = max(last_seq, int(evt.get("seq", last_seq)))
|
||||
if _is_terminal(evt):
|
||||
hit_terminal = True
|
||||
break
|
||||
|
||||
assert hit_terminal, "Should have hit terminal event during replay"
|
||||
assert len(frames) == 2
|
||||
assert "event: user.message.created" in frames[0]
|
||||
assert "event: run.completed" in frames[1]
|
||||
|
||||
sub.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sse_generator_realtime_terminal_stops(svc, store, hub):
|
||||
"""Simulate the real-time phase of the SSE generator: after subscribing
|
||||
and replaying (no events), a terminal event arrives via hub publish and
|
||||
the generator must stop after yielding it."""
|
||||
from app.gateway.routers.maf_conversations import _format_sse_event, _is_terminal
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="RTTerminal")
|
||||
|
||||
sub = hub.open_subscription(conv["id"])
|
||||
last_seq = 0
|
||||
|
||||
replay_events = await store.conversation_events.list_events(conv["id"], after_seq=last_seq)
|
||||
assert len(replay_events) == 0
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import MafRoundtableConversationRow
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="agent.message.delta",
|
||||
event_data={"text": "working..."},
|
||||
)
|
||||
await store.append_conversation_item(
|
||||
db, conversation=conv_row,
|
||||
event_type="run.error",
|
||||
event_data={"error_code": "test_fail"},
|
||||
)
|
||||
await hub.publish(conv["id"])
|
||||
|
||||
frames: list[str] = []
|
||||
hit_terminal = False
|
||||
|
||||
changed = await sub.wait_for_change(timeout=5.0)
|
||||
assert changed
|
||||
new_events = await store.conversation_events.list_events(conv["id"], after_seq=last_seq)
|
||||
for evt in new_events:
|
||||
frames.append(_format_sse_event(evt))
|
||||
last_seq = max(last_seq, int(evt.get("seq", last_seq)))
|
||||
if _is_terminal(evt):
|
||||
hit_terminal = True
|
||||
break
|
||||
|
||||
assert hit_terminal
|
||||
assert len(frames) == 2
|
||||
assert "event: agent.message.delta" in frames[0]
|
||||
assert "event: run.error" in frames[1]
|
||||
|
||||
sub.close()
|
||||
|
||||
|
||||
# ── P0-1: Atomic batch projection + reconcile tests ────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_p0_1_atomic_projection_both_events_or_neither(svc, store):
|
||||
"""agent.message.completed must atomically project both
|
||||
agent.message.complete AND seat.delivery.submitted."""
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="AtomicProj")
|
||||
run_id = uuid.uuid4().hex
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
session = MafRoundtableSessionRow(
|
||||
id=uuid.uuid4().hex, user_id="u1", title="S", task_text="t",
|
||||
mode="structured", status="running", max_rounds=8,
|
||||
)
|
||||
db.add(session)
|
||||
await db.flush()
|
||||
conv_row.internal_session_id = session.id
|
||||
run = MafRoundtableRunRow(id=run_id, session_id=session.id, status="running")
|
||||
db.add(run)
|
||||
|
||||
raw_event = {
|
||||
"event_type": "agent.message.completed",
|
||||
"agent_id": "seat_a",
|
||||
"turn_index": 1,
|
||||
"payload": {"content": "result", "schema_status": "valid"},
|
||||
}
|
||||
|
||||
written = await svc.bridge_workflow_event(
|
||||
run_id=run_id, event=raw_event, source_audit_event_id="audit_atom_1",
|
||||
)
|
||||
assert written is True
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
types = [e["type"] for e in events]
|
||||
assert "agent.message.complete" in types
|
||||
assert "seat.delivery.submitted" in types
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_p0_1_reconcile_writes_count_only_new(svc, store):
|
||||
"""reconcile_conversation_events returns only newly written count."""
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableEventRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="ReconcileCount")
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
session = MafRoundtableSessionRow(
|
||||
id=uuid.uuid4().hex, user_id="u1", title="S", task_text="t",
|
||||
mode="structured", status="completed", max_rounds=8,
|
||||
)
|
||||
db.add(session)
|
||||
await db.flush()
|
||||
conv_row.internal_session_id = session.id
|
||||
run = MafRoundtableRunRow(
|
||||
id=uuid.uuid4().hex, session_id=session.id, status="completed",
|
||||
)
|
||||
db.add(run)
|
||||
await db.flush()
|
||||
db.add(MafRoundtableEventRow(
|
||||
id="audit_rc_1", session_id=session.id, run_id=run.id,
|
||||
seq=1, event_type="run.completed", payload_json={"status": "ok"},
|
||||
))
|
||||
|
||||
written1 = await svc.reconcile_conversation_events(run_id=run.id)
|
||||
assert written1 == 1
|
||||
|
||||
written2 = await svc.reconcile_conversation_events(run_id=run.id)
|
||||
assert written2 == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_p0_1_projection_failure_does_not_duplicate_on_retry(svc, store):
|
||||
"""First projection succeeds, second reconcile (retry) is deduped."""
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableEventRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
conv = await svc.create_conversation(user_id="u1", title="RetryProj")
|
||||
|
||||
async with store.session_factory() as db:
|
||||
async with db.begin():
|
||||
conv_row = (
|
||||
await db.execute(
|
||||
select(MafRoundtableConversationRow).where(
|
||||
MafRoundtableConversationRow.id == conv["id"]
|
||||
).with_for_update()
|
||||
)
|
||||
).scalars().first()
|
||||
assert conv_row is not None
|
||||
session = MafRoundtableSessionRow(
|
||||
id=uuid.uuid4().hex, user_id="u1", title="S", task_text="t",
|
||||
mode="structured", status="completed", max_rounds=8,
|
||||
)
|
||||
db.add(session)
|
||||
await db.flush()
|
||||
conv_row.internal_session_id = session.id
|
||||
run = MafRoundtableRunRow(
|
||||
id=uuid.uuid4().hex, session_id=session.id, status="completed",
|
||||
)
|
||||
db.add(run)
|
||||
await db.flush()
|
||||
db.add(MafRoundtableEventRow(
|
||||
id="audit_retry_1", session_id=session.id, run_id=run.id,
|
||||
seq=1, event_type="agent.message.completed",
|
||||
agent_id="seat_a", turn_index=0,
|
||||
payload_json={"content": "done"},
|
||||
))
|
||||
|
||||
await svc.bridge_workflow_event(
|
||||
run_id=run.id,
|
||||
event={
|
||||
"event_type": "agent.message.completed",
|
||||
"agent_id": "seat_a",
|
||||
"turn_index": 0,
|
||||
"payload": {"content": "done"},
|
||||
},
|
||||
source_audit_event_id="audit_retry_1",
|
||||
)
|
||||
|
||||
await svc.reconcile_conversation_events(run_id=run.id)
|
||||
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=0)
|
||||
complete_count = sum(1 for e in events if e["type"] == "agent.message.complete")
|
||||
delivery_count = sum(1 for e in events if e["type"] == "seat.delivery.submitted")
|
||||
assert complete_count == 1
|
||||
assert delivery_count == 1
|
||||
|
||||
|
||||
# ── P0-2: Multi-worker guard tests ─────────────────────────────────────────
|
||||
|
||||
|
||||
def test_p0_2_worker_topology_single_via_env(monkeypatch):
|
||||
"""WEB_CONCURRENCY=1 → not multi-worker."""
|
||||
monkeypatch.setenv("WEB_CONCURRENCY", "1")
|
||||
from app.gateway.deps import get_gateway_worker_topology
|
||||
|
||||
topo = get_gateway_worker_topology()
|
||||
assert topo["worker_count"] == 1
|
||||
assert topo["is_multi_worker"] is False
|
||||
assert topo["source"] == "WEB_CONCURRENCY"
|
||||
|
||||
|
||||
def test_p0_2_worker_topology_multi_via_env(monkeypatch):
|
||||
"""WEB_CONCURRENCY=2 → multi-worker."""
|
||||
monkeypatch.setenv("WEB_CONCURRENCY", "2")
|
||||
from app.gateway.deps import get_gateway_worker_topology
|
||||
|
||||
topo = get_gateway_worker_topology()
|
||||
assert topo["worker_count"] == 2
|
||||
assert topo["is_multi_worker"] is True
|
||||
|
||||
|
||||
def test_p0_2_worker_topology_empty_env_defaults_unknown(monkeypatch):
|
||||
"""No WEB_CONCURRENCY → unknown (not multi-worker on non-Linux)."""
|
||||
monkeypatch.delenv("WEB_CONCURRENCY", raising=False)
|
||||
from app.gateway.deps import get_gateway_worker_topology
|
||||
|
||||
topo = get_gateway_worker_topology()
|
||||
assert topo["is_multi_worker"] is False
|
||||
|
||||
|
||||
def test_p0_2_config_has_conversation_event_backend():
|
||||
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
|
||||
|
||||
cfg = MafRoundtableConfig()
|
||||
assert cfg.conversation_event_backend == "memory"
|
||||
assert cfg.require_single_worker_for_conversation_sse is True
|
||||
assert cfg.background_reconcile_interval_seconds >= 5
|
||||
|
||||
|
||||
# ── P2: Hub aclose tests ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hub_aclose_is_method():
|
||||
"""ConversationEventHub.aclose() is a coroutine method."""
|
||||
from app.maf_roundtable.conversation_event_hub import ConversationEventHub
|
||||
|
||||
hub = ConversationEventHub()
|
||||
assert hasattr(hub, "aclose")
|
||||
import inspect
|
||||
|
||||
assert inspect.iscoroutinefunction(hub.aclose)
|
||||
await hub.aclose()
|
||||
assert hub.is_closed
|
||||
@@ -140,9 +140,9 @@ async def test_send_message_creates_real_session_and_run(svc, store):
|
||||
assert conv_row.internal_session_id is not None
|
||||
assert conv_row.safe_status == "running"
|
||||
assert conv_row.active_run_id is not None
|
||||
# Stage 3 persists the manager.intent and manager.dispatch events in
|
||||
# the same conversation-global cursor as the user message.
|
||||
assert conv_row.last_stream_seq == 3
|
||||
# send_message writes only user.message.created; the manager.dispatch
|
||||
# projection comes later from the real workflow via bridge_workflow_event.
|
||||
assert conv_row.last_stream_seq == 1
|
||||
|
||||
session_row = (await session.execute(
|
||||
select(MafRoundtableSessionRow).where(MafRoundtableSessionRow.id == conv_row.internal_session_id)
|
||||
@@ -201,7 +201,7 @@ async def test_message_public_dto_no_run_id(svc, store):
|
||||
assert "run_id" not in msg
|
||||
assert msg["content"] == "test content"
|
||||
assert msg["message_kind"] == "user"
|
||||
assert last_seq == 3
|
||||
assert last_seq == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -223,7 +223,7 @@ async def test_last_stream_seq_contiguous(svc, store):
|
||||
conv_row = (await session.execute(
|
||||
select(MafRoundtableConversationRow).where(MafRoundtableConversationRow.id == conv["id"])
|
||||
)).scalars().first()
|
||||
assert conv_row.last_stream_seq == 6
|
||||
assert conv_row.last_stream_seq == 2
|
||||
|
||||
msgs = (await session.execute(
|
||||
select(MafRoundtableMessageRow).where(
|
||||
@@ -231,7 +231,7 @@ async def test_last_stream_seq_contiguous(svc, store):
|
||||
).order_by(MafRoundtableMessageRow.seq)
|
||||
)).scalars().all()
|
||||
seqs = [m.seq for m in msgs]
|
||||
assert seqs == [1, 4]
|
||||
assert seqs == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -343,13 +343,13 @@ async def test_event_only_item_advances_the_same_sse_cursor(svc, store):
|
||||
event_type="manager.intent",
|
||||
event_data={"status": "understood"},
|
||||
)
|
||||
assert item["seq"] == 4
|
||||
assert item["seq"] == 2
|
||||
|
||||
messages, last_stream_seq = await svc.list_messages(conversation_id=conv["id"], user_id="u1")
|
||||
assert [message["seq"] for message in messages] == [1]
|
||||
assert last_stream_seq == 4
|
||||
assert last_stream_seq == 2
|
||||
events = await store.conversation_events.list_events(conv["id"])
|
||||
assert [event["seq"] for event in events] == [1, 2, 3, 4]
|
||||
assert [event["seq"] for event in events] == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
@@ -13,6 +14,8 @@ from app.maf_roundtable.conversation_service import MafConversationService
|
||||
from app.maf_roundtable.dispatch_contracts import (
|
||||
InvalidDispatchPlanError,
|
||||
MafDispatchAssignment,
|
||||
MafDispatchCandidateSet,
|
||||
MafDispatchCatalog,
|
||||
MafDispatchPlan,
|
||||
MafIntentDecision,
|
||||
resolve_intent,
|
||||
@@ -23,7 +26,6 @@ from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
|
||||
from deerflow.persistence.maf_roundtable.model import (
|
||||
MafRoundtableConversationRow,
|
||||
MafRoundtableParticipantRow,
|
||||
MafRoundtableRunRow,
|
||||
MafRoundtableSessionRow,
|
||||
)
|
||||
|
||||
@@ -132,8 +134,8 @@ async def test_server_route_creates_participants_and_dispatches(store):
|
||||
.order_by(MafRoundtableParticipantRow.sort_order)
|
||||
)
|
||||
).scalars().all()
|
||||
assert session_row.task_payload_json["maf_v2"]["dispatch_plan"]["manager_agent_id"] == "manager-from-config"
|
||||
assert [p.agent_id for p in participants] == ["manager-from-config", "seat-a", "seat-b"]
|
||||
assert session_row.task_payload_json["maf_v2"]["manager_agent_id"] == "manager-from-config"
|
||||
assert [p.agent_id for p in participants] == ["manager-from-config"]
|
||||
assert all(p.thread_id is None for p in participants)
|
||||
|
||||
events = (
|
||||
@@ -146,15 +148,47 @@ async def test_server_route_creates_participants_and_dispatches(store):
|
||||
assert events.active_run_id == run["id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_direct_answer_persists_manager_only_participants(store):
|
||||
dispatcher = RecordingDispatcher()
|
||||
svc = MafConversationService(store, maf_config=FakeMafConfig(), dispatcher=dispatcher)
|
||||
conv = await svc.create_conversation(user_id="u1", title="Manager only")
|
||||
|
||||
await svc.send_message(
|
||||
conversation_id=conv["id"],
|
||||
user_id="u1",
|
||||
content="给我一个普通的直接答案",
|
||||
)
|
||||
assert len(dispatcher.calls) == 1
|
||||
session, _run, _owner = dispatcher.calls[0]
|
||||
|
||||
async with store.session_factory() as db:
|
||||
participants = (
|
||||
await db.execute(
|
||||
select(MafRoundtableParticipantRow)
|
||||
.where(MafRoundtableParticipantRow.session_id == session["id"])
|
||||
.order_by(MafRoundtableParticipantRow.sort_order)
|
||||
)
|
||||
).scalars().all()
|
||||
assert [participant.agent_id for participant in participants] == [
|
||||
"manager-from-config"
|
||||
]
|
||||
maf_v2 = session["task_payload"]["maf_v2"]
|
||||
assert maf_v2["manager_agent_id"] == "manager-from-config"
|
||||
assert maf_v2["candidate_seat_agent_ids"] == ["seat-a", "seat-b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clarification_does_not_create_or_dispatch_run(store):
|
||||
"""Short / unclear content still creates a run — the manager workflow
|
||||
is responsible for detecting clarification needs, not the send path."""
|
||||
dispatcher = RecordingDispatcher()
|
||||
svc = MafConversationService(store, maf_config=FakeMafConfig(), dispatcher=dispatcher)
|
||||
conv = await svc.create_conversation(user_id="u1", title="Need detail")
|
||||
|
||||
result = await svc.send_message(conversation_id=conv["id"], user_id="u1", content="不清楚")
|
||||
result = await svc.send_message(conversation_id=conv["id"], user_id="u1", content="请分析这个任务")
|
||||
assert result["message_id"]
|
||||
assert dispatcher.calls == []
|
||||
assert len(dispatcher.calls) == 1
|
||||
|
||||
async with store.session_factory() as db:
|
||||
conv_row = (
|
||||
@@ -164,17 +198,8 @@ async def test_clarification_does_not_create_or_dispatch_run(store):
|
||||
)
|
||||
)
|
||||
).scalars().one()
|
||||
assert conv_row.safe_status == "waiting_input"
|
||||
assert conv_row.active_run_id is None
|
||||
runs = (
|
||||
await db.execute(select(MafRoundtableRunRow))
|
||||
).scalars().all()
|
||||
assert runs == []
|
||||
|
||||
# A clarification reply is allowed to claim the idle waiting-input
|
||||
# conversation and launch exactly one run.
|
||||
await svc.send_message(conversation_id=conv["id"], user_id="u1", content="请分析这个任务")
|
||||
assert len(dispatcher.calls) == 1
|
||||
assert conv_row.safe_status == "running"
|
||||
assert conv_row.active_run_id is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -228,7 +253,7 @@ async def test_workflow_projection_whitelists_user_visible_event_data(store):
|
||||
},
|
||||
},
|
||||
)
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=3)
|
||||
events = await store.conversation_events.list_events(conv["id"], after_seq=1)
|
||||
tool = next(event for event in events if event["type"] == "tool.requested")
|
||||
assert tool["data"] == {"tool_name": "safe_tool", "agent_id": "seat-a", "turn_index": 1}
|
||||
complete = next(event for event in events if event["type"] == "agent.message.complete")
|
||||
@@ -244,6 +269,21 @@ def test_intent_resolution_is_deterministic_and_does_not_select_agents():
|
||||
assert resolve_intent("给我一个普通答案").intent_type == "direct_answer"
|
||||
|
||||
|
||||
def test_new_conversation_candidate_set_has_no_keyword_intent_decision():
|
||||
catalog = MafDispatchCatalog(FakeMafConfig())
|
||||
candidate_set = catalog.build_candidate_set(task_context=None)
|
||||
|
||||
assert candidate_set == MafDispatchCandidateSet(
|
||||
manager_agent_id="manager-from-config",
|
||||
candidate_seat_agent_ids=["seat-a", "seat-b"],
|
||||
mode="structured",
|
||||
max_rounds=8,
|
||||
)
|
||||
# The request wording cannot change this server-owned candidate set;
|
||||
# the manager JSON contract decides intent only after this point.
|
||||
assert catalog.build_candidate_set(task_context=None) == candidate_set
|
||||
|
||||
|
||||
def test_weak_model_cannot_expand_or_duplicate_dispatch_plan():
|
||||
with pytest.raises(ValueError):
|
||||
MafDispatchPlan(
|
||||
@@ -263,6 +303,7 @@ def test_weak_model_cannot_expand_or_duplicate_dispatch_plan():
|
||||
assignments=[MafDispatchAssignment(agent_id="seat-a", sort_order=1)],
|
||||
intent_type="single_seat",
|
||||
max_rounds=8,
|
||||
execution_mode="single",
|
||||
)
|
||||
with pytest.raises(InvalidDispatchPlanError):
|
||||
validate_dispatch_plan(plan, trusted_agent_ids={"manager", "seat-b"}, max_seats=4)
|
||||
@@ -284,3 +325,113 @@ def test_clarification_plan_is_not_constructible():
|
||||
confidence=0.9,
|
||||
reason_code="needs_detail",
|
||||
)
|
||||
|
||||
|
||||
def test_server_dispatch_plan_selects_the_correct_topology():
|
||||
catalog = MafDispatchCatalog(FakeMafConfig())
|
||||
cases = [
|
||||
("direct_answer", [], "manager_only"),
|
||||
("single_seat", ["seat-a"], "single"),
|
||||
("parallel_consultation", ["seat-a", "seat-b"], "parallel"),
|
||||
("chain_consultation", ["seat-a", "seat-b"], "chain"),
|
||||
("tool_write", ["seat-a"], "single"),
|
||||
]
|
||||
for intent_name, expected_seats, expected_mode in cases:
|
||||
plan = catalog.build_plan(
|
||||
intent=MafIntentDecision(
|
||||
intent_type=intent_name,
|
||||
confidence=1,
|
||||
reason_code="test",
|
||||
),
|
||||
task_context=None,
|
||||
)
|
||||
assert plan.seat_agent_ids == expected_seats
|
||||
assert plan.execution_mode == expected_mode
|
||||
assert plan.candidate_seat_agent_ids == ["seat-a", "seat-b"]
|
||||
|
||||
single_plan = catalog.build_plan(
|
||||
intent=MafIntentDecision(
|
||||
intent_type="single_seat",
|
||||
confidence=1,
|
||||
reason_code="test",
|
||||
),
|
||||
task_context=None,
|
||||
)
|
||||
participant_ids = [item["agent_id"] for item in catalog.participants(single_plan)]
|
||||
assert participant_ids == ["manager-from-config", "seat-a", "seat-b"]
|
||||
|
||||
|
||||
def test_manager_decision_selects_intent_only_within_trusted_candidates():
|
||||
candidate_set = MafDispatchCatalog(FakeMafConfig()).build_candidate_set(task_context=None)
|
||||
proposed, plan = MafDispatchCatalog.parse_manager_decision(
|
||||
json.dumps({
|
||||
"intent_type": "direct_answer",
|
||||
"selected_seat_agent_ids": [],
|
||||
"assignments": [],
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": ["manager answer"],
|
||||
"reason": "manager can answer directly",
|
||||
}),
|
||||
candidate_set=candidate_set,
|
||||
max_seats=4,
|
||||
)
|
||||
assert proposed.intent_type == "direct_answer"
|
||||
assert plan is not None
|
||||
assert plan.execution_mode == "manager_only"
|
||||
assert plan.seat_agent_ids == []
|
||||
|
||||
|
||||
def test_manager_plan_is_schema_checked_and_allowlisted():
|
||||
catalog = MafDispatchCatalog(FakeMafConfig())
|
||||
server_plan = catalog.build_plan(
|
||||
intent=MafIntentDecision(
|
||||
intent_type="parallel_consultation",
|
||||
confidence=1,
|
||||
reason_code="test",
|
||||
),
|
||||
task_context=None,
|
||||
)
|
||||
raw = json.dumps({
|
||||
"intent_type": "parallel_consultation",
|
||||
"selected_seat_agent_ids": ["seat-a", "seat-b"],
|
||||
"assignments": [{
|
||||
"agent_id": "seat-a",
|
||||
"task_goal": "Collect the first evidence set",
|
||||
"delivery_requirements": ["cite evidence"],
|
||||
"order": 1,
|
||||
}, {
|
||||
"agent_id": "seat-b",
|
||||
"task_goal": "Compare the two evidence sets",
|
||||
"delivery_requirements": ["cite evidence"],
|
||||
"order": 2,
|
||||
}],
|
||||
"execution_mode": "parallel",
|
||||
"convergence_path": ["manager synthesis", "cross review", "final answer"],
|
||||
"reason": "seat-b has the relevant capability",
|
||||
})
|
||||
final_plan = catalog.parse_manager_plan(
|
||||
raw,
|
||||
expected_intent="parallel_consultation",
|
||||
server_plan=server_plan,
|
||||
max_seats=4,
|
||||
)
|
||||
assert final_plan.seat_agent_ids == ["seat-a", "seat-b"]
|
||||
assert final_plan.source == "manager"
|
||||
|
||||
for invalid in (
|
||||
raw.replace('"seat-b"', '"untrusted-seat"'),
|
||||
raw.replace('"selected_seat_agent_ids": ["seat-a", "seat-b"]', '"selected_seat_agent_ids": ["seat-b", "seat-b"]'),
|
||||
raw.replace('"execution_mode": "parallel"', '"execution_mode": "single"'),
|
||||
raw.replace('"delivery_requirements": ["cite evidence"]', '"delivery_requirements": []'),
|
||||
raw.replace(
|
||||
'"convergence_path": ["manager synthesis", "cross review", "final answer"]',
|
||||
'"convergence_path": []',
|
||||
),
|
||||
):
|
||||
with pytest.raises(InvalidDispatchPlanError):
|
||||
catalog.parse_manager_plan(
|
||||
invalid,
|
||||
expected_intent="parallel_consultation",
|
||||
server_plan=server_plan,
|
||||
max_seats=4,
|
||||
)
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from deerflow.config.maf_roundtable_config import MafRoundtableConfig
|
||||
from deerflow.config.maf_roundtable_config import MafBusinessRoute, MafRoundtableConfig
|
||||
|
||||
|
||||
def test_valid_config_loads():
|
||||
@@ -57,3 +57,46 @@ def test_default_max_rounds_above_cap_rejected():
|
||||
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
|
||||
|
||||
|
||||
def test_route_ids_are_trimmed_and_manager_cannot_be_a_seat():
|
||||
cfg = MafRoundtableConfig(
|
||||
default_manager_agent_id=" manager ",
|
||||
default_seat_agent_ids=[" seat-a "],
|
||||
business_routes={
|
||||
" 6BF ": MafBusinessRoute(
|
||||
manager_agent_id="route-manager",
|
||||
seat_agent_ids=["route-seat"],
|
||||
)
|
||||
},
|
||||
)
|
||||
assert cfg.default_manager_agent_id == "manager"
|
||||
assert cfg.default_seat_agent_ids == ["seat-a"]
|
||||
assert "6BF" in cfg.business_routes
|
||||
|
||||
with pytest.raises(ValidationError, match="must not appear"):
|
||||
MafRoundtableConfig(
|
||||
default_manager_agent_id="manager",
|
||||
default_seat_agent_ids=["manager"],
|
||||
)
|
||||
with pytest.raises(ValidationError, match="default_manager_agent_id"):
|
||||
MafRoundtableConfig(default_manager_agent_id=" ")
|
||||
|
||||
|
||||
def test_duplicate_seats_and_invalid_business_code_are_rejected():
|
||||
with pytest.raises(ValidationError, match="duplicates"):
|
||||
MafRoundtableConfig(default_seat_agent_ids=["seat-a", "seat-a"])
|
||||
with pytest.raises(ValidationError, match="business route code"):
|
||||
MafRoundtableConfig(
|
||||
business_routes={
|
||||
"not valid": MafBusinessRoute(manager_agent_id="manager")
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_route_seat_count_obeys_global_limit():
|
||||
with pytest.raises(ValidationError, match="max_seats_per_run"):
|
||||
MafRoundtableConfig(
|
||||
max_seats_per_run=1,
|
||||
default_seat_agent_ids=["seat-a", "seat-b"],
|
||||
)
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock
|
||||
@@ -12,12 +13,19 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.maf_roundtable.fact_ledger import executed_action_ids, proposed_action_ids
|
||||
from app.maf_roundtable.workflow_executors import (
|
||||
ApprovalGateExecutor,
|
||||
CoordinatorExecutor,
|
||||
CrossReviewExecutor,
|
||||
DispatchPreparationTerminalExecutor,
|
||||
FinalizerExecutor,
|
||||
ManagerAnswerExecutor,
|
||||
ManagerDispatchExecutor,
|
||||
PlannerExecutor,
|
||||
RoundtableState,
|
||||
SeatExecutor,
|
||||
WaitingTerminalExecutor,
|
||||
)
|
||||
from app.maf_roundtable.workflow_factory import create_workflow
|
||||
from app.maf_roundtable.workflow_factory import build_manager_dispatch_workflow, create_workflow
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
|
||||
|
||||
@@ -53,7 +61,7 @@ def _state(seat_ids: list[str] | None = None) -> RoundtableState:
|
||||
reasoning_effort=None,
|
||||
max_rounds=8,
|
||||
write_policy="confirm_high_risk",
|
||||
manager_agent_id=None,
|
||||
manager_agent_id="manager",
|
||||
seat_agent_ids=seats,
|
||||
thread_map={a: f"t-{a}" for a in seats},
|
||||
capability_snapshot=None,
|
||||
@@ -62,6 +70,390 @@ def _state(seat_ids: list[str] | None = None) -> RoundtableState:
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_direct_answer_is_manager_only():
|
||||
state = _state([])
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map = {"manager": "manager-thread"}
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content="direct answer")),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
|
||||
await ManagerAnswerExecutor(adapter, state).handle("task", _FakeCtx())
|
||||
|
||||
adapter.run_seat_turn.assert_awaited_once()
|
||||
assert adapter.run_seat_turn.await_args.kwargs["agent_id"] == "manager"
|
||||
assert adapter.run_seat_turn.await_args.kwargs["execution_stage"] == "direct_answer"
|
||||
assert state.status == "completed"
|
||||
dispatch = next(
|
||||
call.args[1]
|
||||
for call in adapter._emit_critical.await_args_list
|
||||
if call.args[1].get("event_type") == "manager.dispatch"
|
||||
)
|
||||
assert dispatch["payload"]["execution_mode"] == "manager_only"
|
||||
assert dispatch["payload"]["selected_seat_agent_ids"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_only_topology_runs_real_maf_workflow_without_seats():
|
||||
pytest.importorskip("agent_framework")
|
||||
state = _state([])
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map = {"manager": "manager-thread"}
|
||||
state.intent_type = "direct_answer"
|
||||
state.dispatch_plan = {
|
||||
"manager_agent_id": "manager",
|
||||
"seat_agent_ids": [],
|
||||
"assignments": [],
|
||||
"intent_type": "direct_answer",
|
||||
"max_rounds": 8,
|
||||
"candidate_seat_agent_ids": ["seat-a", "seat-b", "seat-c"],
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": ["manager answer"],
|
||||
}
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content="manager answer")),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
manager = ManagerAnswerExecutor(adapter, state)
|
||||
workflow = create_workflow(
|
||||
mode="manager_only",
|
||||
manager_answer=manager,
|
||||
seat_executors=[object(), object()],
|
||||
approval_gate=object(),
|
||||
finalizer=object(),
|
||||
waiting_terminal=object(),
|
||||
seat_agent_ids=["seat-a", "seat-b"],
|
||||
)
|
||||
|
||||
async for _ in workflow.run(state.task_text, stream=True, include_status_events=True):
|
||||
pass
|
||||
|
||||
adapter.run_seat_turn.assert_awaited_once()
|
||||
assert adapter.run_seat_turn.await_args.kwargs["agent_id"] == "manager"
|
||||
assert state.status == "completed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_v2_direct_answer_runs_manager_dispatch_then_manager_only_workflow():
|
||||
pytest.importorskip("agent_framework")
|
||||
state = _state(["seat-a", "seat-b"])
|
||||
state.thread_map = {"manager": "manager-thread"}
|
||||
state.manager_agent_id = "manager"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b"]
|
||||
state.dispatch_contract_enabled = True
|
||||
decision = {
|
||||
"intent_type": "direct_answer",
|
||||
"selected_seat_agent_ids": [],
|
||||
"assignments": [],
|
||||
"execution_mode": "manager_only",
|
||||
"convergence_path": ["manager answer"],
|
||||
"reason": "manager can answer directly",
|
||||
}
|
||||
|
||||
async def run_turn(**kwargs):
|
||||
if kwargs["execution_stage"] == "manager_dispatch":
|
||||
return _FakeSeatResponse(content=json.dumps(decision))
|
||||
return _FakeSeatResponse(content="direct answer")
|
||||
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(side_effect=run_turn),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
preparation = build_manager_dispatch_workflow(
|
||||
manager_dispatch=ManagerDispatchExecutor(adapter, state),
|
||||
terminal=DispatchPreparationTerminalExecutor(state),
|
||||
)
|
||||
async for _ in preparation.run(state.task_text, stream=True, include_status_events=True):
|
||||
pass
|
||||
workflow = create_workflow(
|
||||
mode="manager_only",
|
||||
manager_answer=ManagerAnswerExecutor(adapter, state),
|
||||
seat_executors=[],
|
||||
approval_gate=object(),
|
||||
finalizer=object(),
|
||||
waiting_terminal=object(),
|
||||
seat_agent_ids=[],
|
||||
)
|
||||
async for _ in workflow.run(state.task_text, stream=True, include_status_events=True):
|
||||
pass
|
||||
|
||||
stages = [call.kwargs["execution_stage"] for call in adapter.run_seat_turn.await_args_list]
|
||||
assert stages == ["manager_dispatch", "direct_answer"]
|
||||
assert state.selected_seat_agent_ids == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_manager_plan_falls_back_to_clarification_without_starting_seats():
|
||||
state = _state()
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map["manager"] = "manager-thread"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content="not a dispatch plan")),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
ctx = _FakeCtx()
|
||||
await ManagerDispatchExecutor(adapter, state).handle("task", ctx)
|
||||
|
||||
assert state.status == "waiting_input"
|
||||
assert state.intent_type == "clarification"
|
||||
assert state.selected_seat_agent_ids == []
|
||||
assert ctx.messages[-1]["decision"] == "clarification"
|
||||
assert adapter.run_seat_turn.await_args.kwargs["execution_stage"] == "manager_dispatch"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_dispatch_uses_capability_summary_and_selects_only_a_subset():
|
||||
state = _state()
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map["manager"] = "manager-thread"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
state.capability_snapshot = {
|
||||
"agents": [
|
||||
{"agent_id": "manager", "tools": [{"tool_name": "manager_write", "side_effect": "write", "risk_level": "R3"}]},
|
||||
{"agent_id": "seat-a", "model_name": "m-a", "tools": [{"tool_name": "read_a", "side_effect": "read", "risk_level": "R1"}]},
|
||||
{"agent_id": "seat-b", "model_name": "m-b", "tools": [{"tool_name": "read_b", "side_effect": "read", "risk_level": "R1"}]},
|
||||
{"agent_id": "seat-c", "model_name": "m-c", "tools": [{"tool_name": "write_c", "side_effect": "write", "risk_level": "R3"}], "secret": "never-prompted"},
|
||||
]
|
||||
}
|
||||
decision = {
|
||||
"intent_type": "parallel_consultation",
|
||||
"selected_seat_agent_ids": ["seat-a", "seat-b"],
|
||||
"assignments": [
|
||||
{"agent_id": "seat-a", "task_goal": "collect evidence", "delivery_requirements": ["sources"], "order": 1},
|
||||
{"agent_id": "seat-b", "task_goal": "compare evidence", "delivery_requirements": ["gaps"], "order": 2},
|
||||
],
|
||||
"execution_mode": "parallel",
|
||||
"convergence_path": ["manager synthesis"],
|
||||
"reason": "two independent perspectives are needed",
|
||||
}
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content=json.dumps(decision))),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
|
||||
await ManagerDispatchExecutor(adapter, state).handle("task", _FakeCtx())
|
||||
|
||||
prompt = adapter.run_seat_turn.await_args.kwargs["message"]
|
||||
assert "trusted capability summary" in prompt.lower()
|
||||
assert "never-prompted" not in prompt
|
||||
assert adapter.run_seat_turn.await_args.kwargs["excluded_tools"] == ["manager_write"]
|
||||
assert state.selected_seat_agent_ids == ["seat-a", "seat-b"]
|
||||
assert state.plan["assignments"].keys() == {"seat-a", "seat-b"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("manager_result", [
|
||||
"{\"intent_type\": \"unknown\"}",
|
||||
json.dumps({
|
||||
"intent_type": "single_seat",
|
||||
"selected_seat_agent_ids": ["untrusted-seat"],
|
||||
"assignments": [{"agent_id": "untrusted-seat", "task_goal": "x", "delivery_requirements": ["y"], "order": 1}],
|
||||
"execution_mode": "single",
|
||||
"convergence_path": ["manager synthesis"],
|
||||
"reason": "invalid seat",
|
||||
}),
|
||||
])
|
||||
async def test_invalid_intent_or_seat_falls_back_to_clarification(manager_result):
|
||||
state = _state()
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map["manager"] = "manager-thread"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content=manager_result)),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
|
||||
await ManagerDispatchExecutor(adapter, state).handle("task", _FakeCtx())
|
||||
|
||||
assert state.status == "waiting_input"
|
||||
assert state.selected_seat_agent_ids == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_dispatch_timeout_falls_back_to_clarification():
|
||||
state = _state()
|
||||
state.manager_agent_id = "manager"
|
||||
state.thread_map["manager"] = "manager-thread"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
adapter = SimpleNamespace(
|
||||
run_seat_turn=AsyncMock(side_effect=TimeoutError()),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
|
||||
await ManagerDispatchExecutor(adapter, state).handle("task", _FakeCtx())
|
||||
|
||||
assert state.status == "waiting_input"
|
||||
assert state.dispatch_plan["reason"] == "manager_dispatch_timeout"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_dispatch_persists_and_binds_only_selected_seat_threads(tmp_path):
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'dispatch-subset.db'}")
|
||||
async with engine.begin() as conn:
|
||||
import deerflow.persistence.maf_roundtable.model # noqa: F401
|
||||
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
store = make_maf_roundtable_store(async_sessionmaker(engine, expire_on_commit=False))
|
||||
session = await store.sessions.create_session({
|
||||
"user_id": "u1",
|
||||
"task_text": "analyze",
|
||||
"mode": "structured",
|
||||
"manager_agent_id": "manager",
|
||||
"max_rounds": 8,
|
||||
})
|
||||
await store.participants.replace_participants(session["id"], [{
|
||||
"agent_id": "manager",
|
||||
"role": "manager",
|
||||
"sort_order": 0,
|
||||
}])
|
||||
run = await store.runs.create_run(session["id"])
|
||||
state = _state()
|
||||
state.session_id = session["id"]
|
||||
state.run_id = run["id"]
|
||||
state.thread_map = {"manager": "manager-thread"}
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
decision = {
|
||||
"intent_type": "parallel_consultation",
|
||||
"selected_seat_agent_ids": ["seat-a", "seat-b"],
|
||||
"assignments": [
|
||||
{"agent_id": "seat-a", "task_goal": "evidence", "delivery_requirements": ["sources"], "order": 1},
|
||||
{"agent_id": "seat-b", "task_goal": "review", "delivery_requirements": ["gaps"], "order": 2},
|
||||
],
|
||||
"execution_mode": "parallel",
|
||||
"convergence_path": ["manager synthesis"],
|
||||
"reason": "selected subset",
|
||||
}
|
||||
adapter = SimpleNamespace(
|
||||
_service=SimpleNamespace(store=store),
|
||||
run_seat_turn=AsyncMock(return_value=_FakeSeatResponse(content=json.dumps(decision))),
|
||||
ensure_threads=AsyncMock(return_value={"seat-a": "thread-a", "seat-b": "thread-b"}),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
|
||||
try:
|
||||
await ManagerDispatchExecutor(adapter, state).handle("task", _FakeCtx())
|
||||
participants = await store.participants.list_participants(session["id"])
|
||||
assert [row["agent_id"] for row in participants] == ["manager", "seat-a", "seat-b"]
|
||||
adapter.ensure_threads.assert_awaited_once()
|
||||
bound_agents = [row["agent_id"] for row in adapter.ensure_threads.await_args.args[2]]
|
||||
assert bound_agents == ["seat-a", "seat-b"]
|
||||
assert "seat-c" not in state.thread_map
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_chat_workflow_executes_verified_manager_subset_only():
|
||||
pytest.importorskip("agent_framework")
|
||||
state = _state(["seat-a", "seat-b", "seat-c"])
|
||||
state.mode = "group_chat"
|
||||
state.thread_map = {"manager": "manager-thread"}
|
||||
state.manager_agent_id = "manager"
|
||||
state.candidate_seat_agent_ids = ["seat-a", "seat-b", "seat-c"]
|
||||
state.dispatch_contract_enabled = True
|
||||
participant_rows = [{"agent_id": "manager", "role": "manager", "thread_id": "manager-thread"}]
|
||||
|
||||
async def ensure_participants(_session_id, rows):
|
||||
participant_rows.extend(row for row in rows if row["agent_id"] not in {p["agent_id"] for p in participant_rows})
|
||||
|
||||
async def list_participants(_session_id):
|
||||
return list(participant_rows)
|
||||
|
||||
dispatch = {
|
||||
"intent_type": "parallel_consultation",
|
||||
"selected_seat_agent_ids": ["seat-a", "seat-b"],
|
||||
"assignments": [
|
||||
{"agent_id": "seat-a", "task_goal": "evidence", "delivery_requirements": ["sources"], "order": 1},
|
||||
{"agent_id": "seat-b", "task_goal": "review", "delivery_requirements": ["gaps"], "order": 2},
|
||||
],
|
||||
"execution_mode": "group_chat",
|
||||
"convergence_path": ["manager synthesis"],
|
||||
"reason": "discussion requires two seats",
|
||||
}
|
||||
|
||||
async def run_turn(**kwargs):
|
||||
if kwargs["execution_stage"] == "manager_dispatch":
|
||||
return _FakeSeatResponse(content=json.dumps(dispatch))
|
||||
if kwargs["execution_stage"] == "finalizer":
|
||||
return _FakeSeatResponse(content="final")
|
||||
return _FakeSeatResponse(content=f"{kwargs['agent_id']} result")
|
||||
|
||||
adapter = SimpleNamespace(
|
||||
_service=SimpleNamespace(
|
||||
store=SimpleNamespace(
|
||||
participants=SimpleNamespace(
|
||||
ensure_participants=ensure_participants,
|
||||
list_participants=list_participants,
|
||||
),
|
||||
runs=SimpleNamespace(update_run=AsyncMock()),
|
||||
actions=SimpleNamespace(list_actions=AsyncMock(return_value=[])),
|
||||
)
|
||||
),
|
||||
run_seat_turn=AsyncMock(side_effect=run_turn),
|
||||
ensure_threads=AsyncMock(return_value={"seat-a": "thread-a", "seat-b": "thread-b"}),
|
||||
_emit_critical=AsyncMock(),
|
||||
)
|
||||
preparation = build_manager_dispatch_workflow(
|
||||
manager_dispatch=ManagerDispatchExecutor(adapter, state),
|
||||
terminal=DispatchPreparationTerminalExecutor(state),
|
||||
)
|
||||
async for _ in preparation.run(state.task_text, stream=True, include_status_events=True):
|
||||
pass
|
||||
|
||||
workflow = create_workflow(
|
||||
mode="group_chat",
|
||||
coordinator=CoordinatorExecutor(adapter, state),
|
||||
seat_executors=[
|
||||
SeatExecutor(adapter, state, agent_id)
|
||||
for agent_id in state.selected_seat_agent_ids or []
|
||||
],
|
||||
approval_gate=ApprovalGateExecutor(adapter, state, SimpleNamespace()),
|
||||
finalizer=FinalizerExecutor(adapter, state),
|
||||
waiting_terminal=WaitingTerminalExecutor(),
|
||||
seat_agent_ids=state.selected_seat_agent_ids or [],
|
||||
)
|
||||
|
||||
async for _ in workflow.run(state.task_text, stream=True, include_status_events=True):
|
||||
pass
|
||||
|
||||
stages = [call.kwargs["execution_stage"] for call in adapter.run_seat_turn.await_args_list]
|
||||
assert stages.count("manager_dispatch") == 1
|
||||
assert stages.count("group_chat") == 2
|
||||
assert "seat-c" not in [call.kwargs["agent_id"] for call in adapter.run_seat_turn.await_args_list]
|
||||
assert [row["agent_id"] for row in participant_rows] == ["manager", "seat-a", "seat-b"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("execution_mode", "seat_count"),
|
||||
[("single", 1), ("parallel", 2), ("chain", 2)],
|
||||
)
|
||||
def test_structured_factory_builds_each_trusted_topology(execution_mode, seat_count):
|
||||
pytest.importorskip("agent_framework")
|
||||
state = _state(["seat-a", "seat-b"][:seat_count])
|
||||
adapter = SimpleNamespace(_emit_critical=AsyncMock())
|
||||
seat_executors = [SeatExecutor(adapter, state, agent_id) for agent_id in state.seat_agent_ids]
|
||||
workflow = create_workflow(
|
||||
mode="structured",
|
||||
planner=PlannerExecutor(adapter, state),
|
||||
cross_review=CrossReviewExecutor(adapter, state),
|
||||
seat_executors=seat_executors,
|
||||
approval_gate=ApprovalGateExecutor(adapter, state, SimpleNamespace()),
|
||||
finalizer=FinalizerExecutor(adapter, state),
|
||||
waiting_terminal=WaitingTerminalExecutor(),
|
||||
seat_agent_ids=state.seat_agent_ids,
|
||||
execution_mode=execution_mode,
|
||||
)
|
||||
assert workflow is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_planner_deterministic_assignments():
|
||||
state = _state()
|
||||
|
||||
Reference in new issue
Block a user