dicemy's picture
Upload 655 files
e8c001c verified
Raw
History Blame Contribute Delete
28 kB
def grade(workspace_path, **kwargs):
"""
mysql_016 rule-based grading: 应用X模型与组织关系小时表全量迁移
总分结构 (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_app_xmodel_and_org_relation_hour_src_mysql_016"
OUTPUT_TABLE = "t_app_xmodel_and_org_relation_hour_cand_mysql_016"
FULL_OUTPUT = f"{DB_NAME}.{OUTPUT_TABLE}"
FULL_INPUT = f"{DB_NAME}.{INPUT_TABLE}"
KEY_COLUMNS = ["xsoa_id"]
EXPECTED_COL_COUNT = 12
EXPECTED_ROW_COUNT = 8
MYSQL_CONFIG = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "root123",
"charset": "utf8mb4",
}
# Expected output (full migration of all source rows)
EXPECTED_ROWS = [
{"xsoa_id": "xsoa_001", "principal": "zhangsan", "xsoa_org_principal": "lisi",
"xsoa_team_name": "TeamA", "xsoa_team_id": "T001", "xsoa_center_name": "CenterX",
"xsoa_center_id": "C001", "xsoa_dept_name": "DeptAlpha", "xsoa_dept_id": "D001",
"xsoa_principal_index": 1, "xsoa_dimension": "employeeName", "ds": 2026060918},
{"xsoa_id": "xsoa_002", "principal": "wangwu", "xsoa_org_principal": "zhaoliu",
"xsoa_team_name": "TeamB", "xsoa_team_id": "T002", "xsoa_center_name": "CenterY",
"xsoa_center_id": "C002", "xsoa_dept_name": "DeptBeta", "xsoa_dept_id": "D002",
"xsoa_principal_index": 2, "xsoa_dimension": "employeeId", "ds": 2026060918},
{"xsoa_id": "xsoa_003", "principal": "sunqi", "xsoa_org_principal": "zhouba",
"xsoa_team_name": "TeamC", "xsoa_team_id": "T003", "xsoa_center_name": "CenterZ",
"xsoa_center_id": "C003", "xsoa_dept_name": "DeptGamma", "xsoa_dept_id": "D003",
"xsoa_principal_index": 3, "xsoa_dimension": "employeeLevel", "ds": 2026060918},
{"xsoa_id": "xsoa_004", "principal": "qianjiu", "xsoa_org_principal": "wushi",
"xsoa_team_name": "TeamA", "xsoa_team_id": "T001", "xsoa_center_name": "CenterX",
"xsoa_center_id": "C001", "xsoa_dept_name": "DeptAlpha", "xsoa_dept_id": "D001",
"xsoa_principal_index": 1, "xsoa_dimension": "employeeDept", "ds": 2026060918},
{"xsoa_id": "xsoa_005", "principal": "liuyi", "xsoa_org_principal": "chener",
"xsoa_team_name": "TeamD", "xsoa_team_id": "T004", "xsoa_center_name": "CenterW",
"xsoa_center_id": "C004", "xsoa_dept_name": "DeptDelta", "xsoa_dept_id": "D004",
"xsoa_principal_index": 4, "xsoa_dimension": "employeeName", "ds": 2026060918},
{"xsoa_id": "xsoa_006", "principal": "zhengshi", "xsoa_org_principal": "wanger",
"xsoa_team_name": "TeamB", "xsoa_team_id": "T002", "xsoa_center_name": "CenterY",
"xsoa_center_id": "C002", "xsoa_dept_name": "DeptBeta", "xsoa_dept_id": "D002",
"xsoa_principal_index": 2, "xsoa_dimension": "employeeName", "ds": 2026061006},
{"xsoa_id": "xsoa_007", "principal": "maba", "xsoa_org_principal": "songjiu",
"xsoa_team_name": "TeamC", "xsoa_team_id": "T003", "xsoa_center_name": "CenterZ",
"xsoa_center_id": "C003", "xsoa_dept_name": "DeptGamma", "xsoa_dept_id": "D003",
"xsoa_principal_index": 3, "xsoa_dimension": "employeeId", "ds": 2026061006},
{"xsoa_id": "xsoa_008", "principal": "tianyi", "xsoa_org_principal": "gaoqi",
"xsoa_team_name": "TeamE", "xsoa_team_id": "T005", "xsoa_center_name": "CenterV",
"xsoa_center_id": "C005", "xsoa_dept_name": "DeptEpsilon", "xsoa_dept_id": "D005",
"xsoa_principal_index": 5, "xsoa_dimension": "employeeLevel", "ds": 2026061018},
]
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 (save BEFORE running GT)
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 = []
# Read columns info (save BEFORE running GT)
pred_cols_info = None
try:
pred_cols_info = _mysql_columns(FULL_OUTPUT)
pred_columns = [c["Field"] for c in pred_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 running ground_truth.py)
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_set = set(c.lower() for c in ["xsoa_id", "principal", "xsoa_org_principal",
"xsoa_team_name", "xsoa_team_id",
"xsoa_center_name", "xsoa_center_id",
"xsoa_dept_name", "xsoa_dept_id",
"xsoa_principal_index", "xsoa_dimension", "ds"])
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 (compare pred schema saved BEFORE GT vs GT schema after GT)
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 pred_cols_info} if pred_cols_info else {}
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 = ["xsoa_principal_index", "ds"]
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 columns
string_cols = ["xsoa_id", "principal", "xsoa_org_principal", "xsoa_team_name",
"xsoa_team_id", "xsoa_center_name", "xsoa_center_id",
"xsoa_dept_name", "xsoa_dept_id", "xsoa_dimension"]
# 10 string cols x 2.2 each = 22, remaining from 40 - 18 (2 numeric) = 22
per_string_max = 22 / len(string_cols) if string_cols else 0
for col in string_cols:
if not hit_row_keys:
d_items[col] = {"pass_rate": 0.0, "score": 0, "max": round(per_string_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(per_string_max * pass_rate, 2), "max": round(per_string_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 xsoa_ids present
expected_ids = {"xsoa_001", "xsoa_002", "xsoa_003", "xsoa_004", "xsoa_005", "xsoa_006", "xsoa_007", "xsoa_008"}
pred_ids = set(str(row.get("xsoa_id", "")).strip() for row in pred_rows)
e1_pass = len(expected_ids & pred_ids)
e_items["E1_xsoa_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_app_xmodel_and_org_relation_hour_src_mysql_016"
OUTPUT_TABLE_SHORT = "t_app_xmodel_and_org_relation_hour_cand_mysql_016"
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
for idx, entry in enumerate(transcript_entries):
content = entry.get("content", [])
if isinstance(content, str):
content = [content]
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 == "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 ds 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 "COUNT" in inp.upper() or "GROUP BY" in inp.upper():
g3_pass = True
break
g_items["G3_data_distribution"] = 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 "xsoa" 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)