"""Tests for topological DAG workflow execution, edge branching, and Earth stateless routing.""" from __future__ import annotations import copy 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() @pytest.mark.asyncio async def test_generic_dag_supports_output_schema_field_routing_and_guardrail_edges(): from app.services.ai import dag_executor class _RepairAI: def __init__(self): self.calls = 0 async def analyze(self, _req): self.calls += 1 if self.calls == 1: return SimpleNamespace(content="暂时分析完成,结论是需要补查 need_followup。", model="m1", provider="p1") return SimpleNamespace( content=json.dumps({"decision": "need_followup", "reason": "need extra proof"}), model="m1", provider="p1", ) workflow = { "workflow_id": "custom.routing_test", "name": "Generic Routing Test", "published_graph": { "nodes": [ {"id": "t", "node_type": "trigger", "title": "Start"}, { "id": "judge", "node_type": "llm_agent", "title": "Judge", "params": { "output_schema": { "type": "object", "properties": { "decision": {"type": "string", "enum": ["direct", "need_followup"]}, "reason": {"type": "string"}, }, "required": ["decision", "reason"], } }, }, {"id": "branch_direct", "node_type": "output", "title": "Direct Branch"}, {"id": "branch_followup", "node_type": "output", "title": "Followup Branch"}, ], "edges": [ {"id": "e1", "source": "t", "target": "judge", "condition": "always"}, { "id": "e2", "source": "judge", "target": "branch_direct", "condition": "on_field_equals", "condition_value": "decision=direct", }, { "id": "e3", "source": "judge", "target": "branch_followup", "condition": "on_field_equals", "condition_value": "decision=need_followup", }, ], }, "bindings": {}, } ai = _RepairAI() events = [] async for evt in dag_executor.run_workflow_dag_stream( db=None, workflow=workflow, question="Route test", ai_client=ai, ): events.append(evt) assert ai.calls == 2 node_statuses = { e["data"]["node_id"]: e["data"]["status"] for e in events if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"} } assert node_statuses["branch_direct"] == "skipped" assert node_statuses["branch_followup"] == "completed" @pytest.mark.asyncio async def test_location_resolve_unknown_runs_real_generic_dag(monkeypatch): from app.services.ai import dag_executor from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS from app.services.location import workflow_tools monkeypatch.setattr( workflow_tools, "lookup_wikidata_facility", lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), ) monkeypatch.setattr( workflow_tools, "lookup_peeringdb_facility", lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())), ) monkeypatch.setattr( "app.services.compute_center_locations._lookup_ror_organization", lambda _q: None, ) monkeypatch.setattr( workflow_tools, "_agent_geocoder", lambda _q: { "lat": "64.0025", "lon": "-22.5594", "display_name": "Keflavik, Iceland", "address": {"city": "Keflavik", "country": "Iceland"}, }, ) class _Search: async def search(self, _q, max_results=5): return [ SimpleNamespace( title="ISEG2 Verne Global", url="https://verneglobal.com/iseg2", snippet="Nebius ISEG2 sits in Keflavik, Iceland.", source_provider="tavily", ) ] class _JudgeAI: def __init__(self): self.calls = 0 async def is_ready(self): return True, "minimax", "MiniMax-M3.1-Flash" async def analyze(self, req): self.calls += 1 items = (req.context or {}).get("evidence_items") or [] assert items and items[0]["id"] == "E1" return SimpleNamespace( content=json.dumps( { "decision": "located", "facility_name": "Verne Global", "city": "Keflavik", "country": "Iceland", "precision": "city", "confidence": 0.92, "evidence_ids": ["E1"], "country_override_reason": "Nebius HQ is NL while cluster sits in Iceland.", "reasoning": "E1 confirms Keflavik, Iceland.", } ), model="MiniMax-M3.1-Flash", provider="minimax", ) builtin_loc = copy.deepcopy(next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown")) workflow = { "workflow_id": builtin_loc["workflow_id"], "name": builtin_loc["name"], "published_graph": builtin_loc["graph"], "bindings": builtin_loc["bindings"], } ai = _JudgeAI() events = [] async for evt in dag_executor.run_workflow_dag_stream( db=None, workflow=workflow, question="定位 ISEG2", targets=[{"entity_type": "compute_center", "entity_id": "top500_13", "label": "ISEG2"}], earth_context={ "name": "ISEG2", "operator": "Nebius", "country": "荷兰", "_location_runtime": {"web_search_client": _Search()}, }, ai_client=ai, allow_external_tools=True, ): events.append(evt) assert ai.calls == 1 statuses = { e["data"]["node_id"]: e["data"]["status"] for e in events if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"} } assert statuses["l0_normalize"] == "completed" assert statuses["l1_knowledge"] == "completed" assert statuses["l2_research_r1"] == "completed" assert statuses["l2_judge_r1"] == "completed" assert statuses["l2_research_r2"] == "skipped" assert statuses["l2_judge_r2"] == "skipped" assert statuses["l3_geocode"] == "completed" assert statuses["l3_geo_guardrail"] == "completed" assert statuses["l4_persist_outcome"] == "completed" done_ev = next(e["data"] for e in events if e.get("event") == "done") so = done_ev["structured_output"] assert so["success"] is True assert so["best_candidate"]["city"] == "Keflavik" assert so["best_candidate"]["country"] == "冰岛" assert so["best_candidate"]["raw_payload"]["citations"] == ["https://verneglobal.com/iseg2"] assert done_ev["scene_spec"]["fly_to"]["lat"] == pytest.approx(64.0025) async def _async_val(v): return v