Spaces:
Sleeping
Sleeping
Commit Β·
d4b572f
1
Parent(s): 59746b9
again fixed graders
Browse files123456789101112131415161718192021222324252627282930315 unmodified lines373839404142434445464748495051525354555657585960616263646566672 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571587 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722813 unmodified lines24224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532611 unmodified lines3383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054061 unmodified line4084094104114124134144154164174186 unmodified lines425426427428429430431432433434435436import refrom env.models import Action, DifficultyLevelfrom env.tasks import task_manager# HELPERSSCORE_MIN = 0.001SCORE_MAX = 0.999def _clamp(value: float) -> float:"""Clamp a score to strictly (0, 1) β never 0.0 or 1.0."""return round(max(min(float(value), SCORE_MAX), SCORE_MIN), 4)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 SCORE_MINexplanation = explanation.strip()5 unmodified linesreturn 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 SCORE_MINdef _query_similarity(submitted: str, expected: str) -> float:"""Multi-level SQL similarity check.Returns SCORE_MIN - SCORE_MAX based on how close the submitted query is to expected.Handles case, whitespace, and keyword-level matching."""s = _normalize(submitted)e = _normalize(expected)# Exact match after normalization# NOTE: max similarity is SCORE_MAX (0.999), so threshold must be <= SCORE_MAXif s == e:return SCORE_MAX# Tokenize and check keyword overlaps_tokens = set(s.split())e_tokens = set(e.split())2 unmodified linesoverlap = len(s_tokens & e_tokens) / len(e_tokens)# Check critical keywords presentcritical_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# Weighted combinationsimilarity = round((overlap * 0.4) + (critical_score * 0.6), 4)return _clamp(similarity)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 SCORE_MINs = submitted_type.strip().lower()e = expected_type.strip().lower()if s == e:return 0.10# Partial: performance β optimization are relatedrelated = {"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:"""Score for correctly identifying WHERE in the query the error is."""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.15# Partial: check if key location words overlape_words = set(e.split())s_words = set(s.split())overlap = len(e_words & s_words) / len(e_words) if e_words else 0.0return _clamp(overlap * 0.10)# GRADERS PER DIFFICULTYdef grade_easy(action: Action, ground_truth: dict) -> tuple[float, dict, str]:"""Easy task grader β syntax errors.Max score: SCORE_MAXPartial credit across: fix correctness, error location, error type, explanation, confidence.DETERMINISTIC: same input always returns same score."""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. 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)# Threshold uses SCORE_MAX (0.999) since that is the exact-match ceilingif similarity >= SCORE_MAX:fix_score = 0.50feedback_parts.append("Correct fix applied.")7 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or not provided.")score += fix_scorebreakdown["fix_correctness"] = _clamp(fix_score) if fix_score > 0 else SCORE_MIN# ββ 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"] = _clamp(loc_score)if loc_score > SCORE_MIN: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"] = _clamp(type_score)if 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", "")expl_score = _score_explanation(str(explanation) if explanation else "")score += expl_scorebreakdown["explanation"] = _clamp(expl_score)if expl_score > SCORE_MIN:feedback_parts.append("Explanation provided.")# ββ 5. Confidence (0.05) βββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = _clamp(conf_score)final_score = _clamp(score)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 (wrong JOINs, wrong aggregations, etc).Max score: SCORE_MAXHigher bar: must correctly identify the logic flaw, not just syntax.DETERMINISTIC: same input always returns same score."""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. 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)13 unmodified linesfix_score = 0.0feedback_parts.append("Fix is incorrect or missing.")score += fix_scorebreakdown["fix_correctness"] = _clamp(fix_score) if fix_score > 0 else SCORE_MIN# ββ 2. Identifies the logic flaw (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))score += logic_scorebreakdown["logic_flaw_identification"] = _clamp(logic_score)if logic_score > SCORE_MIN: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"] = _clamp(loc_score)# ββ 4. Explanation quality (0.15) ββββββββββββββββββββββββββββexpl_score = _score_explanation(explanation)score += expl_scorebreakdown["explanation"] = _clamp(expl_score)# ββ 5. Confidence (0.05) βββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = _clamp(conf_score)# ββ 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"] = SCORE_MINfinal_score = _clamp(score)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 (N+1, missing index, cartesian, etc).Max score: SCORE_MAX but frontier models expected ~0.10-0.20.Extremely strict β requires deep understanding of performance concepts.DETERMINISTIC: same input always returns same score."""if action is None or action.payload is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."# ββ FIX: initialize all variables before use ββββββββββββββββββpayload = action.payloadscore = 0.0breakdown = {}feedback_parts = []rubric = ground_truth.get("scoring_rubric", {})# ββ 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.3011 unmodified linesfix_score = 0.0feedback_parts.append("Query does not address the performance issue.")score += fix_scorebreakdown["query_correctness"] = _clamp(fix_score) if fix_score > 0 else SCORE_MIN# ββ 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 = SCORE_MINfor 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 = _clamp(min(hits * 0.06, 0.30))breakscore += concept_scorebreakdown["performance_concept"] = _clamp(concept_score)if concept_score > SCORE_MIN: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"] = _clamp(expl_score)# ββ 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"] = SCORE_MIN# ββ 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"] = SCORE_MIN# ββ 6. Confidence (0.05) ββββββββββββββββββββββββββββββββββββββconfidence = _safe_get(payload, "confidence", None)conf_score = _score_confidence(confidence)score += conf_scorebreakdown["confidence"] = _clamp(conf_score)final_score = _clamp(score)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."""if action is None:return SCORE_MIN, {"error": "null_action"}, "No action provided."6 unmodified linestry: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 SCORE_MIN, {"error": "unknown_difficulty"}, f"Unknown difficulty: {difficulty}"except Exception as e:return SCORE_MIN, {"error": str(e)}, f"Grader error: {str(e)}"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515 unmodified lines575859606162636465666768697071727374757677787980812 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671687 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924013 unmodified lines25425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433511 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204211 unmodified line4234244254264274284294304314326 unmodified lines439440441442443444445446447448449450451452453454455456457458459460461462import 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()5 unmodified linesreturn 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())2 unmodified linesoverlap = 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:return 0.10related = {"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.")7 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)13 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.3011 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."6 unmodified linestry: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)}"
env/graders.py+193-167