File size: 29,304 Bytes
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
82ae30c
 
9b9fe74
 
82ae30c
 
9b9fe74
82ae30c
9b9fe74
82ae30c
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
9b9fe74
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
9b9fe74
 
 
 
82ae30c
 
 
9b9fe74
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
9b9fe74
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
82ae30c
 
9b9fe74
 
82ae30c
9b9fe74
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
 
 
 
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
9b9fe74
 
 
 
82ae30c
 
9b9fe74
 
 
 
 
 
 
82ae30c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
"""
Pipeline rollout driver for the 3-stage collaborative-ORPO experiment.

Three-stage pipeline:
    q  →  PLANNER (Qwen-Coder-0.5B SFT'd)         →  plan + first-cut SQL
       →  VALIDATOR (Qwen-Coder-0.5B SFT'd)        →  free-form critique (4 sections)
       →  FIXER (Qwen-Coder-0.5B SFT'd)            →  final SQL

For each input question we sample K planner outputs with stochastic decoding,
then for each planner output we sample K_val validator outputs, and for each
(planner, validator) we sample K_fix fixer outputs. Each leaf trajectory is
graded by execution of the fixer's final SQL.

The output JSONL is consumed by build_rl_data_collaborative.py to construct
preference pairs (planner-indep / planner-collab / validator-collab / fixer).

Usage:
    # Three vLLM endpoints, e.g.
    #   GPU 0:8100 = planner
    #   GPU 1:8101 = validator
    #   GPU 1:8102 = fixer    (can co-locate validator+fixer on one GPU since both 0.5B)
    python scripts/run_pipeline_rollouts.py \\
        --input_file data/sft_bird_with_evidence_train_text2sql.json \\
        --output_file data/rollouts/bird_train_3stage_K4.jsonl \\
        --planner_host http://localhost:8100 \\
        --validator_host http://localhost:8101 \\
        --fixer_host http://localhost:8102 \\
        --K 4 --K_val 2 --K_fix 1 \\
        --temperature 0.7 --top_p 0.9 \\
        --max_questions 1000
"""

import argparse
import json
import os
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Dict

# Bypass HTTP proxy for local vLLM endpoints
os.environ["NO_PROXY"] = "localhost,127.0.0.1"
os.environ["no_proxy"] = "localhost,127.0.0.1"

import requests
from tqdm import tqdm

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(ROOT)
sys.path.insert(0, ROOT)

from validator_data.validator import _execute_sql
from data_processing.planner import is_execution_correct

# Griffith NL schema lookup: populated by load_griffith_prompts() when --griffith_prompts is set.
# Maps question_lower -> griffith user message (full schema + evidence + question block).
_griffith_lookup: Dict[str, str] = {}
# When True, griffith prompts are also used for the planner (qwen format only).
# For llama3/thanhdath planner, keep old dict format since that's what it was trained on.
_griffith_for_planner: bool = False


def load_griffith_prompts(hf_cache: str = "/weka/s225250685/Huggingface/hub") -> None:
    """Load griffith-bigdata/bird_dev_prompts into _griffith_lookup."""
    from datasets import load_dataset
    global _griffith_lookup
    print("Loading griffith dev prompts from HF...", flush=True)
    ds = load_dataset("griffith-bigdata/bird_dev_prompts", cache_dir=hf_cache)
    split = list(ds.keys())[0]
    for row in ds[split]:
        msgs = row.get("messages", [])
        user_msg = msgs[1]["content"] if len(msgs) > 1 else ""
        if not user_msg:
            continue
        q = row.get("question", "").strip()
        if q:
            _griffith_lookup[q.lower()] = user_msg
    print(f"  griffith lookup: {len(_griffith_lookup)} dev questions", flush=True)


PLANNER_PROMPT_TEMPLATE = (
    "{schema}\n\n"
    "Question: {question}\n"
    "External knowledge: {evidence}\n\n"
    "Planning:"
)

# Validator prompt — must match what the validator was SFT'd to expect.
VALIDATOR_PROMPT_HEADER = (
    "You are a SQL critique agent. Output FOUR critique sections "
    "(<select>...</select>, <condition>...</condition>, <join>...</join>, <order>...</order>) "
    "analysing the SQL query below; do NOT output any SQL.\n\n"
)

# Specialized 2-validator headers — paper format (matches data_processing/generate_sft_data_for_validator.py).
# Both val-sel and val-cond share the same prompt; they differ only by their training completion
# (SELECT./CONDITION. leading token), so post-SFT each model auto-outputs its respective block.
VALIDATOR_SEL_HEADER = ""
VALIDATOR_COND_HEADER = ""

VALIDATOR_PROMPT_BODY = (
    "Generate feedbacks to fix the following SQL query:\n"
    "Database Schema:\n{schema}\n\n"
    "Question: {question}\n"
    "External knowledge: {evidence}\n\n"
    "SQL query: {sql_query}\n\n"
    "Execution response:\n{execution_response}\n\n"
    "Feedback:"
)

# Fixer prompt — must match what the fixer was SFT'd to expect.
FIXER_PROMPT_HEADER = (
    "You are a SQL fixer. Given the question, schema, original SQL query, "
    "execution response, and the validator's critique below, output ONLY the corrected "
    "final SQL inside ```sql ... ``` markers.\n\n"
)

# Exec-error fixer prompt — matches build_fixer_v2_execerr.py FIXER_PROMPT exactly.
# Used when planner_exec_ok=False so the exec-error fixer model sees the prompt
# format it was trained on (no validator critique, "Failed SQL" / "Execution error").
EXEC_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"
)

# Semantic fixer v3 prompt — for exec_ok=True but wrong trajectories.
SEMANTIC_FIXER_PROMPT = (
    "You are a SQL semantic fixer. The SQL below executes without errors but returns "
    "incorrect results for the given question. Analyze the execution result and the question "
    "carefully, then output ONLY a corrected SQL using ```sql ... ``` markers.\n\n"
    "Database schema:\n{schema}\n\n"
    "Question: {question}\n"
    "External knowledge: {evidence}\n\n"
    "SQL (executes but returns wrong results):\n{wrong_sql}\n\n"
    "Execution result (incorrect):\n{exec_result}\n"
)


def qwen_chat(prompt: str) -> str:
    return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"


def llama3_chat(prompt: str) -> str:
    """Llama-3 chat format used by thanhdath/orpo-llama-3b-iter-2-bird-planner."""
    return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n"
            f"{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n")


def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed=100):
    payload = {
        "model": model,
        "prompt": prompt,
        "max_tokens": max_tokens,
        "n": n,
        "temperature": temperature,
        "top_p": top_p,
        "stop": ["<|im_end|>", "<|endoftext|>"],
        "seed": seed,
    }
    for attempt in range(3):
        try:
            r = requests.post(f"{host}/v1/completions", json=payload, timeout=120)
            r.raise_for_status()
            return [c["text"] for c in r.json()["choices"]]
        except Exception as e:
            if attempt == 2:
                print(f"vLLM call failed: {e}", file=sys.stderr)
                return []
            time.sleep(1)
    return []


def extract_sql_from_planner(text):
    if text is None:
        return ""
    m = re.search(r"Final SQL query:\s*```(.+?)```", text, re.DOTALL)
    if m:
        s = m.group(1).strip()
    else:
        m = re.search(r"```(.+?)```", text, re.DOTALL)
        if m:
            s = m.group(1).strip()
        else:
            return text.strip()
    if s.startswith("sql"):
        s = s[3:].strip()
    return s


def extract_sql_from_fixer(text):
    if text is None:
        return ""
    m = re.search(r"```sql\s*\n?(.+?)```", text, re.DOTALL | re.IGNORECASE)
    if m:
        return m.group(1).strip()
    m = re.search(r"```(.+?)```", text, re.DOTALL)
    if m:
        s = m.group(1).strip()
        if s.lower().startswith("sql"):
            s = s[3:].strip()
        return s
    return text.strip().strip("`").strip()


def parse_validator_sections(text):
    sections = {"select": "", "condition": "", "join": "", "order": ""}
    for tag in sections:
        m = re.search(fr"<{tag}>(.*?)</{tag}>", text, re.DOTALL | re.IGNORECASE)
        if m:
            sections[tag] = m.group(1).strip()
    return sections


def safe_execute(db_path, sql):
    if not sql or sql.strip() == "":
        return ("", True)
    try:
        return _execute_sql("./" + db_path, sql)
    except Exception as e:
        return (str(e), True)


def build_planner_prompt(sample):
    q_key = sample.get("question", "").strip().lower()
    if _griffith_for_planner and _griffith_lookup and q_key in _griffith_lookup:
        # Use full griffith user message verbatim + "Planning:" trigger.
        # Matches Dataset C training format exactly (qwen planner only).
        return _griffith_lookup[q_key].rstrip() + "\n\nPlanning:"
    return PLANNER_PROMPT_TEMPLATE.format(
        schema=sample.get("schema_sequence") or sample.get("schema") or "",
        question=sample.get("question", ""),
        evidence=sample.get("evidence", "") or "None",
    )


def build_validator_prompt(sample, planner_sql, exec_response):
    body = VALIDATOR_PROMPT_BODY.format(
        schema=sample.get("schema_sequence") or sample.get("schema") or "",
        question=sample.get("question", ""),
        evidence=sample.get("evidence", "") or "None",
        sql_query=planner_sql,
        execution_response=exec_response,
    )
    return VALIDATOR_PROMPT_HEADER + body


def _build_paper_validator_body(sample, planner_sql, exec_response):
    """Build the paper-format 'Generate feedbacks...' prompt body. val-sel and val-cond share it."""
    # Prefer the griffith rich-NL schema (passed via 'user_msg' on rollout samples or schema_sequence).
    schema = sample.get("schema_sequence") or sample.get("schema") or ""
    if isinstance(schema, dict) or (isinstance(schema, str) and schema.startswith("{'")):
        # Schema came in as a parsed dict — fall back to schema_sequence string if available
        schema = sample.get("schema_sequence") or str(schema)
    return VALIDATOR_PROMPT_BODY.format(
        schema=schema,
        question=sample.get("question", ""),
        evidence=sample.get("evidence", "") or "None",
        sql_query=planner_sql,
        execution_response=exec_response,
    )


def build_validator_sel_prompt(sample, planner_sql, exec_response):
    return _build_paper_validator_body(sample, planner_sql, exec_response)


def build_validator_cond_prompt(sample, planner_sql, exec_response):
    return _build_paper_validator_body(sample, planner_sql, exec_response)


def build_fixer_prompt(sample, planner_sql, exec_response, critique):
    body = (
        f"database schema:\n{sample.get('schema_sequence') or sample.get('schema') or ''}\n\n"
        f"Question: {sample.get('question', '')}\n"
        f"External knowledge: {sample.get('evidence','') or 'None'}\n\n"
        f"Generated SQL query: {planner_sql}\n\n"
        f"Execution response:\n{exec_response}\n\n"
    )
    return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"


def build_exec_fixer_prompt(sample, failed_sql, exec_error):
    """Exec-error fixer prompt — matches fixer_prompt() format in mega_valfix_sft_griffith.sbatch.
    When griffith prompts are loaded, uses griffith user message verbatim (matching training).
    """
    q_key = sample.get('question', '').strip().lower()
    if _griffith_lookup and q_key in _griffith_lookup:
        gmsg = _griffith_lookup[q_key]
        # Match fixer_prompt() from valfix sbatch Stage A exactly.
        return ("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"
                + gmsg.rstrip()
                + "\n\nFailed SQL:\n" + failed_sql
                + "\n\nExecution error:\n" + exec_error + "\n")
    schema = sample.get('schema_sequence') or sample.get('schema') or ''
    return EXEC_FIXER_PROMPT.format(
        schema=schema,
        question=sample.get('question', ''),
        evidence=sample.get('evidence', '') or 'None',
        failed_sql=failed_sql,
        exec_error=exec_error,
    )


def process_sample(sample, args):
    db_path = sample["db_path"]
    gold_sql = sample["sql"]
    true_exec = safe_execute(db_path, gold_sql)
    if true_exec[1]:
        return None  # gold has error; skip

    # Stage 1: planner — K samples (optionally split across temperatures via --mixed_temp)
    planner_prompt_raw = build_planner_prompt(sample)
    _planner_fmt = getattr(args, "planner_format", "qwen")
    planner_chat = llama3_chat(planner_prompt_raw) if _planner_fmt == "llama3" else qwen_chat(planner_prompt_raw)
    if getattr(args, "mixed_temp", "").strip():
        temps = [float(x) for x in args.mixed_temp.split(",") if x.strip()]
        # distribute args.K samples across temperatures
        per_temp = max(1, args.K // len(temps))
        remainder = args.K - per_temp * len(temps)
        planner_outputs = []
        for i, t in enumerate(temps):
            n_t = per_temp + (1 if i < remainder else 0)
            if n_t <= 0:
                continue
            outs = vllm_complete(
                args.planner_host, "planner", planner_chat,
                n=n_t, temperature=t, top_p=args.top_p,
                max_tokens=args.max_planner_tokens, seed=args.seed + i * 31,
            )
            planner_outputs.extend(outs)
    else:
        planner_outputs = vllm_complete(
            args.planner_host, "planner", planner_chat,
            n=args.K, temperature=args.temperature, top_p=args.top_p,
            max_tokens=args.max_planner_tokens, seed=args.seed,
        )
    if not planner_outputs:
        return None

    trajectories = []
    for plan in planner_outputs:
        planner_sql = extract_sql_from_planner(plan)
        if not planner_sql:
            continue
        planner_exec = safe_execute(db_path, planner_sql)
        exec_response = (
            f"Error: {planner_exec[0]}" if planner_exec[1]
            else f"OK. Result rows (preview): {str(planner_exec[0])[:300]}"
        )

        # Stage 2: validator — K_val samples per planner output (or skip if validator_host empty)
        # Three modes:
        # (a) Two specialized validators: --validator_sel_host + --validator_cond_host (per-paper design)
        # (b) Legacy unified validator:    --validator_host (single 4-section model)
        # (c) None: insert all-OK placeholder
        v_sel = getattr(args, "validator_sel_host", "") or ""
        v_cond = getattr(args, "validator_cond_host", "") or ""
        if v_sel and v_sel.lower() != "none" and v_cond and v_cond.lower() != "none":
            sel_prompt = build_validator_sel_prompt(sample, planner_sql, exec_response)
            cond_prompt = build_validator_cond_prompt(sample, planner_sql, exec_response)
            sel_outputs = vllm_complete(
                v_sel, "validator_sel", qwen_chat(sel_prompt),
                n=args.K_val, temperature=args.temperature, top_p=args.top_p,
                max_tokens=args.max_validator_tokens, seed=args.seed,
            )
            cond_outputs = vllm_complete(
                v_cond, "validator_cond", qwen_chat(cond_prompt),
                n=args.K_val, temperature=args.temperature, top_p=args.top_p,
                max_tokens=args.max_validator_tokens, seed=args.seed + 1,
            )
            # Pair selection+condition outputs index-wise. Paper format: each output is
            # "SELECT.\n1. ... 4. Conclude: correct/incorrect." Wrap in legacy <select>/<condition>
            # tags before combining so the downstream fixer (trained on wrapper-tag critiques) sees
            # the format it expects.
            DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct."
            DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct."
            validator_outputs = []
            for i in range(args.K_val):
                s_out = sel_outputs[i].strip() if i < len(sel_outputs) else DEFAULT_SEL
                c_out = cond_outputs[i].strip() if i < len(cond_outputs) else DEFAULT_COND
                combined = (
                    f"<select>\n{s_out}\n</select>\n\n"
                    f"<condition>\n{c_out}\n</condition>\n\n"
                    "<join>\nJOIN.\nNone\n</join>\n\n"
                    "<order>\nORDER BY.\nNone\n</order>"
                )
                validator_outputs.append(combined)
            validator_prompt_raw = sel_prompt + "\n\n[+]\n\n" + cond_prompt  # for logging
        elif args.validator_host and args.validator_host.lower() != "none":
            validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
            validator_chat = qwen_chat(validator_prompt_raw)
            validator_outputs = vllm_complete(
                args.validator_host, "validator", validator_chat,
                n=args.K_val, temperature=args.temperature, top_p=args.top_p,
                max_tokens=args.max_validator_tokens, seed=args.seed,
            )
        else:
            validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
            validator_outputs = [
                "<select>\nSELECT.\nNone\n</select>\n\n"
                "<condition>\nCONDITION.\nNone\n</condition>\n\n"
                "<join>\nJOIN.\nNone\n</join>\n\n"
                "<order>\nORDER BY.\nNone\n</order>"
            ] * args.K_val

        for val_out in validator_outputs:
            sections = parse_validator_sections(val_out)
            critique_text = val_out.strip()  # full critique as the validator's "completion"

            planner_exec_ok = not planner_exec[1]
            # Stage 3a: exec-error fixer (fixer_host) — only on exec_ok=False trajectories when gate set.
            # Use EXEC_FIXER_PROMPT (no validator critique) to match fixer_v2 training format.
            gate_skip = getattr(args, "fixer_gate_exec_ok", False) and planner_exec_ok
            if getattr(args, "fixer_gate_exec_ok", False):
                # Exec-error fixer: standalone prompt matching training data format
                exec_error = exec_response  # "Error: ..." when exec_ok=False
                fixer_prompt_raw = build_exec_fixer_prompt(sample, planner_sql, exec_error)
            else:
                # Legacy mode (no gate): use full fixer prompt with validator critique
                fixer_prompt_raw = build_fixer_prompt(sample, planner_sql, exec_response, critique_text)
            if args.fixer_host and args.fixer_host.lower() != "none" and not gate_skip:
                fixer_chat = qwen_chat(fixer_prompt_raw)
                fixer_outputs = vllm_complete(
                    args.fixer_host, "fixer", fixer_chat,
                    n=args.K_fix, temperature=args.temperature, top_p=args.top_p,
                    max_tokens=args.max_fixer_tokens, seed=args.seed,
                )
            else:
                # Stage 3b: semantic fixer v3 — exec_ok=True AND validator flagged an issue.
                # Only runs if fixer_v3_host is set and validator output is non-trivial.
                fixer_v3_host = getattr(args, "fixer_v3_host", "") or ""
                def _is_ok(s):
                    s = s.lower().strip()
                    if "incorrect" in s: return False
                    return (not s or "none" in s or "no issues" in s
                            or "looks correct" in s or "is correct" in s or "correct." in s)
                no_gate = getattr(args, "sem_fixer_no_gate", False)
                validator_flagged = (
                    not _is_ok(sections.get("select", ""))
                    or not _is_ok(sections.get("condition", ""))
                )
                # Gate: no_gate=True → run on all exec_ok=True; no_gate=False → only when validator flags
                run_sem_fixer = (fixer_v3_host and fixer_v3_host.lower() != "none"
                                 and planner_exec_ok and (no_gate or validator_flagged))
                if run_sem_fixer:
                    # Format exec result for semantic fixer prompt
                    if planner_exec[1]:
                        exec_str = f"Error: {str(planner_exec[0])[:300]}"
                    else:
                        exec_str = f"Rows: {str(planner_exec[0])[:400]}"
                    sem_prompt = SEMANTIC_FIXER_PROMPT.format(
                        schema=sample.get("schema_sequence") or sample.get("schema", ""),
                        question=sample["question"],
                        evidence=sample.get("evidence", "") or "None",
                        wrong_sql=planner_sql,
                        exec_result=exec_str,
                    )
                    fixer_outputs = vllm_complete(
                        fixer_v3_host, "fixer_v3", qwen_chat(sem_prompt),
                        n=args.K_fix, temperature=args.temperature, top_p=args.top_p,
                        max_tokens=args.max_fixer_tokens, seed=args.seed + 7,
                    )
                    fixer_prompt_raw = sem_prompt  # log semantic prompt
                else:
                    fixer_outputs = [""] * args.K_fix  # keep planner_sql unchanged

            for fix_out in fixer_outputs:
                fixed_sql = extract_sql_from_fixer(fix_out) or planner_sql
                trajectories.append({
                    "planner_prompt": planner_prompt_raw,
                    "planner_output": plan,
                    "planner_sql": planner_sql,
                    "planner_exec_ok": not planner_exec[1],
                    "validator_prompt": validator_prompt_raw,
                    "validator_output": critique_text,
                    "fb_select": sections["select"],
                    "fb_condition": sections["condition"],
                    "fb_join": sections["join"],
                    "fb_order": sections["order"],
                    "fixer_prompt": fixer_prompt_raw,
                    "fixer_output": fix_out,
                    "fixed_sql": fixed_sql,
                })

    if not trajectories:
        return None

    # Grade each trajectory
    with ThreadPoolExecutor(max_workers=8) as exe:
        planner_execs = list(exe.map(
            lambda t: safe_execute(db_path, t["planner_sql"]), trajectories
        ))
        fixed_execs = list(exe.map(
            lambda t: safe_execute(db_path, t["fixed_sql"]), trajectories
        ))

    for i, t in enumerate(trajectories):
        pe, fe = planner_execs[i], fixed_execs[i]
        t["is_planner_correct"] = (
            (not pe[1]) and is_execution_correct(true_exec[0], pe[0])
        )
        t["is_fixed_correct"] = (
            (not fe[1]) and is_execution_correct(true_exec[0], fe[0])
        )

    return {
        "question": sample["question"],
        "evidence": sample.get("evidence", ""),
        "db_path": db_path,
        "db_id": sample.get("db_id", ""),
        "schema": sample.get("schema_sequence") or sample.get("schema") or "",
        "sql": gold_sql,
        "trajectories": trajectories,
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_file", required=True)
    parser.add_argument("--output_file", required=True)
    parser.add_argument("--planner_host", default="http://localhost:8100")
    parser.add_argument("--validator_host", default="http://localhost:8101",
                        help="Single unified validator host (legacy 4-section). "
                             "Ignored when --validator_sel_host AND --validator_cond_host are set.")
    parser.add_argument("--validator_sel_host", default="",
                        help="Specialized SELECT-clause validator host (paper v_s). "
                             "When both this and --validator_cond_host are set, the unified validator is bypassed.")
    parser.add_argument("--validator_cond_host", default="",
                        help="Specialized CONDITION validator host (paper v_c).")
    parser.add_argument("--fixer_host", default="http://localhost:8102")
    parser.add_argument("--fixer_gate_exec_ok", action="store_true",
                        help="Skip exec-error fixer when planner SQL already executes cleanly. "
                             "Prevents the fixer from breaking correct SQL (saves ~0.5pp pass@K).")
    parser.add_argument("--fixer_v3_host", default="",
                        help="Semantic fixer v3 host. By default runs only on exec_ok=True trajectories "
                             "flagged by the validator. Use --sem_fixer_no_gate to run on all exec_ok=True.")
    parser.add_argument("--sem_fixer_no_gate", action="store_true",
                        help="Run semantic fixer v3 on ALL exec_ok=True trajectories (no validator gate). "
                             "Requires --fixer_v3_host. Model must be trained with preserve pairs to "
                             "avoid corrupting correct SQL. Best oracle: +3-5pp vs gated (+1-2pp).")
    parser.add_argument("--planner_format", default="qwen",
                        choices=["qwen", "llama3"],
                        help="Chat template for the planner: 'qwen' (default) or 'llama3' (for thanhdath/orpo-llama-3b).")
    parser.add_argument("--K", type=int, default=4, help="planner samples per question")
    parser.add_argument("--K_val", type=int, default=2, help="validator samples per planner output")
    parser.add_argument("--K_fix", type=int, default=1, help="fixer samples per (planner, validator)")
    parser.add_argument("--temperature", type=float, default=0.7)
    parser.add_argument("--top_p", type=float, default=0.9)
    parser.add_argument("--seed", type=int, default=100)
    parser.add_argument("--max_planner_tokens", type=int, default=1024)
    parser.add_argument("--max_validator_tokens", type=int, default=512)
    parser.add_argument("--max_fixer_tokens", type=int, default=512)
    parser.add_argument("--max_questions", type=int, default=-1)
    parser.add_argument("--n_threads", type=int, default=8)
    parser.add_argument("--mixed_temp", type=str, default="",
                        help="Comma-separated temperatures to mix across K planner samples (e.g. '0.5,0.7,0.9,1.1'). "
                             "If set, args.temperature is ignored for the planner stage. Used to boost pass@K diversity.")
    parser.add_argument("--griffith_prompts", action="store_true",
                        help="Use griffith NL schema prompts (from griffith-bigdata/bird_dev_prompts) for the "
                             "planner (qwen format only), validators, and exec-error fixer. Required when the "
                             "planner/validators were SFT'd on griffith-format training data (Dataset C).")
    args = parser.parse_args()

    if args.griffith_prompts:
        load_griffith_prompts()
        global _griffith_for_planner
        # Only use griffith schema for the planner if it's the qwen planner (Dataset C training format).
        # The thanhdath/llama3 planner was trained on old dict schema — don't change its input.
        _griffith_for_planner = (args.planner_format == "qwen")

    print(f"Loading {args.input_file}...")
    with open(args.input_file) as f:
        data = json.load(f)
    if args.max_questions > 0:
        data = data[: args.max_questions]
    print(f"  {len(data)} questions")

    os.makedirs(os.path.dirname(args.output_file), exist_ok=True)

    seen = set()
    if os.path.exists(args.output_file):
        with open(args.output_file) as f:
            for line in f:
                try:
                    d = json.loads(line)
                    seen.add((d["question"], d.get("db_id", "")))
                except Exception:
                    pass
        print(f"  resuming: skip {len(seen)} already-processed")

    todo = [s for s in data if (s["question"], s.get("db_id", "")) not in seen]
    print(f"  to process: {len(todo)}")

    fout = open(args.output_file, "a")
    n_ok = 0
    n_winloss = 0

    with ThreadPoolExecutor(max_workers=args.n_threads) as pool:
        futures = {pool.submit(process_sample, s, args): s for s in todo}
        pbar = tqdm(total=len(todo), desc="rollouts")
        for fut in futures:
            try:
                result = fut.result()
            except Exception as e:
                print(f"sample failed: {e}", file=sys.stderr)
                pbar.update(1)
                continue
            if result is None:
                pbar.update(1)
                continue
            n_ok += 1
            wins = sum(1 for t in result["trajectories"] if t["is_fixed_correct"])
            losses = sum(1 for t in result["trajectories"] if not t["is_fixed_correct"])
            if wins > 0 and losses > 0:
                n_winloss += 1
            fout.write(json.dumps(result) + "\n")
            fout.flush()
            pbar.update(1)
            pbar.set_postfix(ok=n_ok, winloss=n_winloss)
        pbar.close()

    fout.close()
    print(f"Done. processed={n_ok}, with_winloss={n_winloss} ({100*n_winloss/max(n_ok,1):.1f}%)")


if __name__ == "__main__":
    main()