File size: 7,999 Bytes
778d47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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]  # None means no error (SQL succeeded — shouldn't happen here)


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)
    # Re-execute to get the actual error (with timeout)
    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()  # (question_hash, fail_norm)

    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", [])

                # Use gold SQL as fallback chosen — expands training data 4x
                # (previously only used questions where a correct planner SQL existed)
                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

                # Pick chosen SQL: prefer a correct in-question planner SQL, fall back to gold
                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 each failing trajectory, pair with the chosen correct 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

                    # Dedup by (question, bad_sql) — don't need to distinguish chosen
                    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()