Spaces:
Sleeping
Sleeping
Commit Β·
2146d9e
1
Parent(s): d4b572f
corrected everytihng
Browse filesFiles changed (2)
- env/graders.py+177-217
- inference.py+43-26
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141 unmodified line1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681696 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432449 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363379 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204211 unmodified line423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462import reimport mathfrom env.models import Action, DifficultyLevelfrom env.tasks import task_manager# βββββββββββββββββββββββββββββββββββββββββββββ# SCORE BOUNDS (strictly between 0 and 1)# βββββββββββββββββββββββββββββββββββββββββββββSCORE_MIN = 0.001 # 0 < SCORE_MIN < 1SCORE_MAX = 0.999 # 0 < SCORE_MAX < 1def _clamp(value) -> float:"""Guarantee the returned float is strictly inside (0, 1).Handles NaN, Inf, None, strings, and any numeric type safely.The round() call is applied AFTER the clamp, never before."""try:v = float(value)except (TypeError, ValueError):return SCORE_MIN# Guard against NaN and Β±Inf before any comparisonif not math.isfinite(v):return SCORE_MINclamped = max(min(v, SCORE_MAX), SCORE_MIN)return round(clamped, 4)# βββββββββββββββββββββββββββββββββββββββββββββ# HELPERS# βββββββββββββββββββββββββββββββββββββββββββββdef _normalize(text: str) -> str:if not isinstance(text, str):return ""return re.sub(r"\s+", " ", text.strip().lower())def _safe_get(payload: dict, key: str, default=None):if not isinstance(payload, dict):return defaultreturn payload.get(key, default)def _score_explanation(explanation: str) -> float:if not explanation or not isinstance(explanation, str):return SCORE_MINexplanation = explanation.strip()if len(explanation) < 10:return SCORE_MINif len(explanation) < 30:return 0.05if len(explanation) < 80:return 0.10return 0.15def _score_confidence(confidence) -> float:try:c = float(confidence)if math.isfinite(c) and 0.0 <= c <= 1.0:return 0.05except (TypeError, ValueError):passreturn SCORE_MINdef _query_similarity(submitted: str, expected: str) -> float:s = _normalize(submitted)e = _normalize(expected)if s == e:# Exact match β return SCORE_MAX, NOT 1.0return SCORE_MAXs_tokens = set(s.split())e_tokens = set(e.split())if not e_tokens:return SCORE_MINoverlap = len(s_tokens & e_tokens) / len(e_tokens)critical_keywords = _extract_critical_keywords(e)critical_found = sum(1 for kw in critical_keywords if kw in s)critical_score = (critical_found / len(critical_keywords)if critical_keywords else 0.0)raw = (overlap * 0.4) + (critical_score * 0.6)return _clamp(raw)def _extract_critical_keywords(query: str) -> list:keywords = ["left join", "inner join", "right join","group by", "order by", "having","partition by", "coalesce", "distinct","where", "on", "and", "or", "not","count", "sum", "avg", "max", "min","select", "from", "join",]q = query.lower()return [kw for kw in keywords if kw in q]def _score_error_type(submitted_type: str, expected_type: str) -> float:if not submitted_type:return SCORE_MINs = submitted_type.strip().lower()e = expected_type.strip().lower()if s == e:1 unmodified linerelated = {"performance": ["optimization", "slow", "index", "scan"],"logic": ["semantic", "incorrect", "wrong"],"syntax": ["parse", "grammar", "token"],}for canonical, aliases in related.items():if e == canonical and any(alias in s for alias in aliases):return 0.05return SCORE_MINdef _score_error_location(submitted_location: str,expected_location: str) -> float:if not submitted_location or not expected_location:return SCORE_MINs = submitted_location.strip().lower()e = expected_location.strip().lower()if s == e:return 0.15e_words = set(e.split())s_words = set(s.split())if not e_words:return SCORE_MINoverlap = len(e_words & s_words) / len(e_words)return _clamp(overlap * 0.10)# βββββββββββββββββββββββββββββββββββββββββββββ# GRADERS# βββββββββββββββββββββββββββββββββββββββββββββdef grade_easy(action: Action, ground_truth: dict) -> tuple:"""Easy β syntax errors.Scoring budget: fix(0.50) + loc(0.15) + type(0.10) + expl(0.15) + conf(0.05) = 0.95"""if action is None or action.payload is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."payload = action.payloadscore = 0.0breakdown = {}feedback_parts = []# 1. Fix correctness (0.50)submitted_query = (_safe_get(payload, "fixed_query", "")or _safe_get(payload, "optimized_query", "") or "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= SCORE_MAX:fix_score = 0.50feedback_parts.append("Correct fix applied.")elif similarity >= 0.75:6 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or not provided.")breakdown["fix_correctness"] = _clamp(fix_score)score += fix_score# 2. Error location (0.15)loc_score = _score_error_location(str(_safe_get(payload, "error_location", "") or ""),ground_truth.get("error_location", ""),)breakdown["error_location"] = _clamp(loc_score)score += loc_scoreif loc_score > SCORE_MIN:feedback_parts.append("Correctly identified error location.")# 3. Error type (0.10)type_score = _score_error_type(str(_safe_get(payload, "error_type", "") or ""),ground_truth.get("error_type", "syntax"),)breakdown["error_type"] = _clamp(type_score)score += type_scoreif type_score > SCORE_MIN:feedback_parts.append("Correctly identified error type.")# 4. Explanation quality (0.15)explanation = (_safe_get(payload, "explanation", "")or _safe_get(payload, "change_made", "") or "")expl_score = _score_explanation(str(explanation))breakdown["explanation"] = _clamp(expl_score)score += expl_scoreif expl_score > SCORE_MIN:feedback_parts.append("Explanation provided.")# 5. Confidence (0.05)conf_score = _score_confidence(_safe_get(payload, "confidence", None))breakdown["confidence"] = _clamp(conf_score)score += conf_scorefinal_score = _clamp(score)feedback = " ".join(feedback_parts) or "No valid response provided."return final_score, breakdown, feedbackdef grade_medium(action: Action, ground_truth: dict) -> tuple:"""Medium β logic errors.Scoring budget: fix(0.40) + logic(0.20) + loc(0.15) + expl(0.15)+ conf(0.05) + impact(0.05) = 1.00 -> clamped to SCORE_MAX"""if action is None or action.payload is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."payload = action.payloadscore = 0.0breakdown = {}feedback_parts = []# 1. Fix correctness (0.40)submitted_query = (_safe_get(payload, "fixed_query", "")or _safe_get(payload, "optimized_query", "") or "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= SCORE_MAX:fix_score = 0.40feedback_parts.append("Correct fix applied.")elif similarity >= 0.80:9 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or missing.")breakdown["fix_correctness"] = _clamp(fix_score)score += fix_score# 2. Logic flaw identification (0.20)explanation = str(_safe_get(payload, "explanation", "")or _safe_get(payload, "change_made", "") or "")error_type = ground_truth.get("error_type", "logic")logic_keywords = {"logic": ["join", "left join", "inner join", "having", "where","group by", "aggregate", "subquery", "correlation","distinct", "count"],"performance": ["index", "scan", "n+1", "correlated","cartesian", "window"],}keywords_to_check = logic_keywords.get(error_type, logic_keywords["logic"])expl_lower = explanation.lower()keyword_hits = sum(1 for kw in keywords_to_check if kw in expl_lower)logic_score = _clamp(min(keyword_hits * 0.05, 0.20))breakdown["logic_flaw_identification"] = _clamp(logic_score)score += logic_scoreif logic_score > SCORE_MIN:feedback_parts.append("Shows understanding of the logic flaw.")# 3. Error location (0.15)loc_score = _score_error_location(str(_safe_get(payload, "error_location", "") or ""),ground_truth.get("error_location", ""),)breakdown["error_location"] = _clamp(loc_score)score += loc_score# 4. Explanation quality (0.15)expl_score = _score_explanation(explanation)breakdown["explanation"] = _clamp(expl_score)score += expl_score# 5. Confidence (0.05)conf_score = _score_confidence(_safe_get(payload, "confidence", None))breakdown["confidence"] = _clamp(conf_score)score += conf_score# 6. Impact analysis bonus (0.05)impact = str(_safe_get(payload, "impact", "") or "")impact_score = 0.05 if len(impact.strip()) > 20 else 0.0breakdown["impact_analysis"] = _clamp(impact_score)score += impact_scoreif impact_score > 0:feedback_parts.append("Impact analysis provided.")final_score = _clamp(score)feedback = " ".join(feedback_parts) or "No valid response provided."return final_score, breakdown, feedbackdef grade_hard(action: Action, ground_truth: dict) -> tuple:"""Hard β performance issues (N+1, missing index, cartesian, etc).Scoring budget: query(0.30) + concept(0.30) + expl(0.15)+ root(0.10) + improvement(0.10) + conf(0.05) = 1.00 -> clamped"""if action is None or action.payload is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."# All variables initialised before first usepayload = action.payloadscore = 0.0breakdown = {}feedback_parts = []_rubric = ground_truth.get("scoring_rubric", {}) # reserved for future use# 1. Query correctness (0.30)submitted_query = (_safe_get(payload, "optimized_query", "")or _safe_get(payload, "fixed_query", "") or "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= SCORE_MAX:fix_score = 0.30feedback_parts.append("Perfectly optimized query.")elif similarity >= 0.85:9 unmodified linesfix_score = 0.0feedback_parts.append("Query does not address the performance issue.")breakdown["query_correctness"] = _clamp(fix_score)score += fix_score# 2. Performance concept identification (0.30)explanation = str(_safe_get(payload, "explanation", "")or _safe_get(payload, "change_made", "") or "")optimization = str(_safe_get(payload, "optimization_type", "") or "")combined_text = (explanation + " " + optimization).lower()perf_issue = ground_truth.get("performance_issue", {})issue_type = (perf_issue.get("type", "").lower()if isinstance(perf_issue, dict) else "")performance_concept_map = {"n+1": ["n+1", "correlated subquery", "subquery per row","multiple queries", "join instead"],"full table scan": ["full table scan", "index not used","function on column", "sargable","range scan", "seek"],"cartesian product": ["cartesian", "cross join","missing join condition","implicit join", "comma join"],"select *": ["select *", "over-fetch", "covering index","column projection", "unnecessary columns"],"window function": ["window function", "partition by", "row_number","subquery filter", "where clause window"],}concept_score = 0.0for concept, keywords in performance_concept_map.items():if any(part in issue_type for part in concept.split()):hits = sum(1 for kw in keywords if kw in combined_text)concept_score = min(hits * 0.06, 0.30)breakbreakdown["performance_concept"] = _clamp(concept_score)score += concept_scoreif concept_score > 0:feedback_parts.append("Demonstrates understanding of the performance issue.")# 3. Explanation depth (0.15)expl_score = _score_explanation(explanation)if len(explanation.strip()) > 150:expl_score = min(expl_score + 0.05, 0.15)breakdown["explanation_depth"] = _clamp(expl_score)score += expl_score# 4. Root cause analysis (0.10)root_cause = str(_safe_get(payload, "root_cause", "") or "")root_score = 0.10 if len(root_cause.strip()) > 30 else 0.0breakdown["root_cause_analysis"] = _clamp(root_score)score += root_scoreif root_score > 0:feedback_parts.append("Root cause analysis provided.")# 5. Expected improvement (0.10)improvement = str(_safe_get(payload, "expected_improvement", "") or "")imp_score = 0.10 if len(improvement.strip()) > 20 else 0.0breakdown["expected_improvement"] = _clamp(imp_score)score += imp_scoreif imp_score > 0:feedback_parts.append("Performance improvement estimate provided.")# 6. Confidence (0.05)conf_score = _score_confidence(_safe_get(payload, "confidence", None))breakdown["confidence"] = _clamp(conf_score)score += conf_scorefinal_score = _clamp(score)feedback = " ".join(feedback_parts) or "Performance issue not identified."return final_score, breakdown, feedback1 unmodified line# MAIN GRADER DISPATCHER# βββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββdef grade(action: Action, task_id: str) -> tuple:"""Main entry point. Always returns (float, dict, str) β never crashes.The returned float is always strictly inside (0, 1)."""if action is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."ground_truth = task_manager.get_ground_truth(task_id)if ground_truth is None:return SCORE_MIN, {"error": "unknown_task"}, f"Task '{task_id}' not found."difficulty = ground_truth.get("id", "").split("_")[0]try:if difficulty == "easy":result = grade_easy(action, ground_truth)elif difficulty == "medium":result = grade_medium(action, ground_truth)elif difficulty == "hard":result = grade_hard(action, ground_truth)else:return (SCORE_MIN,{"error": "unknown_difficulty"},f"Unknown difficulty: {difficulty}")# Final safety net: re-clamp the returned score and every breakdown valuefinal_score, breakdown, feedback = resultsafe_score = _clamp(final_score)safe_breakdown = {k: _clamp(v) if isinstance(v, (int, float)) else vfor k, v in breakdown.items()}return safe_score, safe_breakdown, feedbackexcept Exception as e:return SCORE_MIN, {"error": str(e)}, f"Grader error: {str(e)}"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431446 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162179 unmodified lines2272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113129 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903911 unmodified line393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422import refrom env.models import Action, DifficultyLevelfrom env.tasks import task_manager# βββββββββββββββββββββββββββββββββββββββββββββ# HELPERS# βββββββββββββββββββββββββββββββββββββββββββββdef _normalize(text: str) -> str:"""Normalize SQL for comparison β lowercase, strip whitespace, collapse spaces."""if not isinstance(text, str):return ""return re.sub(r"\s+", " ", text.strip().lower())def _safe_get(payload: dict, key: str, default=None):"""Safe dict access β never KeyError."""if not isinstance(payload, dict):return defaultreturn payload.get(key, default)def _score_explanation(explanation: str) -> float:"""Score explanation quality by length and keyword richness."""if not explanation or not isinstance(explanation, str):return 0.0explanation = explanation.strip()if len(explanation) < 10:return 0.0if len(explanation) < 30:return 0.05if len(explanation) < 80:return 0.10return 0.15def _score_confidence(confidence) -> float:"""Give partial credit for providing a valid confidence score."""try:c = float(confidence)if 0.0 <= c <= 1.0:return 0.05except (TypeError, ValueError):passreturn 0.0def _query_similarity(submitted: str, expected: str) -> float:"""Multi-level SQL similarity check.Returns 0.0 - 1.0 based on how close the submitted query is to expected."""s = _normalize(submitted)e = _normalize(expected)if s == e:return 1.0s_tokens = set(s.split())e_tokens = set(e.split())if not e_tokens:return 0.0overlap = len(s_tokens & e_tokens) / len(e_tokens)critical_keywords = _extract_critical_keywords(e)critical_found = sum(1 for kw in critical_keywords if kw in s)critical_score = critical_found / len(critical_keywords) if critical_keywords else 0.0return round((overlap * 0.4) + (critical_score * 0.6), 4)def _extract_critical_keywords(query: str) -> list[str]:"""Extract SQL keywords that are critical to correctness."""keywords = ["left join", "inner join", "right join","group by", "order by", "having","partition by", "coalesce", "distinct","where", "on", "and", "or", "not","count", "sum", "avg", "max", "min","select", "from", "join"]found = []q = query.lower()for kw in keywords:if kw in q:found.append(kw)return founddef _score_error_type(submitted_type: str, expected_type: str) -> float:"""Score for correctly identifying the error type."""if not submitted_type:return 0.0s = submitted_type.strip().lower()e = expected_type.strip().lower()if s == e:1 unmodified linerelated = {"performance": ["optimization", "slow", "index", "scan"],"logic": ["semantic", "incorrect", "wrong"],"syntax": ["parse", "grammar", "token"]}for canonical, aliases in related.items():if e == canonical and any(alias in s for alias in aliases):return 0.05return 0.0def _score_error_location(submitted_location: str, expected_location: str) -> float:"""Score for correctly identifying WHERE in the query the error is."""if not submitted_location or not expected_location:return 0.0s = submitted_location.strip().lower()e = expected_location.strip().lower()if s == e:return 0.15e_words = set(e.split())s_words = set(s.split())overlap = len(e_words & s_words) / len(e_words) if e_words else 0.0return round(overlap * 0.10, 4)# βββββββββββββββββββββββββββββββββββββββββββββ# GRADERS PER DIFFICULTY# βββββββββββββββββββββββββββββββββββββββββββββdef grade_easy(action: Action, ground_truth: dict) -> tuple[float, dict, str]:"""Easy task grader β syntax errors.Max score: 0.999 (strictly less than 1.0)DETERMINISTIC: same input always returns same score."""if action is None or action.payload is None:return 0.001, {"error": "null_action"}, "No action provided."payload = action.payloadscore = 0.0breakdown = {}feedback_parts = []# ββ 1. Query fix correctness (0.50) ββββββββββββββββββββββββββsubmitted_query = _safe_get(payload, "fixed_query", "") or _safe_get(payload, "optimized_query", "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= 1.0:fix_score = 0.50feedback_parts.append("Correct fix applied.")elif similarity >= 0.75:6 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or not provided.")score += fix_scorebreakdown["fix_correctness"] = round(fix_score, 4)# ββ 2. Error location (0.15) βββββββββββββββββββββββββββββββββsubmitted_location = _safe_get(payload, "error_location", "")expected_location = ground_truth.get("error_location", "")loc_score = _score_error_location(str(submitted_location), expected_location)score += loc_scorebreakdown["error_location"] = round(loc_score, 4)if loc_score > 0:feedback_parts.append("Correctly identified error location.")# ββ 3. Error type (0.10) βββββββββββββββββββββββββββββββββββββsubmitted_type = _safe_get(payload, "error_type", "")expected_type = ground_truth.get("error_type", "syntax")type_score = _score_error_type(str(submitted_type), expected_type)score += type_scorebreakdown["error_type"] = round(type_score, 4)if type_score > 0:feedback_parts.append("Correctly identified error type.")# ββ 4. Explanation quality (0.15) βββββββββββοΏ½οΏ½ββββββββββββββββexplanation = _safe_get(payload, "explanation", "") or _safe_get(payload, "change_made", "")expl_score = _score_explanation(str(explanation) if explanation else "")score += expl_scorebreakdown["explanation"] = round(expl_score, 4)if expl_score > 0:feedback_parts.append("Explanation provided.")# ββ 5. Confidence (0.05) βββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = round(conf_score, 4)# Clamp strictly between 0 and 1 exclusivefinal_score = round(max(0.001, min(0.999, score)), 4)feedback = " ".join(feedback_parts) if feedback_parts else "No valid response provided."return final_score, breakdown, feedbackdef grade_medium(action: Action, ground_truth: dict) -> tuple[float, dict, str]:"""Medium task grader β logic errors.Max score: 0.999 (strictly less than 1.0)DETERMINISTIC: same input always returns same score."""if action is None or action.payload is None:return 0.001, {"error": "null_action"}, "No action provided."payload = action.payloadscore = 0.0breakdown = {}feedback_parts = []# ββ 1. Query fix correctness (0.40) ββββββββββββββββββββββββββsubmitted_query = _safe_get(payload, "fixed_query", "") or _safe_get(payload, "optimized_query", "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= 1.0:fix_score = 0.40feedback_parts.append("Correct fix applied.")elif similarity >= 0.80:9 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or missing.")score += fix_scorebreakdown["fix_correctness"] = round(fix_score, 4)# ββ 2. Logic flaw identification (0.20) ββββββββββββββββββββββexplanation = str(_safe_get(payload, "explanation", "") or _safe_get(payload, "change_made", "") or "")error_type = ground_truth.get("error_type", "logic")logic_keywords = {"logic": ["join", "left join", "inner join", "having", "where", "group by","aggregate", "subquery", "correlation", "distinct", "count"],"performance": ["index", "scan", "n+1", "correlated", "cartesian", "window"]}keywords_to_check = logic_keywords.get(error_type, logic_keywords["logic"])expl_lower = explanation.lower()keyword_hits = sum(1 for kw in keywords_to_check if kw in expl_lower)logic_score = min(keyword_hits * 0.05, 0.20)score += logic_scorebreakdown["logic_flaw_identification"] = round(logic_score, 4)if logic_score > 0:feedback_parts.append("Shows understanding of the logic flaw.")# ββ 3. Error location (0.15) βββββββββββββββββββββββββββββββββsubmitted_location = _safe_get(payload, "error_location", "")expected_location = ground_truth.get("error_location", "")loc_score = _score_error_location(str(submitted_location), expected_location)score += loc_scorebreakdown["error_location"] = round(loc_score, 4)# ββ 4. Explanation quality (0.15) ββββββββββββββββββββββββββββexpl_score = _score_explanation(explanation)score += expl_scorebreakdown["explanation"] = round(expl_score, 4)# ββ 5. Confidence (0.05) βββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = round(conf_score, 4)# ββ 6. Impact analysis bonus (0.05) ββββββββββββββββββββββββββimpact = str(_safe_get(payload, "impact", "") or "")if len(impact.strip()) > 20:score += 0.05breakdown["impact_analysis"] = 0.05feedback_parts.append("Impact analysis provided.")else:breakdown["impact_analysis"] = 0.0# Clamp strictly between 0 and 1 exclusivefinal_score = round(max(0.001, min(0.999, score)), 4)feedback = " ".join(feedback_parts) if feedback_parts else "No valid response provided."return final_score, breakdown, feedbackdef grade_hard(action: Action, ground_truth: dict) -> tuple[float, dict, str]:"""Hard task grader β performance issues.Max score: 0.999 (strictly less than 1.0)Frontier models expected ~0.10-0.20.DETERMINISTIC: same input always returns same score."""if action is None or action.payload is None:return 0.001, {"error": "null_action"}, "No action provided."payload = action.payloadscore = 0.0breakdown = {}feedback_parts = []# ββ 1. Query correctness (0.30) ββββββββββββββββββββββββββββββsubmitted_query = (_safe_get(payload, "optimized_query", "")or _safe_get(payload, "fixed_query", "")or "")expected_query = ground_truth.get("fixed_query", "")similarity = _query_similarity(submitted_query, expected_query)if similarity >= 1.0:fix_score = 0.30feedback_parts.append("Perfectly optimized query.")elif similarity >= 0.85:9 unmodified linesfix_score = 0.0feedback_parts.append("Query does not address the performance issue.")score += fix_scorebreakdown["query_correctness"] = round(fix_score, 4)# ββ 2. Performance concept identification (0.30) ββββββββββββββexplanation = str(_safe_get(payload, "explanation", "") or _safe_get(payload, "change_made", "") or "")optimization = str(_safe_get(payload, "optimization_type", "") or "")combined_text = (explanation + " " + optimization).lower()perf_issue = ground_truth.get("performance_issue", {})issue_type = perf_issue.get("type", "").lower()performance_concept_map = {"n+1": ["n+1", "correlated subquery", "subquery per row", "multiple queries", "join instead"],"full table scan": ["full table scan", "index not used", "function on column", "sargable", "range scan", "seek"],"cartesian product": ["cartesian", "cross join", "missing join condition", "implicit join", "comma join"],"select *": ["select *", "over-fetch", "covering index", "column projection", "unnecessary columns"],"window function": ["window function", "partition by", "row_number", "subquery filter", "where clause window"]}concept_score = 0.0for concept, keywords in performance_concept_map.items():if any(concept_part in issue_type for concept_part in concept.split()):hits = sum(1 for kw in keywords if kw in combined_text)concept_score = min(hits * 0.06, 0.30)breakscore += concept_scorebreakdown["performance_concept"] = round(concept_score, 4)if concept_score > 0:feedback_parts.append("Demonstrates understanding of the performance issue.")# ββ 3. Explanation depth (0.15) βββββββββββββββββββββββββββββββexpl_score = _score_explanation(explanation)if len(explanation.strip()) > 150:expl_score = min(expl_score + 0.05, 0.15)score += expl_scorebreakdown["explanation_depth"] = round(expl_score, 4)# ββ 4. Root cause analysis (0.10) βββββββββββββββββββββββββββββroot_cause = str(_safe_get(payload, "root_cause", "") or "")if len(root_cause.strip()) > 30:score += 0.10breakdown["root_cause_analysis"] = 0.10feedback_parts.append("Root cause analysis provided.")else:breakdown["root_cause_analysis"] = 0.0# ββ 5. Expected improvement (0.10) ββββββββββββββββββββββββββββimprovement = str(_safe_get(payload, "expected_improvement", "") or "")if len(improvement.strip()) > 20:score += 0.10breakdown["expected_improvement"] = 0.10feedback_parts.append("Performance improvement estimate provided.")else:breakdown["expected_improvement"] = 0.0# ββ 6. Confidence (0.05) ββββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = round(conf_score, 4)# Clamp strictly between 0 and 1 exclusivefinal_score = round(max(0.001, min(0.999, score)), 4)feedback = " ".join(feedback_parts) if feedback_parts else "Performance issue not identified."return final_score, breakdown, feedback1 unmodified line# MAIN GRADER DISPATCHER# βββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββdef grade(action: Action, task_id: str) -> tuple[float, dict, str]:"""Main grader entry point.Looks up ground truth, dispatches to correct grader by difficulty.ALWAYS returns (float, dict, str) β never crashes.Score is always strictly between 0.001 and 0.999."""if action is None:return 0.001, {"error": "null_action"}, "No action provided."ground_truth = task_manager.get_ground_truth(task_id)if ground_truth is None:return 0.001, {"error": "unknown_task"}, f"Task '{task_id}' not found."difficulty = ground_truth.get("id", "").split("_")[0]try:if difficulty == "easy":return grade_easy(action, ground_truth)elif difficulty == "medium":return grade_medium(action, ground_truth)elif difficulty == "hard":return grade_hard(action, ground_truth)else:return 0.001, {"error": "unknown_difficulty"}, f"Unknown difficulty: {difficulty}"except Exception as e:return 0.001, {"error": str(e)}, f"Grader error: {str(e)}"
10 unmodified lines111213141516171819204 unmodified lines252627282930313233343536373839404142434468 unmodified lines11311411511611711811930 unmodified lines1501511521531541551565 unmodified lines1621631641651661671681691701711721731741751761771782 unmodified lines1811821831841851861871881891901 unmodified line19219319419519619719819910 unmodified lines2102112122132142152162172182192202212222232242252262272282296 unmodified lines23623723823924024112 unmodified lines25425525625725825926010 unmodified linesfrom openai import OpenAIfrom dotenv import load_dotenvload_dotenv()from env.environment import SQLDebuggerEnvironmentfrom env.models import Action, ActionType, DifficultyLevel# βββββββββββββββββββββββββββββββββββββββββββββ# ENVIRONMENT VARIABLES# βββββββββββββββββββββββββββββββββββββββββββββ4 unmodified linesif HF_TOKEN is None:raise ValueError("HF_TOKEN environment variable is required")API_KEY = HF_TOKENBENCHMARK = "sql-query-debugger"MAX_STEPS = 10SUCCESS_SCORE_THRESHOLD = 0.5# βββββββββββββββββββββββββββββββββββββββββββββdef log_start(task: str, env: str, model: str) -> None:print(f"[START] task={task} env={env} model={model}", flush=True)def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}", flush=True)SYSTEM_PROMPT = textwrap.dedent("""You are an expert SQL debugger. You will be given a buggy SQL query and must fix it.68 unmodified lines)text = (completion.choices[0].message.content or "").strip()# Parse JSON response# Remove markdown code blocks if presentif "```" in text:text = text.split("```")[1]30 unmodified linesexcept Exception as exc:print(f"[DEBUG] LLM call failed: {exc}", flush=True)# Fallback to identify_error actionreturn Action(action_type=ActionType.IDENTIFY_ERROR,payload={5 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββ# MAIN INFERENCE LOOP# βββββββββββββββββββββββββββββββββββββββββββββdef run_episode(client: OpenAI, difficulty: str, task_id: str) -> dict:"""Run one full episode and return results."""env = SQLDebuggerEnvironment()obs = env.reset(difficulty=difficulty, task_id=task_id)rewards = []steps = 0success = Falsescore = 0.001 # Initialize to minimum valid scorelog_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)2 unmodified linesif env.state().done:break# Get action from LLMaction = get_llm_action(client, obs, step)action_str = f"{action.action_type.value}"error_str = Nonetry:resp = env.step(action)1 unmodified linedone = resp.doneobs = resp.observationexcept Exception as e:reward = -0.1done = Falseerror_str = str(e)[:100]rewards.append(reward)10 unmodified linesif done:break# Calculate scoretotal_reward = sum(rewards)score = min(max(total_reward / MAX_STEPS, 0.001), 0.999)success = score >= SUCCESS_SCORE_THRESHOLDexcept Exception as e:print(f"[DEBUG] Episode error: {e}", flush=True)error_str = str(e)[:100]finally:log_end(success = success,steps = steps,score = score,rewards = rewards)6 unmodified lines}def main():"""Main entry point β runs inference on all 3 difficulty levels."""print(f"[DEBUG] API_BASE_URL={API_BASE_URL}", flush=True)12 unmodified linesresult = run_episode(client, difficulty, task_id)results.append(result)# Final summaryavg_score = sum(r["score"] for r in results) / len(results)print(f"\n[DEBUG] Average Score: {avg_score:.3f}", flush=True)for r in results:10 unmodified lines11121314151617181920214 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585968 unmodified lines12812913013113213330 unmodified lines1641651661671681695 unmodified lines1751761771781791801811821831841851861871881891901912 unmodified lines1941951961971981992002012021 unmodified line20420520620720820921021110 unmodified lines2222232242252262272282292302312322332342352362372382392402412422436 unmodified lines25025125225325425525625725825912 unmodified lines27227327427527627710 unmodified linesfrom openai import OpenAIfrom dotenv import load_dotenvload_dotenv()from env.environment import SQLDebuggerEnvironmentfrom env.models import Action, ActionType, DifficultyLevel# βββββββββββββββββββββββββββββββββββββββββββββ# ENVIRONMENT VARIABLES# βββββββββββββββββββββββββββββββββββββββββββββ4 unmodified linesif HF_TOKEN is None:raise ValueError("HF_TOKEN environment variable is required")API_KEY = HF_TOKENBENCHMARK = "sql-query-debugger"MAX_STEPS = 10SUCCESS_SCORE_THRESHOLD = 0.5# βββββββββββββββββββββββββββββββββββββββββββββ# LOGGING FUNCTIONS# βββββββββββββββββββββββββββββββββββββββββββββdef log_start(task: str, env: str, model: str) -> None:print(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:error_val = error if error else "null"done_val = str(done).lower()print(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}", flush=True)def log_end(success: bool, steps: int, rewards: List[float]) -> None:rewards_str = ",".join(f"{r:.2f}" for r in rewards)print(f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}", flush=True)# βββββββββββββββββββββββββββββββββββββββββββββ# SYSTEM PROMPT# βββββββββββββββββββββββββββββββββββββββββββββSYSTEM_PROMPT = textwrap.dedent("""You are an expert SQL debugger. You will be given a buggy SQL query and must fix it.68 unmodified lines)text = (completion.choices[0].message.content or "").strip()# Remove markdown code blocks if presentif "```" in text:text = text.split("```")[1]30 unmodified linesexcept Exception as exc:print(f"[DEBUG] LLM call failed: {exc}", flush=True)return Action(action_type=ActionType.IDENTIFY_ERROR,payload={5 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββ# EPISODE RUNNER# βββββββββββββββββββββββββββββββββββββββββββββdef run_episode(client: OpenAI, difficulty: str, task_id: str) -> dict:"""Run one full episode and return results."""env = SQLDebuggerEnvironment()obs = env.reset(difficulty=difficulty, task_id=task_id)rewards = []steps = 0success = Falsescore = 0.0log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)2 unmodified linesif env.state().done:breakaction = get_llm_action(client, obs, step)action_str = action.action_type.valueerror_str = Nonetry:resp = env.step(action)1 unmodified linedone = resp.doneobs = resp.observationexcept Exception as e:reward = -0.1done = Falseerror_str = str(e)[:100]rewards.append(reward)10 unmodified linesif done:break# Score must be strictly between 0 and 1 (not 0.0, not 1.0)total_reward = sum(rewards)raw_score = total_reward / MAX_STEPS if MAX_STEPS > 0 else 0.0# Clamp strictly between 0 and 1 exclusivescore = max(0.001, min(0.999, raw_score))success = score >= SUCCESS_SCORE_THRESHOLDexcept Exception as e:print(f"[DEBUG] Episode error: {e}", flush=True)score = 0.001success = Falsefinally:log_end(success = success,steps = steps,rewards = rewards)6 unmodified lines}# βββββββββββββββββββββββββββββββββββββββββββββ# MAIN# βββββββββββββββββββββββββββββββββββββββββββββdef main():"""Main entry point β runs inference on all 3 difficulty levels."""print(f"[DEBUG] API_BASE_URL={API_BASE_URL}", flush=True)12 unmodified linesresult = run_episode(client, difficulty, task_id)results.append(result)avg_score = sum(r["score"] for r in results) / len(results)print(f"\n[DEBUG] Average Score: {avg_score:.3f}", flush=True)for r in results:
env/graders.py+177-217
inference.py+43-26