| """ |
| Fixer v2 training data builder — targeted at exec_ok=False trajectories. |
| |
| Key insight from analysis (2026-05-15): |
| - 65.4% of BIRD-dev questions have ≥1 correct planner SQL (oracle pass@8) |
| - 22.5% of questions have NO correct planner AND have exec_ok=False trajectories |
| → Perfect fixer on exec-err cases would push pass@8 to 87.9% |
| |
| Training setup (ORPO): |
| prompt = fixer prompt with the WRONG SQL that has an exec error |
| chosen = any correct alternative SQL from the same question's K trajectories |
| rejected = the original wrong SQL (so model learns NOT to reproduce it) |
| |
| Filtering: |
| - Only use (wrong, correct) pairs where wrong trajectory has planner_exec_ok=False |
| - Both from the SAME question's rollout (natural hard pairs) |
| - Dedupe by normalized SQL |
| |
| Adds "preserve" pairs (exec_ok=True, already correct) only if requested — in |
| practice the --fixer_gate_exec_ok flag in run_pipeline_rollouts.py makes fixer |
| skip those cases entirely, so we omit them to keep data clean. |
| """ |
| import json, os, re, sys, random, sqlite3, threading |
| from datasets import Dataset, DatasetDict |
|
|
| ROOT = "/weka/s225250685/mats-tist" |
| os.chdir(ROOT); sys.path.insert(0, ROOT) |
|
|
| SRC_PATHS = [ |
| "data/rollouts/bird_train_3stage_K4.jsonl", |
| "data/rollouts/scaleup_bird_train_2stage_K4.jsonl", |
| "data/rollouts/scaleup_bird_train_3stage_K4.jsonl", |
| "data/rollouts/iter2_bird_train_3stage_K8.jsonl", |
| ] |
| OUT_DIR = "data/hf_fixer_v2_execerr" |
|
|
| FIXER_PROMPT = ( |
| "You are a SQL fixer. The SQL query below failed to execute. " |
| "Given the question, database schema, the failed SQL, and its error message, " |
| "output ONLY a corrected SQL that will execute successfully and correctly answer " |
| "the question. Use ```sql ... ``` markers.\n\n" |
| "database schema:\n{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "Failed SQL:\n{failed_sql}\n\n" |
| "Execution error:\n{exec_error}\n" |
| ) |
|
|
|
|
| def normalize_sql(sql): |
| return re.sub(r"\s+", " ", (sql or "").strip().lower()) |
|
|
|
|
| def safe_truncate(s, n=3500): |
| s = str(s) if s is not None else "" |
| return s if len(s) <= n else s[:n] + "..." |
|
|
|
|
| def _exec_with_timeout(db_path, sql, timeout=5): |
| """Execute SQL against db_path with a hard timeout (seconds). |
| Returns error string or None if no error (unexpected). |
| Returns "TIMEOUT" if execution hangs beyond timeout. |
| """ |
| result = [None] |
| error = [None] |
|
|
| def _run(): |
| try: |
| conn = sqlite3.connect(db_path) |
| conn.text_factory = lambda b: b.decode(errors="ignore") |
| conn.execute(sql) |
| 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 "TIMEOUT" |
| return error[0] |
|
|
|
|
| def get_exec_error(t, db_path=None, sql=None): |
| """Return error text for a trajectory known to have exec_ok=False. |
| Prefers stored response; falls back to re-executing against the DB to get |
| the real error message (avoids generic placeholder that hurts fixer training). |
| Re-execution has a 5-second timeout to avoid hanging on slow queries. |
| """ |
| resp = t.get("planner_exec_response") or t.get("exec_response") or "" |
| if isinstance(resp, str) and resp.strip(): |
| return safe_truncate(resp, 500) |
| |
| if db_path and sql and os.path.exists(db_path): |
| err = _exec_with_timeout(db_path, sql, timeout=5) |
| if err and err != "TIMEOUT": |
| return safe_truncate(err, 500) |
| return "RuntimeError: SQL execution failed (syntax error or unknown column/table)." |
|
|
|
|
| def main(): |
| rng = random.Random(42) |
| pairs = [] |
| seen = set() |
|
|
| for src in SRC_PATHS: |
| if not os.path.exists(src): |
| print(f"skip missing: {src}", flush=True) |
| continue |
| n_q = 0 |
| n_pairs = 0 |
| with open(src) as f: |
| for line in f: |
| line = line.strip() |
| if not line: continue |
| s = json.loads(line) |
| n_q += 1 |
| traj = s.get("trajectories", []) |
|
|
| |
| |
| gold_sql = (s.get("sql") or "").strip() |
| correct = [t for t in traj if t.get("is_planner_correct") or t.get("is_fixed_correct")] |
| exec_err = [t for t in traj if not t.get("planner_exec_ok") |
| and not t.get("is_planner_correct")] |
|
|
| if not exec_err or not gold_sql: |
| continue |
|
|
| schema = safe_truncate(str(s.get("schema", "")), 3000) |
| question = s.get("question", "") |
| evidence = s.get("evidence", "") or "None" |
|
|
| db_path = s.get("db_path", "") |
| if not os.path.exists(db_path): |
| db_id = s.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): |
| db_path = tmpl; break |
|
|
| |
| if correct: |
| best_correct = min(correct, key=lambda t: len(t.get("planner_sql") or t.get("fixed_sql") or "")) |
| good_sql = (best_correct.get("fixed_sql") or best_correct.get("planner_sql") or gold_sql).strip() |
| else: |
| good_sql = gold_sql |
| good_norm = normalize_sql(good_sql) |
|
|
| |
| for bad_t in exec_err: |
| bad_sql = (bad_t.get("planner_sql") or "").strip() |
| if not bad_sql: continue |
| bad_norm = normalize_sql(bad_sql) |
| if good_norm == bad_norm: continue |
|
|
| |
| key = (hash(question), bad_norm[:80]) |
| if key in seen: continue |
| seen.add(key) |
|
|
| exec_error_txt = get_exec_error(bad_t, db_path=db_path, sql=bad_sql) |
|
|
| prompt = FIXER_PROMPT.format( |
| schema=schema, question=question, evidence=evidence, |
| failed_sql=safe_truncate(bad_sql, 800), |
| exec_error=exec_error_txt, |
| ) |
| chosen_text = f"```sql\n{good_sql}\n```" |
| rejected_text = f"```sql\n{bad_sql}\n```" |
|
|
| pairs.append({ |
| "prompt": prompt, |
| "chosen": chosen_text, |
| "rejected": rejected_text, |
| "question": question, |
| "db_id": s.get("db_id", ""), |
| "db_path": s.get("db_path", ""), |
| }) |
| n_pairs += 1 |
|
|
| print(f" {src}: {n_q} questions, {n_pairs} new pairs (running total: {len(pairs)})", flush=True) |
|
|
| rng.shuffle(pairs) |
| n_test = max(100, len(pairs) // 20) |
| test, train = pairs[:n_test], pairs[n_test:] |
| print(f"\n=== Fixer v2 exec-err data ===") |
| print(f" train: {len(train)} ORPO pairs") |
| print(f" test: {len(test)} ORPO pairs") |
| print(f" avg prompt len: {sum(len(p['prompt']) for p in train)//max(len(train),1)} chars") |
|
|
| DatasetDict({ |
| "train_dpo": Dataset.from_list(train), |
| "test_dpo": Dataset.from_list(test), |
| }).save_to_disk(OUT_DIR) |
| print(f" saved → {OUT_DIR}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|