test_sql_pipeline.py 30.7 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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
"""数据问答 P0 闭环的端到端测试。

元数据库用临时 SQLite 顶掉 MySQL,业务库也用 SQLite,LLM 全部打桩 ——
所以这组用例不打网络、不依赖 192.168.3.92,CI 里能直接跑。

覆盖的是「验收」里那几条:内省 → 启用表 → 提问 → 生成 → 校验 → 执行 → 沉淀,
外加越权 SQL 必须被拦、自愈重试必须能救回来。
"""
from __future__ import annotations
import sys
import time
from pathlib import Path

import pytest
from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.orm import Session

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

from app.core import db as core_db                                    # noqa: E402
from app.core.config import DEFAULT_RUNTIME                           # noqa: E402
from app.text2sql import (                                            # noqa: E402
    executor, introspect, library, linker, pipeline, prompts, semantic,
)
from app.text2sql.connectors.base import (                            # noqa: E402
    ColumnInfo, Connector, ForeignKeyInfo, Introspection, QueryFailed,
    QueryResult, TableInfo,
)

# 被 patch 的模块都是 `from ..core.db import engine` 绑定的,
# 改 core.db.engine 不会传导过去,必须逐个换。
_ENGINE_HOLDERS = [core_db, semantic, library, executor, introspect]


# ---------------- 假业务库 ----------------
class FakeConnector(Connector):
    """SQLite 版的业务库。只实现管线真正用到的那几个方法。"""
    dialect = "mysql"

    def __init__(self, path: Path):
        super().__init__({"id": 1, "ds_type": "mysql"}, "")
        self.engine = create_engine(f"sqlite:///{path}", future=True)
        self.executed: list[str] = []
        with self.engine.begin() as c:
            c.execute(sa_text(
                "CREATE TABLE store (id INTEGER PRIMARY KEY, store_name TEXT, "
                "brand_name TEXT, level TEXT)"))
            c.execute(sa_text(
                "CREATE TABLE order_item (id INTEGER PRIMARY KEY, store_id INTEGER, "
                "amount REAL, created_at TEXT)"))
            for i, (nm, brand, lv) in enumerate(
                    [("杭州体验中心", "问界", "A"), ("南京用户中心", "问界", "B"),
                     ("苏州体验中心", "智界", "A")], start=1):
                c.execute(sa_text("INSERT INTO store VALUES (:i,:n,:b,:l)"),
                          {"i": i, "n": nm, "b": brand, "l": lv})
            for i in range(1, 7):
                c.execute(sa_text("INSERT INTO order_item VALUES (:i,:s,:a,'2026-09-01')"),
                          {"i": i, "s": (i % 3) + 1, "a": 100.0 * i})

    def test(self) -> dict:
        return {"version": "8.0.0-fake", "database": "biz", "table_count": 2,
                "account_writable": False}

    def introspect(self) -> Introspection:
        return Introspection(
            tables=[
                TableInfo(name="store", comment="门店主数据", row_count_est=3,
                          primary_key=["id"], columns=[
                              ColumnInfo("id", "int", False, "门店ID"),
                              ColumnInfo("store_name", "varchar(64)", True, "门店名称"),
                              ColumnInfo("brand_name", "varchar(32)", True, "二级品牌"),
                              ColumnInfo("level", "varchar(8)", True, "门店等级")]),
                TableInfo(name="order_item", comment="订单成交明细", row_count_est=6,
                          primary_key=["id"], columns=[
                              ColumnInfo("id", "int", False, ""),
                              ColumnInfo("store_id", "int", True, "门店ID"),
                              ColumnInfo("amount", "decimal(10,2)", True, "成交金额"),
                              ColumnInfo("created_at", "varchar(32)", True, "成交日期")]),
            ],
            foreign_keys=[ForeignKeyInfo("order_item", "store_id", "store", "id", "fk_store")])

    def sample_values(self, table, column, limit, max_distinct):
        with self.engine.connect() as c:
            rows = c.execute(sa_text(
                f'SELECT DISTINCT "{column}" FROM "{table}" '
                f'WHERE "{column}" IS NOT NULL LIMIT {int(limit)}')).fetchall()
        vals = [str(r[0]) for r in rows]
        return vals, len(vals)

    def null_ratios(self, table, columns, sample=50000):
        with self.engine.connect() as c:
            total = c.execute(sa_text(f'SELECT COUNT(*) FROM "{table}"')).scalar_one()
            if not total:
                return {}
            out = {}
            for col in columns:
                n = c.execute(sa_text(
                    f'SELECT COUNT(*) FROM "{table}" WHERE "{col}" IS NULL')).scalar_one()
                out[col] = float(n) / float(total)
        return out

    def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
        self.executed.append(sql)
        started = time.time()
        try:
            with self.engine.connect() as c:
                cur = c.execute(sa_text(sql))
                cols = list(cur.keys())
                rows = cur.fetchmany(row_limit + 1)
        except Exception as e:  # noqa: BLE001
            raise QueryFailed(str(e)) from e
        truncated = len(rows) > row_limit
        return QueryResult(columns=cols, rows=[list(r) for r in rows[:row_limit]],
                           row_count=min(len(rows), row_limit),
                           duration_ms=int((time.time() - started) * 1000),
                           truncated=truncated)


# ---------------- 打桩的 LLM ----------------
class FakeLLM:
    """按脚本依次返回。chat_json 给计划,chat 给 SQL。"""

    def __init__(self):
        self.sql_script: list[str] = []
        self.plan = {"kind": "data_query", "clarify": "", "answer": "",
                     "plan": {"summary": "按门店统计成交金额", "models": ["order_item", "store"],
                              "grain": "每个门店一行", "measures": ["成交金额合计"],
                              "dimensions": ["门店名称"], "filters": [], "time_range": ""},
                     "calibre": "无特殊口径"}
        self.prompts_seen: list[str] = []

    def chat_json(self, messages, **kw):
        self.prompts_seen.append(messages[-1]["content"])
        return self.plan

    def chat(self, messages, **kw):
        self.prompts_seen.append(messages[-1]["content"])
        return self.sql_script.pop(0) if self.sql_script else "SELECT 1"

    def chat_stream(self, messages, **kw):
        yield "(解释)"

    def chat_stream_cached(self, messages, **kw):
        """SQL 起草走的是流式。整段一次吐出去就行 —— 这里要验的是管线,
        不是打字机效果,分不分片对下游没有区别。"""
        yield self.chat(messages, **kw)

    @staticmethod
    def count_tokens(text: str) -> int:
        return len(text or "")


# ---------------- fixture ----------------
@pytest.fixture()
def env(tmp_path, monkeypatch):
    meta_engine = create_engine(f"sqlite:///{tmp_path / 'meta.db'}", future=True)
    from app.text2sql import models as t2s_models  # noqa: F401  注册建表
    core_db.Base.metadata.create_all(meta_engine)
    with Session(meta_engine) as s:
        for k, v in DEFAULT_RUNTIME.items():
            s.add(core_db.Config(cfg_key=k, cfg_value=v))
        s.commit()
    for mod in _ENGINE_HOLDERS:
        monkeypatch.setattr(mod, "engine", meta_engine)

    conn = FakeConnector(tmp_path / "biz.db")
    monkeypatch.setattr(semantic, "connector_for", lambda ds_id, fresh=False: conn)
    # 口令加解密走真实实现,但要有主密钥
    monkeypatch.setattr(semantic.crypto, "encrypt", lambda p: f"enc:{p}")
    monkeypatch.setattr(semantic.crypto, "decrypt", lambda t: t[4:] if t.startswith("enc:") else "")

    fake_llm = FakeLLM()
    for mod in (pipeline, linker):
        monkeypatch.setattr(mod, "llm", fake_llm)

    ds_id = semantic.create_datasource(
        name="测试库", ds_type="mysql", host="127.0.0.1", port=3306,
        db_name="biz", username="ro", password="pw")
    return {"ds_id": ds_id, "conn": conn, "llm": fake_llm}


def introspect_and_enable(ds_id: int) -> list[dict]:
    events = list(introspect.run_introspection(ds_id))
    assert events[-1]["stage"] == "done", events[-1]
    models = semantic.list_models(ds_id)
    semantic.set_models_enabled(ds_id, [m["id"] for m in models], True)
    return models


def run(ds_id: int, question: str, **kw) -> list[dict]:
    return list(pipeline.run_ask(ds_id, question, **kw))


def by_type(events: list[dict], t: str) -> list[dict]:
    return [e for e in events if e.get("type") == t]


# ---------------- 内省 ----------------
def test_内省把表和列都建出来(env):
    models = introspect_and_enable(env["ds_id"])
    assert {m["physical_table"] for m in models} == {"store", "order_item"}
    full = semantic.models_with_columns(env["ds_id"])
    cols = {m["physical_table"]: {c["name"] for c in m["columns"]} for m in full}
    assert cols["store"] == {"id", "store_name", "brand_name", "level"}


def test_内省采到枚举列的真实取值(env):
    """这一步是准确率的关键:模型得看见 brand_name 里存的是「问界」。"""
    introspect_and_enable(env["ds_id"])
    full = semantic.models_with_columns(env["ds_id"])
    brand = next(c for m in full if m["physical_table"] == "store"
                 for c in m["columns"] if c["name"] == "brand_name")
    assert "问界" in brand["sample_values"]


def test_新表默认不启用(env):
    list(introspect.run_introspection(env["ds_id"]))
    assert all(not m["enabled"] for m in semantic.list_models(env["ds_id"]))


def test_外键推导出关系(env):
    introspect_and_enable(env["ds_id"])
    rels = semantic.list_relations(env["ds_id"])
    assert len(rels) == 1
    assert rels[0]["condition_sql"] == "order_item.store_id = store.id"


def test_重复内省不冲掉人工写的描述(env):
    introspect_and_enable(env["ds_id"])
    full = semantic.models_with_columns(env["ds_id"])
    col = next(c for m in full if m["physical_table"] == "store"
               for c in m["columns"] if c["name"] == "level")
    semantic.update_column(col["id"], description="人工写的:门店分级 A/B/C",
                           synonyms=["等级", "门店等级"])

    list(introspect.run_introspection(env["ds_id"]))

    full = semantic.models_with_columns(env["ds_id"])
    col2 = next(c for m in full if m["physical_table"] == "store"
                for c in m["columns"] if c["name"] == "level")
    assert col2["description"] == "人工写的:门店分级 A/B/C"
    assert col2["synonyms"] == ["等级", "门店等级"]


# ---------------- 闭环 ----------------
def test_单表问答跑通全链路(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name, level FROM store"]

    events = run(env["ds_id"], "各门店的等级是什么")
    types = [e["type"] for e in events]
    for expected in ("start", "retrieve", "plan", "sql_draft", "validate", "execute", "rows", "done"):
        assert expected in types, f"缺少 {expected} 事件:{types}"

    rows = by_type(events, "rows")[0]
    assert rows["columns"] == ["store_name", "level"]
    assert len(rows["rows"]) == 3
    assert by_type(events, "done")[0]["outcome"] == "ok"


def test_没写limit会被自动补上(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    run(env["ds_id"], "门店都有哪些")
    assert "LIMIT" in env["conn"].executed[-1].upper()


def test_跨表join走声明过的关系(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        "SELECT s.store_name, SUM(o.amount) AS amt FROM order_item o "
        "JOIN store s ON o.store_id = s.id GROUP BY s.store_name"]
    events = run(env["ds_id"], "每个门店的成交金额")
    assert by_type(events, "done")[0]["outcome"] == "ok"
    assert by_type(events, "validate")[0]["ok"]


def test_未声明的join被拦下并触发自愈(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        # 第一次瞎关联
        "SELECT s.store_name FROM order_item o JOIN store s ON o.amount = s.id",
        # 自愈后改成声明过的路径
        "SELECT s.store_name FROM order_item o JOIN store s ON o.store_id = s.id",
    ]
    events = run(env["ds_id"], "有成交的门店")
    assert by_type(events, "repair"), "应该触发自愈重试"
    assert not by_type(events, "validate")[0]["ok"]
    assert by_type(events, "done")[0]["outcome"] == "ok"


def test_写错列名能被自愈救回来(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        "SELECT store_nam FROM store",       # 列名打错,guard 只 warn,执行时报错
        "SELECT store_name FROM store",
    ]
    events = run(env["ds_id"], "门店名单")
    assert by_type(events, "repair")
    assert by_type(events, "done")[0]["outcome"] == "ok"


def test_越权表被拒且不执行(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT * FROM sqlite_master"] * 5
    events = run(env["ds_id"], "系统里有哪些表")
    assert by_type(events, "done")[0]["outcome"] == "failed"
    assert not env["conn"].executed, "未建模的表不该真的打到业务库上"


def test_写操作一路到底都被拒(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["DELETE FROM store"] * 5
    events = run(env["ds_id"], "把门店清空")
    assert by_type(events, "done")[0]["outcome"] == "failed"
    assert not env["conn"].executed


def test_自愈次数不超过配置上限(env):
    introspect_and_enable(env["ds_id"])
    core_db.set_config({"SQL_MAX_REPAIR": "1"})
    env["llm"].sql_script = ["SELECT * FROM sqlite_master"] * 5
    events = run(env["ds_id"], "系统表")
    assert len(by_type(events, "repair")) == 1


def test_一张表都没启用时给明确提示(env):
    list(introspect.run_introspection(env["ds_id"]))    # 只内省,不启用
    events = run(env["ds_id"], "门店有哪些")
    err = by_type(events, "error")[0]
    assert "没有启用任何表" in err["error"]


# ---------------- 计划分支 ----------------
def test_需要澄清时停在计划步骤(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].plan = {"kind": "clarify", "clarify": "要看哪个品牌?", "answer": "",
                       "plan": {}, "calibre": ""}
    events = run(env["ds_id"], "渗透率多少")
    assert by_type(events, "done")[0]["outcome"] == "clarify"
    assert not by_type(events, "sql_draft")


def test_澄清问题跟着done一起回去(env):
    """前端要靠 done 上的 clarify 渲染提示。只发在 plan 事件里的话,
    它会被当成轨迹渲染掉,用户看到一张没有任何说明的空卡片。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].plan = {"kind": "clarify", "clarify": "要看哪个品牌?", "answer": "",
                       "plan": {}, "calibre": ""}
    done = by_type(run(env["ds_id"], "渗透率多少"), "done")[0]
    assert done["clarify"] == "要看哪个品牌?"


def test_元数据问题要给出回答而不是空卡片(env):
    """问「有哪些表」不产出 SQL。以前 answer 只躺在 plan 事件里被前端丢掉,
    整轮问答界面上什么都没有 —— 这类问题必须有一条独立的 answer 事件。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].plan = {"kind": "metadata", "clarify": "",
                       "answer": "这个库里有 store 和 order_item 两张表。",
                       "plan": {}, "calibre": ""}
    events = run(env["ds_id"], "有哪些表")
    answers = by_type(events, "answer")
    assert answers and "store" in answers[0]["text"]
    done = by_type(events, "done")[0]
    assert done["outcome"] == "metadata"
    assert done["answer"] == answers[0]["text"]
    assert not by_type(events, "sql_draft")


def test_闲聊也要有一句回话(env):
    """模型对 not_data 经常不填 answer。那种情况下也不能让界面空着。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].plan = {"kind": "not_data", "clarify": "", "answer": "",
                       "plan": {}, "calibre": ""}
    answers = by_type(run(env["ds_id"], "你好"), "answer")
    assert answers and answers[0]["text"].strip()


# ---------------- 流式与出场顺序 ----------------
def test_sql是流式吐出来的(env):
    """生成 SQL 是整条链路最长的一次等待。必须边写边出,
    否则界面上十几秒只有一个转圈,和卡死长得一模一样。"""
    introspect_and_enable(env["ds_id"])
    events = run(env["ds_id"], "每个门店的成交金额")
    deltas = by_type(events, "sql_delta")
    assert deltas, "没有 sql_delta,SQL 又退回阻塞式生成了"
    # 增量拼起来要能还原出最终那条 SQL,前端才敢直接拿去显示
    draft = by_type(events, "sql_draft")[0]
    assert "".join(d["text"] for d in deltas).strip().rstrip(";") == draft["sql"]


def test_管线只出结论不出解释(env):
    """「这条 SQL 在做什么」默认是折叠的,改成按需生成(POST /api/sql/explain)。
    留在管线里意味着:用户看完结论还要再等一轮往返,done 才发得出来,
    输入框在这几秒里一直锁着 —— 为一段没人展开的文字付这个代价不划算。"""
    introspect_and_enable(env["ds_id"])
    events = run(env["ds_id"], "每个门店的成交金额")
    assert by_type(events, "summary"), "结论必须还在管线里"
    assert not by_type(events, "explain")
    assert not by_type(events, "explain_delta")
    # 结论要排在 done 前面,否则前端拿到 done 就收尾了,结论会丢
    types = [e["type"] for e in events]
    assert types.index("summary") < types.index("done")


def test_关掉流式开关就退回整段返回(env):
    introspect_and_enable(env["ds_id"])
    core_db.set_config({"SQL_STREAM_DRAFT": "0"})
    events = run(env["ds_id"], "每个门店的成交金额")
    assert not by_type(events, "sql_delta")
    assert by_type(events, "sql_draft")


def test_开启计划确认后停下来等用户(env):
    introspect_and_enable(env["ds_id"])
    core_db.set_config({"SQL_REQUIRE_PLAN": "1"})
    events = run(env["ds_id"], "每个门店的成交金额")
    done = by_type(events, "done")[0]
    assert done["outcome"] == "await_plan"
    assert not by_type(events, "sql_draft")


def test_带着已确认的计划继续能出sql(env):
    introspect_and_enable(env["ds_id"])
    core_db.set_config({"SQL_REQUIRE_PLAN": "1"})
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    events = run(env["ds_id"], "门店名单",
                 approved_plan={"summary": "列出门店", "models": ["store"]})
    assert by_type(events, "plan")[0]["approved"] is True
    assert by_type(events, "done")[0]["outcome"] == "ok"


# ---------------- 沉淀 ----------------
def test_执行成功自动存成草稿(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    run(env["ds_id"], "门店名单")

    pairs = library.list_pairs(env["ds_id"])
    assert len(pairs) == 1
    assert pairs[0]["status"] == "draft" and pairs[0]["source"] == "auto"


def test_草稿不进fewshot采纳后才进(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    run(env["ds_id"], "门店名单")
    pair = library.list_pairs(env["ds_id"])[0]

    ctx = linker.retrieve(env["ds_id"], "门店名单")
    assert ctx["pairs"] == [], "草稿不该被当成示例"

    library.set_status(pair["id"], "verified")
    ctx2 = linker.retrieve(env["ds_id"], "门店名单")
    assert [p["id"] for p in ctx2["pairs"]] == [pair["id"]]


def test_采纳过的示例会进提示词(env):
    introspect_and_enable(env["ds_id"])
    library.set_status(library.capture(
        env["ds_id"], "门店名单", "SELECT store_name FROM store"), "verified")
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    run(env["ds_id"], "门店名单")
    assert any("SELECT store_name FROM store" in p for p in env["llm"].prompts_seen)


def test_同一个问题问两次不堆重复草稿(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store"] * 2
    run(env["ds_id"], "门店名单")
    run(env["ds_id"], "门店名单?")     # 标点不同,判重后应视为同一个问题
    assert len(library.list_pairs(env["ds_id"])) == 1


def test_执行都会留审计(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store"]
    run(env["ds_id"], "门店名单")
    runs = executor.list_runs(env["ds_id"])
    assert len(runs) == 1 and runs[0]["status"] == "ok"
    assert runs[0]["row_count"] == 3


def test_失败也留审计(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["DROP TABLE store"] * 5
    run(env["ds_id"], "删表")
    runs = executor.list_runs(env["ds_id"])
    assert len(runs) == 1 and runs[0]["status"] == "invalid"


# ---------------- 召回 ----------------
def test_样例值命中能把对的表召回来(env):
    introspect_and_enable(env["ds_id"])
    ctx = linker.retrieve(env["ds_id"], "问界的门店有哪些")
    assert "store" in [m["physical_table"] for m in ctx["models"]]
    assert any("问界" in str(h) for h in ctx["hits"]["models"]) or ctx["hits"]["terms"]


def test_停用的表不会进召回(env):
    introspect_and_enable(env["ds_id"])
    oi = next(m for m in semantic.list_models(env["ds_id"])
              if m["physical_table"] == "order_item")
    semantic.set_models_enabled(env["ds_id"], [oi["id"]], False)
    ctx = linker.retrieve(env["ds_id"], "成交金额")
    assert "order_item" not in [m["physical_table"] for m in ctx["models"]]


def test_停用的表也查不了(env):
    """停用 = 收回授权,不只是不召回。"""
    introspect_and_enable(env["ds_id"])
    oi = next(m for m in semantic.list_models(env["ds_id"])
              if m["physical_table"] == "order_item")
    semantic.set_models_enabled(env["ds_id"], [oi["id"]], False)
    outcome = executor.execute(env["ds_id"], "SELECT * FROM order_item")
    assert not outcome.ok and outcome.error_kind == "guard"


# ---------------- 管线契约 ----------------
# 前端靠 done 事件关掉「处理中」状态。任何一条出口漏发 done,界面就会永远转圈 ——
# 这个 bug 真的发生过一次,所以把它钉成用例。
def test_每条出口都以done收尾(env):
    ds_id = env["ds_id"]
    cases: list[tuple[str, callable]] = []

    # 1) 数据源不存在
    cases.append(("数据源不存在", lambda: run(999999, "随便问问")))

    # 2) 一张表都没启用
    def no_models():
        list(introspect.run_introspection(ds_id))
        return run(ds_id, "门店有哪些")
    cases.append(("没有启用的表", no_models))

    # 3) 计划阶段 LLM 抛异常
    def plan_boom():
        introspect_and_enable(ds_id)
        env["llm"].chat_json = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("模拟计划失败"))
        return run(ds_id, "门店有哪些")
    cases.append(("计划阶段报错", plan_boom))

    for label, fn in cases:
        events = fn()
        assert events, f"{label}:一个事件都没有"
        assert events[-1]["type"] == "done", \
            f"{label}:最后一个事件是 {events[-1]['type']},不是 done"
        assert by_type(events, "error"), f"{label}:应该有 error 事件"


def test_生成sql阶段报错也收尾(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].chat = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("模拟生成失败"))
    events = run(env["ds_id"], "门店有哪些")
    assert events[-1]["type"] == "done"
    assert events[-1]["outcome"] == "failed"


def test_校验失败到底也收尾(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["DROP TABLE store"] * 5
    events = run(env["ds_id"], "删表")
    assert events[-1]["type"] == "done"
    assert events[-1]["outcome"] == "failed"


# ---------------- 空结果自我修正 ----------------
# 跑通但 0 行几乎总是过滤条件写错,而不是「业务上没数据」。
# 给模型一次带着「返回了 0 行」重写的机会,实测能救回时间区间算空这类错。
def test_空结果会触发一次自我修正(env):
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        "SELECT store_name FROM store WHERE brand_name = 'AITO'",   # 品牌写法不对,0 行
        "SELECT store_name FROM store WHERE brand_name LIKE '%问界%'",
    ]
    events = run(env["ds_id"], "问界的门店")
    repairs = by_type(events, "repair")
    assert repairs and repairs[0]["kind"] == "empty", [r.get("kind") for r in repairs]
    assert by_type(events, "rows")[0]["rows"], "修正后应该查到数据"
    assert by_type(events, "done")[0]["outcome"] == "ok"


def test_空结果只重试一次(env):
    """业务上真的没数据时,不能无限重试 —— 如实返回空结果。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = ["SELECT store_name FROM store WHERE brand_name = 'NOPE'"] * 5
    events = run(env["ds_id"], "某个不存在的品牌的门店")
    assert len([r for r in by_type(events, "repair") if r.get("kind") == "empty"]) == 1
    assert by_type(events, "done")[0]["outcome"] == "ok"
    assert by_type(events, "rows")[0]["rows"] == []


def test_空结果重试不占报错自愈的额度(env):
    """空结果先烧掉 1 轮之后,真出错了仍然要有完整的报错自愈额度。"""
    introspect_and_enable(env["ds_id"])
    core_db.set_config({"SQL_MAX_REPAIR": "2"})
    env["llm"].sql_script = [
        "SELECT store_name FROM store WHERE brand_name = 'NOPE'",  # 0 行 → 空重试
        "SELECT store_nam FROM store",                             # 列名错 → 执行报错
        "SELECT store_nam2 FROM store",                            # 再错一次
        "SELECT store_name FROM store",                            # 终于对了
    ]
    events = run(env["ds_id"], "门店名单")
    kinds = [r.get("kind") for r in by_type(events, "repair")]
    assert kinds.count("empty") == 1 and kinds.count("error") == 2, kinds
    assert by_type(events, "done")[0]["outcome"] == "ok"
    assert by_type(events, "rows")[0]["rows"]


# ---------------- 多轮追问 ----------------
def test_历史里的助手轮次会带上上一轮的取数方式(env):
    """「那上个月呢」这类省略句,只有看得见上一轮实际怎么取的数才接得上。
    只回传用户问句的话,模型每轮都在从头重猜。"""
    introspect_and_enable(env["ds_id"])
    history = [
        {"role": "user", "content": "每个门店的成交金额"},
        {"role": "assistant",
         "content": "取数思路:按门店汇总成交金额\n执行的 SQL:SELECT store_name, SUM(amount) FROM order_item"},
    ]
    run(env["ds_id"], "那上个月呢", history=history)
    plan_prompt = env["llm"].prompts_seen[0]
    assert "SELECT store_name, SUM(amount) FROM order_item" in plan_prompt
    assert "每个门店的成交金额" in plan_prompt


def test_助手历史不会被截成一句话(env):
    """SQL 比问句长得多。沿用问句那套 300 字截断会把 SQL 从中间切断,
    模型看到半条 SQL 反而更容易改错地方。"""
    long_sql = "SELECT " + ", ".join(f"col_{i}" for i in range(80)) + " FROM order_item"
    out = prompts._fmt_history([{"role": "assistant", "content": f"执行的 SQL:{long_sql}"}])
    assert len(out) > 400


# ---------------- 分类 ----------------
def test_自动归类只填空不覆盖人工改过的(env):
    ds_id = env["ds_id"]
    introspect_and_enable(ds_id)
    model_id = semantic.list_models(ds_id)[0]["id"]
    mine = semantic.upsert_metric(ds_id, name="总产值", expression="SUM(amount)",
                                  base_model_id=model_id, category="我自己定的")
    auto = semantic.upsert_metric(ds_id, name="整车延保渗透率", expression="SUM(a)/SUM(b)",
                                  base_model_id=model_id)
    semantic.upsert_instruction(0, scope="sql", content="过滤品牌一律用 LIKE 模糊匹配",
                                is_default=1, priority=10)

    done = semantic.autocategorize(ds_id)
    assert done["metrics"] == 1 and done["instructions"] >= 1

    by_id = {m["id"]: m for m in semantic.list_metrics(ds_id)}
    assert by_id[mine]["category"] == "我自己定的", "人工写过的分类不该被覆盖"
    assert by_id[auto]["category"] == "渗透与转化"
    assert semantic.list_instructions(ds_id)[0]["category"] == "取值与写法"


def test_分类不进提示词(env):
    """分类纯粹是给人看的。一旦它影响到召回或提示词,猜错分类就会伤准确率。"""
    ds_id = env["ds_id"]
    introspect_and_enable(ds_id)
    model_id = semantic.list_models(ds_id)[0]["id"]
    semantic.upsert_metric(ds_id, name="总产值", expression="SUM(amount)",
                           base_model_id=model_id, category="不该出现的分类名")
    run(ds_id, "每个门店的成交金额")
    assert not any("不该出现的分类名" in p for p in env["llm"].prompts_seen)


def test_聚合查出一行NULL也算空结果(env):
    """最阴的一种空结果:`SELECT SUM(x) WHERE 条件恒假` 返回的是
    **一行、值为 NULL**,不是 0 行。按 row_count 判空的话自愈完全不会触发,
    用户拿到一格 NULL 和一段「可能确实没有数据」的结论 —— 全是错的。

    实测触发方式:模型把时间区间的上下界写成同一个表达式,区间恒空。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        "SELECT SUM(amount) FROM order_item WHERE created_at >= '2030-01-01'",  # 恒空区间
        "SELECT SUM(amount) FROM order_item",                                   # 修好了
    ]
    events = run(env["ds_id"], "上个月的成交金额")
    repairs = [r for r in by_type(events, "repair") if r.get("kind") == "empty"]
    assert repairs, "一行 NULL 没有触发空结果自愈"
    assert "NULL" in repairs[0]["reason"], "报错信息要点明是「一行全 NULL」这种形态"
    assert "区间" in repairs[0]["reason"], "要提示检查时间区间是不是写空了"
    rows = by_type(events, "rows")[0]["rows"]
    assert rows and rows[0][0] is not None, "修正后应该拿到真实数字"


def test_确实没数据时如实返回那行NULL(env):
    """自愈救不回来就得如实返回,不能无限重试,也不能假装查到了。"""
    introspect_and_enable(env["ds_id"])
    env["llm"].sql_script = [
        "SELECT SUM(amount) FROM order_item WHERE created_at >= '2030-01-01'"] * 5
    events = run(env["ds_id"], "三千年的成交金额")
    assert len([r for r in by_type(events, "repair") if r.get("kind") == "empty"]) == 1
    assert by_type(events, "done")[0]["outcome"] == "ok"
    assert by_type(events, "rows")[0]["rows"] == [[None]]