File size: 3,078 Bytes
57e38c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run SQL against a locked read-only DuckDB and classify the outcome. Also validates the benchmark: gold SQL must pass, naive SQL must fail silently.

Usage: python code/score.py validate

"""
from __future__ import annotations

import json
import re
import sys
import threading
from pathlib import Path

import duckdb

ROOT = Path(__file__).resolve().parents[1]
DB = ROOT / "data" / "geosql.duckdb"


def connect():
    c = duckdb.connect(str(DB), read_only=True)
    c.execute("LOAD spatial; SET geometry_always_xy=true; SET enable_external_access=false; SET lock_configuration=true;")
    return c


def extract_sql(text: str) -> str | None:
    t = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S)
    m = re.search(r"```(?:sql)?\s*(.*?)```", t, flags=re.S | re.I)
    s = (m.group(1) if m else t).strip().rstrip(";").strip()
    return s if re.match(r"(?is)^\s*(select|with)\b", s) else None


def run(con, sql: str, timeout: float = 20.0):
    out: dict = {}

    def work():
        try:
            out["rows"] = con.execute(sql).fetchall()
        except Exception as e:  # any SQL failure is a result to record
            out["error"] = f"{type(e).__name__}: {str(e)[:200]}"

    th = threading.Thread(target=work, daemon=True)
    th.start()
    th.join(timeout)
    if th.is_alive():
        con.interrupt()
        th.join(5)
        return None, "timeout"
    return out.get("rows"), out.get("error")


def classify(q: dict, rows, error) -> tuple[str, object]:
    if error:
        return ("timeout" if error == "timeout" else "sql_error"), None
    if not rows or not rows[0] or rows[0][0] is None:
        return "wrong_silent", None
    v = rows[0][0]
    if q["kind"] == "text":
        return ("correct" if str(v).strip() == q["answer"] else "wrong_silent"), str(v)
    try:
        n = float(v)
    except (TypeError, ValueError):
        return "wrong_silent", str(v)
    if q["kind"] == "int":
        return ("correct" if n == q["answer"] else "wrong_silent"), n
    return ("correct" if abs(n - q["answer"]) <= q["tolerance"] * abs(q["answer"]) else "wrong_silent"), n


def validate() -> None:
    con = connect()
    bad, naive_same, n = [], [], 0
    for line in open(ROOT / "data" / "questions.jsonl", encoding="utf-8"):
        q = json.loads(line)
        n += 1
        r, e = run(con, q["gold_sql"])
        c, v = classify(q, r, e)
        if c != "correct":
            bad.append((q["id"], c, v, q["answer"], e))
        if q["naive_sql"]:
            r, e = run(con, q["naive_sql"])
            c, v = classify(q, r, e)
            if c == "correct":
                naive_same.append((q["id"], v, q["answer"]))
            elif c != "wrong_silent":
                bad.append((q["id"], "naive-" + c, v, q["answer"], e))
    print("questions", n, "gold or naive problems", len(bad), "naive accidentally correct", len(naive_same))
    for b in bad[:12]:
        print(b)
    print(naive_same[:12])


if __name__ == "__main__":
    validate()