Spaces:
Sleeping
Sleeping
Download server/grader.py from Akshayaitis/sql-debug-env: direct link, hf CLI and curl.
- Browser
- Download file 5.59 kB
-
https://huggingface.co/spaces/Akshayaitis/sql-debug-env/resolve/main/server/grader.py
- Command line
-
hf download hf://spaces/Akshayaitis/sql-debug-env/server/grader.py
-
curl -L -o grader.py https://huggingface.co/spaces/Akshayaitis/sql-debug-env/resolve/main/server/grader.py
5.59 kB
| """ | |
| 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 | |