File size: 9,645 Bytes
6285644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Build paper-format validator SFT data from planner-3B greedy predictions.

Reads:  data/planner_3B_greedy_bird_train.jsonl   (gen_planner_preds_for_validator.py output)
Writes: data/hf_val_sel_paper_v1, data/hf_val_cond_paper_v1   (HF DatasetDict {train, test})

Paper format (from data_processing/generate_sft_data_for_validator.py +
              validator_data/few_shot_prompt_select.txt):
  Prompt:
    Generate feedbacks to fix the following SQL query:
    {schema}                  # griffith rich NL schema (from user_msg)
    Question: {Q}
    External knowledge: {E}
    SQL query: {SQL}
    Execution response:
    {response}
    Feedback:
  Completion (val-sel):
    SELECT.
    1. Based on the SQL query, the query selects: [pred_cols]
    2. Based on the question, the query should select: [gold_cols]
    3. Compare 1. and 2., the SQL query <diff_text>.
    4. Conclude: <correct|incorrect>.
  Completion (val-cond): same shape, but CONDITION. + WHERE/HAVING content.

Conclusion is derived from EXECUTION CORRECTNESS (gold_exec == pred_exec):
  planner_correct=True  ⇒ Conclude: correct.
  planner_correct=False ⇒ Conclude: incorrect.

This deterministic approach mirrors how thanhdath/mats-sql-bundle/v3 was built (templated),
just with paper's Feedback+Conclude format instead of <select> wrapper tags.
"""
import argparse, json, os, re, random
os.environ.setdefault("PYTHONNOUSERSITE", "1")
import sqlparse
from datasets import Dataset, DatasetDict


def extract_select_clause(sql):
    """Return text between SELECT and FROM (or end if no FROM)."""
    if not sql: return ""
    m = re.search(r"\bSELECT\b\s+(.+?)\s+\bFROM\b", sql, re.IGNORECASE | re.DOTALL)
    if m: return _normalize_whitespace(m.group(1))
    m = re.search(r"\bSELECT\b\s+(.+)$", sql, re.IGNORECASE | re.DOTALL)
    return _normalize_whitespace(m.group(1)) if m else ""


def extract_where_clause(sql):
    """Return text between WHERE and (GROUP BY|ORDER BY|HAVING|LIMIT|end)."""
    if not sql: return ""
    m = re.search(r"\bWHERE\b\s+(.+?)(?=\s+\bGROUP\s+BY\b|\s+\bORDER\s+BY\b|\s+\bHAVING\b|\s+\bLIMIT\b|$)",
                  sql, re.IGNORECASE | re.DOTALL)
    return _normalize_whitespace(m.group(1)) if m else ""


def extract_having_clause(sql):
    if not sql: return ""
    m = re.search(r"\bHAVING\b\s+(.+?)(?=\s+\bORDER\s+BY\b|\s+\bLIMIT\b|$)",
                  sql, re.IGNORECASE | re.DOTALL)
    return _normalize_whitespace(m.group(1)) if m else ""


def _normalize_whitespace(s):
    return re.sub(r"\s+", " ", s.strip()) if s else ""


def _normalize_for_compare(s):
    """Lowercase + strip backticks + collapse whitespace, for clause equivalence check."""
    s = s.lower().replace("`", "").replace("\"", "")
    return _normalize_whitespace(s)


def build_select_completion(pred_sql, gold_sql, pred_err, planner_correct):
    """Generate paper-format SELECT-clause critique completion."""
    if pred_err and not pred_sql:
        return ("SELECT.\n"
                "1. The SQL query is empty or could not be extracted.\n"
                "2. Conclude: incorrect.")
    pred_sel = extract_select_clause(pred_sql)
    gold_sel = extract_select_clause(gold_sql)
    if pred_err:
        return (f"SELECT.\n"
                f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
                f"2. The SQL query fails to execute: {pred_err[:200]}\n"
                f"3. Conclude: incorrect.")
    if planner_correct or _normalize_for_compare(pred_sel) == _normalize_for_compare(gold_sel):
        return (f"SELECT.\n"
                f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
                f"2. Based on the question, the query should select: [{gold_sel}]\n"
                f"3. Compare 1. and 2., the SQL query selects correct columns.\n"
                f"4. Conclude: correct.")
    return (f"SELECT.\n"
            f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
            f"2. Based on the question, the query should select: [{gold_sel}]\n"
            f"3. Compare 1. and 2., the SQL query selects different columns than required.\n"
            f"4. Conclude: incorrect.")


def build_condition_completion(pred_sql, gold_sql, pred_err, planner_correct):
    """Generate paper-format CONDITION-clause (WHERE/HAVING) critique completion."""
    if pred_err and not pred_sql:
        return ("CONDITION.\n"
                "1. The SQL query is empty or could not be extracted.\n"
                "2. Conclude: incorrect.")
    pred_where = extract_where_clause(pred_sql)
    gold_where = extract_where_clause(gold_sql)
    pred_having = extract_having_clause(pred_sql)
    gold_having = extract_having_clause(gold_sql)
    pred_cond = (pred_where + (" HAVING " + pred_having if pred_having else "")) or "None"
    gold_cond = (gold_where + (" HAVING " + gold_having if gold_having else "")) or "None"
    if pred_err:
        return (f"CONDITION.\n"
                f"1. The SQL query uses conditions: [{pred_cond}]\n"
                f"2. The SQL query fails to execute: {pred_err[:200]}\n"
                f"3. Conclude: incorrect.")
    if planner_correct or _normalize_for_compare(pred_cond) == _normalize_for_compare(gold_cond):
        return (f"CONDITION.\n"
                f"1. The SQL query uses conditions: [{pred_cond}]\n"
                f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
                f"3. Compare 1. and 2., the SQL query uses correct conditions.\n"
                f"4. Conclude: correct.")
    return (f"CONDITION.\n"
            f"1. The SQL query uses conditions: [{pred_cond}]\n"
            f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
            f"3. Compare 1. and 2., the SQL query uses different conditions than required.\n"
            f"4. Conclude: incorrect.")


def build_prompt(user_msg, question, evidence, sql_query, exec_response):
    """Paper-format validator prompt: 'Generate feedbacks ... Feedback:'.
    Uses griffith rich NL schema (extracted from user_msg's 'Database Schema:' section)."""
    # user_msg contains "Database Schema:\n...\n\nQuestion: ...\n..." — extract schema portion
    if "Database Schema:" in user_msg:
        schema = user_msg.split("Database Schema:", 1)[1]
        # cut off at "Question:" if present
        if "Question:" in schema:
            schema = schema.split("Question:", 1)[0]
        schema = "Database Schema:" + schema.rstrip()
    else:
        schema = user_msg.rstrip()
    return (f"Generate feedbacks to fix the following SQL query:\n"
            f"{schema}\n\n"
            f"Question: {question}\n"
            f"External knowledge: {evidence}\n\n"
            f"SQL query: {sql_query}\n\n"
            f"Execution response:\n"
            f"{exec_response}\n\n"
            f"Feedback:")


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
    p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
    p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
    p.add_argument("--max_questions", type=int, default=-1)
    p.add_argument("--seed", type=int, default=42)
    args = p.parse_args()

    print(f"Reading {args.input}...", flush=True)
    rows = []
    with open(args.input) as f:
        for line in f:
            rows.append(json.loads(line))
    print(f"  loaded {len(rows)} predictions", flush=True)
    if args.max_questions > 0: rows = rows[:args.max_questions]

    sel_rows, cond_rows = [], []
    n_pred_correct = 0; n_pred_err = 0
    for r in rows:
        prompt = build_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
                              r["pred_sql"], r["pred_exec"])
        pred_err = r["pred_exec"].startswith("Error:") if r["pred_exec"] else True
        planner_correct = r.get("planner_correct", False)
        if planner_correct: n_pred_correct += 1
        if pred_err: n_pred_err += 1

        sel_comp = build_select_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)
        cond_comp = build_condition_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)

        sel_rows.append({"prompt": prompt, "completion": sel_comp})
        cond_rows.append({"prompt": prompt, "completion": cond_comp})

    print(f"\n  pred correct: {n_pred_correct} ({100*n_pred_correct/len(rows):.1f}%)")
    print(f"  pred error:   {n_pred_err} ({100*n_pred_err/len(rows):.1f}%)")
    print(f"  pred wrong:   {len(rows) - n_pred_correct - n_pred_err}")
    print()

    # 95/5 train/test split
    random.seed(args.seed)
    indices = list(range(len(sel_rows)))
    random.shuffle(indices)
    n_train = int(0.95 * len(indices))
    train_idx, test_idx = indices[:n_train], indices[n_train:]

    for name, data, out_path in [("val-sel", sel_rows, args.out_sel), ("val-cond", cond_rows, args.out_cond)]:
        train = [data[i] for i in train_idx]
        test = [data[i] for i in test_idx]
        # Distribution sanity
        n_correct = sum(1 for r in train if "Conclude: correct" in r["completion"])
        n_incorrect = sum(1 for r in train if "Conclude: incorrect" in r["completion"])
        print(f"  {name}: train={len(train)} test={len(test)}  "
              f"correct={n_correct} ({100*n_correct/len(train):.1f}%)  "
              f"incorrect={n_incorrect} ({100*n_incorrect/len(train):.1f}%)")
        DatasetDict({
            "train": Dataset.from_list(train),
            "test": Dataset.from_list(test),
        }).save_to_disk(out_path)
        print(f"   saved → {out_path}")


if __name__ == "__main__":
    main()