dicemy's picture
Upload 655 files
e8c001c verified
Raw
History Blame Contribute Delete
29.2 kB
"""hivesql_013 精细评分脚本
业务场景:汇总当天有生产量的 消息队列MQ topic 维度信息,派生 mq_full_topic 等字段,落地为 topic 治理项明细表
难度: EASY | 特征: INSERT_OVERWRITE|PARTITION|SINGLE_TABLE|FIELD_MAPPING|DERIVED_COLUMN
评分范式: 产物100分 = A(15) + B(10) + C(15) + D(40) + F(20)
A_executability (15分): result.sql 能跑通且产出非空
B_schema (10分): 30列(5) + 列名匹配(5)
C_row_alignment (15分): 行数比例(7) + key覆盖率(8)
D_field_mapping (25分): 字段别名映射正确性(app_group/bid_*等)
D_derived_mq_full_topic (15分): mq_full_topic 派生列拼接逻辑正确性
F_insert_overwrite (5分): INSERT OVERWRITE + PARTITION
F_partition_value (5分): dt 分区值 = 20260507
F_filter_condition (10分): WHERE dt='20260507' AND total_produce_pkg_last_90d>0
权重: EASY -> product=0.5, process=0.5
"""
import os
import re
import subprocess
import tempfile
import json
import math
def grade(workspace_path, **kwargs):
# ========== Case 配置 ==========
OUTPUT_TABLE = "internal_platform_db.ads_mq_topic_governance_item_d_cand_query_engine_013"
DIFFICULTY = "EASY"
SOURCE_TABLES = ["dws_mq_production_feature_d_increase_query_engine_013", "ads_mq_topic_governance_item_d_query_engine_013"]
KEY_COLUMNS = ["business_id", "bid_incharge", "bid_description", "bid_create_time", "bid_modify_time", "cluster_id", "dt"]
EXPECTED_COL_COUNT = 30
FIELD_MAPPINGS = {
"dw_appgroup": "app_group",
"in_charge": "bid_incharge",
"description": "bid_description",
"create_time": "bid_create_time",
"modify_time": "bid_modify_time",
}
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 = '20260507'
_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_derived_mq_full_topic', 'D_field_mapping', 'F_filter_condition', 'F_insert_overwrite', '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_derived_mq_full_topic', 'D_field_mapping', 'F_filter_condition', 'F_insert_overwrite', '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_derived_mq_full_topic', 'D_field_mapping', 'F_filter_condition', 'F_insert_overwrite', '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_derived_mq_full_topic', 'D_field_mapping', 'F_filter_condition', 'F_insert_overwrite', '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_derived_mq_full_topic', 'D_field_mapping', 'F_filter_condition', 'F_insert_overwrite', '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 = {}
# B1: 列数 (5分)
if len(pred_headers) == EXPECTED_COL_COUNT:
b_items["B1_col_count"] = 5
elif abs(len(pred_headers) - EXPECTED_COL_COUNT) <= 2:
b_items["B1_col_count"] = 3
else:
b_items["B1_col_count"] = 0
# B2: 列名匹配 (5分)
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)
# C1: 行数比例 (7分)
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
# C2: key覆盖率 (8分)
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}
# 构建索引
if key_cols_avail:
pred_index = {}
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
gt_index = {}
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_index[key] = row
else:
pred_index = {}
gt_index = {}
# ========== D. 字段映射正确性 (25分) ==========
d_map_items = {}
per_mapping_weight = 25.0 / max(len(FIELD_MAPPINGS), 1)
d_map_score = 0
for src_col, dst_col in FIELD_MAPPINGS.items():
# GT 中该列用 dst_col 名
gt_ci = gt_col_map.get(dst_col)
pred_ci = pred_col_map.get(dst_col)
if gt_ci is None or pred_ci is None:
d_map_items[dst_col] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
continue
matches = 0
total = 0
for key, gt_row in gt_index.items():
pred_row = pred_index.get(key)
if pred_row is None:
total += 1
continue
gt_val = gt_row[gt_ci].strip() if gt_ci < len(gt_row) else ""
pred_val = pred_row[pred_ci].strip() if pred_ci < len(pred_row) else ""
if values_match(pred_val, gt_val):
matches += 1
total += 1
rate = matches / max(total, 1)
col_score = rate * per_mapping_weight
d_map_score += col_score
d_map_items[dst_col] = {"pass_rate": round(rate, 4), "score": round(col_score, 2), "mapped_from": src_col}
result["details"]["D_field_mapping"] = {
"score": round(d_map_score, 2), "max": 25, "detail": d_map_items,
}
# ========== D. mq_full_topic 派生列 (15分) ==========
d_mq_items = {}
d_mq_score = 0
mq_ci = pred_col_map.get("mq_full_topic")
gt_mq_ci = gt_col_map.get("mq_full_topic")
if mq_ci is None or gt_mq_ci is None:
d_mq_items["mq_full_topic"] = {"pass_rate": 0.0, "score": 0, "reason": "column_missing"}
else:
matches = 0
total = 0
for key, gt_row in gt_index.items():
pred_row = pred_index.get(key)
if pred_row is None:
total += 1
continue
gt_val = gt_row[gt_mq_ci].strip() if gt_mq_ci < len(gt_row) else ""
pred_val = pred_row[mq_ci].strip() if mq_ci < len(pred_row) else ""
if values_match(pred_val, gt_val):
matches += 1
total += 1
rate = matches / max(total, 1)
d_mq_score = rate * 15
d_mq_items["mq_full_topic"] = {"pass_rate": round(rate, 4), "score": round(d_mq_score, 2)}
result["details"]["D_derived_mq_full_topic"] = {
"score": round(d_mq_score, 2), "max": 15, "detail": d_mq_items,
}
# ========== F. INSERT OVERWRITE (5分) ==========
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 = ""
f_insert_items = {}
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"] = 5
elif has_overwrite:
f_insert_items["insert_overwrite_partition"] = 3
else:
f_insert_items["insert_overwrite_partition"] = 0
result["details"]["F_insert_overwrite"] = {
"score": f_insert_items["insert_overwrite_partition"], "max": 5, "detail": f_insert_items,
}
# ========== F. 分区值 (5分) ==========
f_part_items = {}
if "dt" in sql_text and "20260507" in sql_text:
f_part_items["partition_value"] = 5
else:
f_part_items["partition_value"] = 0
result["details"]["F_partition_value"] = {
"score": f_part_items["partition_value"], "max": 5, "detail": f_part_items,
}
# ========== F. 过滤条件 (10分) ==========
f_filter_items = {}
has_dt_filter = "dt" in sql_text and "20260507" in sql_text
has_pkg_filter = "total_produce_pkg_last_90d" in sql_text and (">0" in sql_text.replace(" ", "") or "> 0" in sql_text)
if has_dt_filter and has_pkg_filter:
f_filter_items["filter_condition"] = 10
elif has_dt_filter:
f_filter_items["filter_condition"] = 5
elif has_pkg_filter:
f_filter_items["filter_condition"] = 3
else:
f_filter_items["filter_condition"] = 0
result["details"]["F_filter_condition"] = {
"score": f_filter_items["filter_condition"], "max": 10, "detail": f_filter_items,
}
# 汇总
total = (15 + b_score + c_score + d_map_score + d_mq_score
+ f_insert_items["insert_overwrite_partition"]
+ f_part_items["partition_value"]
+ f_filter_items["filter_condition"])
# ========== 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)