test_modeling_v11.py 11.6 KB
"""AI 建模流水线 v11:各批同时读文档、只从数据库起步、暂停与继续、从某一步重跑、
采纳即上线(不进审批与待办)、AI 调用追踪与终止。

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

import sys
from pathlib import Path

import pytest

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

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

DOC = ("# 工单管理\n\n## 工单\n工单是门店报修产生的单据。\n\n" + "填充说明。" * 400 +
       "\n\n## 超时\n工单(又叫维修单)处理时长超过 48 小时未关闭即为超时,由维修主管升级。\n").encode("utf-8")


def fake_json(msgs, **k):
    text = msgs[-1]["content"]
    if "文档片段" in text:
        # 两批里同一个东西换了叫法:并发读完后要合成一条
        if "超时" in text:
            return {"concepts": [
                {"kind": "object_type", "name": "维修单", "synonyms": ["工单"], "confidence": 0.9},
                {"kind": "function", "name": "超时判定", "spec": {"category": "rule", "text": "超过 48 小时"},
                 "confidence": 0.8}]}
        return {"concepts": [{"kind": "object_type", "name": "工单", "description": "门店报修单据",
                              "spec": {"properties": [{"name": "编号", "is_key": True}]}, "confidence": 0.9}]}
    if "能直接算" in text:
        return {"rules": [{"name": "超时判定", "rule_kind": "judgement", "expression": "hours > 48",
                           "inputs": [{"name": "hours", "label": "处理时长", "type": "number"}],
                           "tests": [{"name": "超过 48 小时", "inputs": {"hours": 50}, "expect": {"result": True}}]}]}
    return {}


def _small_batches(monkeypatch):
    from app.kernel import modeling, propose
    monkeypatch.setattr(modeling, "WHOLE_DOC_TOKENS", 100)     # 这份文档不算小:按章节切成几块、分几批读
    monkeypatch.setattr(modeling, "DOC_CHUNK_TOKENS", 600)
    monkeypatch.setattr(propose, "BATCH_TOKENS", 300)
    monkeypatch.setattr(llm, "chat_json", fake_json)


def test_各批同时读_合并同一个东西(env, monkeypatch):
    from app.kernel import modeling
    _small_batches(monkeypatch)
    run = modeling.create("工单", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "rules", "draft"])
    events = list(modeling.execute(run["id"]))
    assert events[-1]["stage"] == "done", events[-1]
    g = modeling.get(run["id"])
    objs = [x["payload"] for x in g["items"]["object_type"]]
    assert len(objs) == 1 and objs[0]["name"] == "工单" and "维修单" in objs[0]["synonyms"]
    conv = next(s for s in g["stages"] if s["key"] == "convert")
    assert conv["started_at"] and conv["ended_at"] and conv["log"][0]["t"]           # 每个环节有起止时间和带时间的日志
    assert any("同时读" in x["msg"] for x in conv["log"])
    assert g["elapsed_ms"] >= 0


def test_只从数据库起步_表直接成为草案(env, monkeypatch):
    from app.kernel import modeling
    monkeypatch.setattr(llm, "chat_json", lambda *a, **k: pytest.fail("只选数据库时不该调模型"))
    run = modeling.create("测试库", doc_ids=[], ds_ids=[env["ds_id"]])
    st = {s["key"]: s["status"] for s in run["stages"]}
    assert st["convert"] == st["rules"] == st["actions"] == st["sop"] == "skipped" and st["data"] == "pending"
    events = list(modeling.execute(run["id"]))
    assert events[-1]["stage"] == "done", events[-1]
    g = modeling.get(run["id"])
    assert len(g["items"]["object_type"]) >= 2 and g["items"]["link_type"]
    assert all(x["payload"]["bindings"] for x in g["items"]["object_type"])


def test_采纳即上线_不进审批与待办(env, monkeypatch):
    from app.governance import review
    from app.kernel import modeling, service
    _small_batches(monkeypatch)
    run = modeling.create("工单", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "rules", "draft"])
    list(modeling.execute(run["id"]))
    g = modeling.get(run["id"])
    ids = [x["id"] for col in ("object_type", "function") for x in g["items"][col]]
    # 草案不出现在审批与待办里,角标也不算
    assert not [x for x in review.list_items(inbox=True)["items"] if x["source"].startswith("modeling:")]
    assert sum(review.counts().values()) == 0
    assert modeling.pending_count() == len(ids)
    out = modeling.adopt(run["id"], ids)
    assert len(out["accepted"]) == len(ids) and out["published"] >= 1 and not out["failed"]
    c = service.find("工单", "object_type")
    assert service.get_concept(c["id"])["status"] == "published"
    assert not review.list_items(kind="release")["items"]                             # 没有建变更提案
    g = modeling.get(run["id"])
    assert g["items"]["object_type"][0]["concept"]["status"] == "published"
    assert modeling.pending_count() == 0


def test_不要_标成不采纳(env, monkeypatch):
    from app.kernel import modeling
    _small_batches(monkeypatch)
    run = modeling.create("工单", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "draft"])
    list(modeling.execute(run["id"]))
    it = modeling.get(run["id"])["items"]["function"][0]
    assert modeling.discard(run["id"], [it["id"]])["discarded"] == 1
    assert modeling.get(run["id"])["items"]["function"][0]["status"] == "rejected"


def test_暂停后继续_从某一步重跑(env, monkeypatch):
    from app.kernel import modeling
    _small_batches(monkeypatch)
    run = modeling.create("工单", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "rules", "draft"])
    rid = run["id"]

    def pausing(msgs, **k):
        out = fake_json(msgs, **k)
        if "文档片段" in msgs[-1]["content"]:
            modeling._ctl[modeling._k(rid)] = "stop"          # 读文档时有人按了暂停
        return out
    monkeypatch.setattr(llm, "chat_json", pausing)
    events = list(modeling.execute(rid))
    assert events[-1]["stage"] == "stopped"
    g = modeling.get(rid)
    st = {s["key"]: s["status"] for s in g["stages"]}
    assert g["status"] == "stopped" and st["convert"] == "done" and st["rules"] == "pending"

    monkeypatch.setattr(llm, "chat_json", fake_json)
    assert list(modeling.execute(rid))[-1]["stage"] == "done"            # 继续:从没跑完的那一步接着跑
    g = modeling.get(rid)
    n = len(g["items"]["object_type"]) + len(g["items"]["function"])
    assert g["items"]["function"][0]["payload"]["deepened"]

    # 从「读文档」重跑:上次待定的草案先清掉,不会翻倍
    rows = modeling._load(rid)
    from app.core.dbx import jdump, jload, session
    from app.kernel.models import ModelRun
    with session() as s:
        row = s.get(ModelRun, rid)
        stages = jload(row.stages_json, [])
        for x in stages:
            if x["key"] in ("convert", "rules", "draft"):
                x["status"] = "pending"
        row.stages_json = jdump(stages)
        s.commit()
    assert rows
    list(modeling.execute(rid))
    g = modeling.get(rid)
    assert len(g["items"]["object_type"]) + len(g["items"]["function"]) == n


def test_调用追踪_终止不重试(env, monkeypatch):
    from app.core.dbx import session
    from app.kernel import modeling
    from app.kernel.models import ModelCall
    run = modeling.create("工单", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "draft"])
    rid = run["id"]
    calls = {"n": 0}

    def traced(model, messages, temperature, sink, handle):
        calls["n"] += 1
        sink.update(handle, "先想一想……", "")
        modeling._ctl[modeling._k(rid)] = "cancel"
        sink.update(handle, "还在想", "")                    # 终止:流式进行中直接打断
        return "{}", "", {}
    monkeypatch.setattr(llm, "_chat_dashscope_traced", traced)
    monkeypatch.setattr(llm, "_cache_on", lambda: False)
    monkeypatch.setattr(llm.db, "get_config", lambda k, d="": {"QWEN_MODEL": "m", "LLM_BASE_URL": ""}.get(k, d))
    events = list(modeling.execute(rid))
    assert events[-1]["stage"] == "cancelled"
    assert calls["n"] == 1                                    # 没有拿「终止」去重试
    with session() as s:
        rows = s.query(ModelCall).filter(ModelCall.run_id == rid).all()
    assert rows and rows[0].stage == "convert" and rows[0].status == "cancelled"
    assert rows[0].reasoning == "先想一想……" and "第 1/" in rows[0].label
    assert modeling.get(rid)["status"] == "cancelled"
    assert modeling.calls(rid, "convert")[0]["reasoning_chars"] > 0


def test_合并换了说法的重复(env, monkeypatch):
    """各批分开读:别名撞上另一条的名字直接并;换了说法的由 AI 指出来再并(只在同一种元素之间)。"""
    from app.kernel import propose
    monkeypatch.setattr(propose, "BATCH_TOKENS", 300)
    seen = {}

    def fake(msgs, **k):
        text = msgs[-1]["content"]
        if "文档片段" in text:
            if "超时" in text:
                return {"concepts": [
                    {"kind": "action", "name": "发起调拨", "synonyms": ["强制调拨"], "spec": {"text": "调货"}},
                    {"kind": "function", "name": "赊销额度剩余", "spec": {"category": "rule", "text": "额度减已用"}}]}
            return {"concepts": [
                {"kind": "action", "name": "强制调拨", "spec": {"text": "强制调货"}},
                {"kind": "function", "name": "剩余赊销额度", "spec": {"category": "aggregate", "formula_text": "额度-已用"}},
                {"kind": "object_type", "name": "工单"}]}
        if "其实是同一个东西" in text:
            seen["prompt"] = text
            idx = {line.split("]")[0][1:]: line for line in text.splitlines() if line.startswith("[")}
            keep = next(i for i, line in idx.items() if "剩余赊销额度" in line)
            other = next(i for i, line in idx.items() if "赊销额度剩余" in line)
            obj = next(i for i, line in idx.items() if "工单" in line)
            act = next(i for i, line in idx.items() if "调拨" in line)
            return {"groups": [{"keep": int(keep), "merge": [int(other)]},
                               {"keep": int(obj), "merge": [int(act)]}]}    # 跨种类的不合
        return {}
    monkeypatch.setattr(llm, "chat_json", fake)
    chunks = [{"id": "a:c0", "heading": "订货", "text": "订货要看额度。" * 200},
              {"id": "a:c1", "heading": "超时", "text": "超时要调拨。" * 200}]
    out = list(propose.from_documents(chunks, source="t"))
    assert out[-1]["stage"] == "done", out[-1]
    from app.governance import review
    names = sorted(x["payload"]["name"] for x in review.list_items(source="t")["items"])
    assert names == ["剩余赊销额度", "工单", "强制调拨"] or names == ["剩余赊销额度", "发起调拨", "工单"], names
    assert "合并换了说法" not in seen["prompt"]
    fn = next(x["payload"] for x in review.list_items(source="t")["items"] if x["payload"]["name"] == "剩余赊销额度")
    assert "赊销额度剩余" in fn["synonyms"] and fn["spec"]["category"] == "aggregate"


def test_同一空间两次建模各有各的草案(env, monkeypatch):
    from app.kernel import modeling
    _small_batches(monkeypatch)
    a = modeling.create("一", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "draft"])
    list(modeling.execute(a["id"]))
    b = modeling.create("二", files=[("工单.md", DOC)], ds_ids=[], stages=["convert", "draft"])
    list(modeling.execute(b["id"]))
    assert len(modeling.get(a["id"])["items"]["object_type"]) == 1
    assert len(modeling.get(b["id"])["items"]["object_type"]) == 1