def grade(workspace_path, **kwargs): """ mysql_017 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_news_dt_others_imp_hi_mysql_017" OUTPUT_TABLE = "dwd_news_dt_others_imp_si_cand_mysql_017" FULL_OUTPUT = f"{DB_NAME}.{OUTPUT_TABLE}" FULL_INPUT = f"{DB_NAME}.{INPUT_TABLE}" KEY_COLUMNS = ["platform_user_id"] EXPECTED_COL_COUNT = 186 # 185 data columns + _id surrogate key EXPECTED_UNIQUE_KEYS = 2 # unique platform_user_id values: omg1, omg2 EXPECTED_ROW_COUNT = 3 # 3 rows including one duplicate platform_user_id MYSQL_CONFIG = { "host": "localhost", "port": 3306, "user": "root", "password": "root123", "charset": "utf8mb4", } # Expected output (from query_engine_115 output/expected.csv) EXPECTED_ROWS = [{'_id': 1, 'iceberg_imp_date': '202606091710', 'watermark_ts': 1749489000000, 'ftime': '2026-06-09 17:10:00.000', 'imp_hour': '2026060917', 'time_range': 'morning', 'platform_user_id': 'omg1', 'device_id': 'qimei_aaa', 'social_uid': 'suid_a', 'os': 'android', 'network_type': 'wifi', 'app_version': '7.0.1', 'callfrom': 'icon', 'page_start_from': 'icon', 'start_article_id': 'art1', 'start_article_type': 'news', 'article_uuid': 'uuid1', 'article_page': 1, 'article_type': 'news', 'article_pos': 1, 'article_real_pos': 1, 'rcmd_reason': 'hot', 'is_tagversion': '0', 'event_time': '2026-06-09 17:10:00', 'client_ts': '1749489000000', 'server_time': '2026-06-09 17:10:01', 'social_openid': 'uid_101', 'suid': 'suid1', 'session_id': 'sess1', 'session_ts': '1749489000000', 'brand': 'xiaomi', 'manufacturer': 'xiaomi', 'model': 'mi14', 'login_type': 'social', 'country': 'CN', 'province': 'GD', 'pgid': 'pg1', 'ref_pgid': 'pg0', 'media_id': 'media1', 'chl_id': 'chl1', 'video_id': 'v1', 'article_id': 'a1', 'article_ptype': 'p1', 'article_cmt_id': 'cmt1', 'is_hotnews': '0', 'is_cpfans': '0', 'is_xiaoshipin': '0', 'is_coldstart': '0', 'is_minivideo': '0', 'imp_date': '20260609', 'is_landingpage': '0', 'article_imp_pv': 1, 'video_imp_pv': 0, 'imgtext_imp_pv': 1, 'eid': 'e1', 'tag_id': 't1', 'pg_tag_id': 'pt1', 'pg_tag_type': 'tt1', 'pg_article_type': 'news', 'pg_article_id': 'pa1', 'is_major_upgrade': '0', 'idfv': 'idfv1', 'android_id': 'aid1', 'tab_id': 'tab1', 'context_type': 'ctx1', 'element_path': '/p/1', 'p1_article_ptype': 'p1p', 'refpg_article_type': 'news', 'tag_type': 'tag', 'pg_tab_id': 'ptab1', 'brand_type': 'brand1', 'fulltext_imp_pv': 0, 'scheme_type': 'scheme1', 'module': '3', 'cmt_replyid': 'cmt_r1', 'comment_imp_pv': 0, 'bubble_msg_type': 'b1', 'untitled': 'u1', 'hot_rank_imp_pv': 0, 'pg_tag_scene': 'sc1', 'header_type': 'image', 'window_open_from': 'w1', 'user_more_id': 'um1', 'section_id': 'sec1', 'search_cell_type': 'sct1', 'pg_source2': 'src1', 'bar_name': 'bar1', 'scheme_url': 'url1', 'member_btn_id': 'mb1', 'vert_cell_scheme_url': 'vurl1', 'article_title': 'title1', 'pg_article_title': 'ptitle1', 'bigevent_type': 'be1', 'schedule_type': 'st1', 'pg_path': '/path1', 'ussn': 'ussn1', 'top_banner_type': 'static', 'pendant_type': 'pd1', 'banner_url': 'burl1', 'sort_menu_id': 'sm1', 'video_pid': 'vp1', 'error_tips': '', 'gameid': 'g1', 'ad_atype': 'ad1', 'ad_action': 'act1', 'article_module_pos': 'amp1', 'refpg_chl_id': 'rchl1', 'refpg_last_clck_ele': 'rele1', 'live_article_id': 'live1', 'nav_item_id': 'nav1', 'nav_item_name': 'navname1', 'have_redpoint': '0', 'nav_pos': '1', 'undetermined': '', 'pg_tab2_from': 'tb2f1', 'scheme_scene_type': 'trailer', 'is_reservable': '0', 'is_reserve': '0', 'pg_subtab_id': 'sub1', 'pg_article_live_status': '0', 'pg_article_relate_event_type': '1', 'pg_search_keyword': 'kw1', 'vert_cell_title': 'vt1', 'mod_article_type': 'mod1', 'pub_btn_type': 'pub1', 'pg_hotask_type': 'hot1', 'mod_article_ptype': 'modp1', 'question_id': 'q1', 'answer_id': 'ans1', 'is_answerer': '0', 'article_review_status': 'ok', 'banner_module_id': 'bm1', 'article_live_status': '0', 'article_pay_status': '0', 'pg_article_pay_status': '0', 'tag_scene': 'ts1', 'pg_detail_type': 'dt1', 'column_type': 'article', 'pg_column_type': 'article', 'is_column_purchased': '0', 'pg_is_column_purchased': '0', 'pay_product_id': 'pp1', 'huaci_type': 'hc1', 'panel_btn_id': 'pb1', 'is_user_self': '0', 'crepg_chl_id': 'cc1', 'crepg_article_id': 'ca1', 'crepg_article_type': 'cat1', 'dt_cre_pgid': 'dtc1', 'crepg_last_clck_ele': 'clk1', 'dialog_type': 'new', 'pg_subtab_name': 'stn1', 'e_pos': 'ep1', 'sug_word': 'sw1', 'e_from': 'alp1', 'e_type': 'ef1', 'article_list_pos': 'et1', 'pg_article_bool_parad_platform': 'pabp1', 'city_level': 'cl1', 'has_authority': '1', 'pg_is_audio': '0', 'etl_pgid': 'etl1', 'search_keyword': 'sk1', 'cardpanel_type': 'cp1', 'mod_article_page': 'mp1', 'mod_alg_info': 'mai1', 'mod_article_real_pos': 'mrp1', 'article_id_list': 'ail1', 'e_state': 'es1', 'user_suid': 'us1', 'pg_login_from': 'plf1', 'pg_last_login_type': 'plt1', 'is_ad': '0', 'hometown_adcode': 'hc1', 'user_service_id': 'usi1', 'user_cpcenter_id': 'uci1', 'agent_id': 'ag1', 'e_title': 'etl1', 'tab_setid': 'tsi1', 'pg_page_start_from': 'pps1', 'is_flash_keyword': '0', 'search_query_from': 'sqf1', 'is_query_from_cache': '0', 'p1_search_cell_type': 'p1sct1', 'pg_search_query_from': 'psqf1', 'refpg_search_query_from': 'rsqf1'}, {'_id': 2, 'iceberg_imp_date': '202606091750', 'watermark_ts': 1749491400000, 'ftime': '2026-06-09 17:50:00.000', 'imp_hour': '2026060917', 'time_range': 'evening', 'platform_user_id': 'omg2', 'device_id': 'qimei_bbb', 'social_uid': 'suid_b', 'os': 'ios', 'network_type': '5g', 'app_version': '8.2.0', 'callfrom': 'push', 'page_start_from': 'push', 'start_article_id': 'art2', 'start_article_type': 'video', 'article_uuid': 'uuid2', 'article_page': 2, 'article_type': 'video', 'article_pos': 2, 'article_real_pos': 2, 'rcmd_reason': 'rec', 'is_tagversion': '1', 'event_time': '2026-06-09 17:50:00', 'client_ts': '1749491400000', 'server_time': '2026-06-09 17:50:01', 'social_openid': 'wx2', 'suid': 'suid2', 'session_id': 'sess2', 'session_ts': '1749491400000', 'brand': 'apple', 'manufacturer': 'apple', 'model': 'iphone15', 'login_type': 'platformw', 'country': 'CN', 'province': 'BJ', 'pgid': 'pg2', 'ref_pgid': 'pg1', 'media_id': 'media2', 'chl_id': 'chl2', 'video_id': 'v2', 'article_id': 'a2', 'article_ptype': 'p2', 'article_cmt_id': 'cmt2', 'is_hotnews': '1', 'is_cpfans': '1', 'is_xiaoshipin': '1', 'is_coldstart': '1', 'is_minivideo': '1', 'imp_date': '20260609', 'is_landingpage': '1', 'article_imp_pv': 2, 'video_imp_pv': 1, 'imgtext_imp_pv': 0, 'eid': 'e2', 'tag_id': 't2', 'pg_tag_id': 'pt2', 'pg_tag_type': 'tt2', 'pg_article_type': 'video', 'pg_article_id': 'pa2', 'is_major_upgrade': '1', 'idfv': 'idfv2', 'android_id': 'aid2', 'tab_id': 'tab2', 'context_type': 'ctx2', 'element_path': '/p/2', 'p1_article_ptype': 'p2p', 'refpg_article_type': 'video', 'tag_type': 'tag', 'pg_tab_id': 'ptab2', 'brand_type': 'brand2', 'fulltext_imp_pv': 1, 'scheme_type': 'scheme2', 'module': '4', 'cmt_replyid': 'cmt_r2', 'comment_imp_pv': 1, 'bubble_msg_type': 'b2', 'untitled': 'u2', 'hot_rank_imp_pv': 1, 'pg_tag_scene': 'sc2', 'header_type': 'video', 'window_open_from': 'w2', 'user_more_id': 'um2', 'section_id': 'sec2', 'search_cell_type': 'sct2', 'pg_source2': 'src2', 'bar_name': 'bar2', 'scheme_url': 'url2', 'member_btn_id': 'mb2', 'vert_cell_scheme_url': 'vurl2', 'article_title': 'title2', 'pg_article_title': 'ptitle2', 'bigevent_type': 'be2', 'schedule_type': 'st2', 'pg_path': '/path2', 'ussn': 'ussn2', 'top_banner_type': 'dynamic', 'pendant_type': 'pd2', 'banner_url': 'burl2', 'sort_menu_id': 'sm2', 'video_pid': 'vp2', 'error_tips': '', 'gameid': 'g2', 'ad_atype': 'ad2', 'ad_action': 'act2', 'article_module_pos': 'amp2', 'refpg_chl_id': 'rchl2', 'refpg_last_clck_ele': 'rele2', 'live_article_id': 'live2', 'nav_item_id': 'nav2', 'nav_item_name': 'navname2', 'have_redpoint': '1', 'nav_pos': '2', 'undetermined': '', 'pg_tab2_from': 'tb2f2', 'scheme_scene_type': 'plaai_assistantack', 'is_reservable': '1', 'is_reserve': '1', 'pg_subtab_id': 'sub2', 'pg_article_live_status': '1', 'pg_article_relate_event_type': '2', 'pg_search_keyword': 'kw2', 'vert_cell_title': 'vt2', 'mod_article_type': 'mod2', 'pub_btn_type': 'pub2', 'pg_hotask_type': 'hot2', 'mod_article_ptype': 'modp2', 'question_id': 'q2', 'answer_id': 'ans2', 'is_answerer': '1', 'article_review_status': 'ok', 'banner_module_id': 'bm2', 'article_live_status': '1', 'article_pay_status': '1', 'pg_article_pay_status': '1', 'tag_scene': 'ts2', 'pg_detail_type': 'dt2', 'column_type': 'video', 'pg_column_type': 'video', 'is_column_purchased': '1', 'pg_is_column_purchased': '1', 'pay_product_id': 'pp2', 'huaci_type': 'hc2', 'panel_btn_id': 'pb2', 'is_user_self': '1', 'crepg_chl_id': 'cc2', 'crepg_article_id': 'ca2', 'crepg_article_type': 'cat2', 'dt_cre_pgid': 'dtc2', 'crepg_last_clck_ele': 'clk2', 'dialog_type': 'history', 'pg_subtab_name': 'stn2', 'e_pos': 'ep2', 'sug_word': 'sw2', 'e_from': 'alp2', 'e_type': 'ef2', 'article_list_pos': 'et2', 'pg_article_bool_parad_platform': 'pabp2', 'city_level': 'cl2', 'has_authority': '0', 'pg_is_audio': '1', 'etl_pgid': 'etl2', 'search_keyword': 'sk2', 'cardpanel_type': 'cp2', 'mod_article_page': 'mp2', 'mod_alg_info': 'mai2', 'mod_article_real_pos': 'mrp2', 'article_id_list': 'ail2', 'e_state': 'es2', 'user_suid': 'us2', 'pg_login_from': 'plf2', 'pg_last_login_type': 'plt2', 'is_ad': '1', 'hometown_adcode': 'hc2', 'user_service_id': 'usi2', 'user_cpcenter_id': 'uci2', 'agent_id': 'ag2', 'e_title': 'etl2', 'tab_setid': 'tsi2', 'pg_page_start_from': 'pps2', 'is_flash_keyword': '1', 'search_query_from': 'sqf2', 'is_query_from_cache': '1', 'p1_search_cell_type': 'p1sct2', 'pg_search_query_from': 'psqf2', 'refpg_search_query_from': 'rsqf2'}, {'_id': 3, 'iceberg_imp_date': '202606091710', 'watermark_ts': 1749489001000, 'ftime': '2026-06-09 17:10:01.000', 'imp_hour': '2026060917', 'time_range': 'morning', 'platform_user_id': 'omg1', 'device_id': 'qimei_aaa2', 'social_uid': 'suid_a', 'os': 'android', 'network_type': '4g', 'app_version': '7.0.1', 'callfrom': 'icon', 'page_start_from': 'push', 'start_article_id': 'art3', 'start_article_type': 'news', 'article_uuid': 'uuid1b', 'article_page': 2, 'article_type': 'news', 'article_pos': 2, 'article_real_pos': 2, 'rcmd_reason': 'hot', 'is_tagversion': '0', 'event_time': '2026-06-09 17:10:01', 'client_ts': '1749489001000', 'server_time': '2026-06-09 17:10:02', 'social_openid': 'uid_101', 'suid': 'suid1', 'session_id': 'sess1b', 'session_ts': '1749489001000', 'brand': 'xiaomi', 'manufacturer': 'xiaomi', 'model': 'mi14', 'login_type': 'social', 'country': 'CN', 'province': 'GD', 'pgid': 'pg1', 'ref_pgid': 'pg0', 'media_id': 'media1', 'chl_id': 'chl1', 'video_id': 'v3', 'article_id': 'a3', 'article_ptype': 'p3', 'article_cmt_id': 'cmt1b', 'is_hotnews': '0', 'is_cpfans': '0', 'is_xiaoshipin': '0', 'is_coldstart': '0', 'is_minivideo': '0', 'imp_date': '20260609', 'is_landingpage': '0', 'article_imp_pv': 1, 'video_imp_pv': 1, 'imgtext_imp_pv': 0, 'eid': 'e1b', 'tag_id': 't1b', 'pg_tag_id': 'pt1b', 'pg_tag_type': 'tt1b', 'pg_article_type': 'news', 'pg_article_id': 'pa1b', 'is_major_upgrade': '0', 'idfv': 'idfv1', 'android_id': 'aid1', 'tab_id': 'tab1', 'context_type': 'ctx1', 'element_path': '/p/1b', 'p1_article_ptype': 'p1pb', 'refpg_article_type': 'news', 'tag_type': 'tag', 'pg_tab_id': 'ptab1', 'brand_type': 'brand1', 'fulltext_imp_pv': 1, 'scheme_type': 'scheme1', 'module': '3', 'cmt_replyid': 'cmt_r1b', 'comment_imp_pv': 1, 'bubble_msg_type': 'b1b', 'untitled': 'u1b', 'hot_rank_imp_pv': 1, 'pg_tag_scene': 'sc1b', 'header_type': 'image', 'window_open_from': 'w1b', 'user_more_id': 'um1b', 'section_id': 'sec1b', 'search_cell_type': 'sct1b', 'pg_source2': 'src1b', 'bar_name': 'bar1b', 'scheme_url': 'url1b', 'member_btn_id': 'mb1b', 'vert_cell_scheme_url': 'vurl1b', 'article_title': 'title1b', 'pg_article_title': 'ptitle1b', 'bigevent_type': 'be1b', 'schedule_type': 'st1b', 'pg_path': '/path1b', 'ussn': 'ussn1b', 'top_banner_type': 'static', 'pendant_type': 'pd1b', 'banner_url': 'burl1b', 'sort_menu_id': 'sm1b', 'video_pid': 'vp1b', 'error_tips': '', 'gameid': 'g1b', 'ad_atype': 'ad1b', 'ad_action': 'act1b', 'article_module_pos': 'amp1b', 'refpg_chl_id': 'rchl1b', 'refpg_last_clck_ele': 'rele1b', 'live_article_id': 'live1b', 'nav_item_id': 'nav1b', 'nav_item_name': 'navname1b', 'have_redpoint': '0', 'nav_pos': '1', 'undetermined': '', 'pg_tab2_from': 'tb2f1b', 'scheme_scene_type': 'trailer', 'is_reservable': '0', 'is_reserve': '0', 'pg_subtab_id': 'sub1b', 'pg_article_live_status': '0', 'pg_article_relate_event_type': '1', 'pg_search_keyword': 'kw1b', 'vert_cell_title': 'vt1b', 'mod_article_type': 'mod1b', 'pub_btn_type': 'pub1b', 'pg_hotask_type': 'hot1b', 'mod_article_ptype': 'modp1b', 'question_id': 'q1b', 'answer_id': 'ans1b', 'is_answerer': '0', 'article_review_status': 'ok', 'banner_module_id': 'bm1b', 'article_live_status': '0', 'article_pay_status': '0', 'pg_article_pay_status': '0', 'tag_scene': 'ts1b', 'pg_detail_type': 'dt1b', 'column_type': 'article', 'pg_column_type': 'article', 'is_column_purchased': '0', 'pg_is_column_purchased': '0', 'pay_product_id': 'pp1b', 'huaci_type': 'hc1b', 'panel_btn_id': 'pb1b', 'is_user_self': '0', 'crepg_chl_id': 'cc1b', 'crepg_article_id': 'ca1b', 'crepg_article_type': 'cat1b', 'dt_cre_pgid': 'dtc1b', 'crepg_last_clck_ele': 'clk1b', 'dialog_type': 'new', 'pg_subtab_name': 'stn1b', 'e_pos': 'ep1b', 'sug_word': 'sw1b', 'e_from': 'alp1b', 'e_type': 'ef1b', 'article_list_pos': 'et1b', 'pg_article_bool_parad_platform': 'pabp1b', 'city_level': 'cl1b', 'has_authority': '1', 'pg_is_audio': '0', 'etl_pgid': 'etl1b', 'search_keyword': 'sk1b', 'cardpanel_type': 'cp1b', 'mod_article_page': 'mp1b', 'mod_alg_info': 'mai1b', 'mod_article_real_pos': 'mrp1b', 'article_id_list': 'ail1b', 'e_state': 'es1b', 'user_suid': 'us1b', 'pg_login_from': 'plf1b', 'pg_last_login_type': 'plt1b', 'is_ad': '0', 'hometown_adcode': 'hc1b', 'user_service_id': 'usi1b', 'user_cpcenter_id': 'uci1b', 'agent_id': 'ag1b', 'e_title': 'etl1b', 'tab_setid': 'tsi1b', 'pg_page_start_from': 'pps1b', 'is_flash_keyword': '0', 'search_query_from': 'sqf1b', 'is_query_from_cache': '0', 'p1_search_cell_type': 'p1sct1b', 'pg_search_query_from': 'psqf1b', 'refpg_search_query_from': 'rsqf1b'}] 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 # Save agent output to a temp table before GT overwrites the output table _TEMP_TABLE = f"{OUTPUT_TABLE}__pred_tmp" try: _mysql_execute(f"DROP TABLE IF EXISTS {DB_NAME}.{_TEMP_TABLE}") _mysql_execute( f"CREATE TABLE {DB_NAME}.{_TEMP_TABLE} AS SELECT * FROM {FULL_OUTPUT}" ) except Exception as e: result["diagnostics"].append(f"save_pred_to_tmp_failed: {e}") # Re-read agent output from temp table (safe from GT overwrite) try: pred_rows = _mysql_fetch_dicts(f"SELECT * FROM {DB_NAME}.{_TEMP_TABLE}") except Exception as e: result["diagnostics"].append(f"mysql_read_pred_tmp_failed: {e}") pred_rows = [] # Re-read columns info from temp table try: cols_info = _mysql_columns(f"{DB_NAME}.{_TEMP_TABLE}") pred_columns = [c["Field"] for c in cols_info] except Exception: pred_columns = list(pred_rows[0].keys()) if pred_rows else [] # Clean up temp table try: _mysql_execute(f"DROP TABLE IF EXISTS {DB_NAME}.{_TEMP_TABLE}") 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 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 # Key output columns to verify expected_col_names = [ "_id", "iceberg_imp_date", "watermark_ts", "ftime", "imp_hour", "time_range", "platform_user_id", "device_id", "social_uid", "os", "network_type", "app_version", "callfrom", "page_start_from", "start_article_id", "start_article_type", "article_uuid", "article_page", "article_type", "article_pos", "article_real_pos", "rcmd_reason", "is_tagversion", "event_time", "client_ts", "server_time", "social_openid", "suid", "session_id", "session_ts", "brand", "manufacturer", "model", "login_type", "country", "province", "pgid", "ref_pgid", "media_id", "chl_id", "video_id", "article_id", "article_ptype", "article_cmt_id", "is_hotnews", "is_cpfans", "is_xiaoshipin", "is_coldstart", "is_minivideo", "imp_date", "is_landingpage", "article_imp_pv", "video_imp_pv", "imgtext_imp_pv", "eid", "tag_id", "pg_tag_id", "pg_tag_type", "pg_article_type", "pg_article_id", "is_major_upgrade", "idfv", "android_id", "tab_id", "context_type", "element_path", "p1_article_ptype", "refpg_article_type", "tag_type", "pg_tab_id", "brand_type", "fulltext_imp_pv", "scheme_type", "module", "cmt_replyid", "comment_imp_pv", "bubble_msg_type", "untitled", "hot_rank_imp_pv", "pg_tag_scene", "header_type", "window_open_from", "user_more_id", "section_id", "search_cell_type", "pg_source2", "bar_name", "scheme_url", "member_btn_id", "vert_cell_scheme_url", "article_title", "pg_article_title", "bigevent_type", "schedule_type", "pg_path", "ussn", "top_banner_type", "pendant_type", "banner_url", "sort_menu_id", "video_pid", "error_tips", "gameid", "ad_atype", "ad_action", "article_module_pos", "refpg_chl_id", "refpg_last_clck_ele", "live_article_id", "nav_item_id", "nav_item_name", "have_redpoint", "nav_pos", "undetermined", "pg_tab2_from", "scheme_scene_type", "is_reservable", "is_reserve", "pg_subtab_id", "pg_article_live_status", "pg_article_relate_event_type", "pg_search_keyword", "vert_cell_title", "mod_article_type", "pub_btn_type", "pg_hotask_type", "mod_article_ptype", "question_id", "answer_id", "is_answerer", "article_review_status", "banner_module_id", "article_live_status", "article_pay_status", "pg_article_pay_status", "tag_scene", "pg_detail_type", "column_type", "pg_column_type", "is_column_purchased", "pg_is_column_purchased", "pay_product_id", "huaci_type", "panel_btn_id", "is_user_self", "crepg_chl_id", "crepg_article_id", "crepg_article_type", "dt_cre_pgid", "crepg_last_clck_ele", "dialog_type", "pg_subtab_name", "e_pos", "sug_word", "e_from", "e_type", "article_list_pos", "pg_article_bool_parad_platform", "city_level", "has_authority", "pg_is_audio", "etl_pgid", "search_keyword", "cardpanel_type", "mod_article_page", "mod_alg_info", "mod_article_real_pos", "article_id_list", "e_state", "user_suid", "pg_login_from", "pg_last_login_type", "is_ad", "hometown_adcode", "user_service_id", "user_cpcenter_id", "agent_id", "e_title", "tab_setid", "pg_page_start_from", "is_flash_keyword", "search_query_from", "is_query_from_cache", "p1_search_cell_type", "pg_search_query_from", "refpg_search_query_from", ] gt_col_set = set(c.lower() for c in expected_col_names) pred_col_set = set(c.lower() for c in pred_columns) if gt_col_set == pred_col_set: b_items["B3_col_names"] = 5 elif len(gt_col_set & pred_col_set) / len(gt_col_set) >= 0.9: b_items["B3_col_names"] = 3 else: b_items["B3_col_names"] = 0 # B4: column type alignment type_match_count = 0 try: gt_cols_info = _mysql_columns(FULL_OUTPUT) gt_types = {c["Field"].lower(): c["Type"].lower() for c in gt_cols_info} pred_types = {c["Field"].lower(): c["Type"].lower() for c in cols_info} common_cols = gt_col_set & pred_col_set if common_cols: for col in common_cols: if pred_types.get(col, "") == gt_types.get(col, ""): type_match_count += 1 except Exception: type_match_count = len(gt_col_set & pred_col_set) common_count = len(gt_col_set & pred_col_set) if common_count > 0 and type_match_count / common_count >= 0.9: b_items["B4_col_types"] = 3 elif common_count > 0 and type_match_count / common_count >= 0.7: b_items["B4_col_types"] = 2 else: b_items["B4_col_types"] = 0 b_items["B5_engine_format"] = 2 # MySQL InnoDB b_score = sum(b_items.values()) result["details"]["B_schema"] = {"score": b_score, "max": 15, "items": b_items} # ===== Anti-cheat lock ===== if not result["anti_cheat"]["passed"]: result["details"]["C_row_alignment"] = {"score": 0, "max": 20, "items": {"anti_cheat_failed": True}} result["details"]["D_numerical_accuracy"] = {"score": 0, "max": 40, "items": {"anti_cheat_failed": True}} result["details"]["E_labels"] = {"score": 0, "max": 10, "items": {}} result["diagnostics"].append("Anti-cheat failed: C/D dimensions scored 0") return # ===== C. 行集一致性 (20分) ===== c_items = {} def make_key(row): return tuple(str(row.get(k, "")).strip() for k in KEY_COLUMNS) gt_keys = set() for row in gt_rows: gt_keys.add(make_key(row)) pred_keys = [] pred_key_set = set() for row in pred_rows: k = make_key(row) pred_keys.append(k) pred_key_set.add(k) # C1: unique key count n_gt = len(gt_keys) n_pred = len(pred_key_set) if n_pred == EXPECTED_UNIQUE_KEYS: c_items["C1_row_count"] = 6 elif n_pred > 0 and n_pred <= EXPECTED_UNIQUE_KEYS + 1: c_items["C1_row_count"] = 3 else: c_items["C1_row_count"] = 0 # C2: correct row count (total rows including duplicates) total_pred_rows = len(pred_rows) total_gt_rows = len(gt_rows) if total_pred_rows == total_gt_rows: c_items["C2_row_count_total"] = 5 elif total_pred_rows > 0 and abs(total_pred_rows - total_gt_rows) <= 1: c_items["C2_row_count_total"] = 2 else: c_items["C2_row_count_total"] = 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 = {} # Sort both gt and pred rows by numeric columns for positional comparison. # This avoids the bug where duplicate platform_user_id keys cause gt_index and pred_index # to pick different rows (dict comprehension keeps last, first-keep keeps first). sort_key_cols = ["watermark_ts", "article_page", "article_pos"] def _sort_key(row): return tuple(row.get(c, 0) or 0 for c in sort_key_cols) gt_sorted = sorted(gt_rows, key=_sort_key) pred_sorted = sorted(pred_rows, key=_sort_key) # Align by matching pairs; only compare rows that exist in both sides n_compare = min(len(gt_sorted), len(pred_sorted)) # Numeric columns to check (BIGINT) numeric_cols = ["watermark_ts", "article_page", "article_pos", "article_real_pos", "article_imp_pv", "video_imp_pv", "imgtext_imp_pv", "fulltext_imp_pv", "comment_imp_pv", "hot_rank_imp_pv"] # 10 numeric cols x 4 points each = 40 max for col in numeric_cols: if n_compare == 0: d_items[col] = {"pass_rate": 0.0, "score": 0, "max": 4} continue passed = 0 first_mismatch = None for i in range(n_compare): gt_val = gt_sorted[i].get(col) pred_val = pred_sorted[i].get(col) if values_match(pred_val, gt_val): passed += 1 elif first_mismatch is None: first_mismatch = { "row_index": i, "column": col, "pred": pred_val, "gt": gt_val, } pass_rate = passed / n_compare col_score = round(4 * pass_rate, 2) d_items[col] = {"pass_rate": round(pass_rate, 4), "score": col_score, "max": 4} if first_mismatch and pass_rate < 0.95: result["diagnostics"].append(first_mismatch) 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 platform_user_ids present expected_ids = {"uid_001", "uid_002"} pred_ids = set(str(row.get("platform_user_id", "")).strip() for row in pred_rows) e1_pass = len(expected_ids & pred_ids) e_items["E1_platform_user_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 = "dwd_news_dt_others_imp_hi_mysql_017" OUTPUT_TABLE_SHORT = "dwd_news_dt_others_imp_si_cand_mysql_017" 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 imp_hour / time range distribution g3_pass = False for idx, name, inp in tool_uses: if idx >= before_first_write: break if name == "Bash" and "imp_hour" 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_date_range"] = 8 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"] = 9 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"] = 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"] = 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_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 "imp" in inp.lower() or "article" 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)