| """ |
| v8 — Build enriched-prompt pointwise data from BIRD-TRAIN paper-format rollouts. |
| |
| Enriched prompt contains: |
| - Rich schema (table/column descriptions, sample values, FKs) |
| - Question + evidence |
| - Candidate SQL |
| - Execution result (rows preview) |
| - Validator critique (fb_select / fb_condition / fb_join / fb_order) |
| - Planner reasoning trace (planner_output, first ~400 chars) |
| - Structural hints: has LIMIT?, GROUP BY?, JOINs count, DISTINCT, aggregate functions |
| |
| Output: HF DatasetDict at data/sft_selector_v8_pointwise_enriched/{train,test} |
| """ |
| import argparse, json, os, re, sys, random |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| os.environ.setdefault("PYTHONNOUSERSITE", "1") |
| os.environ.setdefault("DB_EXEC_API_DISABLE", "1") |
| ROOT = "/weka/s225250685/mats-tist" |
| os.chdir(ROOT); sys.path.insert(0, ROOT) |
| from validator_data.validator import _execute_sql |
| from datasets import Dataset, DatasetDict |
| from scripts.rich_schema import render_rich_schema |
|
|
| ENRICHED_PROMPT = ( |
| "You are a SQL correctness judge for the BIRD benchmark. Use ALL the " |
| "context below to decide if the candidate SQL is correct.\n\n" |
| "Database Schema:\n{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "Candidate SQL:\n{sql}\n\n" |
| "Execution result of the candidate:\n{exec_result}\n\n" |
| "Structural features of the candidate:\n{struct}\n\n" |
| "Validator critique of the planner draft:\n" |
| " - select: {fb_select}\n" |
| " - condition: {fb_condition}\n" |
| " - join: {fb_join}\n" |
| " - order: {fb_order}\n\n" |
| "Planner reasoning (excerpt):\n{planner_excerpt}\n\n" |
| "Does this SQL correctly answer the question? Answer YES or NO." |
| ) |
| MAX_SCHEMA_CHARS = 2500 |
|
|
|
|
| def safe_truncate(s, n): |
| s = str(s) if s is not None else "" |
| return s if len(s) <= n else s[:n] + "..." |
|
|
|
|
| def exec_str_for(db_path, sql, timeout=8): |
| if not sql or not sql.strip(): return "Error: empty SQL" |
| try: |
| r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout) |
| except Exception as e: |
| return f"Error: {str(e)[:160]}" |
| if err: return f"Error: {str(r)[:160]}" |
| rows = str(r)[:260] |
| return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)" |
|
|
|
|
| def struct_features(sql): |
| sl = sql.lower() |
| feats = [] |
| if " distinct" in sl or "distinct " in sl: feats.append("uses DISTINCT") |
| if " limit " in sl or sl.endswith("limit"): feats.append("uses LIMIT") |
| if " group by " in sl: feats.append("uses GROUP BY") |
| if " order by " in sl: feats.append("uses ORDER BY") |
| if " having " in sl: feats.append("uses HAVING") |
| n_joins = sl.count(" join ") |
| if n_joins > 0: feats.append(f"{n_joins} JOIN(s)") |
| aggs = [] |
| for a in ("count(", "sum(", "avg(", "max(", "min("): |
| if a in sl: aggs.append(a.rstrip("(")) |
| if aggs: feats.append("aggregates: " + ", ".join(aggs)) |
| if " is null" in sl: feats.append("uses IS NULL") |
| if "strftime" in sl or " date(" in sl or " datetime(" in sl: feats.append("uses date functions") |
| if "cast(" in sl: feats.append("uses CAST") |
| return "; ".join(feats) if feats else "(plain SELECT)" |
|
|
|
|
| def render(sample, t, schema_text): |
| sql_fixed = (t.get("fixed_sql") or "").strip() |
| sql = sql_fixed or (t.get("planner_sql") or "").strip() |
| if not sql: return None |
| is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct")) |
| ex = exec_str_for(sample["db_path"], sql) |
| label = "YES" if is_correct else "NO" |
| planner_out = (t.get("planner_output") or "").strip() |
| |
| planner_excerpt = safe_truncate(re.sub(r"\s+", " ", planner_out), 400) |
| prompt = ENRICHED_PROMPT.format( |
| schema=schema_text, |
| question=sample.get("question", ""), |
| evidence=sample.get("evidence", "") or "None", |
| sql=safe_truncate(sql, 700), |
| exec_result=safe_truncate(ex, 260), |
| struct=struct_features(sql), |
| fb_select=safe_truncate(t.get("fb_select") or "None", 180), |
| fb_condition=safe_truncate(t.get("fb_condition") or "None", 180), |
| fb_join=safe_truncate(t.get("fb_join") or "None", 180), |
| fb_order=safe_truncate(t.get("fb_order") or "None", 180), |
| planner_excerpt=planner_excerpt or "None", |
| ) |
| return { |
| "prompt": prompt, |
| "completion": label, |
| "messages": [{"role": "user", "content": prompt}, {"role": "assistant", "content": label}], |
| "question": sample.get("question", ""), |
| "db_id": sample.get("db_id", ""), |
| "is_yes": int(label == "YES"), |
| "sql": sql, |
| } |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--input", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl") |
| ap.add_argument("--out", default="data/sft_selector_v8_pointwise_enriched") |
| args = ap.parse_args() |
|
|
| rng = random.Random(42) |
| schema_cache = {} |
| n_rows = 0 |
|
|
| |
| jobs = [] |
| with open(args.input) as f: |
| for line in f: |
| line = line.strip() |
| if not line: continue |
| s = json.loads(line) |
| n_rows += 1 |
| seen = set() |
| for t in s.get("trajectories", []): |
| sql_fixed = (t.get("fixed_sql") or "").strip() |
| sql = sql_fixed or (t.get("planner_sql") or "").strip() |
| if not sql: continue |
| norm = re.sub(r"\s+", " ", sql.lower()) |
| if norm in seen: continue |
| seen.add(norm) |
| jobs.append((s, t)) |
| print(f"questions: {n_rows}, jobs: {len(jobs)}", flush=True) |
|
|
| for s, _ in jobs: |
| key = s["db_id"] |
| if key not in schema_cache: |
| schema_cache[key] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS) |
|
|
| records = [] |
| n_yes = n_no = 0 |
| n_done = 0 |
| def _job(it): |
| s, t = it |
| return render(s, t, schema_cache[s["db_id"]]) |
| with ThreadPoolExecutor(max_workers=32) as exe: |
| futs = [exe.submit(_job, it) for it in jobs] |
| for fut in as_completed(futs): |
| try: |
| r = fut.result() |
| except Exception: |
| continue |
| n_done += 1 |
| if r is None: continue |
| records.append(r) |
| if r["is_yes"]: n_yes += 1 |
| else: n_no += 1 |
| if n_done % 2000 == 0: |
| print(f" rendered {n_done}/{len(jobs)} records={len(records)} (Y={n_yes}, N={n_no})", flush=True) |
| print(f"\nTotal: {len(records)} (Y={n_yes}, N={n_no})", flush=True) |
|
|
| |
| print("Injecting gold candidates...", flush=True) |
| |
| by_q = {} |
| for r in records: |
| by_q.setdefault((r["question"], r["db_id"]), []).append(r) |
|
|
| |
| gold_added = 0 |
| with open(args.input) as f: |
| for line in f: |
| line = line.strip() |
| if not line: continue |
| s = json.loads(line) |
| existing = by_q.get((s.get("question",""), s.get("db_id",""))) |
| if not existing: continue |
| gold_norm = re.sub(r"\s+", " ", (s.get("sql") or "").strip().lower()) |
| if not gold_norm: continue |
| already = any(re.sub(r"\s+", " ", r["sql"].lower()) == gold_norm for r in existing) |
| if already: continue |
| ex = exec_str_for(s["db_path"], s["sql"]) |
| if ex.startswith("Error"): continue |
| |
| t_synth = { |
| "planner_sql": s["sql"], "fixed_sql": "", |
| "is_planner_correct": True, "is_fixed_correct": False, |
| "planner_exec_ok": True, |
| "fb_select": "None", "fb_condition": "None", "fb_join": "None", "fb_order": "None", |
| "planner_output": "(gold reference)", |
| } |
| schema_text = schema_cache[s["db_id"]] |
| rec = render(s, t_synth, schema_text) |
| if rec: |
| records.append(rec) |
| n_yes += 1 |
| gold_added += 1 |
| print(f"gold injected: {gold_added}", flush=True) |
|
|
| |
| yes_r = [r for r in records if r["is_yes"]] |
| no_r = [r for r in records if not r["is_yes"]] |
| rng.shuffle(no_r) |
| keep_no = no_r[: min(len(no_r), int(1.2 * len(yes_r)))] |
| final = yes_r + keep_no |
| rng.shuffle(final) |
| print(f"balanced: {len(final)} (Y={len(yes_r)}, N={len(keep_no)})", flush=True) |
|
|
| by_q = {} |
| for r in final: |
| by_q.setdefault(r["question"], []).append(r) |
| qs = list(by_q.keys()); rng.shuffle(qs) |
| n_test_q = max(40, len(qs) // 25) |
| test_qs = set(qs[:n_test_q]) |
| train, test = [], [] |
| for q, recs in by_q.items(): |
| (test if q in test_qs else train).extend(recs) |
| rng.shuffle(train); rng.shuffle(test) |
| |
| for r in train + test: |
| r.pop("sql", None) |
| print(f"train: {len(train)} test: {len(test)}") |
| DatasetDict({ |
| "train": Dataset.from_list(train), |
| "test": Dataset.from_list(test), |
| }).save_to_disk(args.out) |
| print(f"SAVED: {args.out}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|