""" 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" # existing v3 data (sel) V3_COND = "data/sft-validator-condition-v3" # existing v3 data (cond) 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 " " 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 " "... 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") # Subquery difference 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"" 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 = [] # JOIN count 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"\nCONDITION.\n{detail}\n" NONE_SEL = "" NONE_COND = "\nCONDITION.\nNone\n" def build_prompt(instr, schema, question, evidence, sql, exec_str): # Field labels must match run_pipeline_rollouts.py VALIDATOR_PROMPT_BODY exactly. 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) # "chosen" key for train_fixer_v2.py compatibility; "completion" for legacy 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: # POSITIVE: SQL is correct 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: # NEGATIVE: exec_ok=True but wrong — semantic error 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: # NEGATIVE: exec error — clear signal err_msg = exec_str[:200] sel_crit = f"" cond_crit = f"\nCONDITION.\nSQL fails to execute: {err_msg}\n" 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)}") # Load existing v3 data and merge 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:] # Use train_dpo/test_dpo split names for train_fixer_v2.py compatibility 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()