dicemy's picture
Upload 655 files
e8c001c verified
Raw
History Blame Contribute Delete
32.5 kB
def grade(workspace_path, **kwargs):
"""
mysql_012 rule-based grading: Notebook 管道任务实例分钟级 GPU 利用率统计
总分结构 (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 = "dwd_notebook_instance_pod_detail_d_mysql_012"
OUTPUT_TABLE = "dws_notebook_instance_execute_minute_stat_d_cand_mysql_012"
FULL_OUTPUT = f"{DB_NAME}.{OUTPUT_TABLE}"
FULL_INPUT = f"{DB_NAME}.{INPUT_TABLE}"
KEY_COLUMNS = ["trace_id", "p_date", "pkg_agg_time"]
EXPECTED_COL_COUNT = 25
EXPECTED_ROW_COUNT = 7
MYSQL_CONFIG = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "root123",
"charset": "utf8mb4",
}
# Expected output (from query_engine_020 output/expected.csv)
EXPECTED_ROWS = [
{"trace_id": "trace_001", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 10:01:00",
"dt": "20260507", "datawd_project_id": "proj_01", "datawd_task_id": "task_01",
"datawd_task_instance_id": "inst_01", "compute_type": "GPU", "status_code": 0,
"instance_run_time": 120, "code_run_time": 100, "resource_wait_time": 20,
"code_start_time": "2026-05-07 10:00:00", "code_end_time": "2026-05-07 10:05:00",
"instance_start_time": "2026-05-07 09:58:00", "instance_end_time": "2026-05-07 10:06:00",
"serving_id": "srv_01", "is_permanent": 1, "apply_for_gpu_count": 2,
"code_gpu_count": 4, "instance_gpu_util": 80.0, "code_gpu_util": 80.0,
"is_code_running": 1, "used_gpu_count": 3.2, "code_used_gpu_count": 3.2},
{"trace_id": "trace_001", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 10:02:00",
"dt": "20260507", "datawd_project_id": "proj_01", "datawd_task_id": "task_01",
"datawd_task_instance_id": "inst_01", "compute_type": "GPU", "status_code": 0,
"instance_run_time": 120, "code_run_time": 100, "resource_wait_time": 20,
"code_start_time": "2026-05-07 10:00:00", "code_end_time": "2026-05-07 10:05:00",
"instance_start_time": "2026-05-07 09:58:00", "instance_end_time": "2026-05-07 10:06:00",
"serving_id": "srv_01", "is_permanent": 1, "apply_for_gpu_count": 2,
"code_gpu_count": 2, "instance_gpu_util": 80.0, "code_gpu_util": 80.0,
"is_code_running": 1, "used_gpu_count": 1.6, "code_used_gpu_count": 1.6},
{"trace_id": "trace_001", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 10:06:00",
"dt": "20260507", "datawd_project_id": "proj_01", "datawd_task_id": "task_01",
"datawd_task_instance_id": "inst_01", "compute_type": "GPU", "status_code": 0,
"instance_run_time": 120, "code_run_time": 100, "resource_wait_time": 20,
"code_start_time": "2026-05-07 10:00:00", "code_end_time": "2026-05-07 10:05:00",
"instance_start_time": "2026-05-07 09:58:00", "instance_end_time": "2026-05-07 10:06:00",
"serving_id": "srv_01", "is_permanent": 1, "apply_for_gpu_count": 2,
"code_gpu_count": 2, "instance_gpu_util": 60.0, "code_gpu_util": None,
"is_code_running": 0, "used_gpu_count": 1.2, "code_used_gpu_count": 0.0},
{"trace_id": "trace_002", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 11:01:00",
"dt": "20260507", "datawd_project_id": "proj_02", "datawd_task_id": "task_02",
"datawd_task_instance_id": "inst_02", "compute_type": "CPU", "status_code": 1,
"instance_run_time": 200, "code_run_time": 150, "resource_wait_time": 50,
"code_start_time": None, "code_end_time": None,
"instance_start_time": "2026-05-07 11:00:00", "instance_end_time": "2026-05-07 11:10:00",
"serving_id": "srv_02", "is_permanent": 0, "apply_for_gpu_count": 0,
"code_gpu_count": None, "instance_gpu_util": None, "code_gpu_util": None,
"is_code_running": 0, "used_gpu_count": 0.0, "code_used_gpu_count": 0.0},
{"trace_id": "trace_002", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 11:02:00",
"dt": "20260507", "datawd_project_id": "proj_02", "datawd_task_id": "task_02",
"datawd_task_instance_id": "inst_02", "compute_type": "CPU", "status_code": 1,
"instance_run_time": 200, "code_run_time": 150, "resource_wait_time": 50,
"code_start_time": None, "code_end_time": None,
"instance_start_time": "2026-05-07 11:00:00", "instance_end_time": "2026-05-07 11:10:00",
"serving_id": "srv_02", "is_permanent": 0, "apply_for_gpu_count": 0,
"code_gpu_count": 1, "instance_gpu_util": 50.0, "code_gpu_util": None,
"is_code_running": 0, "used_gpu_count": 0.5, "code_used_gpu_count": 0.0},
{"trace_id": "trace_003", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 12:05:00",
"dt": "20260507", "datawd_project_id": "proj_03", "datawd_task_id": "task_03",
"datawd_task_instance_id": "inst_03", "compute_type": "GPU", "status_code": 0,
"instance_run_time": 300, "code_run_time": 250, "resource_wait_time": 50,
"code_start_time": "2026-05-07 12:00:00", "code_end_time": "2026-05-07 12:10:00",
"instance_start_time": "2026-05-07 11:58:00", "instance_end_time": "2026-05-07 12:12:00",
"serving_id": "srv_03", "is_permanent": 1, "apply_for_gpu_count": 4,
"code_gpu_count": 4, "instance_gpu_util": 90.0, "code_gpu_util": 90.0,
"is_code_running": 1, "used_gpu_count": 3.6, "code_used_gpu_count": 3.6},
{"trace_id": "trace_003", "p_date": "2026-05-07", "pkg_agg_time": "2026-05-07 12:15:00",
"dt": "20260507", "datawd_project_id": "proj_03", "datawd_task_id": "task_03",
"datawd_task_instance_id": "inst_03", "compute_type": "GPU", "status_code": 0,
"instance_run_time": 300, "code_run_time": 250, "resource_wait_time": 50,
"code_start_time": "2026-05-07 12:00:00", "code_end_time": "2026-05-07 12:10:00",
"instance_start_time": "2026-05-07 11:58:00", "instance_end_time": "2026-05-07 12:12:00",
"serving_id": "srv_03", "is_permanent": 1, "apply_for_gpu_count": 4,
"code_gpu_count": 4, "instance_gpu_util": 0.0, "code_gpu_util": None,
"is_code_running": 0, "used_gpu_count": 0.0, "code_used_gpu_count": 0.0},
]
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 numeric_match(pred_val, gt_val, tol=0.01):
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 = float(pred_val)
gv = float(gt_val)
if abs(pv - gv) < tol:
return True
if gv != 0 and abs((pv - gv) / gv) < tol:
return True
return abs(pv - gv) < tol
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 (save before GT overwrites)
try:
pred_rows_raw = _mysql_fetch_dicts(f"SELECT * FROM {FULL_OUTPUT}")
except Exception as e:
result["diagnostics"].append(f"mysql_read_pred_failed: {e}")
pred_rows_raw = []
# Deep copy pred_rows so GT overwrite doesn't affect it
import copy
pred_rows = copy.deepcopy(pred_rows_raw)
# Read columns info
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 run overwrites 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
# ===== 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_names = ["dt", "trace_id", "p_date", "pkg_agg_time",
"datawd_project_id", "datawd_task_id", "datawd_task_instance_id",
"compute_type", "status_code", "instance_run_time",
"code_run_time", "resource_wait_time", "code_start_time",
"code_end_time", "instance_start_time", "instance_end_time",
"serving_id", "is_permanent", "apply_for_gpu_count",
"code_gpu_count", "instance_gpu_util", "code_gpu_util",
"is_code_running", "used_gpu_count", "code_used_gpu_count"]
gt_col_set = set(c.lower() for c in gt_col_names)
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)
# Core computed numeric columns (6 cols x 6 points = 36)
numeric_cols = ["code_gpu_count", "instance_gpu_util", "code_gpu_util",
"is_code_running", "used_gpu_count", "code_used_gpu_count"]
for col in numeric_cols:
if not hit_row_keys:
d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 6}
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 numeric_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(6 * pass_rate, 2)
d_items[col] = {"pass_rate": round(pass_rate, 4), "score": col_score, "max": 6}
if first_mismatch and pass_rate < 0.95:
result["diagnostics"].append(first_mismatch)
# Aggregated pass-through numeric columns (2 cols x 2 points = 4)
agg_numeric_cols = ["status_code", "apply_for_gpu_count"]
for col in agg_numeric_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 = gt_index[key].get(col)
pred_val = pred_index.get(key, {}).get(col)
if numeric_match(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 trace_ids present
expected_ids = {"trace_001", "trace_002", "trace_003"}
pred_ids = set(str(row.get("trace_id", "")).strip() for row in pred_rows)
e1_pass = len(expected_ids & pred_ids)
e_items["E1_trace_ids"] = round(4 * (e1_pass / len(expected_ids)), 2)
# E2: key column values match (trace_id, p_date, pkg_agg_time)
if hit_row_keys:
key_match = 0
for key in hit_row_keys:
pk = pred_index.get(key, {})
gt_pk = gt_index.get(key, {})
if (str(pk.get("trace_id", "")).strip() == str(gt_pk.get("trace_id", "")).strip() and
str(pk.get("p_date", "")).strip() == str(gt_pk.get("p_date", "")).strip() and
str(pk.get("pkg_agg_time", "")).strip() == str(gt_pk.get("pkg_agg_time", "")).strip()):
key_match += 1
e_items["E2_key_values"] = round(3 * (key_match / len(hit_row_keys)), 2)
else:
e_items["E2_key_values"] = 0
# E3: compute_type labels correct
if hit_row_keys:
ct_match = 0
for key in hit_row_keys:
gt_val = str(gt_index[key].get("compute_type", "")).strip()
pred_val = str(pred_index.get(key, {}).get("compute_type", "")).strip()
if gt_val == pred_val:
ct_match += 1
e_items["E3_compute_type"] = round(3 * (ct_match / len(hit_row_keys)), 2)
else:
e_items["E3_compute_type"] = 0
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 = "dwd_notebook_instance_pod_detail_d_mysql_012"
OUTPUT_TABLE_SHORT = "dws_notebook_instance_execute_minute_stat_d_cand_mysql_012"
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
tool_uses = []
first_write_result_idx = None
last_exec_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_exec_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 == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper()) and INPUT_TABLE_SHORT in inp:
g1_pass = True
break
if name == "Read" 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 dt / partition values
g3_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 "DISTINCT" in inp.upper() or "GROUP BY" in inp.upper() or "dt" in inp:
g3_pass = True
break
g_items["G3_partition_check"] = 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"] = 14
h_items["H2_moderate_submissions"] = 6
elif write_result_count <= 4:
h_items["H1_few_submissions"] = 0
h_items["H2_moderate_submissions"] = 6
else:
h_items["H1_few_submissions"] = 0
h_items["H2_moderate_submissions"] = 0
if logic_error_retries == 0:
h_items["H3_no_logic_errors"] = 14
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"] = 6 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_exec_success_idx is not None:
post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
if idx > last_exec_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"] = 9 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"] = 8 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 "gpu_util" in inp.lower() or "gpu_count" 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)