Datasets:
File size: 30,683 Bytes
e8c001c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | def grade(workspace_path, **kwargs):
"""
mysql_019 rule-based grading: 传感器事件宽表关联用户组帖子分类圈组维度
总分结构 (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_knowledge_base_sensors_event_di_mysql_019"
OUTPUT_TABLE = "dwd_knowledge_base_k_bar_posts_event_di_cand_mysql_019"
FULL_OUTPUT = f"{DB_NAME}.{OUTPUT_TABLE}"
FULL_INPUT = f"{DB_NAME}.{INPUT_TABLE}"
KEY_COLUMNS = ["event", "distinct_id"]
EXPECTED_COL_COUNT = 27
EXPECTED_ROW_COUNT = 5
MYSQL_CONFIG = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "root123",
"charset": "utf8mb4",
}
# Expected output (from GT SQL execution with clean MySQL data)
# Columns: event, distinct_id, appname, user_id, event_time, receive_time, os,
# track_signup_original_id, author_nick, platform_type, target_type, target_id,
# ip, post_id, show_groups, group_id, source_page, source_module, operation_type,
# pc_or_mobile, is_group_member, post_authorship, posts_category_id,
# posts_category_name, year, month, day
EXPECTED_ROWS = [{'event': 'postdetailview', 'distinct_id': 'nick_a', 'appname': 'knowledge_base', 'user_id': 'u001', 'event_time': '2026-06-08 10:00:00', 'receive_time': '2026-06-08 10:00:01', 'os': 'ios', 'track_signup_original_id': 'track01', 'author_nick': 'author_a', 'platform_type': 'pc', 'target_type': 'target_t1', 'target_id': 'tid1', 'ip': '192.168.1.1', 'post_id': '1001', 'show_groups': '101', 'group_id': '101', 'source_page': 'page1', 'source_module': 'mod1', 'operation_type': 'op_type1', 'pc_or_mobile': 'pc', 'is_group_member': 1, 'post_authorship': 'original', 'posts_category_id': 201, 'posts_category_name': 'Tech Category', 'year': '2026', 'month': '06', 'day': '08'}, {'event': 'postdigg', 'distinct_id': 'nick_b', 'appname': 'knowledge_base', 'user_id': 'u002', 'event_time': '2026-06-08 11:00:00', 'receive_time': '2026-06-08 11:00:01', 'os': 'android', 'track_signup_original_id': 'track02', 'author_nick': 'author_b', 'platform_type': 'android', 'target_type': 'target_t2', 'target_id': 'tid2', 'ip': '10.0.0.1', 'post_id': '1002', 'show_groups': None, 'group_id': '102', 'source_page': 'page2', 'source_module': 'mod2', 'operation_type': 'op_type2', 'pc_or_mobile': 'mobile', 'is_group_member': 1, 'post_authorship': 'repost', 'posts_category_id': 202, 'posts_category_name': 'General Category', 'year': '2026', 'month': '06', 'day': '08'}, {'event': 'postbooknowledge_baseark', 'distinct_id': 'nick_c', 'appname': 'knowledge_base', 'user_id': 'u003', 'event_time': '2026-06-08 12:00:00', 'receive_time': '2026-06-08 12:00:01', 'os': 'h5', 'track_signup_original_id': 'track03', 'author_nick': 'author_c', 'platform_type': 'h5', 'target_type': 'target_t3', 'target_id': 'tid3', 'ip': '172.16.0.1', 'post_id': '1001', 'show_groups': '101', 'group_id': '101', 'source_page': 'page3', 'source_module': 'mod3', 'operation_type': 'op_type3', 'pc_or_mobile': 'mobile', 'is_group_member': 0, 'post_authorship': 'original', 'posts_category_id': 201, 'posts_category_name': 'Tech Category', 'year': '2026', 'month': '06', 'day': '08'}, {'event': 'commentsend', 'distinct_id': 'nick_d', 'appname': 'knowledge_base', 'user_id': 'u004', 'event_time': '2026-06-08 13:00:00', 'receive_time': '2026-06-08 13:00:01', 'os': 'windows', 'track_signup_original_id': 'track04', 'author_nick': 'author_d', 'platform_type': 'windows', 'target_type': 'target_t4', 'target_id': 'tid4', 'ip': '8.8.8.8', 'post_id': '1003', 'show_groups': None, 'group_id': '103', 'source_page': 'page4', 'source_module': 'mod4', 'operation_type': 'op_type4', 'pc_or_mobile': 'pc', 'is_group_member': 0, 'post_authorship': 'original', 'posts_category_id': 201, 'posts_category_name': 'Tech Category', 'year': '2026', 'month': '06', 'day': '08'}, {'event': 'postcomment', 'distinct_id': 'nick_a', 'appname': 'knowledge_base', 'user_id': 'u005', 'event_time': '2026-06-08 14:00:00', 'receive_time': '2026-06-08 14:00:01', 'os': 'ios', 'track_signup_original_id': 'track05', 'author_nick': 'author_e', 'platform_type': 'ios', 'target_type': 'target_t5', 'target_id': 'tid5', 'ip': '1.1.1.1', 'post_id': '1002', 'show_groups': '102', 'group_id': '102', 'source_page': 'page5', 'source_module': 'mod5', 'operation_type': 'op_type5', 'pc_or_mobile': 'mobile', 'is_group_member': 0, 'post_authorship': 'repost', 'posts_category_id': 202, 'posts_category_name': 'General Category', 'year': '2026', 'month': '06', 'day': '08'}]
result = {
"overall_score": 0.0,
"total_points": 0,
"grade": "",
"details": {},
"diagnostics": [],
"anti_cheat": {"passed": True},
}
# ========== Helper: MySQL connection ==========
def _mysql_fetch_all(sql):
import pymysql
conn = pymysql.connect(**MYSQL_CONFIG)
try:
with conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
finally:
conn.close()
def _mysql_execute(sql):
import pymysql
conn = pymysql.connect(**MYSQL_CONFIG)
try:
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
finally:
conn.close()
def _mysql_fetch_dicts(sql):
import pymysql
conn = pymysql.connect(**MYSQL_CONFIG)
try:
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(sql)
return cur.fetchall()
finally:
conn.close()
def _mysql_columns(table_full):
import pymysql
conn = pymysql.connect(**MYSQL_CONFIG)
try:
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(f"DESCRIBE {table_full}")
return cur.fetchall()
finally:
conn.close()
def coverage_to_ratio(rate):
if rate >= 0.995:
return 1.0
elif rate >= 0.90:
return 0.8
elif rate >= 0.70:
return 0.5
else:
return 0.0
def values_match(pred_val, gt_val):
if pred_val is None and gt_val is None:
return True
if pred_val is None or gt_val is None:
return False
try:
pv = int(pred_val)
gv = int(gt_val)
return pv == gv
except (ValueError, TypeError):
return str(pred_val).strip() == str(gt_val).strip()
def finalize(result):
ALPHA = 0.3
product_dims = ["A_executability", "B_schema", "C_row_alignment",
"D_numerical_accuracy", "E_labels"]
product_raw = sum(result["details"].get(d, {}).get("score", 0) for d in product_dims)
product_score = round(product_raw * (1 - ALPHA), 2)
product_ratio = product_raw / 100.0
for dim in ["H_efficiency"]:
if dim in result["details"]:
raw = result["details"][dim].get("score", 0)
result["details"][dim]["score_before_scaling"] = raw
result["details"][dim]["score"] = round(raw * product_ratio, 2)
result["details"][dim]["product_ratio"] = round(product_ratio, 4)
process_dims = ["G_exploration", "H_efficiency", "I_self_verification"]
process_raw = sum(result["details"].get(d, {}).get("score", 0) for d in process_dims)
process_score = round(process_raw * ALPHA, 2)
total = round(product_score + process_score, 2)
result["total_points"] = total
result["product_points"] = product_score
result["process_points"] = round(process_score, 2)
result["overall_score"] = round(total / 100.0, 4)
if total >= 90:
result["grade"] = "优秀"
elif total >= 75:
result["grade"] = "良好"
elif total >= 60:
result["grade"] = "合格"
elif total >= 40:
result["grade"] = "偏弱"
else:
result["grade"] = "不合格"
return result
# ========== Product grading ==========
def _product_grade():
# ===== A. 可执行性 (15分) =====
a_items = {"A1_no_error": 0, "A2_table_produced": 0, "A3_no_manual_fix": 0}
agent_code = os.path.join(workspace_path, "result.py")
if not os.path.exists(agent_code):
result["details"]["A_executability"] = {"score": 0, "max": 15, "items": a_items}
result["error"] = "no_result_file"
return
# Anti-cheat: check if agent references ground_truth.py
with open(agent_code, "r", encoding="utf-8", errors="ignore") as f:
source_code = f.read()
if re.search(r'ground_truth\.py', source_code):
result["anti_cheat"] = {
"passed": False,
"reason": "Directly references ground_truth.py file",
}
# Execute agent code
agent_exec_success = False
agent_stderr = ""
try:
r = subprocess.run(
["python3", agent_code],
capture_output=True, text=True, timeout=300,
cwd=workspace_path,
)
if r.returncode == 0:
agent_exec_success = True
else:
agent_stderr = r.stderr or r.stdout or ""
except subprocess.TimeoutExpired:
agent_stderr = "agent code execution timeout (300s)"
except Exception as e:
agent_stderr = str(e)
if not agent_exec_success:
a_items["A1_no_error"] = 0
result["details"]["A_executability"] = {"score": 0, "max": 15, "items": a_items}
result["error"] = agent_stderr[-2000:]
return
a_items["A1_no_error"] = 5
a_items["A3_no_manual_fix"] = 3
# Check if output table has data
try:
row_count = _mysql_fetch_all(f"SELECT COUNT(*) FROM {FULL_OUTPUT}")[0][0]
except Exception as e:
row_count = 0
result["diagnostics"].append(f"mysql_count_pred_failed: {e}")
if row_count > 0:
a_items["A2_table_produced"] = 7
else:
a_items["A2_table_produced"] = 0
a_score = sum(a_items.values())
result["details"]["A_executability"] = {"score": a_score, "max": 15, "items": a_items}
# Gate: A2=0 => B/C/D/E all 0
if a_items["A2_table_produced"] == 0:
result["details"]["B_schema"] = {"score": 0, "max": 15, "items": {}}
result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {}}
result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {}}
result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}}
result["error"] = "target table empty or not produced"
return
# Read agent output from MySQL
try:
pred_rows = _mysql_fetch_dicts(f"SELECT * FROM {FULL_OUTPUT}")
except Exception as e:
result["diagnostics"].append(f"mysql_read_pred_failed: {e}")
pred_rows = []
# 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 []
# ----- Save pred data to temp table before GT overwrites output -----
_MYSQL_EXEC_CONN = None
try:
import pymysql as _pymysql
_MYSQL_EXEC_CONN = _pymysql.connect(**MYSQL_CONFIG)
with _MYSQL_EXEC_CONN.cursor() as _cur:
_cur.execute(f"DROP TABLE IF EXISTS {DB_NAME}._tmp_pred_mysql_019")
_cur.execute(f"CREATE TABLE {DB_NAME}._tmp_pred_mysql_019 AS SELECT * FROM {FULL_OUTPUT}")
_MYSQL_EXEC_CONN.commit()
except Exception as e:
result["diagnostics"].append(f"save_pred_to_temp_failed: {e}")
finally:
if _MYSQL_EXEC_CONN:
try:
_MYSQL_EXEC_CONN.close()
except Exception:
pass
# ----- 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 (output table now has GT data)
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
# Re-read pred from temp table (GT has overwritten the output table)
try:
pred_rows = _mysql_fetch_dicts(f"SELECT * FROM {DB_NAME}._tmp_pred_mysql_019")
except Exception as e:
result["diagnostics"].append(f"re_read_pred_from_temp_failed: {e}")
pred_rows = []
# Clean up temp table
try:
_mysql_execute(f"DROP TABLE IF EXISTS {DB_NAME}._tmp_pred_mysql_019")
except Exception:
pass
# ===== B. Schema一致性 (15分) =====
b_items = {}
b_items["B1_table_name"] = 2
b_items["B2_col_count"] = 3 if len(pred_columns) == EXPECTED_COL_COUNT else 0
gt_col_set = set(c.lower() for c in [
"event", "distinct_id", "appname", "user_id", "event_time", "receive_time", "os",
"track_signup_original_id", "author_nick", "platform_type", "target_type", "target_id",
"ip", "post_id", "show_groups", "group_id", "source_page", "source_module",
"operation_type", "pc_or_mobile", "is_group_member", "post_authorship",
"posts_category_id", "posts_category_name", "year", "month", "day"
])
pred_col_set = set(c.lower() for c in pred_columns)
if gt_col_set == pred_col_set:
b_items["B3_col_names"] = 5
elif len(gt_col_set & pred_col_set) / len(gt_col_set) >= 0.9:
b_items["B3_col_names"] = 3
else:
b_items["B3_col_names"] = 0
# B4: column type alignment
type_match_count = 0
try:
gt_cols_info = _mysql_columns(FULL_OUTPUT)
gt_types = {c["Field"].lower(): c["Type"].lower() for c in gt_cols_info}
pred_types = {c["Field"].lower(): c["Type"].lower() for c in cols_info}
common_cols = gt_col_set & pred_col_set
if common_cols:
for col in common_cols:
if pred_types.get(col, "") == gt_types.get(col, ""):
type_match_count += 1
except Exception:
type_match_count = len(gt_col_set & pred_col_set)
common_count = len(gt_col_set & pred_col_set)
if common_count > 0 and type_match_count / common_count >= 0.9:
b_items["B4_col_types"] = 3
elif common_count > 0 and type_match_count / common_count >= 0.7:
b_items["B4_col_types"] = 2
else:
b_items["B4_col_types"] = 0
b_items["B5_engine_format"] = 2 # MySQL InnoDB
b_score = sum(b_items.values())
result["details"]["B_schema"] = {"score": b_score, "max": 15, "items": b_items}
# ===== Anti-cheat lock =====
if not result["anti_cheat"]["passed"]:
result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {"anti_cheat_failed": True}}
result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {"anti_cheat_failed": True}}
result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}}
result["diagnostics"].append("Anti-cheat failed: C/D dimensions scored 0")
return
# ===== C. 行集一致性 (20分) =====
c_items = {}
def make_key(row):
return tuple(str(row.get(k, "")).strip() for k in KEY_COLUMNS)
gt_keys = set()
for row in gt_rows:
gt_keys.add(make_key(row))
pred_keys = []
pred_key_set = set()
for row in pred_rows:
k = make_key(row)
pred_keys.append(k)
pred_key_set.add(k)
# C1: row count
n_gt = len(gt_keys)
n_pred = len(pred_key_set)
if n_pred == EXPECTED_ROW_COUNT:
c_items["C1_row_count"] = 6
elif n_pred > 0 and n_pred <= EXPECTED_ROW_COUNT + 1:
c_items["C1_row_count"] = 3
else:
c_items["C1_row_count"] = 0
# C2: no duplicate keys
from collections import Counter
key_counter = Counter(pred_keys)
duplicates = sum(1 for v in key_counter.values() if v > 1)
if duplicates == 0:
c_items["C2_no_duplicates"] = 5
elif duplicates <= 2:
c_items["C2_no_duplicates"] = 2
else:
c_items["C2_no_duplicates"] = 0
# C3: coverage (GT key coverage)
hit_keys = gt_keys & pred_key_set
hit_count = len(hit_keys)
coverage = hit_count / n_gt if n_gt > 0 else 0
c_items["C3_coverage"] = round(5 * coverage_to_ratio(coverage), 2)
c_items["C3_coverage_rate"] = round(coverage, 4)
# C4: no extra rows
extra_keys = pred_key_set - gt_keys
extra_count = len(extra_keys)
no_extra_rate = 1 - (extra_count / n_pred) if n_pred > 0 else 0
c_items["C4_no_extra"] = round(4 * coverage_to_ratio(no_extra_rate), 2)
c_items["C4_no_extra_rate"] = round(no_extra_rate, 4)
c_score = sum(v for k, v in c_items.items() if not k.endswith("_rate"))
result["details"]["C_row_alignment"] = {"score": round(c_score, 2), "max": 20, "items": c_items}
# ===== D. 数值正确性 (40分) =====
d_items = {}
gt_index = {make_key(row): row for row in gt_rows}
pred_index = {}
for row in pred_rows:
k = make_key(row)
if k not in pred_index:
pred_index[k] = row
hit_row_keys = list(hit_keys)
# Numeric columns to check (INT/BIGINT)
# is_group_member is INT, posts_category_id is BIGINT
# These have 2 numeric cols x 7 = 14 points
numeric_cols = ["is_group_member", "posts_category_id"]
for col in numeric_cols:
if not hit_row_keys:
d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 7}
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(7 * pass_rate, 2)
d_items[col] = {"pass_rate": round(pass_rate, 4), "score": col_score, "max": 7}
if first_mismatch and pass_rate < 0.95:
result["diagnostics"].append(first_mismatch)
# String columns to check (2 points each, 13 string cols * 2 = 26)
# D max = 40: 2 numeric cols * 7 = 14, remaining 26 from 13 string cols * 2 = 26
string_cols = [
"group_id", "pc_or_mobile", "platform_type", "post_id", "show_groups",
"track_signup_original_id", "author_nick", "source_page", "source_module",
"operation_type", "target_type", "post_authorship", "posts_category_name"
]
for col in string_cols:
if not hit_row_keys:
d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 2}
continue
passed = 0
for key in hit_row_keys:
gt_val = gt_index[key].get(col)
pred_val = pred_index.get(key, {}).get(col)
if gt_val is None and pred_val is None:
passed += 1
elif gt_val is None or pred_val is None:
pass
elif str(pred_val).strip() == str(gt_val).strip():
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 event+distinct_id pairs present
expected_keys = set()
for row in EXPECTED_ROWS:
expected_keys.add((row["event"], row["distinct_id"]))
pred_keys_set = set()
for row in pred_rows:
pred_keys_set.add((str(row.get("event", "")).strip(), str(row.get("distinct_id", "")).strip()))
e1_pass = len(expected_keys & pred_keys_set)
e_items["E1_key_pairs"] = round(10 * (e1_pass / len(expected_keys)), 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 = "dwd_knowledge_base_sensors_event_di_mysql_019"
OUTPUT_TABLE_SHORT = "dwd_knowledge_base_k_bar_posts_event_di_cand_mysql_019"
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_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" in tool_input and ".py" in tool_input:
write_result_count += 1
if first_write_result_idx is None:
first_write_result_idx = idx
if "ToolResultBlock" in block_str:
if "Traceback" in block_str or "Exception" in block_str:
if any(t[1] == "Bash" and "python" in t[2] and "result.py" in t[2]
for t in tool_uses):
logic_error_retries += 1
if "python" in block_str and "result.py" in block_str:
if "Exit Code: 0" in block_str and "Traceback" not in block_str:
last_spark_submit_success_idx = idx
before_first_write = first_write_result_idx if first_write_result_idx is not None else len(transcript_entries)
# ===== G. 探索充分性 (35分) =====
g_items = {}
# G1: Checked source table schema
g1_pass = False
for idx, name, inp in tool_uses:
if idx >= before_first_write:
break
if name == "Read" and "schema" in inp.lower():
g1_pass = True
break
if name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper()) and INPUT_TABLE_SHORT in inp:
g1_pass = True
break
g_items["G1_source_schema"] = 9 if g1_pass else 0
# G2: Checked source table sample data
g2_pass = False
for idx, name, inp in tool_uses:
if idx >= before_first_write:
break
if name == "Bash" and INPUT_TABLE_SHORT in inp:
if "SELECT" in inp.upper() and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper()):
g2_pass = True
break
g_items["G2_source_sample"] = 9 if g2_pass else 0
# G3: Checked event/group_id values
g3_pass = False
for idx, name, inp in tool_uses:
if idx >= before_first_write:
break
if name == "Bash" and ("group_id" in inp.lower() or "event" in inp.lower()):
if "DISTINCT" in inp.upper() or "COUNT" in inp.upper() or "GROUP BY" in inp.upper():
g3_pass = True
break
g_items["G3_event_group_values"] = 9 if g3_pass else 0
# G4: Checked target table structure
g4_pass = False
for idx, name, inp in tool_uses:
if idx >= before_first_write:
break
if name == "Bash" and ("DESCRIBE" in inp.upper() or "SHOW CREATE" in inp.upper()) and OUTPUT_TABLE_SHORT in inp:
g4_pass = True
break
g_items["G4_target_schema"] = 8 if g4_pass else 0
g_score = sum(g_items.values())
result["details"]["G_exploration"] = {"score": g_score, "max": 35, "items": g_items}
# ===== H. 执行效率 (40分) =====
h_items = {}
if write_result_count <= 2:
h_items["H1_few_submissions"] = 13
h_items["H2_moderate_submissions"] = 7
elif write_result_count <= 4:
h_items["H1_few_submissions"] = 0
h_items["H2_moderate_submissions"] = 7
else:
h_items["H1_few_submissions"] = 0
h_items["H2_moderate_submissions"] = 0
if logic_error_retries == 0:
h_items["H3_no_logic_errors"] = 13
elif logic_error_retries <= 1:
h_items["H3_no_logic_errors"] = 7
else:
h_items["H3_no_logic_errors"] = 0
extra_writes = sum(1 for _, name, inp in tool_uses
if name == "Write" and "result.py" not in inp
and (".py" in inp or ".sql" in inp))
h_items["H4_no_redundant_ops"] = 7 if extra_writes <= 1 else 0
h_score = sum(h_items.values())
result["details"]["H_efficiency"] = {"score": h_score, "max": 40, "items": h_items}
# ===== I. 自验证行为 (25分) =====
i_items = {}
post_submit_uses = []
if last_spark_submit_success_idx is not None:
post_submit_uses = [(idx, name, inp) for idx, name, inp in tool_uses
if idx > last_spark_submit_success_idx]
i1_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp and "SELECT" in inp.upper()
for _, name, inp in post_submit_uses)
i_items["I1_query_output"] = 8 if i1_pass else 0
i2_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
and ("COUNT" in inp.upper() or "GROUP BY" in inp.upper())
for _, name, inp in post_submit_uses)
i_items["I2_check_count_or_group"] = 9 if i2_pass else 0
i3_pass = any(name == "Bash" and OUTPUT_TABLE_SHORT in inp
and ("LIMIT" in inp.upper() or "SELECT *" in inp.upper()
or "group_id" in inp.lower() or "is_group_member" 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)
|