test_four_tuple.py 15.2 KB
"""四元组改造的新能力:决策表、函数试跑、画布、版本对比、问数 Agent、一句话起草、MCP 服务页、业务角色。

复用 test_platform 的夹具:SQLite 元数据库 + 假业务库 + 打桩 LLM。
"""
from __future__ import annotations

import sys
from pathlib import Path

import pytest
from fastapi import HTTPException

sys.path.insert(0, str(Path(__file__).parent))

from app.core import llm                                  # noqa: E402
from test_platform import build_basics, env, make_action  # noqa: E402,F401


# =========================== 决策表 ===========================
def test_决策表单元格写法():
    from app.kernel.decision import cell_expr
    assert cell_expr("x", "") == "" and cell_expr("x", "-") == ""
    assert cell_expr("x", "> 3") == "(x > 3)"
    assert cell_expr("x", ">= 0 and < 3") == "(x >= 0) and (x < 3)"
    assert cell_expr("x", "[0, 3]") == "(x >= 0 and x <= 3)"
    assert cell_expr("x", "0..3") == "(x >= 0 and x <= 3)"
    assert cell_expr("x", "A") == "x == 'A'"
    assert cell_expr("x", "'A'") == "x == 'A'"
    assert cell_expr("x", 12) == "x == 12"
    assert cell_expr("x", "in ['A', 'B']") == "x in ['A', 'B']"


def test_决策表命中策略与默认值():
    from app.kernel import decision
    spec = decision.normalize({
        "inputs": [{"name": "delta"}, {"name": "grade"}], "outputs": ["score", "tag"],
        "rows": [{"when": {"delta": "> 3"}, "then": {"score": 2, "tag": "好"}},
                 {"when": {"delta": "> 0", "grade": "A"}, "then": {"score": "=delta * 10", "tag": "中"}},
                 {"when": {"delta": "> 0"}, "then": {"score": 1, "tag": "一般"}}],
        "default": {"score": 0, "tag": "无"}})
    assert decision.evaluate(spec, {"delta": 5, "grade": "B"})["result"] == {"score": 2, "tag": "好"}
    r = decision.evaluate(spec, {"delta": 0.5, "grade": "A"})
    assert r["result"] == {"score": 5.0, "tag": "中"} and r["matched"] == [2]
    assert decision.evaluate(spec, {"delta": -1, "grade": "A"})["result"] == {"score": 0, "tag": "无"}
    spec["hit_policy"] = "collect"
    assert [x["tag"] for x in decision.evaluate(spec, {"delta": 5, "grade": "A"})["result"]] == ["好", "中", "一般"]
    with pytest.raises(decision.DecisionError):
        decision.normalize({"inputs": ["x"], "outputs": ["y"], "rows": [{"when": {"x": "> > 3"}}]})
    with pytest.raises(decision.DecisionError):
        decision.normalize({"inputs": [], "outputs": ["y"]})


def test_决策表是函数并能被调用(env):
    from app.capability import registry
    from app.kernel import service
    service.create_concept("function", "达成分级", spec={
        "category": "decision", "inputs": [{"name": "rate"}], "outputs": [{"name": "level"}],
        "rows": [{"when": {"rate": ">= 1"}, "then": {"level": "A"}},
                 {"when": {"rate": "< 1"}, "then": {"level": "B"}}]})
    service.publish("决策表")
    assert registry.call_function("decision.eval", {"table": "达成分级", "inputs": {"rate": 1.2}})["result"] == {"level": "A"}
    out = registry.call_function("function.eval", {"name": "达成分级", "args": {"inputs": {"rate": 0.3}}})
    assert out["result"] == {"level": "B"} and out["function"]["category"] == "decision"
    ov = registry.call_function("ontology.overview", {})
    assert ov["concepts"]["decision"][0]["name"] == "达成分级"


# =========================== 试跑 / 画布 / 版本 ===========================
def test_试跑草稿不用发布(env):
    from fastapi.testclient import TestClient
    from app.main import app
    b = build_basics(env["ds_id"])
    c = TestClient(app)
    r = c.post("/api/kernel/try", json={"kind": "function", "spec": {
        "category": "rule", "expression": "max(0, ceil(t * d - o))"}, "args": {"vars": {"t": 0.15, "d": 100, "o": 12}}})
    assert r.status_code == 200 and r.json()["result"] == 3
    r = c.post("/api/kernel/try", json={"kind": "function", "spec": {
        "category": "decision", "inputs": ["x"], "outputs": ["y"],
        "rows": [{"when": {"x": "> 0"}, "then": {"y": "正"}}], "default": {"y": "非正"}},
        "args": {"inputs": {"x": -2}}})
    assert r.json()["result"] == {"y": "非正"}
    # 聚合函数的工作副本可以直接试跑取数
    r = c.post(f"/api/kernel/concepts/{b['metric']['id']}/try", json={"args": {"dimensions": ["网点"]}})
    assert r.status_code == 200 and len(r.json()["rows"]) == 3
    # 动作试跑只预览、不提议
    a = make_action(b["ot"]["id"])
    r = c.post(f"/api/kernel/concepts/{a['id']}/try", json={"args": {"reason": "x"}, "object_key": "1"})
    assert r.status_code == 200 and r.json()["effects"][0]["tool"] == "object.write"
    from app.capability import actions
    assert actions.list_runs() == []


def test_画布数据与布局不算修改(env):
    from fastapi.testclient import TestClient
    from app.main import app
    from app.kernel import service
    b = build_basics(env["ds_id"])
    a = make_action(b["ot"]["id"])
    store2 = service.create_concept("object_type", "区域")
    service.create_concept("link_type", "属于", spec={"from_type": b["ot"]["id"], "to_type": store2["id"]})
    c = TestClient(app)
    g = c.get("/api/kernel/graph").json()
    kinds = {n["id"]: n["type_key"] for n in g["nodes"]}
    assert kinds[b["metric"]["id"]] == "aggregate" and kinds[a["id"]] == "action"
    assert any(e["kind"] == "link" and e["label"] == "属于" for e in g["edges"])
    assert any(e["kind"] == "owns" and e["target"] == a["id"] for e in g["edges"])
    service.publish("加关系")
    assert c.put("/api/kernel/layout", json={"positions": {b["ot"]["id"]: {"x": 10, "y": 20}}}).json()["saved"] == 1
    assert service.pending_diff() == {"added": [], "removed": [], "changed": []}
    assert service.get_concept(b["ot"]["id"])["spec"]["ui"]["pos"] == {"x": 10.0, "y": 20.0}
    # 表单保存不带 ui,也不会冲掉画布位置
    service.update_concept(b["ot"]["id"], description="改")
    assert service.get_concept(b["ot"]["id"])["spec"]["ui"]["pos"]["x"] == 10.0


def test_动作随本体一起发布_版本对比_回滚(env):
    from app.capability import actions, defs
    from app.kernel import service
    b = build_basics(env["ds_id"])                           # 第 1 版
    a = make_action(b["ot"]["id"])                           # 第 2 版:加了动作
    assert defs.find("mark_follow", "action")["status"] == "published"
    service.update_concept(b["metric"]["id"], description="新口径", synonyms=["销售额", "营收"])
    service.publish("第三版")
    cmp = service.compare_revisions(1, 3)
    assert [x["name"] for x in cmp["added"]] == ["mark_follow"] and cmp["added"][0]["type_key"] == "action"
    ch = next(x for x in cmp["changed"] if x["name"] == "成交金额")
    fields = {c["field"]: c for c in ch["changes"]}
    assert fields["description"]["after"] == "新口径" and "营收" in fields["synonyms"]["after"]
    service.rollback(1)                                      # 回到没有动作的版本
    with pytest.raises(HTTPException):
        actions.prepare(a["id"], {"reason": "x"}, "1")
    from fastapi.testclient import TestClient
    from app.main import app
    r = TestClient(app).get("/api/kernel/revisions/compare?from=0&to=1")
    assert r.status_code == 200 and len(r.json()["added"]) == 3


# =========================== 问数 Agent ===========================
def test_问数Agent_命中指标走确定性取数(env, monkeypatch):
    from app.capability import registry
    b = build_basics(env["ds_id"])
    calls = []

    def fake(msgs, **k):
        calls.append(msgs[0]["content"])
        return {"route": "metric", "metric": "成交金额", "dimensions": ["网点"]}
    monkeypatch.setattr(llm, "chat_json", fake)
    events = []
    out = registry.call_function("data.ask", {"question": "各网点的销售额"}, emit=events.append)
    assert out["route"] == "metric" and len(out["rows"]) == 3 and out["run_id"] > 0
    assert "成交金额" in calls[0] and "可拆分维度:网点" in calls[0]
    assert events[0]["type"] == "data_route" and events[0]["route"] == "metric"
    assert out["calibre"]["name"] == "达标判定" and b["metric"]["name"] == "成交金额"


def test_问数Agent_指标失败降级到SQL并做体检(env, monkeypatch):
    from app.data_agent import agent
    from app.text2sql import pipeline
    build_basics(env["ds_id"])
    monkeypatch.setattr(llm, "chat_json", lambda *a, **k: {"route": "metric", "metric": "成交金额",
                                                            "dimensions": ["不存在的维度"]})
    seen = {}

    def fake_run(ds_id, q, history=None, summarize=True):
        seen["q"] = q
        yield {"type": "execute", "sql": "SELECT 1", "truncated": False}
        yield {"type": "rows", "columns": ["v"], "rows": [[None]]}
        yield {"type": "done", "run_id": 9, "outcome": "ok"}
    monkeypatch.setattr(pipeline, "run_ask", fake_run)
    out = agent.ask("上个月的销售额")
    assert out["route"] == "sql" and out["run_id"] == 9
    assert any("改为生成 SQL" in n for n in out["notes"])
    assert any("NULL" in n for n in out["notes"])            # 体检:一行全空
    assert "本体提示" in seen["q"] and "解析为" in seen["q"]         # 时间按本体周期解析后交给 SQL 路


def test_问数Agent_没有指标不花选路调用(env, monkeypatch):
    from app.data_agent import agent
    from app.text2sql import pipeline

    def boom(*a, **k):
        raise AssertionError("没有命中指标时不该调用选路模型")
    monkeypatch.setattr(llm, "chat_json", boom)
    monkeypatch.setattr(pipeline, "run_ask", lambda *a, **k: iter([
        {"type": "rows", "columns": ["n"], "rows": []}, {"type": "done", "run_id": 3}]))
    out = agent.ask("一共有多少条明细")
    assert out["route"] == "sql" and any("没有返回任何行" in n for n in out["notes"])


def test_问数的指标来自本体(env):
    from app.kernel import service
    from app.text2sql import semantic
    b = build_basics(env["ds_id"])
    ms = semantic.list_metrics(env["ds_id"])
    assert [m["name"] for m in ms] == ["成交金额"]
    assert ms[0]["expression"] == "SUM(amount)" and ms[0]["base_model_id"] > 0
    assert ms[0]["id"] == b["metric"]["id"] and "销售额" in ms[0]["synonyms"]
    service.deprecate_concept(b["metric"]["id"])
    service.publish("下线指标")
    assert semantic.list_metrics(env["ds_id"]) == []


# =========================== 一句话起草 ===========================
def test_一句话起草_校验不过自动修一次(env, monkeypatch):
    from app.kernel import draft, service
    service.create_concept("object_type", "网点", spec={"properties": [{"name": "编号", "is_key": True}]})
    replies = iter([
        {"kind": "function", "category": "rule", "name": "差额", "object_type": "网点", "reason": "给定输入算一个数"},
        {"name": "差额", "spec": {"expression": "import os"}},                   # 第一次写坏
        {"name": "差额", "description": "还差多少", "spec": {"expression": "max(0, target - actual)",
                                                              "object_type": "网点"},
         "samples": [{"input": {"target": 10, "actual": 7}}]},
    ])
    monkeypatch.setattr(llm, "chat_json", lambda *a, **k: next(replies))
    evs = list(draft.generate("算一下离目标还差多少"))
    types = [e["type"] for e in evs]
    assert "classify" in types and "entities" in types
    vals = [e for e in evs if e["type"] == "validate"]
    assert [v["ok"] for v in vals] == [False, True]
    done = evs[-1]
    assert done["type"] == "done" and done["ok"]
    assert done["draft"]["spec"]["category"] == "rule"
    assert done["draft"]["spec"]["object_type"] == service.find("网点", "object_type")["id"]
    assert done["samples"][0]["input"]["target"] == 10
    assert service.find("差额", "function") is None             # 起草不落库


# =========================== MCP 服务页 ===========================
def test_MCP在线调用写审计_提议只进审批(env):
    from fastapi.testclient import TestClient
    from app.capability import actions
    from app.main import app
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    c = TestClient(app)
    tools = c.get("/api/cap/mcp/tools").json()
    names = {t["name"] for t in tools["tools"]}
    assert {"data_ask", "execute_function", "impact_analysis", "traverse_link", "execute_runcard",
            "propose_action", "get_action_status"} <= names
    assert not {n for n in names if "approve" in n or "reject" in n}      # 目录里没有审批工具
    # 老名字 function_eval 仍可调用(别名),审计记成新名字
    r = c.post("/api/cap/mcp/call/function_eval", json={"args": {"name": "达标判定",
                                                                 "args": {"vars": {"actual": 2, "target": 1}}}})
    assert r.json()["ok"] and r.json()["result"]["result"] is True
    r = c.post("/api/cap/mcp/call/nope", json={"args": {}})
    assert not r.json()["ok"]
    r = c.post("/api/cap/mcp/call/propose_action", json={"args": {
        "action": "mark_follow", "params": {"reason": "外部 Agent 建议"}, "object_key": "1", "reason": "测"}},
        headers={"X-User-Id": "operator"})
    run = r.json()["result"]
    assert run["status"] == "pending_approval" and run["initiator_kind"] == "ai"
    st = c.post("/api/cap/mcp/call/get_action_status", json={"args": {"run_id": run["id"]}}).json()
    assert st["result"]["status"] == "pending_approval"
    logs = c.get("/api/cap/mcp/logs").json()
    assert len(logs) == 4 and any("调用失败" in x["summary"] for x in logs)
    assert actions.get(run["id"])["status"] == "pending_approval"      # Agent 不能批


# =========================== 业务角色 ===========================
def test_业务角色在成员与角色里维护(env):
    from fastapi.testclient import TestClient
    from app.main import app
    from app.sop import spec as sop_spec
    c = TestClient(app)
    assert c.post("/api/gov/roles", json={"name": "店长", "description": "门店负责人"},
                  headers={"X-User-Id": "viewer"}).status_code == 403
    c.post("/api/gov/roles", json={"name": "店长", "description": "门店负责人"})
    assert [r["name"] for r in c.get("/api/gov/roles").json()] == ["店长"]
    assert "店长" in c.get("/api/kernel/meta").json()["roles"]
    s = sop_spec.normalize({"steps": [
        {"id": "a", "type": "human_task", "title": "巡店", "role": "店长", "next": "b"},
        {"id": "c", "type": "human_task", "title": "复核", "role": "不存在的角色", "next": "b"},
        {"id": "b", "type": "end"}]})
    warns = " ".join(sop_spec.validate(s)["warnings"])
    assert "不存在的角色" in warns and "「店长」" not in warns


def test_数据源提议的关系带上两端对象(env):
    """内省出来的关联基数是大写的 N:1,曾经因此校验失败、关系两端变成空的。"""
    from app.kernel import propose, schema
    assert schema.normalize_spec("link_type", {"cardinality": "N:1"})["cardinality"] == "n:1"
    assert schema.normalize_spec("link_type", {"cardinality": "many_to_many"})["cardinality"] == "n:n"
    links = [p for p in propose.datasource_proposals(env["ds_id"]) if p["kind"] == "link_type"]
    for p in links:
        spec = schema.normalize_spec("link_type", p["spec"])
        assert spec["from_type"] and spec["to_type"]