def grade(workspace_path, **kwargs): """ mysql_001 rule-based grading: 实时广告RPM数据过滤与列重命名 总分结构 (100分, 归一化到0~1): 产物评分 (70%): A~E 维度原始满分100分 x 0.7 = 70分 A. 可执行性 (15分) B. Schema一致性 (15分) C. 行集一致性 (20分) D. 数值正确性 (40分) E. 主键/标签列正确性 (10分) 过程评分 (30%): G~I 维度原始满分100分 x 0.3 = 30分 G. 探索充分性 (35分) H. 执行效率 (40分) I. 自验证行为 (25分) Architecture: pymysql direct connection, no Spark/Hive dependency. """ import os import re import sys import subprocess import time import json DB_NAME = "internal_platform_db" INPUT_TABLE = "t_ad_realtime_rpm_total_mysql_001" OUTPUT_TABLE = "t_ad_realtime_rpm_cand_mysql_001" FULL_OUTPUT = f"{DB_NAME}.{OUTPUT_TABLE}" FULL_INPUT = f"{DB_NAME}.{INPUT_TABLE}" KEY_COLUMNS = ["sub_task_id"] EXPECTED_COL_COUNT = 9 EXPECTED_ROW_COUNT = 7 MYSQL_CONFIG = { "host": "localhost", "port": 3306, "user": "root", "password": "root123", "charset": "utf8mb4", } # Expected output (from query_engine_159 output/expected.csv) EXPECTED_ROWS = [ {"sub_task_id": "sub001", "ptag": "tag_a", "task_id": "task_01", "imp_min": 202606090450, "expose_per_w": 1500, "total_expose_pv": 3000, "total_click_pv": 120, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:01"}, {"sub_task_id": "sub002", "ptag": "tag_b", "task_id": "task_02", "imp_min": 202606090450, "expose_per_w": 2200, "total_expose_pv": 4500, "total_click_pv": 230, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:02"}, {"sub_task_id": "sub003", "ptag": "tag_c", "task_id": "task_01", "imp_min": 202606090450, "expose_per_w": 800, "total_expose_pv": 1200, "total_click_pv": 50, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:03"}, {"sub_task_id": "sub005", "ptag": "tag_d", "task_id": "task_02", "imp_min": 202606090450, "expose_per_w": 3100, "total_expose_pv": 6200, "total_click_pv": 310, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:05"}, {"sub_task_id": "sub007", "ptag": "tag_e", "task_id": "task_04", "imp_min": 202606090450, "expose_per_w": 500, "total_expose_pv": 900, "total_click_pv": 30, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:07"}, {"sub_task_id": "sub008", "ptag": "tag_b", "task_id": "task_05", "imp_min": 202606090450, "expose_per_w": 100, "total_expose_pv": 0, "total_click_pv": 0, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:08"}, {"sub_task_id": "sub009", "ptag": "tag_f", "task_id": "task_03", "imp_min": 202606090450, "expose_per_w": 2700, "total_expose_pv": 5400, "total_click_pv": 270, "ctime": "2026-06-09 04:50:00", "mtime": "2026-06-09 04:50:09"}, ] result = { "overall_score": 0.0, "total_points": 0, "grade": "", "details": {}, "diagnostics": [], "anti_cheat": {"passed": True}, } # ========== Helper: MySQL connection ========== def _mysql_fetch_all(sql): import pymysql conn = pymysql.connect(**MYSQL_CONFIG) try: with conn.cursor() as cur: cur.execute(sql) return cur.fetchall() finally: conn.close() def _mysql_execute(sql): import pymysql conn = pymysql.connect(**MYSQL_CONFIG) try: with conn.cursor() as cur: cur.execute(sql) conn.commit() finally: conn.close() def _mysql_fetch_dicts(sql): import pymysql conn = pymysql.connect(**MYSQL_CONFIG) try: with conn.cursor(pymysql.cursors.DictCursor) as cur: cur.execute(sql) return cur.fetchall() finally: conn.close() def _mysql_columns(table_full): import pymysql conn = pymysql.connect(**MYSQL_CONFIG) try: with conn.cursor(pymysql.cursors.DictCursor) as cur: cur.execute(f"DESCRIBE {table_full}") return cur.fetchall() finally: conn.close() def coverage_to_ratio(rate): if rate >= 0.995: return 1.0 elif rate >= 0.90: return 0.8 elif rate >= 0.70: return 0.5 else: return 0.0 def values_match(pred_val, gt_val): if pred_val is None and gt_val is None: return True if pred_val is None or gt_val is None: return False try: pv = int(pred_val) gv = int(gt_val) return pv == gv except (ValueError, TypeError): return str(pred_val).strip() == str(gt_val).strip() def finalize(result): ALPHA = 0.3 product_dims = ["A_executability", "B_schema", "C_row_alignment", "D_numerical_accuracy", "E_labels"] product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims) product_score = round(product_raw * (1 - ALPHA), 2) product_ratio = product_raw / 100.0 for dim in ["H_efficiency"]: if dim in result["details"]: raw = result["details"][dim].get("score", 0) result["details"][dim]["score_before_scaling"] = raw result["details"][dim]["score"] = round(raw * product_ratio, 2) result["details"][dim]["product_ratio"] = round(product_ratio, 4) process_dims = ["G_exploration", "H_efficiency", "I_self_verification"] process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims) process_score = round(process_raw * ALPHA, 2) total = round(product_score + process_score, 2) result["total_points"] = total result["product_points"] = product_score result["process_points"] = round(process_score, 2) result["overall_score"] = round(total / 100.0, 4) if total >= 90: result["grade"] = "优秀" elif total >= 75: result["grade"] = "良好" elif total >= 60: result["grade"] = "合格" elif total >= 40: result["grade"] = "偏弱" else: result["grade"] = "不合格" return result # ========== Product grading ========== def _product_grade(): # ===== A. 可执行性 (15分) ===== a_items = {"A1_no_error": 0, "A2_table_produced": 0, "A3_no_manual_fix": 0} agent_code = os.path.join(workspace_path, "result.py") if not os.path.exists(agent_code): result["details"]["A_executability"] = {"score": 0, "max": 15, "items": a_items} result["error"] = "no_result_file" return # Anti-cheat: check if agent references ground_truth.py with open(agent_code, "r", encoding="utf-8", errors="ignore") as f: source_code = f.read() if re.search(r'ground_truth\.py', source_code): result["anti_cheat"] = { "passed": False, "reason": "Directly references ground_truth.py file", } # Execute agent code agent_exec_success = False agent_stderr = "" try: r = subprocess.run( ["python3", agent_code], capture_output=True, text=True, timeout=300, cwd=workspace_path, ) if r.returncode == 0: agent_exec_success = True else: agent_stderr = r.stderr or r.stdout or "" except subprocess.TimeoutExpired: agent_stderr = "agent code execution timeout (300s)" except Exception as e: agent_stderr = str(e) if not agent_exec_success: a_items["A1_no_error"] = 0 result["details"]["A_executability"] = {"score": 0, "max": 15, "items": a_items} result["error"] = agent_stderr[-2000:] return a_items["A1_no_error"] = 5 a_items["A3_no_manual_fix"] = 3 # Check if output table has data try: row_count = _mysql_fetch_all(f"SELECT COUNT(*) FROM {FULL_OUTPUT}")[0][0] except Exception as e: row_count = 0 result["diagnostics"].append(f"mysql_count_pred_failed: {e}") if row_count > 0: a_items["A2_table_produced"] = 7 else: a_items["A2_table_produced"] = 0 a_score = sum(a_items.values()) result["details"]["A_executability"] = {"score": a_score, "max": 15, "items": a_items} # Gate: A2=0 => B/C/D/E all 0 if a_items["A2_table_produced"] == 0: result["details"]["B_schema"] = {"score": 0, "max": 15, "items": {}} result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {}} result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {}} result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}} result["error"] = "target table empty or not produced" return # Read agent output from MySQL try: pred_rows = _mysql_fetch_dicts(f"SELECT * FROM {FULL_OUTPUT}") except Exception as e: result["diagnostics"].append(f"mysql_read_pred_failed: {e}") pred_rows = [] # Save pred output to temp table before GT overwrites the output table try: _mysql_execute(f"DROP TABLE IF EXISTS {DB_NAME}._tmp_pred_mysql_001") _mysql_execute(f"CREATE TABLE {DB_NAME}._tmp_pred_mysql_001 AS SELECT * FROM {FULL_OUTPUT}") except Exception as e: result["diagnostics"].append(f"save_pred_to_temp_failed: {e}") # Read columns info from pred output (before GT overwrites) try: cols_info = _mysql_columns(FULL_OUTPUT) pred_columns = [c["Field"] for c in cols_info] except Exception: pred_columns = list(pred_rows[0].keys()) if pred_rows else [] # ----- Run ground truth ----- gt_code = os.path.join(workspace_path, "gt", "ground_truth.py") gt_success = False for _ in range(3): try: r = subprocess.run( ["python3", gt_code], capture_output=True, text=True, timeout=300, cwd=workspace_path, ) if r.returncode == 0: gt_success = True break except subprocess.TimeoutExpired: result["error"] = "ground_truth execution timeout" break except Exception as e: result["error"] = f"ground_truth_failed: {e}" break if not gt_success: if "error" not in result: result["error"] = "ground_truth_failed after retries" result["details"]["B_schema"] = {"score": 0, "max": 15, "items": {}} result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {}} result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {}} result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}} return # Read GT from MySQL (after ground_truth.py has written to output table) try: gt_rows = _mysql_fetch_dicts(f"SELECT * FROM {FULL_OUTPUT}") except Exception as e: result["error"] = f"gt_result_read_failed: {e}" result["details"]["B_schema"] = {"score": 0, "max": 15, "items": {}} result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {}} result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {}} result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}} return # Restore pred_rows from temp table (GT has overwritten output table) try: pred_rows = _mysql_fetch_dicts(f"SELECT * FROM {DB_NAME}._tmp_pred_mysql_001") cols_info = _mysql_columns(f"{DB_NAME}._tmp_pred_mysql_001") pred_columns = [c["Field"] for c in cols_info] except Exception as e: result["diagnostics"].append(f"restore_pred_from_temp_failed: {e}") finally: try: _mysql_execute(f"DROP TABLE IF EXISTS {DB_NAME}._tmp_pred_mysql_001") except Exception: pass # ===== B. Schema一致性 (15分) ===== b_items = {} b_items["B1_table_name"] = 2 b_items["B2_col_count"] = 3 if len(pred_columns) == EXPECTED_COL_COUNT else 0 gt_col_set = set(c.lower() for c in ["sub_task_id", "ptag", "task_id", "imp_min", "expose_per_w", "total_expose_pv", "total_click_pv", "ctime", "mtime"]) pred_col_set = set(c.lower() for c in pred_columns) if gt_col_set == pred_col_set: b_items["B3_col_names"] = 5 elif len(gt_col_set & pred_col_set) / len(gt_col_set) >= 0.9: b_items["B3_col_names"] = 3 else: b_items["B3_col_names"] = 0 # B4: column type alignment type_match_count = 0 try: gt_cols_info = _mysql_columns(FULL_OUTPUT) gt_types = {c["Field"].lower(): c["Type"].lower() for c in gt_cols_info} pred_types = {c["Field"].lower(): c["Type"].lower() for c in cols_info} common_cols = gt_col_set & pred_col_set if common_cols: for col in common_cols: if pred_types.get(col, "") == gt_types.get(col, ""): type_match_count += 1 except Exception: type_match_count = len(gt_col_set & pred_col_set) common_count = len(gt_col_set & pred_col_set) if common_count > 0 and type_match_count / common_count >= 0.9: b_items["B4_col_types"] = 3 elif common_count > 0 and type_match_count / common_count >= 0.7: b_items["B4_col_types"] = 2 else: b_items["B4_col_types"] = 0 b_items["B5_engine_format"] = 2 # MySQL InnoDB b_score = sum(b_items.values()) result["details"]["B_schema"] = {"score": b_score, "max": 15, "items": b_items} # ===== Anti-cheat lock ===== if not result["anti_cheat"]["passed"]: result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {"anti_cheat_failed": True}} result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {"anti_cheat_failed": True}} result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}} result["diagnostics"].append("Anti-cheat failed: C/D dimensions scored 0") return # ===== C. 行集一致性 (20分) ===== c_items = {} def make_key(row): return tuple(str(row.get(k, "")).strip() for k in KEY_COLUMNS) gt_keys = set() for row in gt_rows: gt_keys.add(make_key(row)) pred_keys = [] pred_key_set = set() for row in pred_rows: k = make_key(row) pred_keys.append(k) pred_key_set.add(k) # C1: row count n_gt = len(gt_keys) n_pred = len(pred_key_set) if n_pred == EXPECTED_ROW_COUNT: c_items["C1_row_count"] = 6 elif n_pred > 0 and n_pred <= EXPECTED_ROW_COUNT + 1: c_items["C1_row_count"] = 3 else: c_items["C1_row_count"] = 0 # C2: no duplicate keys from collections import Counter key_counter = Counter(pred_keys) duplicates = sum(1 for v in key_counter.values() if v > 1) if duplicates == 0: c_items["C2_no_duplicates"] = 5 elif duplicates <= 2: c_items["C2_no_duplicates"] = 2 else: c_items["C2_no_duplicates"] = 0 # C3: coverage (GT key coverage) hit_keys = gt_keys & pred_key_set hit_count = len(hit_keys) coverage = hit_count / n_gt if n_gt > 0 else 0 c_items["C3_coverage"] = round(5 * coverage_to_ratio(coverage), 2) c_items["C3_coverage_rate"] = round(coverage, 4) # C4: no extra rows extra_keys = pred_key_set - gt_keys extra_count = len(extra_keys) no_extra_rate = 1 - (extra_count / n_pred) if n_pred > 0 else 0 c_items["C4_no_extra"] = round(4 * coverage_to_ratio(no_extra_rate), 2) c_items["C4_no_extra_rate"] = round(no_extra_rate, 4) c_score = sum(v for k, v in c_items.items() if not k.endswith("_rate")) result["details"]["C_row_alignment"] = {"score": round(c_score, 2), "max": 20, "items": c_items} # ===== D. 数值正确性 (40分) ===== d_items = {} gt_index = {make_key(row): row for row in gt_rows} pred_index = {} for row in pred_rows: k = make_key(row) if k not in pred_index: pred_index[k] = row hit_row_keys = list(hit_keys) # Numeric columns to check (BIGINT) numeric_cols = ["imp_min", "expose_per_w", "total_expose_pv", "total_click_pv"] for col in numeric_cols: if not hit_row_keys: d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 9} continue passed = 0 first_mismatch = None for key in hit_row_keys: gt_val = gt_index[key].get(col) pred_val = pred_index.get(key, {}).get(col) if values_match(pred_val, gt_val): passed += 1 elif first_mismatch is None: first_mismatch = { "key": dict(zip(KEY_COLUMNS, key)), "column": col, "pred": pred_val, "gt": gt_val, } pass_rate = passed / len(hit_row_keys) col_score = round(9 * pass_rate, 2) d_items[col] = {"pass_rate": round(pass_rate, 4), "score": col_score, "max": 9} if first_mismatch and pass_rate < 0.95: result["diagnostics"].append(first_mismatch) # String/datetime columns string_cols = ["ctime", "mtime"] for col in string_cols: if not hit_row_keys: d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 2} continue passed = 0 for key in hit_row_keys: gt_val = str(gt_index[key].get(col, "")).strip() pred_val = str(pred_index.get(key, {}).get(col, "")).strip() if pred_val == gt_val: passed += 1 pass_rate = passed / len(hit_row_keys) d_items[col] = {"pass_rate": round(pass_rate, 4), "score": round(2 * pass_rate, 2), "max": 2} d_score = sum(item["score"] for item in d_items.values()) result["details"]["D_numerical_accuracy"] = {"score": round(d_score, 2), "max": 40, "items": d_items} # ===== E. 主键/标签列正确性 (10分) ===== e_items = {} # E1: all expected sub_task_ids present expected_ids = {"sub001", "sub002", "sub003", "sub005", "sub007", "sub008", "sub009"} pred_ids = set(str(row.get("sub_task_id", "")).strip() for row in pred_rows) e1_pass = len(expected_ids & pred_ids) e_items["E1_sub_task_ids"] = round(10 * (e1_pass / len(expected_ids)), 2) e_score = sum(e_items.values()) result["details"]["E_labels"] = {"score": round(e_score, 2), "max": 10, "items": e_items} _product_grade() # ========== G~I 过程性评分 (30分) ========== TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl" INPUT_TABLE_SHORT = "t_ad_realtime_rpm_total_mysql_001" OUTPUT_TABLE_SHORT = "t_ad_realtime_rpm_cand_mysql_001" transcript_entries = [] has_transcript = False try: if os.path.exists(TRANSCRIPT_PATH): with open(TRANSCRIPT_PATH, "r", encoding="utf-8", errors="ignore") as f: for line in f: line = line.strip() if line: try: transcript_entries.append(json.loads(line)) except json.JSONDecodeError: continue if len(transcript_entries) > 2: has_transcript = True except Exception: pass if not has_transcript: result["details"]["G_exploration"] = {"score": 0, "max": 35, "items": {"no_transcript": True}} result["details"]["H_efficiency"] = {"score": 0, "max": 40, "items": {"no_transcript": True}} result["details"]["I_self_verification"] = {"score": 0, "max": 25, "items": {"no_transcript": True}} return finalize(result) # Parse transcript (reuse pyspark_001 process grading logic) tool_uses = [] first_write_result_idx = None last_spark_submit_success_idx = None write_result_count = 0 logic_error_retries = 0 output_tokens = 0 for idx, entry in enumerate(transcript_entries): content = entry.get("content", []) if isinstance(content, str): content = [content] usage_str = entry.get("usage", "") if isinstance(usage_str, str) and "output_tokens=" in usage_str: try: ot_match = re.search(r"output_tokens=(\d+)", usage_str) if ot_match: output_tokens = int(ot_match.group(1)) except Exception: pass for block_str in content: if not isinstance(block_str, str): continue if "ToolUseBlock" in block_str: name_match = re.search(r"name='([^']+)'", block_str) input_match = re.search(r"input=(\{.*\})", block_str) if name_match: tool_name = name_match.group(1) tool_input = input_match.group(1) if input_match else "" tool_uses.append((idx, tool_name, tool_input)) if tool_name == "Write" and "result" in tool_input and ".py" in tool_input: write_result_count += 1 if first_write_result_idx is None: first_write_result_idx = idx if "ToolResultBlock" in block_str: if "Traceback" in block_str or "Exception" in block_str: if any(t[1] == "Bash" and "python" in t[2] and "result.py" in t[2] for t in tool_uses): logic_error_retries += 1 if "python" in block_str and "result.py" in block_str: if "Exit Code: 0" in block_str and "Traceback" not in block_str: last_spark_submit_success_idx = idx before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries) # ===== G. 探索充分性 (35分) ===== g_items = {} # G1: Checked source table schema g1_pass = False for idx, name, inp in tool_uses: if idx >= before_first_write: break if name == "Read" and "schema" in inp.lower(): g1_pass = True break if name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper()) and INPUT_TABLE_SHORT in inp: g1_pass = True break g_items["G1_source_schema"] = 9 if g1_pass else 0 # G2: Checked source table sample data g2_pass = False for idx, name, inp in tool_uses: if idx >= before_first_write: break if name == "Bash" and INPUT_TABLE_SHORT in inp: if "SELECT" in inp.upper() and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper()): g2_pass = True break g_items["G2_source_sample"] = 9 if g2_pass else 0 # G3: Checked imp_min values g3_pass = False for idx, name, inp in tool_uses: if idx >= before_first_write: break if name == "Bash" and "imp_min" in inp: if "DISTINCT" in inp.upper() or "COUNT" in inp.upper() or "GROUP BY" in inp.upper(): g3_pass = True break g_items["G3_date_range"] = 9 if g3_pass else 0 # G4: Checked target table structure g4_pass = False for idx, name, inp in tool_uses: if idx >= before_first_write: break if name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper()) and OUTPUT_TABLE_SHORT in inp: g4_pass = True break g_items["G4_target_schema"] = 8 if g4_pass else 0 g_score = sum(g_items.values()) result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items} # ===== H. 执行效率 (40分) ===== h_items = {} if write_result_count <= 2: h_items["H1_few_submissions"] = 13 h_items["H2_moderate_submissions"] = 7 elif write_result_count <= 4: h_items["H1_few_submissions"] = 0 h_items["H2_moderate_submissions"] = 7 else: h_items["H1_few_submissions"] = 0 h_items["H2_moderate_submissions"] = 0 if logic_error_retries == 0: h_items["H3_no_logic_errors"] = 13 elif logic_error_retries <= 1: h_items["H3_no_logic_errors"] = 7 else: h_items["H3_no_logic_errors"] = 0 extra_writes = sum(1 for _, name, inp in tool_uses if name == "Write" and "result.py" not in inp and (".py" in inp or ".sql" in inp)) h_items["H4_no_redundant_ops"] = 7 if extra_writes <= 1 else 0 h_score = sum(h_items.values()) result["details"]["H_efficiency"] = {"score": h_score, "max": 40, "items": h_items} # ===== I. 自验证行为 (25分) ===== i_items = {} post_submit_uses = [] if last_spark_submit_success_idx is not None: post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses if idx > last_spark_submit_success_idx] i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper() for _, name, inp in post_submit_uses) i_items["I1_query_output"] = 8 if i1_pass else 0 i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper()) for _, name, inp in post_submit_uses) i_items["I2_check_count_or_group"] = 9 if i2_pass else 0 i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper() or "expose" in inp.lower() or "click" in inp.lower()) for _, name, inp in post_submit_uses) i_items["I3_check_values"] = 8 if i3_pass else 0 i_score = sum(i_items.values()) result["details"]["I_self_verification"] = {"score": i_score, "max": 25, "items": i_items} return finalize(result)