| """ |
| Validator v4 training data builder — augments v3 data with semantic-error negatives. |
| |
| Problem: v3 validators have ~5.8% flagging rate on exec_ok=True wrong SQL. |
| Fix: add exec_ok=True wrong trajectories as negatives with heuristic critiques. |
| |
| Output format: same as v3 (select/condition sections) for pipeline compatibility. |
| """ |
| import json, os, re, random, sqlite3, threading |
| from datasets import load_from_disk, Dataset, DatasetDict |
|
|
| ROOT = "/weka/s225250685/mats-tist" |
| os.chdir(ROOT) |
|
|
| SRC_PATHS = [ |
| "data/rollouts/scaleup_bird_train_2stage_K4.jsonl", |
| "data/rollouts/bird_train_3stage_K4.jsonl", |
| "data/rollouts/iter2_bird_train_3stage_K8.jsonl", |
| ] |
|
|
| V3_DATA = "data/sft-validator-selection-v3" |
| V3_COND = "data/sft-validator-condition-v3" |
| OUT_SEL = "data/hf_validator_v4_sel" |
| OUT_COND = "data/hf_validator_v4_cond" |
|
|
| SEL_INSTR = ("You are a SQL SELECT-clause critique agent. Output ONE critique section " |
| "<select>...</select> analysing the SELECT clause of the SQL query below; " |
| "do NOT output any SQL. Use 'None' if the SELECT clause looks correct.") |
| COND_INSTR = ("You are a SQL CONDITION critique agent. Output ONE critique section " |
| "<condition>...</condition> analysing the WHERE/HAVING/CASE-WHEN conditions " |
| "of the SQL query below; do NOT output any SQL. Use 'None' if the conditions look correct.") |
|
|
|
|
| def resolve_db_path(d): |
| db_path = d.get("db_path", "") |
| if db_path and os.path.exists(db_path): |
| return db_path |
| db_id = d.get("db_id", "") |
| for tmpl in [ |
| f"data/train_databases/{db_id}/{db_id}.sqlite", |
| f"data/dev_databases/{db_id}/{db_id}.sqlite", |
| ]: |
| if os.path.exists(tmpl): |
| return tmpl |
| return None |
|
|
|
|
| def exec_sql(db_path, sql, timeout=5): |
| result = [None]; error = [None] |
| def _run(): |
| try: |
| conn = sqlite3.connect(db_path) |
| conn.text_factory = lambda b: b.decode(errors="ignore") |
| result[0] = conn.execute(sql).fetchmany(5) |
| conn.close() |
| except Exception as e: |
| error[0] = str(e) |
| t = threading.Thread(target=_run, daemon=True) |
| t.start(); t.join(timeout) |
| if t.is_alive(): |
| return None, "TIMEOUT" |
| return result[0], error[0] |
|
|
|
|
| def generate_select_critique(wrong_sql, gold_sql): |
| """Generate specific SELECT critique. Top errors from analysis: |
| DISTINCT mismatch (25.7%), aggregation mismatch (25.5%), subquery diff (12%).""" |
| wl, gl = wrong_sql.lower(), gold_sql.lower() |
| issues = [] |
| for agg in ["count(", "sum(", "avg(", "max(", "min("]: |
| if agg in gl and agg not in wl: |
| issues.append(f"Missing {agg[:-1].upper()} in SELECT") |
| elif agg in wl and agg not in gl: |
| issues.append(f"Unexpected {agg[:-1].upper()} in SELECT") |
| if "distinct" in gl and "distinct" not in wl: |
| issues.append("Missing DISTINCT — query returns duplicate rows") |
| elif "distinct" in wl and "distinct" not in gl: |
| issues.append("Unexpected DISTINCT — query incorrectly deduplicates") |
| |
| gs, ws = gl.count("select") - 1, wl.count("select") - 1 |
| if gs > ws: |
| issues.append(f"Missing subquery (gold has {gs}, wrong has {ws})") |
| elif ws > gs: |
| issues.append(f"Unexpected subquery (gold has {gs}, wrong has {ws})") |
| if issues: |
| detail = "INCORRECT: " + "; ".join(issues) + "." |
| else: |
| detail = "INCORRECT: SELECT clause returns wrong results for this question." |
| return f"<select>\nSELECT.\n{detail}\n</select>" |
|
|
|
|
| def generate_condition_critique(wrong_sql, gold_sql): |
| """Generate specific CONDITION critique. Top errors: JOIN mismatch (30%), |
| GROUP BY (6.9%), ORDER BY (8.3%), LIMIT (7.8%), subtle conditions (30.6%).""" |
| wl, gl = wrong_sql.lower(), gold_sql.lower() |
| issues = [] |
| |
| gj, wj = gl.count("join"), wl.count("join") |
| if gj > wj: |
| issues.append(f"Missing JOIN (gold has {gj}, wrong has {wj})") |
| elif wj > gj: |
| issues.append(f"Extra JOIN (gold has {gj}, wrong has {wj})") |
| if "group by" in gl and "group by" not in wl: |
| issues.append("Missing GROUP BY clause") |
| elif "group by" in wl and "group by" not in gl: |
| issues.append("Unexpected GROUP BY clause") |
| if "having" in gl and "having" not in wl: |
| issues.append("Missing HAVING clause") |
| if ("order by" in gl) != ("order by" in wl): |
| issues.append("ORDER BY mismatch") |
| if ("limit" in gl) != ("limit" in wl): |
| issues.append("LIMIT clause mismatch") |
| if issues: |
| detail = "INCORRECT: " + "; ".join(issues) + "." |
| else: |
| detail = "INCORRECT: WHERE/HAVING conditions return wrong results for this question." |
| return f"<condition>\nCONDITION.\n{detail}\n</condition>" |
|
|
|
|
| NONE_SEL = "<select>\nSELECT.\nNone\n</select>" |
| NONE_COND = "<condition>\nCONDITION.\nNone\n</condition>" |
|
|
|
|
| def build_prompt(instr, schema, question, evidence, sql, exec_str): |
| |
| body = (f"database schema:\n{schema}\n\nQuestion: {question}\n" |
| f"External knowledge: {evidence or 'None'}\n\nGenerated SQL query: {sql}\n\nExecution response:\n{exec_str}\n\n") |
| return instr + "\n\n" + body |
|
|
|
|
| def make_row(instr, schema, question, evidence, sql, exec_str, completion): |
| prompt = build_prompt(instr, schema, question, evidence, sql, exec_str) |
| |
| return {"prompt": prompt, "chosen": completion, "completion": completion, |
| "messages": {"prompt": prompt, "completion": completion}} |
|
|
|
|
| def safe_trunc(s, n=3000): |
| s = str(s or "") |
| return s if len(s) <= n else s[:n] + "..." |
|
|
|
|
| def main(): |
| rng = random.Random(42) |
| new_sel, new_cond = [], [] |
| seen = set() |
|
|
| for src in SRC_PATHS: |
| if not os.path.exists(src): |
| print(f"skip {src}"); continue |
| n_pos = n_neg = 0 |
| with open(src) as f: |
| for line in f: |
| line = line.strip() |
| if not line: continue |
| d = json.loads(line) |
| db_path = resolve_db_path(d) |
| if not db_path: continue |
| schema = safe_trunc(str(d.get("schema", "")), 2800) |
| question = d.get("question", "") |
| evidence = d.get("evidence", "") or "None" |
| gold_sql = (d.get("sql") or "").strip() |
|
|
| for t in d.get("trajectories", []): |
| sql = (t.get("planner_sql") or "").strip() |
| if not sql: continue |
| correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct")) |
| exec_ok = bool(t.get("planner_exec_ok", True)) |
| key = (hash(question), sql[:60]) |
| if key in seen: continue |
| seen.add(key) |
|
|
| rows, err = exec_sql(db_path, sql) |
| if rows is not None: |
| exec_str = "OK. Rows: " + str(rows)[:300] |
| elif err: |
| exec_str = "Error: " + err[:200] |
| else: |
| exec_str = "No result" |
|
|
| if correct and exec_ok: |
| |
| r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, NONE_SEL) |
| r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, NONE_COND) |
| new_sel.append(r_sel) |
| new_cond.append(r_cond) |
| n_pos += 1 |
|
|
| elif not correct and exec_ok and gold_sql: |
| |
| sel_crit = generate_select_critique(sql, gold_sql) |
| cond_crit = generate_condition_critique(sql, gold_sql) |
| r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, sel_crit) |
| r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, cond_crit) |
| new_sel.append(r_sel) |
| new_cond.append(r_cond) |
| n_neg += 1 |
|
|
| elif not exec_ok: |
| |
| err_msg = exec_str[:200] |
| sel_crit = f"<select>\nSELECT.\nSQL fails to execute: {err_msg}\n</select>" |
| cond_crit = f"<condition>\nCONDITION.\nSQL fails to execute: {err_msg}\n</condition>" |
| r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, sel_crit) |
| r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, cond_crit) |
| new_sel.append(r_sel) |
| new_cond.append(r_cond) |
| n_neg += 1 |
|
|
| print(f" {src}: +{n_pos} pos, +{n_neg} neg") |
|
|
| print(f"\nNew rows — sel: {len(new_sel)}, cond: {len(new_cond)}") |
|
|
| |
| def load_v3(path): |
| d = load_from_disk(path) |
| rows = [] |
| for split in ["train", "test", "train_dpo", "test_dpo"]: |
| if split in d: |
| for ex in d[split]: |
| p, c = ex["prompt"], ex["completion"] |
| rows.append({"prompt": p, "chosen": c, "completion": c, |
| "messages": {"prompt": p, "completion": c}}) |
| return rows |
|
|
| v3_sel = load_v3(V3_DATA) |
| v3_cond = load_v3(V3_COND) |
| print(f"V3 existing — sel: {len(v3_sel)}, cond: {len(v3_cond)}") |
|
|
| combined_sel = v3_sel + new_sel |
| combined_cond = v3_cond + new_cond |
| rng.shuffle(combined_sel) |
| rng.shuffle(combined_cond) |
|
|
| def split_and_save(rows, out_dir): |
| n_test = max(200, len(rows) // 20) |
| test, train = rows[:n_test], rows[n_test:] |
| |
| DatasetDict({ |
| "train_dpo": Dataset.from_list(train), |
| "test_dpo": Dataset.from_list(test), |
| }).save_to_disk(out_dir) |
| print(f" saved {len(train)} train_dpo + {len(test)} test_dpo → {out_dir}") |
|
|
| split_and_save(combined_sel, OUT_SEL) |
| split_and_save(combined_cond, OUT_COND) |
| print("DONE") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|