File size: 10,583 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""
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 "
              "<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")
    # 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"<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 = []
    # 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"<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):
    # 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"<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)}")

    # 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()