test_modeling_v14.py 23.2 KB
"""AI 建模 v14:通用的质量改造。

- 规则引擎:like 宽容写法、汇总「指向我的那些记录」(count_of / sum_of)、ceiling 别名;
- 对象:汇总子查询在真实(假)业务库上算得出;本体自有属性(业务表里没有列,值由本系统保存)能写能读;
- 流程卡:计算步骤的字段写成裸名字时自动补前缀,错误文案说清楚该怎么写,where 拿列名当值时给提示;
- 读文档:别名里的表名、子集叫法、实例值挪走;
- 规则名对不上时按去后缀 / 包含关系找回来;体检清单代替可信度;
- 整条流水线(打桩 LLM):列条目 → 计算属性 → 动作用本体自有属性 → 流程卡覆盖文档步骤 → 对账 → 按对账修改。

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

import sys
from pathlib import Path

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

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


# ---------------- 规则引擎 ----------------
def test_like_写法翻成_contains():
    from app.kernel import rules
    assert rules.normalize_text("name like '%灯%' and qty < 20") == "contains(name, '灯') and qty < 20"
    assert rules.evaluate("name like 'A%'", {"name": "Abc"}) is True
    assert rules.evaluate("name not like '%x%'", {"name": "abc"}) is True
    assert rules.evaluate("ceiling(gap / 20) * 20", {"gap": 25}) == 40


def test_汇总函数_逐行求值和编译():
    from app.kernel import rules
    env_ = {"orders": [{"late": True, "amt": 5}, {"late": 1, "amt": 7}, {"late": 0, "amt": 9}]}
    assert rules.evaluate("count_of(orders, 'late') >= 2", env_) is True
    assert rules.evaluate("sum_of(orders, 'amt', 'late')", env_) == 12
    assert rules.evaluate("count_of(orders)", env_) == 3
    assert rules.rollup_names("count_of(orders, 'late') > 1 or x") == ["orders"]
    sql = rules.to_sql("contains(name, 'a') and count_of(o, 'late') > 1", lambda n: f"t.{n}", lambda a, b: f"{a}.{b}",
                       lambda fn, t, f, c: f"R({fn},{t},{f},{c})")
    assert "LOCATE('a', t.name) > 0" in sql and "R(count_of,o,,late)" in sql
    try:
        rules.to_sql("count_of(o)", lambda n: n, lambda a, b: a)
        raise AssertionError("没给汇总回调时应当报错")
    except rules.RuleError:
        pass


# ---------------- 对象:汇总子查询、本体自有属性 ----------------
def _orders_and_stores(ds_id: int, *, extra_store_props: list[dict] | None = None):
    from app.kernel import service
    store = service.create_concept("object_type", "门店", spec={
        "properties": [{"name": "id", "is_key": True}, {"name": "store_name"},
                       {"name": "big_orders", "data_type": "number", "expression": "count_of(下单门店, 'is_big')"},
                       {"name": "total_amt", "data_type": "number", "expression": "sum_of(下单门店, 'amount')"},
                       {"name": "level", "data_type": "string"},
                       # 外层的列和汇总子查询写在同一个公式里:子查询里的表要换别名,不能和外层的 t 撞
                       {"name": "busy_a", "data_type": "boolean", "expression": "level == 'A' and count_of(下单门店) >= 2"},
                       *(extra_store_props or [])],
        "label_property": "store_name"})
    service.set_binding(store["id"], ds_id, "table", {"table": "store", "key_column": "id", "label_column": "store_name",
                                                      "columns": {"id": "id", "store_name": "store_name", "level": "level"}})
    order = service.create_concept("object_type", "订单", spec={
        "properties": [{"name": "id", "is_key": True}, {"name": "store_id"}, {"name": "amount", "data_type": "number"},
                       {"name": "is_big", "data_type": "boolean", "expression": "amount >= 400"}]})
    service.set_binding(order["id"], ds_id, "table", {"table": "order_item", "key_column": "id", "label_column": "",
                                                      "columns": {"id": "id", "store_id": "store_id", "amount": "amount"}})
    link = service.create_concept("link_type", "下单门店", spec={"from_type": "订单", "to_type": "门店", "cardinality": "n:1",
                                                              "inverse_name": "名下订单"})
    service.set_binding(link["id"], ds_id, "join", {"from_column": "store_id", "to_column": "id"})
    service.publish("测试")
    return store, order


def test_计算属性汇总指向我的记录(env):
    from app.kernel import objects
    _orders_and_stores(env["ds_id"])
    res = objects.query("门店", limit=10)
    got = {x["key"]: (x["properties"]["big_orders"], x["properties"]["total_amt"]) for x in res["items"]}
    # 门店 1:订单 3、6(300、600);门店 2:1、4(100、400);门店 3:2、5(200、500)
    assert {k: (int(a), float(b)) for k, (a, b) in got.items()} == {"1": (1, 900.0), "2": (1, 500.0), "3": (1, 700.0)}
    assert {x["key"]: bool(x["properties"]["busy_a"]) for x in res["items"]} == {"1": True, "2": False, "3": True}
    # 没有名称列的对象:用它指向的对象的名称当显示名,不拿主键
    o = objects.query("订单", limit=1)["items"][0]
    assert o["label"] in ("杭州体验中心", "南京用户中心", "苏州体验中心")


def test_本体自有属性_能写能读(env):
    from app.kernel import objects, schema
    spec = schema.normalize_spec("object_type", {"properties": [
        {"name": "id", "is_key": True}, {"name": "risk_note", "data_type": "text", "is_writable": True, "storage": "ontology",
                                         "synonyms": ["风险备注"], "value_hints": ["一号店"]}]})
    p = spec["properties"][1]
    assert p["storage"] == "ontology" and p["synonyms"] == ["风险备注"] and p["value_hints"] == ["一号店"]
    _orders_and_stores(env["ds_id"], extra_store_props=[
        {"name": "risk_note", "display_name": "风险原因", "data_type": "text", "is_writable": True, "storage": "ontology"}])
    out = objects.apply_ops([{"op": "update", "object_type": "门店", "key": "2", "values": {"风险原因": "交期不稳"}}])
    assert out["edit_ids"]
    assert objects.get("门店", "2")["properties"]["risk_note"] == "交期不稳"
    cols = {c["name"]: c for c in objects.columns(__import__("app.kernel.service", fromlist=["x"]).rt_find("门店", "object_type"))}
    assert cols["risk_note"]["stored_here"] is True


# ---------------- 流程卡 ----------------
def test_流程卡_计算字段自动补前缀_错误说清楚():
    from app.sop import spec as sop_spec
    raw = {"start": "c", "steps": [
        {"id": "c", "type": "compute", "title": "汇总", "assign": [
            {"name": "rows", "expr": "where(today, 'on_hand', '<', 'safety_stock')"},
            {"name": "n", "expr": "count(rows)"}], "next": "d"},
        {"id": "d", "type": "decision", "title": "有没有", "branches": [{"label": "有", "when": "n > 0", "next": "m"}],
         "default": "e"},
        {"id": "m", "type": "notify", "title": "通知", "role": "经理", "subject": "共 $n 条", "body": "共 $n 条", "next": "e"},
        {"id": "e", "type": "end", "title": "结束", "outputs": [{"name": "n", "value": "n"}]}]}
    spec = sop_spec.normalize(raw)
    before = sop_spec.validate(spec, check_refs=False)["errors"]
    assert any("要写成 c.n" in e for e in before), before
    assert sop_spec.qualify_refs(spec) >= 4
    v = sop_spec.validate(spec, check_refs=False)
    assert not v["errors"], v["errors"]
    assert spec["steps"][1]["branches"][0]["when"] == "c.n > 0"
    assert spec["steps"][2]["body"] == "共 $c.n 条" and spec["steps"][3]["outputs"][0]["value"] == "$c.n"
    assert any("where 的比较值「safety_stock」" in w for w in v["warnings"])


# ---------------- 读文档:别名整理 ----------------
def test_别名里的表名_子集叫法_实例值挪走(monkeypatch):
    from app.kernel import modeling_world, propose
    monkeypatch.setattr(modeling_world, "sample_values",
                        lambda ds, t, c, limit=500: ["LED 大灯总成", "火花塞 A", "机油滤芯", "刹车片前", "雨刮", "空滤", "轮胎", "电瓶",
                                                     "后视镜", "门把手"])
    bucket = {("object_type", "配件"): {
        "name": "配件", "synonyms": ["otlg_parts", "大灯", "零件", "缺货配件", "已停用"],
        "spec": {"properties": [{"name": "name", "display_name": "名称"},
                                {"name": "status", "enum_values": ["在用", "已停用"]}], "label_property": "name",
                 "_terms": {"配件名": "name"}},
        "bindings": [{"ds_id": 1, "target_kind": "table", "ref": {"table": "otlg_parts", "key_column": "id",
                                                                 "label_column": "name", "columns": {"name": "name"}}}],
        "derived": [{"name": "是否缺货", "subset_names": ["缺货配件"]}],
        "value_hints": {"配件名": ["机油滤芯"]}}}
    stats = propose._tidy_objects(bucket)
    cur = bucket[("object_type", "配件")]
    assert cur["synonyms"] == ["零件"], cur["synonyms"]
    assert stats == {"tables": 1, "subsets": 1, "instances": 2}
    props = {p["name"]: p for p in cur["spec"]["properties"]}
    assert props["name"]["value_hints"] == ["大灯", "机油滤芯"] and props["status"]["value_hints"] == ["已停用"]


def test_动作一次改几个属性也认():
    from app.kernel import modeling
    objs = {"工单": {"name": "工单", "binding": None, "item": None, "id": "",
                     "properties": [{"name": "status", "enum_values": ["处理中", "已关闭"]}, {"name": "remark"}]}}
    many = {"target_type": "工单", "effects": [{"tool": "object.write", "args": {
        "object_type": "工单", "key": "$obj_key", "values": {"status": "已关闭", "remark": "$reason"}}}]}
    assert modeling._check_action_refs(many, objs) == "" and modeling._check_enum_writes(many, objs) == ""
    bad = {"target_type": "工单", "effects": [{"tool": "object.write", "args": {
        "object_type": "工单", "key": "$obj_key", "values": {"status": "作废", "nope": 1}}}]}
    assert "nope" in modeling._check_action_refs(bad, objs) and "只能取" in modeling._check_enum_writes(bad, objs)
    empty = {"target_type": "工单", "effects": [{"tool": "object.write", "args": {"object_type": "工单", "key": "$obj_key"}}]}
    assert "没写要改哪个属性" in modeling._check_action_refs(empty, objs)
    objs["工单"]["properties"].append({"name": "is_late", "expression": "hours > 48"})
    calc = {"target_type": "工单", "effects": [{"tool": "object.write", "args": {
        "object_type": "工单", "key": "$obj_key", "property": "is_late", "value": True}}]}
    assert "按公式算出来的" in modeling._check_action_refs(calc, objs)


def test_流程步骤按流程名归属_同一章节下的几个流程不串():
    from app.kernel import modeling_reqs
    reqs = [{"id": "R1", "kind": "step", "process": "每日巡检", "section": "九、日常作业"},
            {"id": "R2", "kind": "step", "process": "异常处理", "section": "九、日常作业"},
            {"id": "R3", "kind": "step", "process": "", "section": "十、月末盘点"}]
    assert [r["id"] for r in modeling_reqs.steps_of(reqs, "每日巡检 SOP", "九、日常作业")] == ["R1"]
    assert [r["id"] for r in modeling_reqs.steps_of(reqs, "异常处理流程", "九、日常作业")] == ["R2"]
    assert [r["id"] for r in modeling_reqs.steps_of(reqs, "月末盘点", "十、月末盘点")] == ["R3"]


# ---------------- 规则名对不上、体检 ----------------
def test_规则名改了几个字也能对上():
    from app.kernel import modeling
    by = {"补货数量计算规则": 1, "供应商风险标记规则": 2, "补货审批决策表": 3}
    assert modeling._match_fn("补货数量计算", by) == 1
    assert modeling._match_fn("供应商风险标记", by) == 2
    assert modeling._match_fn("补货审批", by) == 3
    assert modeling._match_fn("完全不相干", by) is None


def test_体检清单代替可信度():
    from app.kernel import modeling_grade
    rd = modeling_grade.readiness({"kind": "function", "spec": {"category": "rule", "expression": "a > b",
                                                                  "inputs": [{"name": "a"}], "tests": []}})
    assert not rd["ready"] and any("不是这条规则的输入" in c["text"] for c in rd["checks"])
    rd = modeling_grade.readiness({"kind": "function", "evidence": [{}], "spec": {"category": "aggregate"},
                                   "bindings": [{"target_kind": "metric_expr", "ref": {}}],
                                   "trial": {"ok": True, "summary": "按现在的数据算出来是 37"}})
    assert rd["ready"] and "37" in rd["checks"][0]["text"]
    rd = modeling_grade.readiness({"kind": "action", "evidence": [{}], "spec": {"effects": []},
                                   "schema_gaps": [{"object_type": "工单", "need": "原因", "resolved": "reason"}]})
    assert rd["ready"]


def test_平台能力清单():
    from app.kernel import platform_caps
    t = platform_caps.text()
    assert "审批留痕" in t and "不归本系统管" in t


# ---------------- 整条流水线(打桩 LLM) ----------------
HANDBOOK = """# 工单手册

## 一、术语
| 术语 | 口径 |
|---|---|
| 超时工单 | 处理时长超过 48 小时还没关闭的工单 |

## 二、审批规则
| 场景 | 审批人 |
|---|---|
| 升级工单 | 维修经理 |

## 三、每日工单巡检 SOP(维修主管,每天 9:00)
1. 查出所有超时工单。
2. 逐一升级,写明原因。
"""

CALLS: dict[str, int] = {}


def fake_json(msgs, **k):
    text = msgs[-1]["content"]
    first = msgs[0]["content"]
    if "可落地的条目" in text:
        return {"items": [
            {"section": "一、术语", "kind": "term", "text": "超时工单:处理时长超过 48 小时还没关闭"},
            {"section": "二、审批规则", "kind": "approval", "text": "升级工单由维修经理审批"},
            {"section": "三、每日工单巡检 SOP", "kind": "step", "process": "每日工单巡检", "text": "查出所有超时工单"},
            {"section": "三、每日工单巡检 SOP", "kind": "step", "process": "每日工单巡检", "text": "逐一升级,写明原因"},
            {"section": "三、每日工单巡检 SOP", "kind": "schedule", "text": "每天 9:00 巡检"}]}
    if "文档片段" in text:
        return {"concepts": [
            {"kind": "object_type", "name": "工单", "description": "门店报修单据", "synonyms": ["超时工单", "ticket_tbl"],
             "spec": {"properties": [{"name": "id", "is_key": True}, {"name": "hours", "data_type": "number"},
                                     {"name": "status", "data_type": "enum", "enum_values": ["处理中", "已关闭"]}],
                      "derived": [{"name": "已超时", "kind": "state", "text": "处理时长超过 48 小时还没关闭",
                                   "subset_names": ["超时工单"], "req_ids": ["R01"]}]},
             "req_ids": ["R01"], "evidence": [{"chunk": "x", "quote": "超时"}], "confidence": 0.9},
            {"kind": "action", "name": "升级工单", "spec": {"target_type": "工单", "text": "超时后升级,写明原因"},
             "req_ids": ["R04"], "confidence": 0.7}],
            "roles": [{"name": "维修主管"}, {"name": "维修经理", "description": "审批升级工单"}]}
    if "能直接算" in text:
        return {"properties": [{"object_type": "工单", "name": "is_overdue", "display_name": "已超时", "data_type": "boolean",
                                "expression": "hours > 48 and status != '已关闭'", "synonyms": ["超时工单"], "from": "已超时",
                                "tests": [{"inputs": {"hours": 50, "status": "处理中"}, "expect": True},
                                          {"inputs": {"hours": 50, "status": "已关闭"}, "expect": False}]}]}
    if text.startswith("动作:"):
        assert "维修经理:审批升级工单" in text            # 动作补全时看得到角色职责
        return {"spec": {"target_type": "工单", "params": [{"name": "reason", "label": "原因", "type": "text", "required": True}],
                         "effects": [{"tool": "object.write", "args": {"object_type": "工单", "key": "$obj_key",
                                                                        "property": "escalate_reason", "op": "set",
                                                                        "value": "$reason"}}],
                         "approval": {"mode": "manual", "stages": [{"name": "审批", "approver_roles": ["维修主管"]}]}},
                "new_properties": [{"object_type": "工单", "name": "escalate_reason", "display_name": "升级原因",
                                    "data_type": "text"}]}
    if "业务流程" in text:
        return {"processes": [{"title": "每日工单巡检", "section": "三、每日工单巡检 SOP", "chunks": [],
                               "owner_role": "维修主管", "schedule": "每天 9:00"}]}
    if "可执行的流程卡" in first and "按要求修改" not in text:
        return {"title": "每日工单巡检", "description": "查超时工单并逐条升级", "covers": {"R03": "q", "R04": "t"},
                "start": "q", "steps": [
                    {"id": "q", "type": "query", "title": "查超时工单", "object_type": "工单", "mode": "list", "next": "c"},
                    {"id": "c", "type": "compute", "title": "数一数", "assign": [{"name": "n", "expr": "count(q.items)"}],
                     "next": "d"},
                    {"id": "d", "type": "decision", "title": "有没有", "branches": [{"label": "有", "when": "n > 0", "next": "t"}],
                     "default": "end"},
                    {"id": "t", "type": "human_task", "title": "逐一升级", "role": "维修主管", "instructions": "共 $n 张",
                     "next": "end"},
                    {"id": "end", "type": "end", "title": "结束"}]}
    if "配成监控" in text:
        return {"watches": [{"title": "每日工单巡检", "owner_role": "维修主管", "schedule": {"kind": "daily", "at": "09:00"},
                             "source": {"kind": "sop", "sop": "每日工单巡检"}, "req_ids": ["R05"],
                             "strategies": [{"kind": "run_sop", "sop": "每日工单巡检"}], "basis": "每天 9:00"}]}
    if "逐条核对" in text:
        CALLS["check"] = CALLS.get("check", 0) + 1
        if CALLS["check"] == 1:
            return {"items": [
                {"id": "R01", "status": "covered", "by": ["工单"]},
                {"id": "R02", "status": "partial", "by": ["升级工单"], "doc_says": "维修经理审批", "draft_has": "维修主管审批",
                 "gap": "审批人不对", "fix": {"type": "modify", "target": "升级工单", "instruction": "审批人改成维修经理"}},
                {"id": "R03", "status": "covered", "by": ["每日工单巡检"]},
                {"id": "R04", "status": "covered", "by": ["每日工单巡检"]},
                {"id": "R05", "status": "covered", "by": ["每日工单巡检"]}]}
        return {"items": [{"id": "R02", "status": "covered", "by": ["升级工单"]}]}
    if "按要求修改下面这条草案" in text:
        assert "审批人改成维修经理" in text
        return {"name": "升级工单", "spec": {"target_type": "工单",
                                         "params": [{"name": "reason", "label": "原因", "type": "text", "required": True}],
                                         "effects": [{"tool": "object.write", "args": {
                                             "object_type": "工单", "key": "$obj_key", "property": "escalate_reason",
                                             "op": "set", "value": "$reason"}}],
                                         "approval": {"mode": "manual", "stages": [{"name": "审批", "approver_roles": ["维修经理"]}]}},
                "summary": "审批人改成维修经理"}
    return {}


def test_整条流水线_v14(env, monkeypatch):
    from app.kernel import modeling
    CALLS.clear()
    monkeypatch.setattr(llm, "chat_json", fake_json)
    run = modeling.create("工单", files=[("工单手册.md", HANDBOOK.encode("utf-8"))], ds_ids=[])
    assert [s["key"] for s in run["stages"]] == ["data", "reqs", "convert", "rules", "metrics", "actions", "sop",
                                                  "schedule", "check", "fix", "draft"]
    events = list(modeling.execute(run["id"]))
    assert events[-1]["stage"] == "done", events[-1]
    g = modeling.get(run["id"])
    assert [r["id"] for r in g["reqs"]] == ["R01", "R02", "R03", "R04", "R05"]
    obj = next(x for x in g["items"]["object_type"])["payload"]
    # 子集叫法、表名不当别名;派生状态写成计算属性,子集叫法挂在它上面
    assert obj["synonyms"] == [], obj["synonyms"]
    props = {p["name"]: p for p in obj["spec"]["properties"]}
    assert props["is_overdue"]["expression"] == "hours > 48 and status != '已关闭'"
    assert props["is_overdue"]["synonyms"] == ["超时工单"]
    # 要存的「升级原因」业务表里没有:建成本体自有属性,动作照常能写,不再是空壳
    assert props["escalate_reason"]["storage"] == "ontology" and props["escalate_reason"]["is_writable"]
    act = g["items"]["action"][0]
    assert not act["payload"]["spec"].get("_stub") and act["payload"]["schema_gaps"][0]["resolved"] == "escalate_reason"
    # 对账发现审批人不对 → 按对账修改 → 复核后落实
    assert act["payload"]["spec"]["approval"]["stages"][0]["approver_roles"] == ["维修经理"]
    assert act["payload"]["fix_log"][0]["req_ids"] == ["R02"]
    assert g["check"]["summary"]["covered"] == 5 and g["check"]["summary"]["partial"] == 0, g["check"]["summary"]
    assert g["fixes"] and g["fixes"][0]["ok"] and g["fixes"][0]["target"] == "升级工单"
    r02 = next(x for x in g["check"]["items"] if x["id"] == "R02")
    assert r02["fixed"]["summary"] == "审批人改成维修经理" and r02["before"]["status"] == "partial"
    # 流程卡:裸名字自动补成 c.n,没有错误;文档两步都对上了
    sop = g["sops"][0]
    assert not sop["validation"]["errors"], sop["validation"]["errors"]
    assert sop["coverage"]["total"] == 2 and sop["coverage"]["covered"] == 2
    # 体检清单代替可信度
    assert act["readiness"]["ready"], act["readiness"]
    # 采纳:动作会连带它作用的对象
    dep = modeling.deps(run["id"], [act["id"]])
    assert dep["items"] and dep["items"][0]["name"] == "工单"
    out = modeling.adopt(run["id"], [act["id"]], [sop["id"]])
    assert len(out["accepted"]) == 2 and out["published"] >= 1, out
    # 这里的对象没绑数据表(只给了文档):写它的动作被体检拦在草稿里,原因写清楚
    assert any("还没绑定数据表" in v for v in out["held"].values()), out["held"]


def test_老记录_缺新环节算跳过(env):
    from app.kernel import modeling
    rows = modeling._stage_rows([{"key": "convert", "status": "done"}, {"key": "draft", "status": "done"}])
    st = {r["key"]: r for r in rows}
    assert [r["key"] for r in rows] == modeling.ORDER
    assert st["reqs"]["status"] == "skipped" and st["fix"]["status"] == "skipped"