sql_eval.py 12.1 KB
"""数据问答的准确率评测。

没有这个数字,「效果好不好」就只能靠感觉,改一行提示词是变好还是变坏也说不清。

评分刻意**不比对 SQL 字面**:同一个问题有很多写法都对,字面比对会把正确答案判错。
改成检查几件能自动判定、且真出问题时一定会踩到的事:

    可执行      SQL 过了安全校验并真的在库上跑通
    用对了表    命中了这个问题应该用的表(业务上选错表 = 答案废了)
    有结果      该有数据的问题不能返回空(空结果通常意味着过滤条件写错)
    没踩雷      不该出现的写法没出现(比如用 CURDATE() 查一个数据已经截止的库)
    数字对      有基准答案的用例,返回值要落在容差内

最后这条最值钱:前四条全过、数字却错 20% 的情况真实发生过 ——
把两张日报宽表按 (门店, 日期) 直接关联,而其中一张同一天有多行,
求和被放大,查询照样跑通、结果看着也正常。只有比对基准值才抓得到。

    ./.venv/Scripts/python.exe scripts/sql_eval.py              # 跑全部
    ./.venv/Scripts/python.exe scripts/sql_eval.py -k 渗透率    # 只跑匹配的
    ./.venv/Scripts/python.exe scripts/sql_eval.py --out report.md
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))
sys.stdout.reconfigure(encoding="utf-8")

from app.text2sql import pipeline, semantic          # noqa: E402

DS_NAME_HINT = "data_analyze"

M_TARGET = "dws_merchant_daily_target_wide"
M_DAILY = "dws_merchant_daily_wide"
S_DAILY = "dws_staff_daily_wide"
O_DETAIL = "dws_order_detail_wide"

# 每个用例:
#   q        问题
#   tables   期望命中的表(命中其一即可)
#   rows     是否该有结果,默认 True
#   forbid   不该出现在 SQL 里的写法
#   value    基准答案 —— 在结果的任意数值单元格里找得到即算对
#   tol      相对容差,默认 2%
CASES: list[dict] = [
    # --- 基础聚合 ---
    dict(q="一共有多少家门店", tables=["ods_service_merchant", M_DAILY, M_TARGET], value=8782),
    dict(q="门店总数按省份分布", tables=["ods_service_merchant", M_DAILY, M_TARGET]),
    dict(q="2026年7月的总产值是多少", tables=[M_TARGET, O_DETAIL],
         forbid=["CURDATE", "NOW("], value=78127052, tol=0.01),
    dict(q="2026年7月一共交付了多少台车", tables=[M_TARGET, "oem_delivery_data"],
         forbid=["CURDATE"], value=9913),
    dict(q="2026年7月的成交订单数", tables=[M_TARGET, M_DAILY]),

    # --- 排名 / TOP N ---
    dict(q="产值最高的10家门店", tables=[M_TARGET]),
    dict(q="安心包卖得最好的10家门店", tables=[M_DAILY]),
    dict(q="成交金额最高的10个员工", tables=[S_DAILY]),
    dict(q="哪个省份的交付量最大", tables=[M_TARGET, "oem_delivery_data"]),

    # --- 指标与口径(本系统的重点)---
    dict(q="各门店的整车延保渗透率排名", tables=[M_TARGET]),
    dict(q="2026年7月整车延保渗透率是多少", tables=[M_TARGET],
         forbid=["CURDATE"], value=0.4937, tol=0.03),
    dict(q="电池延保渗透率最低的10家门店", tables=[M_TARGET]),
    dict(q="安心包渗透率怎么样", tables=[M_DAILY]),
    dict(q="触客成交率最高的门店有哪些", tables=[M_TARGET]),
    dict(q="延保成交数最多的10家门店", tables=[M_TARGET, M_DAILY]),

    # --- 品牌(多写法陷阱 + 关联放大陷阱)---
    dict(q="问界品牌的门店有多少家", tables=[M_DAILY, M_TARGET, "ods_merchant_brand_model"]),
    dict(q="问界2026年7月的总产值", tables=[M_TARGET, M_DAILY], forbid=["CURDATE"]),
    # 这一条专门盯「按(门店,日期)直接关联两张日报宽表导致求和放大」:
    # 正确 8916,放大后 11819(高 33%)。前四项检查都抓不到,只有基准值能。
    dict(q="问界2026年7月一共交付了多少台车", tables=[M_TARGET, M_DAILY],
         forbid=["CURDATE"], value=8916, tol=0.03),
    dict(q="智界和享界的交付数各是多少", tables=[M_DAILY, "sub_brand_oem_data", M_TARGET]),

    # --- 时间新鲜度(数据已截止,用 CURDATE 必翻车)---
    dict(q="最近一个月的产值", tables=[M_TARGET], forbid=["CURDATE", "NOW(", "CURRENT_DATE"]),
    dict(q="最新一天的成交情况", tables=[M_TARGET, M_DAILY],
         forbid=["CURDATE", "NOW(", "CURRENT_DATE"]),
    # 「上个月」和「最近一个月」不是一回事,而且是踩过的坑:模型把上下界写成
    # 同一个表达式,区间恒空,SUM 返回**一行 NULL**(不是 0 行),
    # 于是空结果自愈根本不触发,界面上就是一格 NULL。
    # 数据最新日期 2026-08-03,上个月 = 整个 7 月,问界交付数基准 8916。
    dict(q="问界品牌上个月的交付数", tables=[M_TARGET, M_DAILY],
         forbid=["CURDATE", "NOW(", "CURRENT_DATE"], value=8916, tol=0.03),

    # --- 明细 ---
    dict(q="最近成交的10笔订单", tables=[O_DETAIL]),
    dict(q="电池延保的成交金额合计", tables=[M_DAILY, M_TARGET, O_DETAIL]),

    # --- 业务配置 ---
    dict(q="有多少家门店签了兜底协议", tables=["store_guarantee_config"]),
    dict(q="按触客口径考核的门店有哪些", tables=["store_guarantee_config"]),

    # --- 运营策略 ---
    dict(q="下发过多少条运营策略", tables=["ods_strategy_info"]),
]


def find_ds() -> int:
    for ds in semantic.list_datasources():
        if DS_NAME_HINT in ds["db_name"] or DS_NAME_HINT in ds["name"]:
            return ds["id"]
    raise SystemExit(f"没找到指向 {DS_NAME_HINT} 的数据源,请先跑 scripts/setup_daw.py")


def _numbers(rows: list[list]) -> list[float]:
    """把结果里所有能当数字看的单元格摊平。基准值只要能对上其中一个就算对。

    不指定「第几行第几列」是有意的:同一个问题,模型可能多返回几个辅助列,
    死盯位置会把正确答案判错。
    """
    out: list[float] = []
    for r in rows[:50]:
        for v in r:
            if isinstance(v, bool):
                continue
            if isinstance(v, (int, float)):
                out.append(float(v))
            elif isinstance(v, str):
                try:
                    out.append(float(v.replace(",", "").rstrip("%")))
                except ValueError:
                    pass
    return out


def run_case(ds_id: int, case: dict) -> dict:
    question = case["q"]
    want_tables = case.get("tables") or []
    want_rows = case.get("rows", True)
    forbid = case.get("forbid") or []
    want_value = case.get("value")
    tol = case.get("tol", 0.02)

    started = time.time()
    events = list(pipeline.run_ask(ds_id, question))
    by = lambda t: [e for e in events if e.get("type") == t]   # noqa: E731

    exec_ev = by("execute")
    rows_ev = by("rows")
    err_ev = by("error")
    sql = (exec_ev[0]["sql"] if exec_ev else
           (by("sql_draft")[-1]["sql"] if by("sql_draft") else ""))
    tables = set()
    for v in by("validate"):
        tables |= set(v.get("tables") or [])

    rows = rows_ev[0]["rows"] if rows_ev else []
    checks: dict[str, bool] = {
        "可执行": bool(exec_ev),
        "用对了表": (not want_tables) or bool(tables & set(want_tables)),
        "有结果": (not want_rows) or len(rows) > 0,
        "没踩雷": not any(f.upper() in sql.upper() for f in forbid),
    }

    got = None
    if want_value is not None:
        nums = _numbers(rows)
        target = float(want_value)
        hit = next((n for n in nums
                    if abs(n - target) <= max(abs(target) * tol, 1e-9)), None)
        # 比率类问题模型可能直接给百分数,0.4937 与 49.37 视作同一个答案
        if hit is None:
            hit = next((n for n in nums
                        if abs(n / 100.0 - target) <= max(abs(target) * tol, 1e-9)), None)
        checks["数字对"] = hit is not None
        got = hit if hit is not None else (nums[:6] or None)

    return {
        "question": question, "sql": sql, "tables": sorted(tables),
        "row_count": len(rows), "repairs": len(by("repair")),
        "error": err_ev[0]["error"] if err_ev else "",
        "expected": want_value, "got": got,
        "checks": checks, "passed": all(checks.values()),
        "duration_ms": int((time.time() - started) * 1000),
    }


def main() -> None:
    ap = argparse.ArgumentParser(description="数据问答准确率评测")
    ap.add_argument("-k", "--filter", default="", help="只跑问题里含该关键词的用例")
    ap.add_argument("--out", default="", help="把报告写到 markdown 文件")
    ap.add_argument("--json", default="", help="把明细写到 JSON 文件")
    args = ap.parse_args()

    ds_id = find_ds()
    cases = [c for c in CASES if not args.filter or args.filter in c["q"]]
    print(f"数据源 id={ds_id},共 {len(cases)} 个用例\n")

    results = []
    for i, case in enumerate(cases, 1):
        try:
            r = run_case(ds_id, case)
        except Exception as e:  # noqa: BLE001
            r = {"question": case["q"], "sql": "", "tables": [], "row_count": 0, "repairs": 0,
                 "error": f"用例异常:{e}", "duration_ms": 0, "expected": None, "got": None,
                 "checks": {"可执行": False, "用对了表": False, "有结果": False, "没踩雷": True},
                 "passed": False}
        results.append(r)
        bad = [k for k, v in r["checks"].items() if not v]
        print(f"[{i:2d}/{len(cases)}] {'PASS' if r['passed'] else 'FAIL'}  {r['question']}")
        if not r["passed"]:
            detail = f"          未通过:{'、'.join(bad)}"
            if "数字对" in bad:
                detail += f" 期望 {r['expected']},实际 {r['got']}"
            if r["error"]:
                detail += f" {r['error'][:110]}"
            print(detail)
        if r["repairs"]:
            print(f"          (自愈 {r['repairs']} 轮后成功)")

    passed = sum(1 for r in results if r["passed"])
    rate = passed / len(results) * 100 if results else 0
    keys = ["可执行", "用对了表", "有结果", "没踩雷", "数字对"]
    per_check = {k: (sum(1 for r in results if r["checks"].get(k)),
                     sum(1 for r in results if k in r["checks"])) for k in keys}
    avg_ms = sum(r["duration_ms"] for r in results) // max(len(results), 1)

    print(f"\n{'=' * 56}")
    print(f"整体通过率 {passed}/{len(results)} = {rate:.1f}%    平均耗时 {avg_ms} ms")
    for k, (ok, total) in per_check.items():
        if total:
            print(f"  {k}:{ok}/{total}")

    if args.json:
        Path(args.json).write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"\n明细已写入 {args.json}")

    if args.out:
        lines = ["# 数据问答准确率评测", "",
                 f"- 用例 {len(results)} 个,通过 {passed},通过率 **{rate:.1f}%**",
                 f"- 平均耗时 {avg_ms} ms(关闭 LLM 缓存)", "",
                 "评分维度:能否执行 / 是否用对表 / 是否有结果 / 有没有踩已知的坑 / "
                 "有基准答案的用例数字对不对。", "",
                 "| 维度 | 通过 |", "| --- | --- |"]
        lines += [f"| {k} | {ok}/{total} |" for k, (ok, total) in per_check.items() if total]
        lines += ["", "## 逐条", "",
                  "| # | 问题 | 结果 | 用到的表 | 行数 | 基准 | 实际 | 说明 |",
                  "| --- | --- | --- | --- | --- | --- | --- | --- |"]
        for i, r in enumerate(results, 1):
            bad = "、".join(k for k, v in r["checks"].items() if not v) or "—"
            lines.append(
                f"| {i} | {r['question']} | {'通过' if r['passed'] else '未通过'} | "
                f"{'、'.join(r['tables']) or '—'} | {r['row_count']} | "
                f"{r['expected'] if r['expected'] is not None else '—'} | "
                f"{r['got'] if r['got'] is not None else '—'} | {bad} |")
        Path(args.out).write_text("\n".join(lines) + "\n", encoding="utf-8")
        print(f"报告已写入 {args.out}")

    sys.exit(0 if rate >= 80 else 1)


if __name__ == "__main__":
    main()