File size: 14,555 Bytes
d847043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""第二轮新题的把关和改写:data/round2/raw/ → data/new/。

    python scripts/check_round2.py blind      # 每道题让 DeepSeek 不看答案再写一遍,比结果
    python scripts/check_round2.py rewrite    # 留下的题各改写一个口语问法,再盲答一遍确认意思没变
    python scripts/check_round2.py apply      # 写 data/new/<库名>_r2.jsonl 和 <库名>_r2_para.jsonl

DeepSeek 的回复缓存在 data/round2/cache.jsonl,断了重跑不会重复花钱。

「对得上」:在 seed_suite 现生成的 5 份数据上,两条 SQL 结果的行一样(一边多几列也算;
标准答案给名字、盲答给对应的 ID 也算),不管顺序。
查的是 SQL 算出来的东西对不对;返回哪几列由题目文字决定,训练时模型照着题目学。

blind:
1. 5 份数据上都查不出东西的丢掉:空对空,比不出对错
2. deepseek-chat 用训练同一个 prompt(带「部分字段的取值」)答一遍,对得上就留
3. 对不上的让 deepseek-reasoner 再答,对得上也留;两次都对不上的丢掉。
   两次答案彼此一致、只和标准答案不一致的,多半是标准答案错了,但也丢掉,不拿它们的答案顶上
rewrite:
- 题目里有 SQL 术语或列名(「用密集排名」「递归」「parent_building_id」)的,原题不进训练,只留改写
- 改写后的题再用 deepseek-chat 盲答,和标准答案对得上才算意思没变
"""

import argparse
import concurrent.futures as cf
import hashlib
import json
import re
import sys
import threading
from collections import Counter, defaultdict
from pathlib import Path

from eval import _canon, extract_sql, load_dbs, rows_of, superset_result
from prompt import build, values_from_db
from seed_suite import make_suite
from teacher import api_key, post_with_retry

ROOT = Path(__file__).resolve().parent.parent
R2 = ROOT / "data" / "round2"
CACHE = R2 / "cache.jsonl"
REPORT = R2 / "blind.jsonl"
REWRITES = R2 / "rewrite.jsonl"

LEAK = re.compile(
    r"CTE|子查询|窗口|密集排名|DENSE_RANK|ROW_NUMBER|RANK\s*\(|分别汇总|先汇总|各自汇总|各自统计|先各自|"
    r"先(?:按\S{1,6})?聚合|不能因\S{0,8}重复|避免\S{0,6}重复|关联而|口径|递归|NOT\s+IN|EXISTS|JOIN|GROUP\s+BY|"
    r"COALESCE|NULLIF|julianday|strftime", re.I)

REWRITE_PROMPT = """下面是一个业务数据库上的中文问题,和回答它的 SQLite 查询。把问题改写成真实员工在聊天框里会打的样子。

原问题:{question}
SQL:{sql}

要求:
- 意思必须和原问题完全一样:SQL 里的每个筛选条件、时间范围、并列怎么处理、要返回哪些东西,都要能从新问题里读出来
- 更口语、更短,可以省主语、用简称、换个语序;不要照抄原问题的句式
- 不能出现 SQL 术语(递归、窗口、子查询、CTE、JOIN、分组、聚合、密集排名、DENSE_RANK 之类)和英文表名、列名;
  原问题里有的,换成业务说法。比如「用密集排名取前三,并列都留」可以说「前三名,同分算同一名、后面名次不跳」,
  「递归列出部门树」可以说「把所有部门按上下级一层层列出来」
- 取值(状态、类型这种)照 SQL 里的原样写,不要翻译

只输出 JSON:{{"question": "改写后的问题"}}"""

_lock = threading.Lock()


def cache_load() -> dict[str, str]:
    if not CACHE.exists():
        return {}
    out = {}
    for line in CACHE.read_text(encoding="utf-8").splitlines():
        if line.strip():
            r = json.loads(line)
            out[r["key"]] = r["content"]
    return out


def ask_all(jobs: dict[str, dict], cache: dict[str, str], key: str, workers: int = 16) -> None:
    """jobs: {缓存键: payload}。没缓存的并发去问,答案追加进 cache.jsonl 和 cache。"""
    todo = {k: p for k, p in jobs.items() if k not in cache}
    if not todo:
        return
    print(f"要问 DeepSeek {len(todo)} 次", flush=True)

    def one(k: str, payload: dict):
        try:
            return k, post_with_retry(payload, key, timeout=900)
        except Exception as exc:  # noqa: BLE001  重跑会再试
            print(f"放弃这一条:{exc}", file=sys.stderr, flush=True)
            return k, None

    done = 0
    with cf.ThreadPoolExecutor(workers) as pool, CACHE.open("a", encoding="utf-8") as f:
        for k, content in pool.map(lambda kv: one(*kv), todo.items()):
            done += 1
            if content is not None:
                with _lock:
                    cache[k] = content
                    f.write(json.dumps({"key": k, "content": content}, ensure_ascii=False) + "\n")
                    f.flush()
            if done % 100 == 0:
                print(f"  {done}/{len(todo)}", flush=True)


def payload_for(model: str, msgs: list[dict], temperature: float = 0.0, json_out: bool = False) -> dict:
    p = {"model": model, "messages": msgs}
    if model == "deepseek-reasoner":
        p["max_tokens"] = 16000  # 含思考过程
    else:
        p.update(temperature=temperature, max_tokens=2000)
    if json_out:
        p["response_format"] = {"type": "json_object"}
    return p


def keyof(payload: dict, tag: str = "") -> str:
    return hashlib.sha1((tag + json.dumps(payload, ensure_ascii=False, sort_keys=True)).encode()).hexdigest()


def _key(r: tuple) -> tuple:
    return tuple(round(v, 6) if isinstance(v, float) else v for v in r)


def name_vs_id(gold, other) -> bool:
    """标准答案给名字、盲答给 ID(DeepSeek 的老习惯),其余列一模一样:也算对得上。
    名字和 ID 得一一对应;反过来(标准答案给 ID)不算,那种题本来就不该留。"""
    if len(gold) != len(other) or not gold:
        return False
    g, o = _canon(gold), _canon(other)
    w = len(g[0])
    if len(o[0]) != w or w < 2:
        return False
    for i in range(w):
        if not all(isinstance(r[i], str) for r in g):
            continue
        for j in range(w):
            if not all(isinstance(r[j], int) for r in o):
                continue
            rg = {_key(r[:i] + r[i + 1:]): r[i] for r in g}
            ro = {_key(r[:j] + r[j + 1:]): r[j] for r in o}
            if len(rg) != len(g) or len(ro) != len(o) or rg.keys() != ro.keys():
                continue
            pairs = {(rg[k], ro[k]) for k in rg}
            if len({a for a, _ in pairs}) == len(pairs) == len({b for _, b in pairs}):
                return True
    return False


def agree(gold: str, other: str, conns) -> bool:
    if not other:
        return False
    try:
        a = [rows_of(c, gold) for c in conns]
        b = [rows_of(c, other) for c in conns]
    except Exception:  # noqa: BLE001
        return False
    return all(superset_result(x, y, False) or superset_result(y, x, False) or name_vs_id(x, y)
               for x, y in zip(a, b))


def leaks(question: str, names: set[str]) -> bool:
    return bool(LEAK.search(question)) or any(
        w.lower() in names for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]{2,}", question))


def load_raw() -> dict[str, list[dict]]:
    by_db = defaultdict(list)
    for p in sorted((R2 / "raw").glob("*.jsonl")):
        for line in p.read_text(encoding="utf-8").splitlines():
            if line.strip():
                r = json.loads(line)
                by_db[r["db"]].append(r)
    return by_db


def db_context(db: str, items: list[dict]):
    """同一个库的题共用一套数据:字面量从这个库全部 2025 条题里抠,和评测时的做法一样。"""
    ddl, conns = load_dbs(db, make_suite(db, [it["sql"] for it in items], 5))
    names = {n.lower() for (t,) in conns[0].execute("select name from sqlite_master where type='table'")
             for n in [t] + [c[1] for c in conns[0].execute(f'pragma table_info("{t}")')]}
    return ddl, conns, values_from_db(conns), names


def stage_blind(key: str) -> None:
    cache = cache_load()
    by_db = load_raw()
    ctx = {db: db_context(db, items) for db, items in by_db.items()}
    nonempty = {}
    for db, items in by_db.items():
        for it in items:
            try:
                nonempty[id(it)] = sum(bool(rows_of(c, it["sql"])) for c in ctx[db][1])
            except Exception:  # noqa: BLE001
                nonempty[id(it)] = -1

    def msgs(db, it):
        ddl, _, values, _ = ctx[db]
        return build(ddl, it["question"], values)

    chat = {}
    for db, items in by_db.items():
        for it in items:
            if nonempty[id(it)] > 0:
                p = payload_for("deepseek-chat", msgs(db, it))
                chat[id(it)] = (keyof(p), p)
    ask_all(dict(chat.values()), cache, key)

    reason = {}
    for db, items in by_db.items():
        for it in items:
            if id(it) in chat:
                k = chat[id(it)][0]
                if k in cache and not agree(it["sql"], extract_sql(cache[k]), ctx[db][1]):
                    p = payload_for("deepseek-reasoner", msgs(db, it))
                    reason[id(it)] = (keyof(p), p)
    ask_all(dict(reason.values()), cache, key, workers=24)

    stat = Counter()
    with REPORT.open("w", encoding="utf-8") as f:
        for db, items in by_db.items():
            conns, names = ctx[db][1], ctx[db][3]
            for it in items:
                row = dict(it, nonempty=nonempty[id(it)], leak=leaks(it["question"], names))
                ck = chat.get(id(it), (None,))[0]
                rk = reason.get(id(it), (None,))[0]
                row["chat_sql"] = extract_sql(cache[ck]) if ck in cache else None
                row["chat_ok"] = bool(row["chat_sql"]) and agree(it["sql"], row["chat_sql"], conns)
                row["reasoner_sql"] = extract_sql(cache[rk]) if rk in cache else None
                row["reasoner_ok"] = bool(row["reasoner_sql"]) and agree(it["sql"], row["reasoner_sql"], conns)
                both_other = (row["chat_sql"] and row["reasoner_sql"] and not row["chat_ok"]
                              and agree(row["chat_sql"], row["reasoner_sql"], conns))
                if nonempty[id(it)] <= 0:
                    row["verdict"] = "empty" if nonempty[id(it)] == 0 else "error"
                elif ck not in cache or (not row["chat_ok"] and rk not in cache):
                    row["verdict"] = "pending"  # 还没问到,重跑
                elif row["chat_ok"]:
                    row["verdict"] = "keep_chat"
                elif row["reasoner_ok"]:
                    row["verdict"] = "keep_reasoner"
                else:
                    row["verdict"] = "drop_gold_suspect" if both_other else "drop_disagree"
                stat[row["verdict"]] += 1
                stat["leak"] += row["leak"]
                f.write(json.dumps(row, ensure_ascii=False) + "\n")
    print(dict(stat))


def kept_rows() -> list[dict]:
    rows = [json.loads(l) for l in REPORT.read_text(encoding="utf-8").splitlines() if l.strip()]
    return [r for r in rows if r["verdict"].startswith("keep")]


def stage_rewrite(key: str) -> None:
    cache = cache_load()
    kept = kept_rows()
    by_db = load_raw()
    ctx = {db: db_context(db, items) for db, items in by_db.items()}
    attempts = 2  # 原题有泄露的只能靠改写留下来,多给一次机会

    def rw_payload(r, n):
        msg = [{"role": "system", "content": "你只输出 JSON。"},
               {"role": "user", "content": REWRITE_PROMPT.format(question=r["question"], sql=r["sql"])}]
        return payload_for("deepseek-chat", msg, temperature=0.7 + 0.3 * n, json_out=True)

    results = {i: None for i in range(len(kept))}
    for n in range(attempts):
        jobs = {}
        for i, r in enumerate(kept):
            if results[i] is None and (n == 0 or r["leak"]):
                p = rw_payload(r, n)
                jobs[keyof(p, f"rw{n}")] = p
        ask_all(jobs, cache, key)
        blind = {}
        cand = {}
        for i, r in enumerate(kept):
            if results[i] is not None or not (n == 0 or r["leak"]):
                continue
            k = keyof(rw_payload(r, n), f"rw{n}")
            try:
                q = json.loads(cache[k])["question"].strip()
            except Exception:  # noqa: BLE001
                continue
            ddl, conns, values, names = ctx[r["db"]]
            if len(q) < 6 or leaks(q, names) or re.sub(r"\W", "", q) == re.sub(r"\W", "", r["question"]):
                continue
            p = payload_for("deepseek-chat", build(ddl, q, values))
            blind[i] = (keyof(p), p)
            cand[i] = q
        ask_all(dict(blind.values()), cache, key)
        for i, (k, _) in blind.items():
            r = kept[i]
            if k in cache and agree(r["sql"], extract_sql(cache[k]), ctx[r["db"]][1]):
                results[i] = cand[i]

    stat = Counter()
    with REWRITES.open("w", encoding="utf-8") as f:
        for i, r in enumerate(kept):
            stat["ok" if results[i] else "fail"] += 1
            stat["leak_saved" if r["leak"] and results[i] else "leak_lost" if r["leak"] else "_"] += 1
            if results[i]:
                f.write(json.dumps({"db": r["db"], "question": results[i], "sql": r["sql"], "src": r["question"],
                                    "difficulty": r["difficulty"], "type": r["type"]}, ensure_ascii=False) + "\n")
    stat.pop("_", None)
    print(dict(stat))


def stage_apply() -> None:
    kept = kept_rows()
    para = [json.loads(l) for l in REWRITES.read_text(encoding="utf-8").splitlines() if l.strip()]
    out = ROOT / "data" / "new"
    fields = ("db", "question", "sql", "difficulty", "type")
    for db in sorted({r["db"] for r in kept}):
        orig = [{k: r[k] for k in fields} for r in kept if r["db"] == db and not r["leak"]]
        rw = [r for r in para if r["db"] == db]
        (out / f"{db}_r2.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in orig),
                                           encoding="utf-8")
        (out / f"{db}_r2_para.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rw),
                                                encoding="utf-8")
        print(f"{db}: 原题 {len(orig)},改写 {len(rw)}")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("stage", choices=["blind", "rewrite", "apply"])
    args = ap.parse_args()
    if args.stage == "apply":
        stage_apply()
    else:
        (stage_blind if args.stage == "blind" else stage_rewrite)(api_key())


if __name__ == "__main__":
    main()