test_engine_v5.py 24.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
"""借鉴「本体认知引擎」的第五版能力:本体空间、数据管道与关系边、实例级影响分析、变更提案、
MCP 工具目录(提问是 MCP 客户端)、审批单的优先级 / 依据 / 影响面、模型推理函数、业务建模管道、
本地文件数据源、元素的域与映射状态。

复用 test_platform 的夹具:SQLite 元数据库 + 假业务库(store / order_item)+ 打桩 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 identity, llm                                    # noqa: E402
from test_platform import as_user, build_basics, env, make_action     # noqa: E402,F401


def add_orders(ds_id: int, store_type_id: str) -> dict:
    """订单对象 + 「订单属于网点」关系,并发布。"""
    from app.kernel import service
    order = service.create_concept("object_type", "订单", spec={
        "domain": "订单",
        "properties": [{"name": "编号", "is_key": True}, {"name": "金额", "data_type": "number"},
                       {"name": "网点", "is_dimension": True}]})
    service.set_binding(order["id"], ds_id, "table", {
        "table": "order_item", "key_column": "id", "columns": {"编号": "id", "金额": "amount",
                                                               "网点": "store_id"}})
    link = service.create_concept("link_type", "下单网点", spec={
        "from_type": order["id"], "to_type": store_type_id, "cardinality": "n:1"})
    service.set_binding(link["id"], ds_id, "join", {"from_column": "store_id", "to_column": "id"})
    service.publish("订单")
    return {"order": order, "link": link}


# =========================== 元素的域与映射状态 ===========================
def test_域与映射状态(env):
    from app.kernel import service
    b = build_basics(env["ds_id"])
    free = service.create_concept("object_type", "供应商", spec={"domain": "采购", "properties": [{"name": "名称"}]})
    items = {c["name"]: c for c in service.list_concepts()}
    assert items["网点"]["mapped"] is True and items["供应商"]["mapped"] is False
    assert items["供应商"]["domain"] == "采购"
    assert items["成交金额"]["mapped"] is True and items["达标判定"]["mapped"] is None
    assert service.get_concept(free["id"])["spec"]["domain"] == "采购"
    assert b["ot"]


# =========================== 本体空间 ===========================
def test_本体空间隔离_首页总览(env):
    from app.kernel import service, workspaces
    build_basics(env["ds_id"])
    ws = workspaces.create("retail", "零售", "零售行业本体", "零售")
    assert ws["counts"]["object_type"] == 0
    all_ids = {w["id"] for w in workspaces.list_all()}
    assert {"default", "retail"} <= all_ids
    tok = identity.set_current(identity.Actor(workspace="retail"))
    try:
        assert service.list_concepts() == []                        # 另一个空间看不到元素
        from app.text2sql import semantic
        assert semantic.list_datasources() == []                     # 数据源按空间归属
        semantic.create_datasource(name="共用库", ds_type="mysql", host="h", port=3306, db_name="x",
                                   username="u", workspace="")
        assert [d["name"] for d in semantic.list_datasources()] == ["共用库"]   # 老数据(未归属)共用
        home = workspaces.overview()
        assert home["counts"]["object_type"] == 0
        assert any(s["key"] == "modeling" for s in home["next_steps"])
    finally:
        identity.reset(tok)
    home = workspaces.overview()
    assert home["counts"]["object_type"] == 1 and home["revision"] >= 1
    with pytest.raises(HTTPException):
        workspaces.create("Bad Id", "x")
    with pytest.raises(HTTPException):
        workspaces.archive("default")                               # 不能归档正在用的


# =========================== 数据管道 / 关系边 / 影响分析 ===========================
def test_数据管道同步骨架并物化关系边(env):
    from app.kernel import pipeline
    b = build_basics(env["ds_id"])
    o = add_orders(env["ds_id"], b["ot"]["id"])
    p1 = pipeline.create(b["ot"]["id"])
    p2 = pipeline.create(o["order"]["id"], "daily")
    with pytest.raises(HTTPException):
        pipeline.create(b["ot"]["id"])                              # 一个对象类型一条管道
    r1 = pipeline.run(p1["id"])
    assert r1["status"] == "ok" and r1["last_rows"] == 3
    r2 = pipeline.run(p2["id"])
    assert r2["last_rows"] == 6 and r2["last_edges"] == 6             # 每个订单一条「下单网点」边
    st = pipeline.status()
    assert st["objects"] == 9 and st["edges"] == 6 and st["synced_at"]
    ds = pipeline.dataset(o["order"]["id"])
    assert ds["total"] == 6 and "网点" in ds["items"][0]["properties"]
    assert pipeline.ensure_all()["created"] == []                   # 都有管道了
    # 定时:daily 的刚跑过不到期,manual 的永远不自动跑
    assert pipeline.tick() == []
    assert pipeline.run_all() == {"ok": 2, "total": 2, "system_edges": 0}       # 还没有预警 / 动作 / 流程运行
    # 执行器单条查询有行数上限:骨架同步要分页拉全,不能停在上限
    from app.core import db as core_db
    core_db.set_config({"SQL_ROW_LIMIT": "4"})
    assert pipeline.sync_type(o["order"]["id"])["rows"] == 6


def test_遍历与实例级影响分析(env, monkeypatch):
    from app.kernel import pipeline, traverse
    b = build_basics(env["ds_id"])
    o = add_orders(env["ds_id"], b["ot"]["id"])
    make_action(b["ot"]["id"])
    pipeline.sync_type(b["ot"]["id"])
    pipeline.sync_type(o["order"]["id"])
    t = traverse.traverse(o["order"]["id"], "1", depth=2)
    names = {(n["type_name"], n["key"]) for n in t["nodes"]}
    # 订单 1 → 网点 2(1 % 3 + 1)→ 同网点的订单 4
    assert ("网点", "2") in names and ("订单", "4") in names
    assert t["by_type"] == {"网点": 1, "订单": 1}
    # 影响分析沿外键往上走到的网点只算「涉及」,不再绕道网点扩到同网点的其他订单
    imp1 = traverse.instance_impact(o["order"]["id"], "1", depth=2)
    assert imp1["by_type"] == {} and imp1["context"] == {"网点": 1}
    imp = traverse.instance_impact(b["ot"]["id"], "2", depth=1)
    assert imp["by_type"] == {"订单": 2} and "订单 2" in imp["summary"]
    assert imp["live"] and imp["live"][0]["properties"]              # 最外层回业务库取了最新属性
    with pytest.raises(HTTPException):
        traverse.traverse(b["ot"]["id"], "999")                     # 不在骨架里
    # 数据范围:只能看网点 1 的人,遍历结果里看不到别的网点
    tok = identity.set_current(identity.Actor(id="u", roles=["viewer"],
                                              scope={b["ot"]["id"]: {"编号": ["1"]}}))
    try:
        t2 = traverse.traverse(o["order"]["id"], "1", depth=1)
        assert all(n["type_name"] != "网点" for n in t2["nodes"]) and t2["hidden"] == 1
    finally:
        identity.reset(tok)


# =========================== 变更提案 ===========================
def test_变更提案_不能自审_AI不能批_草稿变动要重提(env):
    from app.governance import review
    from app.kernel import service
    build_basics(env["ds_id"])
    tok = as_user("builder")
    try:
        c = service.create_concept("function", "新规则", spec={"category": "rule", "expression": "a > 1"})
        item = service.propose_release("加一条规则")
        with pytest.raises(HTTPException) as e:
            service.propose_release("再来一份")
        assert e.value.status_code == 409                            # 同时只能有一份待审
        with pytest.raises(HTTPException) as e:
            review.decide(item["id"], True)
        assert "自己" in str(e.value.detail)
    finally:
        identity.reset(tok)
    tok = identity.set_current(identity.as_ai(identity.Actor()))
    try:
        with pytest.raises(HTTPException) as e:
            review.decide(item["id"], True)
        assert "AI" in str(e.value.detail)
    finally:
        identity.reset(tok)
    # 提交后又改了草稿:审批时拒绝
    service.update_concept(c["id"], description="改了")
    with pytest.raises(HTTPException) as e:
        review.decide(item["id"], True)
    assert e.value.status_code == 409
    review.decide(item["id"], False, "请重提")
    tok = as_user("builder")
    try:
        item = service.propose_release("重提")
    finally:
        identity.reset(tok)
    rels = service.list_releases("pending")
    assert rels[0]["can_decide"]                                    # 管理员审批别人的提案
    out = review.decide(item["id"], True)
    rev = out["result"]["revision"]
    assert service.rt_fn("新规则", "rule") is not None
    # 回滚也走提案
    tok = as_user("builder")
    try:
        rb = service.propose_rollback(rev - 1)
    finally:
        identity.reset(tok)
    review.decide(rb["id"], True)
    assert service.rt_fn("新规则", "rule") is None


def test_变更提案接口(env):
    from fastapi.testclient import TestClient
    from app.main import app
    from app.kernel import service
    build_basics(env["ds_id"])
    service.create_concept("function", "阈值", spec={"category": "rule", "expression": "x > 2"})
    c = TestClient(app)
    item = c.post("/api/kernel/publish", json={"note": "加阈值"}, headers={"X-User-Id": "builder"}).json()
    assert item["kind"] == "release" and item["status"] == "pending"
    r = c.post(f"/api/kernel/releases/{item['id']}/decide", json={"approve": True},
               headers={"X-User-Id": "builder"})
    assert r.status_code == 403
    inbox = c.get("/api/cap/inbox").json()
    assert inbox["releases"] == 1
    r = c.post(f"/api/kernel/releases/{item['id']}/decide", json={"approve": True})
    assert r.status_code == 200 and r.json()["status"] == "accepted"
    assert c.get("/api/kernel/revisions").json()[0]["note"] == "加阈值"


# =========================== MCP 与提问 ===========================
def test_MCP目录_别名_影响分析工具(env):
    from app.capability import mcp
    from app.kernel import pipeline
    b = build_basics(env["ds_id"])
    o = add_orders(env["ds_id"], b["ot"]["id"])
    pipeline.sync_type(b["ot"]["id"])
    pipeline.sync_type(o["order"]["id"])
    names = {t["name"] for t in mcp.tools()}
    assert "propose_action" in names
    assert mcp.resolve("knowledge.search", {})[0].name == "search_knowledge"
    assert mcp.resolve("skill:归因", {"x": 1}) [1] == {"name": "归因", "inputs": {"x": 1}}
    assert mcp.resolve("rule_eval", {})[0].name == "rule.eval"       # 其余只读函数仍可调,但不在目录
    with pytest.raises(HTTPException):
        mcp.resolve("object.write", {})                             # 有副作用的工具永远调不到
    ok, out = mcp.call_logged(identity.Actor(), "impact_analysis",
                              {"object_type": "网点", "key": "1"}, "agent")
    assert ok and out["by_type"] == {"订单": 2}
    ok, out = mcp.call_logged(identity.Actor(), "traverse_link",
                              {"object_type": "订单", "key": "1", "depth": "1"}, "console")
    assert ok and len(out["nodes"]) == 2
    ok, out = mcp.call_logged(identity.Actor(), "get_object", {"object_type": "网点"}, "agent")
    assert not ok and "key" in out                                  # 按工具声明校验必填参数


def test_审批单带优先级_依据_影响面(env):
    from app.capability import actions, mcp
    from app.kernel import pipeline
    b = build_basics(env["ds_id"])
    o = add_orders(env["ds_id"], b["ot"]["id"])
    make_action(b["ot"]["id"])
    pipeline.sync_type(b["ot"]["id"])
    pipeline.sync_type(o["order"]["id"])
    tok = as_user("operator")
    try:
        ok, run = mcp.call_logged(identity.current(), "propose_action", {
            "action": "mark_follow", "params": {"reason": "连续下滑"}, "object_key": "1",
            "reason": "成交下滑", "priority": "P0",
            "evidence": ["近三月成交下降 40%", {"kind": "rule", "text": "达标判定未通过"}]}, "agent")
    finally:
        identity.reset(tok)
    assert ok, run
    assert run["priority"] == "P0" and len(run["evidence"]) == 2
    assert run["impact"]["by_type"] == {"订单": 2}
    with pytest.raises(HTTPException):
        actions.propose("mark_follow", {"reason": "x"}, object_key="2", priority="P9")
    pend = actions.pending_for(identity.current())
    assert pend[0]["priority"] == "P0"


def test_运行时总览(env):
    from fastapi.testclient import TestClient
    from app.main import app
    build_basics(env["ds_id"])
    c = TestClient(app)
    c.post("/api/cap/mcp/call/list_ontology_types", json={"args": {}})
    c.post("/api/cap/mcp/call/nope", json={"args": {}})
    ov = c.get("/api/cap/runtime/overview").json()
    assert ov["mcp"]["calls_24h"] == 2 and ov["mcp"]["success_rate"] == 0.5
    assert ov["mcp"]["by_via"] == {"console": 2}
    assert "pipelines" in ov and "approvals" in ov


# =========================== 模型推理函数 ===========================
def test_业务建模管道_上传文档到四元组草案(env, monkeypatch):
    from app.governance import review
    from app.kernel import modeling

    def fake_json(msgs, **k):
        text = msgs[-1]["content"]
        if "候选" in text and "章节" in text:
            return {"template": "store_ops", "reason": "门店运营"}
        if "文档片段" in text:
            return {"concepts": [
                {"kind": "object_type", "name": "工单", "description": "维修工单",
                 "spec": {"properties": [{"name": "编号", "is_key": True}]}, "confidence": 0.9},
                {"kind": "function", "name": "超时判定", "description": "超过 48 小时未关闭算超时",
                 "spec": {"category": "rule", "text": "处理时长超过 48 小时"}, "confidence": 0.8},
                {"kind": "action", "name": "升级工单", "spec": {"text": "超时后由主管升级"}, "confidence": 0.7}],
                "roles": [{"name": "维修主管"}]}
        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}}]}]}
        if "业务流程" in text:
            return {"processes": [{"title": "工单超时升级", "chunks": []}]}
        if "可执行的 SOP" in msgs[0]["content"] or "SOP" in text:
            return {"title": "工单超时升级", "description": "超时工单的处理",
                    "steps": [{"id": "s1", "type": "human_task", "title": "主管复核", "role": "维修主管",
                               "next": "end"}, {"id": "end", "type": "end", "title": "结束"}]}
        return {}
    monkeypatch.setattr(llm, "chat_json", fake_json)
    doc = "# 工单管理\n\n## 超时规则\n工单处理时长超过 48 小时未关闭即为超时,由维修主管升级。\n".encode("utf-8")
    run = modeling.create("工单建模", files=[("工单.md", doc)], ds_ids=[])
    assert run["inputs"]["files"] == ["工单.md"] and run["inputs"]["chunks"] >= 1
    events = list(modeling.execute(run["id"]))
    assert events[-1]["stage"] == "done", events[-1]
    g = modeling.get(run["id"])
    assert g["status"] == "done"
    stages = {s["key"]: s for s in g["stages"]}
    assert "route" not in stages and "deepen" not in stages
    assert stages["rules"]["counts"]["deepened"] == 1 and stages["rules"]["counts"]["tests_ok"] == 1
    assert [x["payload"]["name"] for x in g["items"]["object_type"]] == ["工单"]
    rule = g["items"]["function"][0]["payload"]
    assert rule["spec"]["expression"] == "hours > 48" and rule["deepened"]
    assert len(g["sops"]) == 1 and g["counts"]["sop"] == 1
    md = modeling.export_md(run["id"])
    assert "## 对象(1)" in md and "hours > 48" in md and "工单超时升级" in md
    # 采纳后成为草稿元素,来源记为 modeling
    out = review.decide(g["items"]["object_type"][0]["id"], True)
    from app.kernel import service
    assert service.get_concept(out["result"]["concept_id"])["origin"] == "modeling"
    with pytest.raises(HTTPException):                 # 文档和数据库一样都没选
        modeling.create("空", doc_ids=[], ds_ids=[])


def test_业务建模_数据对齐_指标绑定_动作补全_写回业务库(env, monkeypatch):
    """文档 + 已接入的表:对象 / 关系直接绑表并用文档叫法;指标写出取数表达式实跑通过;
    动作骨架补全成「新建订单」,审批后真的写进业务表,撤销会删掉。"""
    from app.capability import actions
    from app.governance import review
    from app.kernel import modeling, service
    from app.text2sql import semantic
    from sqlalchemy import text as sa_text

    rels = semantic.list_relations(env["ds_id"])
    assert any(r["from_column"] == "store_id" for r in rels)          # 没有外键也推出了「订单 → 门店」

    def fake_json(msgs, **k):
        text = msgs[-1]["content"]
        if "文档片段" in text:
            assert "已接入的数据表" in text                         # 表作为命名约束喂给了模型
            return {"concepts": [
                {"kind": "object_type", "name": "门店", "synonyms": ["store"], "confidence": 0.9},
                {"kind": "object_type", "name": "订单", "synonyms": ["order_item"], "confidence": 0.9},
                {"kind": "link_type", "name": "成交门店", "confidence": 0.8,
                 "spec": {"from_type": "订单", "to_type": "门店", "cardinality": "n:1"}},
                {"kind": "function", "name": "成交额", "confidence": 0.8,
                 "spec": {"category": "aggregate", "object_type": "订单", "unit": "元",
                          "formula_text": "订单金额求和"}},
                {"kind": "action", "name": "补录订单", "spec": {"text": "门店可以补录一笔订单"}}]}
        if "取数定义" in text:
            return {"expression": "SUM(amount)", "dimensions": {"store_id": "store_id"},
                    "time_column": "created_at", "object_key_column": "id", "filters": []}
        if text.startswith("动作:"):
            return {"name": "补录订单", "spec": {
                "target_type": "门店",
                "params": [{"name": "order_id", "label": "订单号", "type": "number", "required": True},
                           {"name": "amount", "label": "金额", "type": "number", "required": True}],
                "effects": [{"tool": "object.create", "args": {"object_type": "订单", "values": {
                    "id": "$order_id", "store_id": "$obj_key", "amount": "=amount * 1", "created_at": "$today"}}}],
                "approval": {"mode": "manual", "approver_roles": []}}}
        return {}
    monkeypatch.setattr(llm, "chat_json", fake_json)
    doc = "# 门店订单\n门店每天有订单成交,成交额是订单金额之和。门店可以补录订单。".encode("utf-8")
    run = modeling.create("门店建模", files=[("门店.md", doc)], stages=["data", "convert", "metrics", "actions", "draft"])
    assert run["options"]["ds_ids"] == [env["ds_id"]]                 # 默认对齐所有已内省的数据源
    events = list(modeling.execute(run["id"]))
    assert events[-1]["stage"] == "done", events[-1]
    g = modeling.get(run["id"])
    objs = {x["payload"]["name"]: x["payload"] for x in g["items"]["object_type"]}
    assert set(objs) == {"门店", "订单"}                                # 文档叫法,没有重复的表对象
    assert objs["门店"]["bindings"][0]["ref"]["table"] == "store" and "门店主数据" in objs["门店"]["synonyms"]
    links = [x["payload"] for x in g["items"]["link_type"]]
    assert [x["name"] for x in links] == ["成交门店"]                   # 表推出的关系并进了文档的关系
    assert links[0]["bindings"][0]["ref"] == {"from_column": "store_id", "to_column": "id"}
    metric = g["items"]["function"][0]["payload"]
    assert metric["bindings"][0]["target_kind"] == "metric_expr"
    assert metric["bindings"][0]["ref"]["expression"] == "SUM(amount)"
    act = g["items"]["action"][0]["payload"]
    assert act["completed"] and act["spec"]["effects"][0]["tool"] == "object.create"

    order = {"object_type": 0, "link_type": 1, "function": 2, "action": 3}
    for it in sorted([x for col in g["items"].values() for x in col], key=lambda x: order.get(x["payload"].get("kind"), 9)):
        review.decide(it["id"], True)
    service.publish("门店建模")
    # 已经有文档命名的同一条关系:再从数据源「提议到本体」不会冒出重复的「订单成交明细-门店主数据」
    from app.kernel import propose
    assert propose.submit_proposals(propose.datasource_proposals(env["ds_id"]), "introspect")["proposed"] == 0
    from app.kernel import metrics, workbench
    assert metrics.query("成交额")["rows"][0][0] == 2100.0
    wb = workbench.workbench()                                         # 工作台:已发布指标的当前值 + 能直接问的问题
    assert [k["name"] for k in wb["kpis"]] == ["成交额"] and wb["kpis"][0]["value"] == 2100.0
    assert any("成交额" in q for q in wb["questions"])

    # 数据源没开写回:提交时就拦下并说清楚原因(不用等审批通过了才失败)
    with pytest.raises(HTTPException) as e:
        actions.propose("补录订单", {"order_id": 99, "amount": 88}, object_key="1", reason="补录")
    assert "写回业务库" in e.value.detail
    semantic.update_datasource(env["ds_id"], extra={"writeback": True})
    run2 = actions.propose("补录订单", {"order_id": 100, "amount": 66}, object_key="2", reason="补录")
    tok = as_user("approver")
    try:
        done = actions.decide(run2["id"], True)
    finally:
        identity.reset(tok)
    assert done["status"] == "done", done
    with env["conn"].engine.connect() as c:
        assert c.execute(sa_text("SELECT store_id, amount FROM order_item WHERE id = 100")).one() == (2, 66.0)
    actions.propose_revert(run2["id"], "录错了")
    tok = as_user("approver")
    try:
        rv = [r for r in actions.list_runs(status="pending_approval") if r.get("revert_of") == run2["id"]]
        actions.decide(rv[0]["id"], True)
    finally:
        identity.reset(tok)
    with env["conn"].engine.connect() as c:
        assert c.execute(sa_text("SELECT COUNT(*) FROM order_item WHERE id = 100")).scalar() == 0


# =========================== 本地文件数据源 ===========================
def test_本地文件数据源_导入与只读查询(tmp_path):
    from app.text2sql.connectors import sqlite_file
    from app.text2sql.connectors.base import QueryFailed
    csv_bytes = "编号,名称,金额\n1,杭州店,100.5\n2,南京店,80\n".encode("utf-8")
    res = sqlite_file.import_files(tmp_path / "ds.sqlite", [("门店.csv", csv_bytes),
                                                            ("x.json", b'[{"a": 1, "b": "x"}]')])
    assert [r["rows"] for r in res] == [2, 1]
    conn = sqlite_file.SQLiteFileConnector({"id": 9, "db_name": str(tmp_path / "ds.sqlite")}, "")
    intro = conn.introspect()
    t = next(x for x in intro.tables if x.name == "门店")
    assert [c.data_type for c in t.columns] == ["INTEGER", "TEXT", "REAL"] and t.row_count_est == 2
    out = conn.run_sql('SELECT SUM("金额") FROM "门店"', 10, 5000)
    assert out.rows == [[180.5]]
    with pytest.raises(QueryFailed):
        conn.run_sql('DELETE FROM "门店"', 10, 5000)                 # 只读打开
    # 同名文件再导一次:覆盖同一张表,不新增
    res2 = sqlite_file.import_files(tmp_path / "ds.sqlite", [("门店.csv", "编号,名称,金额\n3,苏州店,1\n".encode())])
    assert res2[0]["table"] == "门店" and res2[0]["rows"] == 1
    conn.dispose()


def test_本体SQL按目标方言转写():
    from app.kernel.sqlutil import to_dialect
    assert to_dialect("SELECT `a` FROM `t` LIMIT 5", "mysql") == "SELECT `a` FROM `t` LIMIT 5"
    assert to_dialect("SELECT `a` FROM `t` LIMIT 5", "postgres") == 'SELECT "a" FROM "t" LIMIT 5'


# =========================== 流程卡 ===========================
def test_流程卡带优先级与域():
    from app.sop import spec as sop_spec
    n = sop_spec.normalize({"priority": "p1", "domain": "质量", "steps": [{"id": "e", "type": "end"}]})
    assert n["priority"] == "P1" and n["domain"] == "质量"
    assert sop_spec.normalize({"priority": "urgent"})["priority"] == "P2"