File size: 5,137 Bytes
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
"""
Compute Best-of-N metrics from a 3-stage pipeline rollout JSONL:
  - greedy:    EX of the first trajectory (K=1 baseline)
  - pass@N:    EX if ANY of the N trajectories is correct (oracle upper bound)
  - majority:  EX of the SQL whose execution result is the most common non-empty
               result among executable trajectories (rule-based selector,
               no extra trained selection agent needed).

Usage:
    python scripts/compute_bestofn_metrics.py <rollout.jsonl> <label>
"""
import json
import sys
import os
from collections import Counter
from concurrent.futures import ThreadPoolExecutor

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


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 hash_result(result):
    """Hash the execution result for majority voting (handles DataFrame, list, str, None)."""
    if result is None:
        return None
    try:
        # DataFrames need to be converted via .values to be hashable
        import pandas as pd
        if isinstance(result, pd.DataFrame):
            return str(tuple(map(tuple, result.values.tolist())))
    except Exception:
        pass
    return str(result)


def is_empty_result(result):
    """Check if execution result is effectively empty."""
    if result is None:
        return True
    try:
        import pandas as pd
        if isinstance(result, pd.DataFrame):
            return result.empty
    except Exception:
        pass
    s = str(result).strip()
    return s == "" or "(no rows)" in s or s == "[]"


def select_majority(traj_list, db_path):
    """
    Rule-based selector: among executable trajectories with NON-empty result,
    pick the SQL whose result hash is most common. Return (selected_sql, selected_idx).
    Tie-breaking: first by frequency, then by trajectory order.
    """
    candidates = []  # (idx, sql, result_hash, is_empty)
    for i, t in enumerate(traj_list):
        sql = t.get("fixed_sql") or t.get("planner_sql")
        if not sql or sql.strip() == "":
            continue
        exec_result, has_err = safe_execute(db_path, sql)
        if has_err:
            continue
        empty = is_empty_result(exec_result)
        candidates.append((i, sql, hash_result(exec_result), empty))

    if not candidates:
        # Nothing executable; fall back to first trajectory
        return traj_list[0].get("fixed_sql") or traj_list[0].get("planner_sql"), 0

    # Prefer non-empty results
    non_empty = [c for c in candidates if not c[3]]
    pool = non_empty if non_empty else candidates

    # Majority vote on result hash
    counter = Counter(c[2] for c in pool)
    best_hash, _ = counter.most_common(1)[0]
    # Pick the first trajectory with this hash
    for i, sql, h, _ in pool:
        if h == best_hash:
            return sql, i
    return pool[0][1], pool[0][0]


def main():
    if len(sys.argv) != 3:
        print("Usage: compute_bestofn_metrics.py <rollout.jsonl> <label>")
        sys.exit(1)

    rollout_path, label = sys.argv[1], sys.argv[2]

    n_q = 0
    n_greedy_correct = 0
    n_pass_at_N = 0
    n_majority_correct = 0
    K_used = None

    with open(rollout_path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            sample = json.loads(line)
            traj = sample.get("trajectories", [])
            if not traj:
                continue
            n_q += 1
            if K_used is None:
                K_used = len(traj)

            # Greedy = first trajectory's correctness
            if traj[0].get("is_fixed_correct"):
                n_greedy_correct += 1

            # pass@N = any trajectory correct
            if any(t.get("is_fixed_correct") for t in traj):
                n_pass_at_N += 1

            # Majority-vote selector
            db_path = sample["db_path"]
            gold_sql = sample["sql"]
            gold_exec = safe_execute(db_path, gold_sql)
            if gold_exec[1]:
                continue  # skip if gold has error

            selected_sql, _idx = select_majority(traj, db_path)
            sel_exec = safe_execute(db_path, selected_sql)
            if not sel_exec[1] and is_execution_correct(gold_exec[0], sel_exec[0]):
                n_majority_correct += 1

    if n_q == 0:
        print(f"{label}: no questions evaluated")
        return

    print()
    print(f"=== {label} ===")
    print(f"  questions evaluated: {n_q}")
    print(f"  K used per question: {K_used}")
    print(f"  greedy (1st traj):   {n_greedy_correct}/{n_q} = {100*n_greedy_correct/n_q:.2f}%")
    print(f"  selector-majority:   {n_majority_correct}/{n_q} = {100*n_majority_correct/n_q:.2f}%")
    print(f"  pass@{K_used} (oracle):    {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%")
    print()


if __name__ == "__main__":
    main()