forked from linkong/planet
610 lines
25 KiB
Python
610 lines
25 KiB
Python
"""Regression tests for the v0.82.0 workflow review: Earth DAG data/evidence/card output and evolver safety."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import json
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from sqlalchemy import create_engine, event, select
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from app.db.session import Base
|
|
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 WorkflowRun
|
|
from app.models.system_setting import SystemSetting
|
|
from app.services.ai import dag_executor
|
|
from app.services.ai.dag_executor import _execute_tool, run_workflow_dag_stream
|
|
from app.services.ai.workflow_evolver import (
|
|
META_WORKFLOW_ID,
|
|
_load_ledger_entries,
|
|
append_ledger_entry,
|
|
build_business_evolution_request,
|
|
evaluate_canary_and_maybe_rollback,
|
|
grade_fixture_result,
|
|
propose_meta_evolution,
|
|
propose_workflow_evolution,
|
|
run_fixture_ab_eval,
|
|
update_evolution_policy,
|
|
)
|
|
from app.services.ai.workflow_registry import (
|
|
_fallback_workflow_dict,
|
|
create_workflow,
|
|
discard_workflow_draft,
|
|
ensure_builtin_workflows,
|
|
list_public_workflow_bindings,
|
|
publish_workflow,
|
|
rollback_workflow,
|
|
save_workflow_draft,
|
|
)
|
|
|
|
|
|
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 flush(self):
|
|
return self._s.flush()
|
|
|
|
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():
|
|
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__,
|
|
SystemSetting.__table__,
|
|
BGPIncident.__table__,
|
|
CollectedData.__table__,
|
|
EarthNewsItem.__table__,
|
|
],
|
|
)
|
|
return engine, _SyncAsAsyncSession(sessionmaker(engine, expire_on_commit=False)())
|
|
|
|
|
|
async def _collect(stream) -> list[dict]:
|
|
return [ev async for ev in stream]
|
|
|
|
|
|
def _done(events: list[dict]) -> dict:
|
|
return next(ev["data"] for ev in events if ev["event"] == "done")
|
|
|
|
|
|
def _text(events: list[dict]) -> str:
|
|
return "".join(ev["data"]["delta"] for ev in events if ev["event"] == "text")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 1. Cross-layer evidence: each source must query its own object regardless of click order
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multi_select_targets_route_each_source_to_its_own_object(monkeypatch):
|
|
seen: dict[str, list] = {"bgp": [], "cable": [], "vessel": []}
|
|
|
|
async def fake_bgp(_db, *, incident_key=None, **_kw):
|
|
seen["bgp"].append(incident_key)
|
|
return []
|
|
|
|
async def fake_cable(_db, *, entity_id=None, **_kw):
|
|
seen["cable"].append(entity_id)
|
|
return {}
|
|
|
|
async def fake_vessel(_db, *, entity_id=None, **_kw):
|
|
seen["vessel"].append(entity_id)
|
|
return {}
|
|
|
|
monkeypatch.setattr(dag_executor, "query_bgp_incidents_tool", fake_bgp)
|
|
monkeypatch.setattr(dag_executor, "query_cable_posture_tool", fake_cable)
|
|
monkeypatch.setattr(dag_executor, "query_vessel_posture_tool", fake_vessel)
|
|
|
|
cable = {"entity_type": "cable", "entity_id": "cable-peace"}
|
|
vessel = {"entity_type": "vessel", "entity_id": "mmsi-413000000"}
|
|
bgp = {"entity_type": "bgp", "entity_id": "bgp-incident-77"}
|
|
for order in ([cable, vessel, bgp], [bgp, vessel, cable], [vessel, bgp, cable]):
|
|
for tool in ("query_bgp_incidents", "query_cable_posture", "query_vessel_posture"):
|
|
await _execute_tool(
|
|
None, tool, question="q", targets=order, earth_context={}, allow_external_tools=False
|
|
)
|
|
assert set(seen["bgp"]) == {"bgp-incident-77"}
|
|
assert set(seen["cable"]) == {"cable-peace"}
|
|
assert set(seen["vessel"]) == {"mmsi-413000000"}
|
|
|
|
# A source with no matching target gets no ID (never another layer's ID).
|
|
seen["vessel"].clear()
|
|
await _execute_tool(None, "query_vessel_posture", question="q", targets=[cable, bgp], earth_context={}, allow_external_tools=False)
|
|
assert seen["vessel"] == [None]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 2. Compute comparison workflow must hand a ViewSpec workbench to the Earth copilot
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_SERIES = {
|
|
"years": (2023, 2024),
|
|
"compute": [
|
|
{"year": 2023, "values": {"CN": 30.0, "US": 52.0}, "evidence_id": "ev-top500-2023"},
|
|
{"year": 2024, "values": {"CN": 37.0, "US": 50.0}, "evidence_id": "ev-top500-2024"},
|
|
],
|
|
"unit": "%",
|
|
"evidence": {
|
|
"ev-top500-2023": {"id": "ev-top500-2023", "title": "TOP500 2023", "publisher": "TOP500", "url": "https://top500.org/2023"},
|
|
"ev-top500-2024": {"id": "ev-top500-2024", "title": "TOP500 2024", "publisher": "TOP500", "url": "https://top500.org/2024"},
|
|
},
|
|
"time_basis": "retrospective",
|
|
}
|
|
|
|
|
|
class _ComputeBriefAI:
|
|
def __init__(self, content: str):
|
|
self.content = content
|
|
self.stream_calls = 0
|
|
|
|
async def is_ready(self):
|
|
return True, "fake", "fake-model"
|
|
|
|
async def analyze(self, req):
|
|
return SimpleNamespace(content=self.content, provider="fake", model="fake-model")
|
|
|
|
async def stream_analyze(self, req, request_id=None):
|
|
self.stream_calls += 1
|
|
yield {"event": "text", "delta": "should not stream"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("valid_brief", [True, False])
|
|
async def test_compute_comparison_workflow_emits_view_spec_and_no_raw_json(monkeypatch, valid_brief):
|
|
async def fake_compute(_db, countries, mode="global_share", **_kw):
|
|
return copy.deepcopy(_SERIES)
|
|
|
|
monkeypatch.setattr(dag_executor, "query_compute_posture_tool", fake_compute)
|
|
brief = {
|
|
"headline": "中国算力份额升至 37%",
|
|
"headline_en": "China share rises to 37%",
|
|
"executive_assertion": "2024 年中国全球算力份额为 37%。",
|
|
"executive_assertion_en": "China held 37% in 2024.",
|
|
"causes": [
|
|
{"label": "装机增长", "detail": "新增超算集中投运", "evidence_ids": ["ev-top500-2024" if valid_brief else "ev-made-up"]}
|
|
],
|
|
"breakthrough_levers": [],
|
|
"blind_spots": ["未覆盖商业云内部集群"],
|
|
"evidence_ids": ["ev-top500-2024"],
|
|
}
|
|
ai = _ComputeBriefAI(json.dumps(brief, ensure_ascii=False))
|
|
workflow = _fallback_workflow_dict("compute.comparison")
|
|
events = await _collect(
|
|
run_workflow_dag_stream(
|
|
db=None,
|
|
workflow=workflow,
|
|
question="对比中美算力",
|
|
earth_context={"selected_codes": ["CN", "US"], "mode": "global_share"},
|
|
ai_client=ai,
|
|
)
|
|
)
|
|
done = _done(events)
|
|
text = _text(events)
|
|
assert ai.stream_calls == 0
|
|
assert not text.lstrip().startswith("{") and '"headline"' not in text
|
|
assert isinstance(done["view_spec"], dict) and done["view_spec"].get("blocks")
|
|
late_meta = [ev["data"] for ev in events if ev["event"] == "meta" and ev["data"].get("view_spec")]
|
|
assert late_meta and late_meta[-1]["domain"] == "compute"
|
|
if valid_brief:
|
|
assert "中国算力份额升至 37%" in text
|
|
else:
|
|
assert "确定性研判" in text
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 3. Evidence guardrail failures must reach the user and the evaluator
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _guarded_graph(system_prompt: str = "研判 BGP 成因") -> dict:
|
|
return {
|
|
"nodes": [
|
|
{"id": "t", "node_type": "trigger", "title": "入口"},
|
|
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": system_prompt},
|
|
{"id": "gr", "node_type": "guardrail", "title": "证据校验", "guardrails": {"require_evidence": True}},
|
|
{"id": "out", "node_type": "output", "title": "输出"},
|
|
],
|
|
"edges": [
|
|
{"id": "e1", "source": "t", "target": "llm"},
|
|
{"id": "e2", "source": "llm", "target": "gr"},
|
|
{"id": "e3", "source": "gr", "target": "out"},
|
|
],
|
|
}
|
|
|
|
|
|
class _StreamAI:
|
|
"""Streams an answer chosen by the node system prompt (lets A/B graphs answer differently)."""
|
|
|
|
def __init__(self, answers: dict[str, str], default: str = "研判完成"):
|
|
self.answers = answers
|
|
self.default = default
|
|
|
|
async def is_ready(self):
|
|
return True, "fake", "fake-model"
|
|
|
|
async def analyze(self, req):
|
|
return SimpleNamespace(content=self._pick(req), provider="fake", model="fake-model")
|
|
|
|
async def stream_analyze(self, req, request_id=None):
|
|
yield {"event": "text", "delta": self._pick(req)}
|
|
|
|
def _pick(self, req) -> str:
|
|
for key, answer in self.answers.items():
|
|
if key in (req.system_prompt or ""):
|
|
return answer
|
|
return self.default
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_missing_evidence_marks_run_unverified_and_delivers_pending_cause():
|
|
workflow = {"workflow_id": "custom.bgp_cause", "name": "BGP 成因", "published_graph": _guarded_graph()}
|
|
events = await _collect(
|
|
run_workflow_dag_stream(
|
|
db=None, workflow=workflow, question="AS4837 为什么异常", ai_client=_StreamAI({}, "成因是上游劫持。")
|
|
)
|
|
)
|
|
done = _done(events)
|
|
assert done["status"] == "unverified"
|
|
assert done["verification"]["passed"] is False
|
|
assert "原因待核实" in done["answer_markdown"] and "待查项" in done["answer_markdown"]
|
|
failures = grade_fixture_result(
|
|
{"answer": done["answer_markdown"], "error": "", "verification_passed": False, "verification_warnings": done["verification"]["warnings"]},
|
|
{},
|
|
)
|
|
assert any("护栏" in f for f in failures)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 4. News: one click runs only the interactive branch
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_news_analysis_runs_only_the_branch_matching_the_trigger(monkeypatch):
|
|
async def fake_news(_db, region=None, limit=10):
|
|
return {"items": [{"title": "headline"}], "evidence": {}}
|
|
|
|
async def fake_global(_db, **_kw):
|
|
return {"items": [], "evidence": {}}
|
|
|
|
monkeypatch.setattr(dag_executor, "query_recent_earth_news_tool", fake_news)
|
|
monkeypatch.setattr(dag_executor, "query_global_situational_tool", fake_global)
|
|
calls: list[str] = []
|
|
|
|
class _AI:
|
|
async def is_ready(self):
|
|
return True, "fake", "fake-model"
|
|
|
|
async def analyze(self, req):
|
|
calls.append("analyze")
|
|
return SimpleNamespace(content='{"location": {}, "localizations": {}}', provider="fake", model="m")
|
|
|
|
async def stream_analyze(self, req, request_id=None):
|
|
calls.append("stream")
|
|
yield {"event": "text", "delta": "研判正文"}
|
|
|
|
workflow = _fallback_workflow_dict("earth.news.analysis")
|
|
events = await _collect(run_workflow_dag_stream(db=None, workflow=workflow, question="分析这条新闻", ai_client=_AI()))
|
|
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
|
|
assert "news_enrich_node" in skipped
|
|
assert calls == ["stream"]
|
|
assert _text(events) == "研判正文"
|
|
|
|
calls.clear()
|
|
events = await _collect(
|
|
run_workflow_dag_stream(db=None, workflow=workflow, question="enrich", ai_client=_AI(), trigger_source="ingest")
|
|
)
|
|
skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"}
|
|
assert "news_analyst_node" in skipped
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 5. Draft bindings stay out of the public Earth entry until publish; rollback restores them
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_draft_bindings_do_not_touch_public_entry_and_roll_back_with_graph():
|
|
engine, db = _make_db()
|
|
try:
|
|
await ensure_builtin_workflows(db)
|
|
wf_id = "earth.news.analysis"
|
|
|
|
async def public_ids() -> set[str]:
|
|
return {item["workflow_id"] for item in await list_public_workflow_bindings(db)}
|
|
|
|
assert wf_id in await public_ids()
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
|
graph = copy.deepcopy(row.published_graph)
|
|
live_bindings = copy.deepcopy(row.bindings)
|
|
disabled = {**live_bindings, "enabled": False}
|
|
|
|
saved = await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
|
|
assert wf_id in await public_ids()
|
|
assert saved["draft_bindings"]["enabled"] is False
|
|
await discard_workflow_draft(db, wf_id)
|
|
assert wf_id in await public_ids()
|
|
|
|
enabled_rev = (await publish_workflow(db, wf_id, graph=graph, bindings=live_bindings))["active_revision"]
|
|
await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin")
|
|
await publish_workflow(db, wf_id)
|
|
assert wf_id not in await public_ids()
|
|
await rollback_workflow(db, wf_id, enabled_rev)
|
|
assert wf_id in await public_ids()
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 6. Canary rollback must not overwrite a newer manual publish
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_canary_rollback_is_superseded_by_manual_publish():
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
engine, db = _make_db()
|
|
try:
|
|
await ensure_builtin_workflows(db)
|
|
wf_id = "default.general"
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
|
graph = copy.deepcopy(row.published_graph)
|
|
await publish_workflow(db, wf_id, graph=graph, actor="system:auto_evolver") # v2 canary
|
|
await append_ledger_entry(
|
|
db,
|
|
{"workflow_id": wf_id, "status": "canary", "base_revision": 1, "target_revision": 2, "canary_runs_target": 5},
|
|
)
|
|
manual = copy.deepcopy(graph)
|
|
manual["nodes"][0]["description"] = "manual v3"
|
|
await publish_workflow(db, wf_id, graph=manual, actor="admin") # v3 manual
|
|
now = datetime.now(UTC) + timedelta(seconds=2)
|
|
for idx in range(2):
|
|
db.add(
|
|
WorkflowRun(
|
|
id=f"v2_fail_{idx}", workflow_id=wf_id, status="failed", access_tier="admin", actor_key="admin",
|
|
question="q", input_params={}, tool_trace=[], budget_used={"workflow_revision": 2},
|
|
error_message="boom", started_at=now + timedelta(seconds=idx), completed_at=now + timedelta(seconds=idx + 1),
|
|
)
|
|
)
|
|
await db.commit()
|
|
res = await evaluate_canary_and_maybe_rollback(db, wf_id)
|
|
assert res["action"] == "superseded"
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
|
assert row.active_revision == 3
|
|
assert row.published_graph["nodes"][0]["description"] == "manual v3"
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 7. Evolver can conclude "no change" (business + meta)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class _EmptyPatchAI:
|
|
async def is_ready(self):
|
|
return True, "fake", "fake-model"
|
|
|
|
async def analyze(self, req):
|
|
return SimpleNamespace(content='{"summary": "无需修改", "node_patches": []}')
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_explicit_empty_patch_ends_round_without_new_version():
|
|
engine, db = _make_db()
|
|
try:
|
|
await ensure_builtin_workflows(db)
|
|
await update_evolution_policy(db, {"business_mode": "auto", "meta_mode": "auto"})
|
|
for wf_id in ("compute.comparison", "default.general"):
|
|
for apply_mode in ("preview", "draft", "auto"):
|
|
res = await propose_workflow_evolution(
|
|
db, wf_id, apply_mode=apply_mode, ai_client=_EmptyPatchAI(), trigger="manual"
|
|
)
|
|
assert res["applied_status"] == "no_change", (wf_id, apply_mode)
|
|
meta_res = await propose_meta_evolution(db, apply_mode="auto", ai_client=_EmptyPatchAI())
|
|
assert meta_res["applied_status"] == "no_change"
|
|
|
|
class _NoAI:
|
|
async def is_ready(self):
|
|
return False, "", ""
|
|
|
|
# No AI, no ledger outcomes, no instruction -> nothing to base a meta rule on.
|
|
meta_fallback = await propose_meta_evolution(db, apply_mode="auto", ai_client=_NoAI())
|
|
assert meta_fallback["applied_status"] == "no_change"
|
|
rows = (await db.execute(select(AIWorkflow))).scalars().all()
|
|
assert all(r.active_revision == 1 and r.draft_graph is None for r in rows)
|
|
assert await _load_ledger_entries(db) == []
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 8. Graded A/B: 37 vs 73 must be a regression, and auto-publish requires the gate
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_graded_fixture_ab_detects_wrong_number_and_gates_auto_publish(monkeypatch):
|
|
engine, db = _make_db()
|
|
try:
|
|
await ensure_builtin_workflows(db)
|
|
base_graph = {
|
|
"nodes": [
|
|
{"id": "t", "node_type": "trigger", "title": "入口"},
|
|
{"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": "PROMPT_BASE"},
|
|
{"id": "out", "node_type": "output", "title": "输出"},
|
|
],
|
|
"edges": [{"id": "e1", "source": "t", "target": "llm"}, {"id": "e2", "source": "llm", "target": "out"}],
|
|
}
|
|
await create_workflow(db, workflow_id="custom.metric", name="指标研判", graph=base_graph)
|
|
proposed = copy.deepcopy(base_graph)
|
|
proposed["nodes"][1]["system_prompt"] = "PROMPT_NEW"
|
|
ai = _StreamAI({"PROMPT_BASE": "观测值为 37。", "PROMPT_NEW": "观测值为 73。"})
|
|
|
|
async def fake_client(_db):
|
|
return ai
|
|
|
|
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
|
|
db.add(
|
|
AIWorkflowFixture(
|
|
workflow_id="custom.metric", name="观测值 37", sample_question="当前观测值是多少?",
|
|
context_json={"expect": {"numbers": [37]}},
|
|
)
|
|
)
|
|
await db.commit()
|
|
ab = await run_fixture_ab_eval(db, "custom.metric", proposed)
|
|
assert (ab["base_passed"], ab["proposed_passed"]) == (1, 0)
|
|
assert ab["verdict"] == "regressed" and ab["regressions"] == ["观测值 37"]
|
|
assert ab["graded_fixture_count"] == 1
|
|
|
|
# Auto-publish of that regressing candidate is blocked by the A/B gate.
|
|
await update_evolution_policy(db, {"business_mode": "auto"})
|
|
|
|
class _PatchAI(_StreamAI):
|
|
async def analyze(self, req):
|
|
return SimpleNamespace(
|
|
content=json.dumps(
|
|
{"summary": "调整提示词", "node_patches": [{"node_id": "llm", "field": "system_prompt", "after": "PROMPT_NEW", "reason": "test"}]}
|
|
)
|
|
)
|
|
|
|
res = await propose_workflow_evolution(
|
|
db, "custom.metric", apply_mode="auto", ai_client=_PatchAI(ai.answers), trigger="manual"
|
|
)
|
|
assert res["applied_status"] == "blocked"
|
|
assert "A/B" in res["blocked_reason"]
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "custom.metric"))).scalar_one()
|
|
assert row.active_revision == 1
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 9. Auto evolution builds from the live revision and never ships human drafts
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_auto_evolution_ignores_unpublished_human_draft(monkeypatch):
|
|
engine, db = _make_db()
|
|
try:
|
|
await ensure_builtin_workflows(db)
|
|
wf_id = "default.general"
|
|
stream_ai = _StreamAI({}, "研判完成:态势稳定。")
|
|
|
|
async def fake_client(_db):
|
|
return stream_ai
|
|
|
|
monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client)
|
|
db.add(
|
|
AIWorkflowFixture(
|
|
workflow_id=wf_id, name="稳定性", sample_question="全球态势",
|
|
context_json={"expect": {"must_include": ["研判完成"]}},
|
|
)
|
|
)
|
|
await db.commit()
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
|
human_draft = copy.deepcopy(row.published_graph)
|
|
for node in human_draft["nodes"][:3]:
|
|
node["description"] = "HUMAN EDIT"
|
|
await save_workflow_draft(db, wf_id, human_draft, actor="admin")
|
|
await update_evolution_policy(db, {"business_mode": "auto"})
|
|
|
|
class _PatchAI(_StreamAI):
|
|
async def analyze(self, req):
|
|
return SimpleNamespace(
|
|
content=json.dumps(
|
|
{"summary": "增加一步", "node_patches": [{"node_id": "advisor_agent", "field": "max_steps", "after": 4, "reason": "test"}]}
|
|
)
|
|
)
|
|
|
|
res = await propose_workflow_evolution(
|
|
db, wf_id, apply_mode="auto", trigger="auto_post_run", ai_client=_PatchAI({}, "研判完成:态势稳定。")
|
|
)
|
|
assert res["applied_status"] == "auto_published", res["blocked_reason"]
|
|
row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one()
|
|
assert all(n.get("description") != "HUMAN EDIT" for n in row.published_graph["nodes"])
|
|
assert row.draft_graph is not None
|
|
assert sum(1 for n in row.draft_graph["nodes"] if n.get("description") == "HUMAN EDIT") == 3
|
|
assert [(c["node_id"], c["field"]) for c in res["changes_vs_live"]] == [("advisor_agent", "max_steps")]
|
|
ledger = await _load_ledger_entries(db)
|
|
assert ledger[0]["changes_vs_live"] == res["changes_vs_live"]
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 10. Every meta-evolvable field changes the downstream business request
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_meta_evolvable_fields_change_business_request():
|
|
base_diag = {"system_prompt": "诊断系统", "prompt": "诊断任务 A", "thinking_enabled": True}
|
|
base_patch = {"system_prompt": "输出 JSON node_patches", "prompt": "补丁任务", "thinking_enabled": True}
|
|
|
|
def build(diag, patch):
|
|
req = build_business_evolution_request(
|
|
workflow_id="default.general", mode="optimize", instruction="", diag_node=diag, patch_node=patch,
|
|
schema={"type": "object"}, context={},
|
|
)
|
|
return req.model_dump()
|
|
|
|
baseline = build(base_diag, base_patch)
|
|
variants = {
|
|
("diag_node", "system_prompt"): build({**base_diag, "system_prompt": "诊断系统 v2"}, base_patch),
|
|
("diag_node", "prompt"): build({**base_diag, "prompt": "诊断任务 B"}, base_patch),
|
|
("patch_node", "system_prompt"): build(base_diag, {**base_patch, "system_prompt": "输出 JSON node_patches v2"}),
|
|
("patch_node", "prompt"): build(base_diag, {**base_patch, "prompt": "补丁任务 v2"}),
|
|
("patch_node", "thinking_enabled"): build(base_diag, {**base_patch, "thinking_enabled": False}),
|
|
}
|
|
from app.services.ai.workflow_evolver import META_EVOLVABLE_FIELDS
|
|
|
|
assert set(variants) == set(META_EVOLVABLE_FIELDS)
|
|
for key, req in variants.items():
|
|
assert req != baseline, key
|
|
assert META_WORKFLOW_ID == "meta.workflow_evolver"
|