dicemy's picture
Upload 655 files
e8c001c verified
Raw
History Blame Contribute Delete
30.6 kB
"""hivesql_138 精细评分脚本
业务场景:好友关系强度加权评分(CTE + COALESCE + LOG + 加权系数 + 重标度)
难度: MEDIUM | 特征: CTE|COALESCE|LOG|WEIGHTED_SUM|ROUND|INSERT_OVERWRITE
评分范式: 产物100分 = A(15) + B(10) + C(15) + D(45) + F(15)
A_executability (15分): result.sql 能跑通且产出非空
B_schema (10分): 列数5 + 列名匹配
C_row_alignment (15分): 行数比例 + key(uin,touin)覆盖率
D_score_correctness (25分): 最终得分列逐行匹配
D_raw_score_correctness(20分): 原始分列逐行匹配
F_null_handling (5分): COALESCE 验证(无不当 NULL)
F_boundary_filter (5分): uin>=10000 && touin>=10000
F_insert_overwrite (3分): 写入模式+分区
F_partition_value (2分): imp_date=20260608
权重: MEDIUM → product=0.6, process=0.4
"""
import os
import re
import subprocess
import tempfile
import json
import math
def grade(workspace_path, **kwargs):
# ========== Case 配置 ==========
OUTPUT_TABLE = "internal_platform_db.ads_qq_sq_frd_recommendation_result_list_df_cand_query_engine_138"
DIFFICULTY = "MEDIUM"
SOURCE_TABLES = ["dwd_relationship_strength_features_v4_di_query_engine_138", "ads_qq_sq_frd_recommendation_result_list_df_query_engine_138"]
KEY_COLUMNS = ["uin", "touin"]
MIN_UIN = 10000
GT_TABLE = OUTPUT_TABLE.replace("_cand_", "_")
DIFFICULTY_WEIGHTS = {
"EASY": (0.5, 0.5),
"MEDIUM": (0.6, 0.4),
"HARD": (0.7, 0.3),
"EXPERT": (0.8, 0.2),
}
_SPARK_SUBMIT_TIMEOUT = 300
_JSON_START = "__GRADE_JSON_START__"
_JSON_END = "__GRADE_JSON_END__"
result = {
"overall_score": 0.0,
"total_points": 0,
"grade": "",
"details": {},
"diagnostics": [],
}
# ========== 内部辅助函数 ==========
def values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
if pred_val is None and gt_val is None:
return True
if pred_val is None or gt_val is None:
return False
s_pred = str(pred_val).strip()
s_gt = str(gt_val).strip()
if s_pred == s_gt:
return True
try:
pv = float(s_pred)
gv = float(s_gt)
if math.isnan(pv) and math.isnan(gv):
return True
if math.isnan(pv) or math.isnan(gv):
return False
if abs(gv) < abs_tol:
return abs(pv - gv) <= abs_tol
return abs(pv - gv) <= abs_tol or abs(pv - gv) / max(abs(gv), 1e-12) <= rel_tol
except (ValueError, TypeError):
pass
return s_pred.lower() == s_gt.lower()
def _run_spark_script(script_code, timeout=_SPARK_SUBMIT_TIMEOUT):
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f:
f.write(script_code)
script_path = f.name
try:
r = subprocess.run(
["spark-submit", script_path],
capture_output=True, text=True, timeout=timeout,
)
stdout = r.stdout or ""
if _JSON_START in stdout and _JSON_END in stdout:
json_str = stdout.split(_JSON_START)[1].split(_JSON_END)[0].strip()
return json.loads(json_str), None
else:
if r.returncode == 0:
for line in stdout.splitlines():
if line.strip().startswith("Traceback"):
return None, f"spark-submit error: {line}"
return None, "spark-submit 无 JSON 输出"
err_msg = (r.stderr or "")[-500:]
return None, f"spark-submit failed: {err_msg}"
except subprocess.TimeoutExpired:
return None, f"spark-submit 超时 ({timeout}s)"
except Exception as e:
return None, f"spark-submit 异常: {e}"
finally:
try:
os.unlink(script_path)
except OSError:
pass
def read_table_via_spark_submit(table_name):
"""Read table via spark-submit subprocess. Returns (cols, rows_as_lists)."""
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_.]*$', table_name):
raise ValueError(f"非法表名: {table_name}")
read_script = f'''
import json
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("grade_read").enableHiveSupport() \\
.config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
try:
df = spark.sql("SELECT * FROM {table_name}")
cols = [c.lower() for c in df.columns]
rows = [[str(v) if v is not None else "" for v in row] for row in df.collect()]
print("{_JSON_START}")
print(json.dumps({{"cols": cols, "rows": rows}}, ensure_ascii=False))
print("{_JSON_END}")
except Exception as e:
print("{_JSON_START}")
print(json.dumps({{"error": str(e)}}))
print("{_JSON_END}")
finally:
spark.stop()
'''
data, err = _run_spark_script(read_script)
if err:
raise RuntimeError(f"read_table failed: {err}")
if "error" in data:
raise RuntimeError(f"query failed: {data['error']}")
return data["cols"], data["rows"]
# SQL executor template (self-contained, no external dependency)
_SQL_EXEC_TEMPLATE = '''
import json, re
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("{app_name}").enableHiveSupport() \\
.config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
try:
with open("{sql_file}", "r", encoding="utf-8") as _f:
_sql = _f.read()
_sql = re.sub(r"^\\s*set\\s+query_engine\\.\\S+\\n?", "", _sql, flags=re.IGNORECASE)
_stmts, _cur, _in_sq, _in_dq, _i = [], [], False, False, 0
while _i < len(_sql):
_ch = _sql[_i]
if _ch == "\\\\" and _i + 1 < len(_sql):
_cur.append(_ch); _cur.append(_sql[_i+1]); _i += 2; continue
if _ch == "-" and _i+1 < len(_sql) and _sql[_i+1] == "-" and not _in_sq and not _in_dq:
while _i < len(_sql) and _sql[_i] != "\\n": _i += 1
_cur.append("\\n"); continue
if _ch == "'" and not _in_dq: _in_sq = not _in_sq
elif _ch == '"' and not _in_sq: _in_dq = not _in_dq
if _ch == ";" and not _in_sq and not _in_dq:
_s = "".join(_cur).strip()
if _s: _stmts.append(_s)
_cur = []
else:
_cur.append(_ch)
_i += 1
_last = "".join(_cur).strip()
if _last: _stmts.append(_last)
for _stmt in _stmts:
spark.sql(_stmt)
print("{_JSON_START}")
print(json.dumps({{"ok": True}}))
print("{_JSON_END}")
except Exception as e:
print("{_JSON_START}")
print(json.dumps({{"ok": False, "error": str(e)}}))
print("{_JSON_END}")
finally:
spark.stop()
'''
def execute_result_sql():
result_sql = os.path.join(workspace_path, "result.sql")
if not os.path.exists(result_sql):
return False, "no_result_file"
# 替换 数据平台WD时间变量(沙箱 spark-sql 不支持 ${...} 语法)
with open(result_sql, 'r', encoding='utf-8') as _rf:
_sql_text = _rf.read()
_bizdate = '20260608'
_sql_text = re.sub(r'\${bdp\.system\.bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
_sql_text = re.sub(r'\${yyyymmdd(?:[+-]\d+)?}', _bizdate, _sql_text)
_sql_text = re.sub(r'\${bizdate(?:[+-]\d+)?}', _bizdate, _sql_text)
_sql_text = re.sub(r'\${[^}]*date[^}]*}', _bizdate, _sql_text)
with open(result_sql, 'w', encoding='utf-8') as _wf:
_wf.write(_sql_text)
script = _SQL_EXEC_TEMPLATE.format(app_name="grade_exec", sql_file=result_sql,
_JSON_START=_JSON_START, _JSON_END=_JSON_END)
data, err = _run_spark_script(script)
if err:
return False, f"execution_error: {err}"
if data and data.get("ok"):
return True, None
return False, f"execution_error: {data.get('error', 'unknown') if data else 'no output'}"
def execute_ground_truth_sql():
gt_sql = os.path.join(workspace_path, "gt", "ground_truth.sql")
if not os.path.exists(gt_sql):
return False, "ground_truth.sql not found"
script = _SQL_EXEC_TEMPLATE.format(app_name="grade_gt", sql_file=gt_sql,
_JSON_START=_JSON_START, _JSON_END=_JSON_END)
data, err = _run_spark_script(script)
if err:
return False, f"gt_execution_error: {err}"
if data and data.get("ok"):
return True, None
return False, f"gt_execution_error: {data.get('error', 'unknown') if data else 'no output'}"
def truncate_table(table_name):
script = f'''
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("truncate").enableHiveSupport() \\
.config("spark.sql.warehouse.dir", "/tmp/hive_warehouse").getOrCreate()
spark.sql("TRUNCATE TABLE {table_name}")
spark.stop()
'''
try:
_run_spark_script(script, timeout=120)
except Exception:
pass
def restore_hive_site():
"""Restore hive-site.xml to canonical state (agent may have modified it)."""
canonical_hive_site = '''<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>hive.metastore.uris</name>
<value>thrift://localhost:9083</value>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/tmp/hive_warehouse</value>
</property>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/tmp/hive_metastore_db;create=true</value>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
</property>
<property>
<name>datanucleus.schema.autoCreateAll</name>
<value>true</value>
</property>
<property>
<name>hive.metastore.schema.verification</name>
<value>false</value>
</property>
</configuration>
'''
hive_site_path = os.path.join(os.environ.get('SPARK_HOME', '/opt/spark'), 'conf', 'hive-site.xml')
try:
with open(hive_site_path, 'w') as f:
f.write(canonical_hive_site)
except Exception:
pass
def finalize(result):
product_weight, process_weight = DIFFICULTY_WEIGHTS.get(DIFFICULTY, (0.7, 0.3))
product_dims = ["A_executability"] + ['B_schema', 'C_row_alignment', 'D_raw_score_correctness', 'D_score_correctness', 'F_boundary_filter', 'F_insert_overwrite', 'F_null_handling', 'F_partition_value']
product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
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)
product_score = round(product_raw * product_weight, 2)
process_score = round(process_raw * process_weight, 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["weights"] = {"product": product_weight, "process": process_weight}
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
# Restore hive-site.xml (agent may have modified it)
restore_hive_site()
# ========== A. 可执行性 (15分) ==========
a_items = {"A1_exec_ok": 0, "A2_has_data": 0}
exec_ok, exec_err = execute_result_sql()
if not exec_ok:
detail = "未产出 result.sql" if exec_err == "no_result_file" else str(exec_err)[:200]
result["details"]["A_executability"] = {"score": 0, "max": 15, "detail": detail}
result["error"] = detail
for dim in ['B_schema', 'C_row_alignment', 'D_raw_score_correctness', 'D_score_correctness', 'F_boundary_filter', 'F_insert_overwrite', 'F_null_handling', 'F_partition_value']:
result["details"][dim] = {"score": 0, "max": 0, "items": {}}
return finalize(result)
a_items["A1_exec_ok"] = 8
pred_headers, pred_rows = [], []
try:
pred_headers, pred_rows = read_table_via_spark_submit(OUTPUT_TABLE)
except Exception as e:
result["diagnostics"].append(f"read_pred_failed: {e}")
if not pred_rows:
result["details"]["A_executability"] = {"score": 8, "max": 15, "items": a_items}
for dim in ['B_schema', 'C_row_alignment', 'D_raw_score_correctness', 'D_score_correctness', 'F_boundary_filter', 'F_insert_overwrite', 'F_null_handling', 'F_partition_value']:
result["details"][dim] = {"score": 0, "max": 0, "items": {}}
return finalize(result)
a_items["A2_has_data"] = 7
result["details"]["A_executability"] = {"score": 15, "max": 15, "items": a_items}
# ========== Execute GT + Read GT ==========
truncate_table(GT_TABLE)
gt_ok, gt_err = execute_ground_truth_sql()
if not gt_ok:
result["error"] = f"ground_truth failed: {gt_err}"
for dim in ['B_schema', 'C_row_alignment', 'D_raw_score_correctness', 'D_score_correctness', 'F_boundary_filter', 'F_insert_overwrite', 'F_null_handling', 'F_partition_value']:
result["details"][dim] = {"score": 0, "max": 0, "items": {}}
return finalize(result)
gt_headers, gt_rows = [], []
try:
gt_headers, gt_rows = read_table_via_spark_submit(GT_TABLE)
except Exception as e:
result["error"] = f"read_gt_failed: {e}"
for dim in ['B_schema', 'C_row_alignment', 'D_raw_score_correctness', 'D_score_correctness', 'F_boundary_filter', 'F_insert_overwrite', 'F_null_handling', 'F_partition_value']:
result["details"][dim] = {"score": 0, "max": 0, "items": {}}
return finalize(result)
# ========== B/C/D/F 维度评分 ==========
pred_col_map = {h: i for i, h in enumerate(pred_headers)}
gt_col_map = {h: i for i, h in enumerate(gt_headers)}
# ========== B. Schema正确性 (10分) ==========
b_items = {}
expected_col_count = 5 # uin, touin, score, raw_score + imp_date(partition)
if len(pred_headers) == expected_col_count:
b_items["B1_col_count"] = 5
elif abs(len(pred_headers) - expected_col_count) <= 1:
b_items["B1_col_count"] = 3
else:
b_items["B1_col_count"] = 0
gt_col_set = set(gt_headers)
pred_col_set = set(pred_headers)
name_match_rate = len(gt_col_set & pred_col_set) / max(len(gt_col_set), 1)
if name_match_rate >= 0.95:
b_items["B2_col_names"] = 5
elif name_match_rate >= 0.8:
b_items["B2_col_names"] = 3
else:
b_items["B2_col_names"] = 0
b_score = sum(b_items.values())
result["details"]["B_schema"] = {
"score": b_score, "max": 10,
"detail": {"col_count": len(pred_headers), "name_match_rate": round(name_match_rate, 4), "items": b_items},
}
# ========== C. 行一致性 (15分) ==========
c_items = {}
gt_row_count = len(gt_rows)
pred_row_count = len(pred_rows)
if gt_row_count > 0:
ratio = pred_row_count / gt_row_count
if 0.95 <= ratio <= 1.05:
c_items["C1_row_ratio"] = 7
elif 0.7 <= ratio <= 1.3:
c_items["C1_row_ratio"] = 4
else:
c_items["C1_row_ratio"] = 0
else:
c_items["C1_row_ratio"] = 7 if pred_row_count == 0 else 0
key_cols_avail = [k for k in KEY_COLUMNS if k in gt_col_map and k in pred_col_map]
if key_cols_avail and gt_row_count > 0:
gt_keys = set()
for row in gt_rows:
key = tuple(row[gt_col_map[k]] if gt_col_map[k] < len(row) else "" for k in key_cols_avail)
gt_keys.add(key)
pred_keys = set()
for row in pred_rows:
key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
pred_keys.add(key)
coverage = len(gt_keys & pred_keys) / max(len(gt_keys), 1)
if coverage >= 0.995:
c_items["C2_key_coverage"] = 8
elif coverage >= 0.9:
c_items["C2_key_coverage"] = 6
elif coverage >= 0.7:
c_items["C2_key_coverage"] = 3
else:
c_items["C2_key_coverage"] = round(8 * coverage, 2)
else:
c_items["C2_key_coverage"] = 0
c_score = sum(v for v in c_items.values())
result["details"]["C_row_alignment"] = {"score": c_score, "max": 15, "detail": c_items}
# 建立 pred 索引(用于后续 D 维度)
pred_index = {}
if key_cols_avail:
for row in pred_rows:
key = tuple(row[pred_col_map[k]] if pred_col_map[k] < len(row) else "" for k in key_cols_avail)
pred_index[key] = row
# ========== D. score 正确性 (25分) ==========
d_score_items = {}
score_col = "score"
score_matches = 0
score_total = 0
gt_score_ci = gt_col_map.get(score_col)
pred_score_ci = pred_col_map.get(score_col)
if gt_score_ci is not None and pred_score_ci is not None and key_cols_avail:
for gt_row in gt_rows:
key = tuple(gt_row[gt_col_map[k]] if gt_col_map[k] < len(gt_row) else "" for k in key_cols_avail)
gt_val = gt_row[gt_score_ci].strip() if gt_score_ci < len(gt_row) else ""
pred_row = pred_index.get(key)
if pred_row is None:
score_total += 1
continue
pred_val = pred_row[pred_score_ci].strip() if pred_score_ci < len(pred_row) else ""
if values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
score_matches += 1
score_total += 1
score_pass_rate = score_matches / max(score_total, 1)
d_score_items["pass_rate"] = round(score_pass_rate, 4)
d_score_items["score"] = round(25 * score_pass_rate, 2)
else:
d_score_items["pass_rate"] = 0.0
d_score_items["score"] = 0
d_score_items["reason"] = "score column missing or no key columns"
result["details"]["D_score_correctness"] = {"score": d_score_items["score"], "max": 25, "detail": d_score_items}
# ========== D. raw_score 正确性 (20分) ==========
d_raw_items = {}
raw_col = "raw_score"
raw_matches = 0
raw_total = 0
gt_raw_ci = gt_col_map.get(raw_col)
pred_raw_ci = pred_col_map.get(raw_col)
if gt_raw_ci is not None and pred_raw_ci is not None and key_cols_avail:
for gt_row in gt_rows:
key = tuple(gt_row[gt_col_map[k]] if gt_col_map[k] < len(gt_row) else "" for k in key_cols_avail)
gt_val = gt_row[gt_raw_ci].strip() if gt_raw_ci < len(gt_row) else ""
pred_row = pred_index.get(key)
if pred_row is None:
raw_total += 1
continue
pred_val = pred_row[pred_raw_ci].strip() if pred_raw_ci < len(pred_row) else ""
if values_match(pred_val, gt_val, abs_tol=1e-6, rel_tol=1e-4):
raw_matches += 1
raw_total += 1
raw_pass_rate = raw_matches / max(raw_total, 1)
d_raw_items["pass_rate"] = round(raw_pass_rate, 4)
d_raw_items["score"] = round(20 * raw_pass_rate, 2)
else:
d_raw_items["pass_rate"] = 0.0
d_raw_items["score"] = 0
d_raw_items["reason"] = "raw_score column missing or no key columns"
result["details"]["D_raw_score_correctness"] = {"score": d_raw_items["score"], "max": 20, "detail": d_raw_items}
# ========== F. NULL 处理 (5分) ==========
f_null_items = {}
null_violations = 0
null_total = 0
if key_cols_avail and gt_score_ci is not None and pred_score_ci is not None:
for gt_row in gt_rows:
key = tuple(gt_row[gt_col_map[k]] if gt_col_map[k] < len(gt_row) else "" for k in key_cols_avail)
gt_val = gt_row[gt_score_ci].strip() if gt_score_ci < len(gt_row) else ""
pred_row = pred_index.get(key)
if pred_row is None:
continue
pred_val = pred_row[pred_score_ci].strip() if pred_score_ci < len(pred_row) else ""
null_total += 1
if gt_val and gt_val.lower() not in ("null", "none", ""):
if not pred_val or pred_val.lower() in ("null", "none", ""):
null_violations += 1
if null_total > 0:
null_pass_rate = 1 - (null_violations / null_total)
else:
null_pass_rate = 1.0
f_null_items["null_handling_rate"] = round(null_pass_rate, 4)
f_null_score = round(5 * null_pass_rate, 2)
result["details"]["F_null_handling"] = {"score": f_null_score, "max": 5, "detail": f_null_items}
# ========== F. 边界过滤 (5分) ==========
f_boundary_items = {}
boundary_violations = 0
user_id_ci = pred_col_map.get("uin")
touser_id_ci = pred_col_map.get("touin")
if user_id_ci is not None and touser_id_ci is not None:
for row in pred_rows:
try:
user_id_val = float(row[user_id_ci].strip()) if user_id_ci < len(row) else 0
touser_id_val = float(row[touser_id_ci].strip()) if touser_id_ci < len(row) else 0
if user_id_val < MIN_UIN or touser_id_val < MIN_UIN:
boundary_violations += 1
except (ValueError, TypeError):
pass
if pred_row_count > 0:
boundary_pass_rate = 1 - (boundary_violations / pred_row_count)
else:
boundary_pass_rate = 0.0
f_boundary_items["boundary_pass_rate"] = round(boundary_pass_rate, 4)
f_boundary_items["violations"] = boundary_violations
f_boundary_score = round(5 * boundary_pass_rate, 2)
result["details"]["F_boundary_filter"] = {"score": f_boundary_score, "max": 5, "detail": f_boundary_items}
# ========== F. INSERT OVERWRITE (3分) ==========
f_insert_items = {}
result_sql_path = os.path.join(workspace_path, "result.sql")
sql_text = ""
try:
with open(result_sql_path, "r", encoding="utf-8") as f:
sql_text = f.read().lower()
except Exception:
sql_text = ""
has_overwrite = "insert overwrite" in sql_text
has_partition = "partition" in sql_text
if has_overwrite and has_partition:
f_insert_items["insert_overwrite_partition"] = 3
elif has_overwrite:
f_insert_items["insert_overwrite_partition"] = 2
else:
f_insert_items["insert_overwrite_partition"] = 0
result["details"]["F_insert_overwrite"] = {
"score": f_insert_items["insert_overwrite_partition"], "max": 3, "detail": f_insert_items,
}
# ========== F. 分区值 (2分) ==========
f_part_items = {}
if "imp_date" in sql_text and "20260608" in sql_text:
f_part_items["partition_value"] = 2
else:
f_part_items["partition_value"] = 0
result["details"]["F_partition_value"] = {
"score": f_part_items["partition_value"], "max": 2, "detail": f_part_items,
}
# 汇总
total = (15 + b_score + c_score + d_score_items["score"] + d_raw_items["score"]
+ f_null_score + f_boundary_score + f_insert_items["insert_overwrite_partition"]
+ f_part_items["partition_value"])
# ========== G~I 过程评分 ==========
TRANSCRIPT_PATH = "/tmp/dataclaw_chat.jsonl"
OUTPUT_TABLE_SHORT = OUTPUT_TABLE.split(".")[-1]
INPUT_TABLE_SHORT = SOURCE_TABLES[0]
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 into structured events
tool_uses = []
first_write_result_idx = None
last_spark_submit_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.sql" 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:
env_errors = ["Derby", "metastore", "HiveMetaStore", "Connection refused",
"db.lck", "TTransportException", "port 10000"]
is_env_error = any(e in block_str for e in env_errors)
has_spark_submit = any(t[1] == "Bash" and "spark-submit" in t[2] and "result.sql" in t[2]
for t in tool_uses)
if not is_env_error and has_spark_submit:
logic_error_retries += 1
if ("spark-submit" in block_str or "spark-sql" in block_str) and "result.sql" 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_pass = any(name == "Read" and "schema" in inp.lower()
for idx, name, inp in tool_uses if idx < before_first_write)
g_items["G1_source_schema"] = 9 if g1_pass else 0
g2_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
and "SELECT" in inp.upper() and "LIMIT" in inp.upper()
for idx, name, inp in tool_uses if idx < before_first_write)
g_items["G2_source_sample"] = 9 if g2_pass else 0
g3_pass = any(name == "Bash" and INPUT_TABLE_SHORT in inp
and ("GROUP BY" in inp.upper() or "DISTINCT" in inp.upper() or "COUNT" in inp.upper())
for idx, name, inp in tool_uses if idx < before_first_write)
g_items["G3_distribution"] = 9 if g3_pass else 0
g4_pass = any(name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper())
and OUTPUT_TABLE_SHORT in inp
for idx, name, inp in tool_uses if idx < before_first_write)
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"] = 20
elif write_result_count <= 4:
h_items["H1_few_submissions"] = 13
elif write_result_count <= 6:
h_items["H1_few_submissions"] = 7
else:
h_items["H1_few_submissions"] = 0
if logic_error_retries == 0:
h_items["H2_no_logic_errors"] = 13
elif logic_error_retries <= 1:
h_items["H2_no_logic_errors"] = 7
else:
h_items["H2_no_logic_errors"] = 0
h_items["H3_no_redundancy"] = 7
h_score = sum(h_items.values())
result["details"]["H_efficiency"] = {"score": min(h_score, 40), "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"] = 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())
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)