Files
planet/backend/tests/test_dag_executor.py
T
linkong 04cebdc504
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.82.0
2026-12-01 18:43:57 +08:00

365 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Tests for topological DAG workflow execution, edge branching, and Earth stateless routing."""
from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from app.db.session import Base, get_db
from app.main import app
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.earth_news import EarthNewsItem
from app.models.situational_assessment import InvestigationSession, WorkflowRun
from app.models.system_setting import SystemSetting
from app.services.ai.dag_executor import render_workflow_template, run_workflow_dag_stream
class _SyncAsAsyncSession:
def __init__(self, sync_session):
self._s = sync_session
def add(self, obj):
return self._s.add(obj)
async def execute(self, stmt, *args, **kwargs):
return self._s.execute(stmt, *args, **kwargs)
async def scalar(self, stmt, *args, **kwargs):
return self._s.scalar(stmt, *args, **kwargs)
async def get(self, model, ident):
return self._s.get(model, ident)
async def delete(self, obj):
return self._s.delete(obj)
async def commit(self):
return self._s.commit()
async def rollback(self):
return self._s.rollback()
async def refresh(self, obj):
return self._s.refresh(obj)
async def close(self):
return self._s.close()
def _make_db_factory():
engine = create_engine("sqlite:///:memory:")
event.listen(
engine,
"connect",
lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v),
)
Base.metadata.create_all(
engine,
tables=[
AIWorkflow.__table__,
AIWorkflowRevision.__table__,
AIWorkflowFixture.__table__,
WorkflowRun.__table__,
InvestigationSession.__table__,
SystemSetting.__table__,
BGPIncident.__table__,
CollectedData.__table__,
EarthNewsItem.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._sess = _SyncAsAsyncSession(sync_factory())
return self._sess
async def __aexit__(self, *_args):
await self._sess.close()
return engine, _Ctx()
def test_render_workflow_template_safely_interpolates_targets_and_nodes():
rendered = render_workflow_template(
"检查 {{target.label}} ({{target.lat}}, {{target.lon}});前序={{node.step1}};全部={{targets_summary}};未知={{evil.__class__}}",
question="有什么异常",
targets=[
{
"entity_type": "cable",
"entity_id": "cable-peace",
"label": "PEACE Cable",
"latitude": 12.3456,
"longitude": 43.21,
}
],
node_outputs={"step1": "周边发现2艘锚泊船"},
)
assert "PEACE Cable" in rendered
assert "12.3456" in rendered
assert "周边发现2艘锚泊船" in rendered
assert "unknown" not in rendered and "__class__" not in rendered
@pytest.mark.asyncio
async def test_dag_executor_multi_llm_chain_edge_conditions_and_fly_to():
engine, factory = _make_db_factory()
calls: list[dict] = []
class _FakeMultiAIClient:
async def is_ready(self):
return True, "openai", "gpt-test"
async def analyze(self, req):
calls.append({"mode": "analyze", "objective": req.objective})
return SimpleNamespace(
content="初筛摘要:已提取海缆坐标与船舶轨迹要点",
provider="openai",
model="gpt-fast",
)
async def stream_analyze(self, req, request_id=None):
calls.append({"mode": "stream", "objective": req.objective, "context": req.context})
yield {"event": "reasoning", "delta": "正在交叉比对阶段一结论…"}
yield {"event": "text", "delta": "最终研判:海缆周边态势稳定。"}
workflow = {
"workflow_id": "custom.multi_stage",
"name": "多阶段研判",
"active_revision": 1,
"bindings": {"prompt_template": "围绕 {{targets_summary}} 分析"},
"published_graph": {
"nodes": [
{"id": "trig", "node_type": "trigger", "title": "触发"},
{
"id": "det_bgp",
"node_type": "deterministic",
"title": "BGP 快照",
"tools": ["query_bgp_incidents"],
},
{
"id": "branch_cable_only",
"node_type": "deterministic",
"title": "海缆分支",
"tools": ["query_cable_posture"],
},
{
"id": "branch_sat_skip",
"node_type": "deterministic",
"title": "卫星分支(应跳过)",
"tools": ["query_satellite_posture"],
},
{
"id": "llm_stage1",
"node_type": "llm_agent",
"title": "阶段一摘要",
"system_prompt": "做初步梳理",
"prompt": "梳理 {{target.label}}",
},
{
"id": "llm_final",
"node_type": "llm_agent",
"title": "阶段二定论",
"system_prompt": "综合定论",
"prompt": "依据阶段一结论:{{node.llm_stage1}}",
},
{
"id": "guard",
"node_type": "guardrail",
"title": "核验声明",
"guardrails": {"append_disclaimer": "以上结论基于内置遥测实时快照。"},
},
{
"id": "out",
"node_type": "output",
"title": "输出联动",
"params": {"fly_to_target": True, "fly_zoom": 1.6},
},
],
"edges": [
{"id": "e1", "source": "trig", "target": "det_bgp", "condition": "always"},
{
"id": "e2",
"source": "det_bgp",
"target": "branch_cable_only",
"condition": "on_entity_type",
"condition_value": "cable",
},
{
"id": "e3",
"source": "det_bgp",
"target": "branch_sat_skip",
"condition": "on_entity_type",
"condition_value": "satellite",
},
{"id": "e4", "source": "branch_cable_only", "target": "llm_stage1", "condition": "always"},
{"id": "e5", "source": "llm_stage1", "target": "llm_final", "condition": "always"},
{"id": "e6", "source": "llm_final", "target": "guard", "condition": "always"},
{"id": "e7", "source": "guard", "target": "out", "condition": "always"},
],
},
}
try:
async with factory() as db:
events: list[dict] = []
async for ev in run_workflow_dag_stream(
db=db,
workflow=workflow,
question="",
targets=[
{
"entity_type": "cable",
"entity_id": "cable-2",
"label": "2Africa",
"latitude": 15.5,
"longitude": 41.2,
}
],
ai_client=_FakeMultiAIClient(),
run_id="run-dag-test",
allow_external_tools=False,
):
events.append(ev)
skipped_nodes = [
e["data"]["node_id"]
for e in events
if e["event"] == "node" and e["data"].get("status") == "skipped"
]
assert "branch_sat_skip" in skipped_nodes
assert "branch_cable_only" not in skipped_nodes
# Verify multi-LLM chaining: stage1 used analyze(), stage2 received stage1 output and used stream_analyze()
assert len(calls) == 2
assert calls[0]["mode"] == "analyze"
assert calls[1]["mode"] == "stream"
assert "初筛摘要:已提取海缆坐标与船舶轨迹要点" in calls[1]["objective"]
done_ev = next(e["data"] for e in events if e["event"] == "done")
assert "最终研判:海缆周边态势稳定。" in done_ev["answer_markdown"]
assert "以上结论基于内置遥测实时快照。" in done_ev["answer_markdown"]
assert done_ev["scene_spec"] == {
"fly_to": {"lat": 15.5, "lon": 41.2, "zoom": 1.6},
"highlight_entities": ["cable-2"],
}
finally:
engine.dispose()
@pytest.mark.asyncio
async def test_earth_stateless_stream_executes_published_custom_workflow_and_blocks_external_tools(monkeypatch):
engine, factory = _make_db_factory()
class _FakePublicAIClient:
llm_config = {"provider": "openai", "model": "gpt-test", "max_tokens": 4096}
async def is_ready(self):
return True, "openai", "gpt-test"
async def stream_analyze(self, req, request_id=None):
yield {"event": "text", "delta": f"已用已发布图回答(外部搜索跳过={req.context.get('tool_results', {}).get('web_search', {}).get('skipped')})"}
from app.services.ai_client import get_ai_provider_client
async def override_db():
async with factory() as session:
yield session
async def fake_client():
return _FakePublicAIClient()
app.dependency_overrides[get_db] = override_db
app.dependency_overrides[get_ai_provider_client] = fake_client
try:
async with factory() as session:
session.add(
AIWorkflow(
workflow_id="custom.earth_pub_only",
name="公开海缆研判",
name_en="Public Cable Check",
category="custom",
is_default=False,
is_builtin=False,
active_revision=1,
published_graph={
"nodes": [
{"id": "t", "node_type": "trigger", "title": "Trigger"},
{
"id": "d",
"node_type": "deterministic",
"title": "Tools",
"tools": ["web_search"],
},
{
"id": "l",
"node_type": "llm_agent",
"title": "Published LLM",
"system_prompt": "Published prompt",
"prompt": "{{target.label}} {{question}}",
},
],
"edges": [
{"id": "e1", "source": "t", "target": "d"},
{"id": "e2", "source": "d", "target": "l"},
],
},
draft_graph={
"nodes": [
{
"id": "l_draft",
"node_type": "llm_agent",
"title": "Draft Secret",
"system_prompt": "SHOULD NOT RUN FOR PUBLIC CALLER",
"prompt": "Draft",
}
],
"edges": [],
},
bindings={
"enabled": True,
"surfaces": ["info_card"],
"entity_types": ["cable"],
"action_label": "海缆排查",
},
)
)
await session.commit()
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
resp = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "分析周边风险",
"workflow_id": "custom.earth_pub_only",
"targets": [
{
"entity_type": "cable",
"entity_id": "cable-1",
"label": "FLAG Cable",
"latitude": 30.0,
"longitude": 32.0,
}
],
},
)
assert resp.status_code == 200
body = resp.text
assert "external_web_search_admin_only" in body
assert "l_draft" not in body
finally:
app.dependency_overrides.clear()
engine.dispose()