mats-sql-bundle / code /scripts /analyse_selector_v5_failures.py
thanhdath's picture
Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)
778d47d verified
Raw
History Blame Contribute Delete
5.09 kB
"""
Phase 4 — Analyse selector v5 failures.
Reads: eval_results/v5_<label>_results.jsonl (from compute_bestofn_pairwise_v5.py)
Writes: stdout report + eval_results/v5_<label>_failures.jsonl
A "failure" = oracle@K is True AND selector pick is wrong (i.e. correct SQL was
in the candidate pool but the tournament dropped it). Each failure is tagged
with buckets:
B1 near-duplicate SQLs — chosen and correct differ by 1-2 tokens
B2 misleading exec rows — wrong SQL returns many rows but is incorrect
B3 schema ambiguity — multiple candidates use semantically similar columns
B4 aggregation/grouping mismatch — agg differs between chosen and correct
B5 date/time semantics — date/strftime present in correct but not chosen
B6 format-parse fail — no <answer> tag parsed in any tournament round
B8 other
"""
import argparse
import json
import os
import re
import sys
from collections import Counter
def tokens(sql):
return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
def jaccard(a, b):
if not a or not b:
return 0.0
return len(a & b) / max(len(a | b), 1)
def bucket(rec):
# Skip non-failures
if not rec.get("oracle_correct"):
return None
if rec.get("pick_correct"):
return None
chosen_sql = rec["pick_sql"]
correct_sqls = [s for s, ok in zip(rec["cand_sqls"], rec["cand_is_correct"]) if ok]
if not correct_sqls:
return None
buckets = []
# B1 near-duplicate
chosen_tok = tokens(chosen_sql)
sims = [jaccard(chosen_tok, tokens(c)) for c in correct_sqls]
if max(sims, default=0) >= 0.85:
buckets.append("B1_near_duplicate")
# B2 misleading rows: chosen has many rows ≠ correct exec
if "Rows preview" in (chosen_sql or "") or "rows" in chosen_sql.lower():
pass # rough check; need exec result for full check
# B4 aggregation mismatch
aggs = ("count", "sum", "avg", "min", "max", "group by")
chosen_has_agg = any(a in chosen_sql.lower() for a in aggs)
correct_has_agg = any(any(a in c.lower() for a in aggs) for c in correct_sqls)
if chosen_has_agg != correct_has_agg:
buckets.append("B4_aggregation")
# B5 date/time
date_kw = ("strftime", "date(", "datetime(", "julianday", " between '")
chosen_has_date = any(k in chosen_sql.lower() for k in date_kw)
correct_has_date = any(any(k in c.lower() for k in date_kw) for c in correct_sqls)
if chosen_has_date != correct_has_date:
buckets.append("B5_date_time")
# B6 format parse fail — check rounds_log for None decisions
rounds_log = rec.get("rounds_log", [])
if rounds_log:
all_decisions = []
for rnd in rounds_log:
for pair in rnd:
if isinstance(pair, list) and len(pair) >= 4 and pair[0] == "pair":
all_decisions.append(pair[3])
if all_decisions and all(d == -1 for d in all_decisions):
buckets.append("B6_parse_or_neither")
if not buckets:
buckets.append("B8_other")
return buckets
def main():
ap = argparse.ArgumentParser()
ap.add_argument("results_jsonl")
ap.add_argument("--top_n_per_bucket", type=int, default=5)
args = ap.parse_args()
rows = []
with open(args.results_jsonl) as f:
for line in f:
line = line.strip()
if line:
rows.append(json.loads(line))
n_total = len(rows)
n_oracle = sum(1 for r in rows if r.get("oracle_correct"))
n_pick = sum(1 for r in rows if r.get("pick_correct"))
print(f"== {args.results_jsonl} ==")
print(f" rows: {n_total} oracle@K: {n_oracle} pick: {n_pick}")
print(f" EX: {100*n_pick/max(n_total,1):.2f}% pick-rate (vs oracle): {100*n_pick/max(n_oracle,1):.2f}%")
failures = []
bucket_counts = Counter()
bucket_examples = {}
for r in rows:
b = bucket(r)
if b is None:
continue
failures.append({**r, "buckets": b})
for bb in b:
bucket_counts[bb] += 1
bucket_examples.setdefault(bb, []).append(r)
print(f"\nFailures (oracle ok, pick wrong): {len(failures)}")
for b, n in bucket_counts.most_common():
print(f" {b}: {n}")
print("\nExamples:")
for b, n in bucket_counts.most_common():
print(f"\n--- bucket {b} ({n}) ---")
for r in bucket_examples[b][: args.top_n_per_bucket]:
print(f"Q[{r.get('db_id','?')}]: {r.get('question','')[:140]}")
print(f" PICK : {r['pick_sql'][:200]}")
for c, ok in zip(r['cand_sqls'], r['cand_is_correct']):
if ok:
print(f" CORR : {c[:200]}")
break
print("")
# Save augmented file
out = args.results_jsonl.replace("_results.jsonl", "_failures.jsonl")
with open(out, "w") as f:
for r in failures:
f.write(json.dumps(r) + "\n")
print(f"Saved failure-tagged: {out}")
if __name__ == "__main__":
main()