File size: 5,590 Bytes
50bf486
 
 
2ef23a4
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef23a4
 
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef23a4
50bf486
 
 
 
 
2ef23a4
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef23a4
 
 
 
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
"""
Grading logic for submitted SQL queries.

We compute a 4-part reward score strictly between 0 and 1 (exclusive):
  - 0.15 for syntax (does it even parse?)
  - 0.55 for row-level F1 (how many right rows did you get?)
  - 0.20 exact match bonus (nailed it perfectly)
  - 0.10 efficiency bonus (task 3 only — did you actually optimize it?)

The idea is to give meaningful partial credit. Getting the syntax right
but the logic wrong should still earn *something*, and getting 90% of the
rows right is way better than getting 0%.
"""

from __future__ import annotations

import sqlite3
from typing import Any


def _run_query(conn: sqlite3.Connection, query: str) -> tuple[list[tuple], str | None]:
    """Try running a query. Returns the rows and an error string if it blew up."""
    try:
        cur = conn.cursor()
        cur.execute(query)
        return cur.fetchall(), None
    except Exception as e:
        return [], str(e)


def _stringify_rows(rows: list[tuple]) -> set[str]:
    """Turn rows into a set of strings so we can do set comparisons.

    Not the most elegant approach, but it handles mixed types cleanly
    and sidesteps the whole "are these floats equal enough" problem.
    """
    return {str(row) for row in rows}


def _compute_f1(result_set: set[str], expected_set: set[str]) -> float:
    """Standard F1 between two sets.

    If both are empty, that's technically a perfect match.
    """
    if not result_set and not expected_set:
        return 1.0
    if not result_set or not expected_set:
        return 0.0

    overlap = result_set & expected_set
    precision = len(overlap) / len(result_set)
    recall = len(overlap) / len(expected_set)

    if precision + recall == 0:
        return 0.0

    return 2 * precision * recall / (precision + recall)


def _check_query_plan_efficiency(conn: sqlite3.Connection, query: str) -> bool:
    """Look at EXPLAIN QUERY PLAN output and check for correlated subqueries.

    We mainly care about whether the optimizer is running a CORRELATED
    scalar subquery — that's the O(n²) pattern we're trying to eliminate.
    Scanning CTE results or small temp tables is fine; it's the correlated
    part that kills performance.
    """
    try:
        cur = conn.cursor()
        cur.execute(f"EXPLAIN QUERY PLAN {query}")
        plan_rows = cur.fetchall()
        plan_text = " ".join(str(row) for row in plan_rows)

        has_correlated = "CORRELATED" in plan_text.upper()

        # Also flag full scans on the base tables (not CTEs though)
        for row in plan_rows:
            detail = str(row).upper()
            if "SCAN" in detail:
                for table in ("USERS", "ORDERS ", "ORDER_ITEMS", "PRODUCTS"):
                    if f"SCAN {table.strip()}" in detail or f"SCAN TABLE {table.strip()}" in detail:
                        pass  # noted, but we only hard-fail on correlated for now

        return not has_correlated
    except Exception:
        return False


def grade(
    submitted_query: str,
    correct_query: str,
    task_id: str,
    conn: sqlite3.Connection,
) -> tuple[float, dict[str, Any]]:
    """Grade a submitted query against the reference answer.

    Returns (score, info) where score is strictly in the open interval
    (0.0, 1.0) — i.e. never exactly 0.0 or 1.0 — and info has
    the per-component breakdown for debugging.
    """
    info: dict[str, Any] = {
        "syntax_valid": False,
        "syntax_score": 0.0,
        "f1_score": 0.0,
        "similarity_score": 0.0,
        "exact_match": False,
        "exact_match_score": 0.0,
        "efficiency_score": 0.0,
        "error_message": None,
        "submitted_row_count": 0,
        "expected_row_count": 0,
    }

    score = 0.0

    # --- Part 1: Can it even parse? (0.15) ---
    try:
        cur = conn.cursor()
        cur.execute(f"EXPLAIN {submitted_query}")
        info["syntax_valid"] = True
        info["syntax_score"] = 0.15
        score += 0.15
    except Exception as e:
        info["error_message"] = str(e)
        # No point checking anything else if the syntax is broken
        return max(0.01, min(score, 0.99)), info

    # --- Run both queries ---
    submitted_rows, submit_err = _run_query(conn, submitted_query)
    if submit_err:
        info["error_message"] = submit_err
        return max(0.01, min(score, 0.99)), info

    expected_rows, _ = _run_query(conn, correct_query)

    info["submitted_row_count"] = len(submitted_rows)
    info["expected_row_count"] = len(expected_rows)

    result_set = _stringify_rows(submitted_rows)
    expected_set = _stringify_rows(expected_rows)

    # --- Part 2: How close are the results? F1 score (0.55) ---
    f1 = _compute_f1(result_set, expected_set)
    info["f1_score"] = round(f1, 4)
    similarity = 0.55 * f1
    info["similarity_score"] = round(similarity, 4)
    score += similarity

    # --- Part 3: Perfect match bonus (0.20) ---
    if result_set == expected_set:
        info["exact_match"] = True
        info["exact_match_score"] = 0.20
        score += 0.20

    # --- Part 4: Efficiency — only matters for the optimization task (0.10) ---
    if task_id == "optimize_query":
        if _check_query_plan_efficiency(conn, submitted_query):
            info["efficiency_score"] = 0.10
            score += 0.10

    # Clamp to strictly open interval (0.0, 1.0) — hackathon requires this.
    # Minimum 0.01: a syntactically valid query earns at least a tiny reward.
    # Maximum 0.99: no query is considered "perfect" by the grader.
    return round(max(0.01, min(score, 0.99)), 4), info